// OpenAI protocol portions are adapted in TypeScript; see third-party-notices.md. import { createOpenAiChatGptAccessHeaders, OPENAI_CHATGPT_CODEX_BASE_URL, OPENAI_CHATGPT_DEFAULT_ORIGINATOR, OpenAiChatGptAuthError, type IOpenAiChatGptReadAccess, } from './smartai.chatgpt.openai.js'; /** * The OpenAI Codex release whose model catalog contract this package implements, sent as the catalog's * `client_version` and `version`. The backend shapes the catalog by it, so a stale value withholds newer * models. It names the same release as the catalog entry of `third-party-notices.md`: move both together, * after checking the catalog fields this module reads against that release. */ export const OPENAI_CHATGPT_CATALOG_CLIENT_VERSION = '0.170.0'; const maximumCatalogBytes = 2 * 1024 * 1024; const maximumCatalogModels = 256; export type TOpenAiChatGptInputModality = 'text' | 'image' | 'audio'; export interface IOpenAiChatGptModelReasoningEffort { effort: string; description: string; } export interface IOpenAiChatGptModelServiceTier { id: string; name: string; description: string; } /** One model of a ChatGPT account's Codex catalog, in the catalog's own priority order. */ export interface IOpenAiChatGptModel { providerId: 'openai'; modelId: string; wireModel: string; displayName: string; description: string; hidden: boolean; /** The Responses API reasoning efforts the model accepts; Codex client modes such as `ultra` are left out. */ reasoningEfforts: IOpenAiChatGptModelReasoningEffort[]; /** The catalog's default effort; a Codex client mode is stated as the effort Codex sends for it. */ defaultReasoningEffort: string; inputModalities: TOpenAiChatGptInputModality[]; supportsPersonality: boolean; serviceTiers: IOpenAiChatGptModelServiceTier[]; defaultServiceTier?: string; /** * The served context window in tokens, as the catalog states it (`context_window`); absent when the * catalog states none. Never the extended `max_context_window`. */ contextWindow?: number; /** * The catalog's automatic compaction point in tokens (`auto_compact_token_limit`); absent when the * catalog states none. */ autoCompactTokenLimit?: number; /** The first listed model, or the first model when none is listed. */ isDefault: boolean; } /** * Why a catalog read failed, other than a rejected access token or an abort. * * - `NETWORK_FAILED`: the request did not complete. * - `HTTP_ERROR`: the backend answered with an error status other than 401; `status` names it. * - `PROTOCOL_ERROR`: the answer was oversized or not a catalog this package can read. */ export type TOpenAiChatGptModelListErrorCode = 'NETWORK_FAILED' | 'HTTP_ERROR' | 'PROTOCOL_ERROR'; export class OpenAiChatGptModelListError extends Error { public readonly code: TOpenAiChatGptModelListErrorCode; public readonly status?: number; constructor(codeArg: TOpenAiChatGptModelListErrorCode, statusArg?: number) { super(`OpenAI ChatGPT model catalog request failed (${codeArg}${statusArg === undefined ? '' : ` ${statusArg}`}).`); this.name = 'OpenAiChatGptModelListError'; this.code = codeArg; if (statusArg !== undefined) this.status = statusArg; } } export interface IOpenAiChatGptModelListOptions { signal?: AbortSignal; /** Stable provider originator header. Defaults to `smartai`. */ originator?: string; /** Optional underlying transport. Defaults to the current global fetch. */ fetch?: typeof fetch; /** * The Codex release to read the catalog as, sent as `client_version` and `version`; defaults to * `OPENAI_CHATGPT_CATALOG_CLIENT_VERSION`. A gateway serving a Codex client passes that client's version, so it * routes by the same catalog the client was offered. The entries are still read by this package's contract. */ clientVersion?: string; } /** A release version as Codex states it, e.g. `0.160.0` or `0.161.0-alpha.2`. */ const clientVersionPattern = /^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][0-9A-Za-z.-]{1,32})?$/; const protocolError = (): OpenAiChatGptModelListError => new OpenAiChatGptModelListError('PROTOCOL_ERROR'); const isRecord = (valueArg: unknown): valueArg is Record => typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg); const textEncoder = new TextEncoder(); const boundedString = ( valueArg: unknown, maximumBytesArg: number, allowEmptyArg = false, ): string => { if ( typeof valueArg !== 'string' || (!allowEmptyArg && valueArg.length === 0) || textEncoder.encode(valueArg).byteLength > maximumBytesArg ) { throw protocolError(); } return valueArg; }; /** * Reads a JSON body of at most `maximumBytesArg` bytes; an oversized or unparsable body fails with * `protocolErrorArg()`, and an abort with the signal's reason. Shared by the OpenAI model reads. */ export const readOpenAiBoundedJson = async ( responseArg: Response, signalArg: AbortSignal | undefined, maximumBytesArg: number, protocolErrorArg: () => Error, ): Promise => { const declared = responseArg.headers.get('content-length'); if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > maximumBytesArg)) { await responseArg.body?.cancel().catch(() => undefined); throw protocolErrorArg(); } if (!responseArg.body) throw protocolErrorArg(); const reader = responseArg.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; let completed = false; const onAbort = (): void => { void reader.cancel().catch(() => undefined); }; signalArg?.addEventListener('abort', onAbort, { once: true }); if (signalArg?.aborted) onAbort(); try { while (true) { signalArg?.throwIfAborted(); const { done, value } = await reader.read(); signalArg?.throwIfAborted(); if (done) break; size += value.byteLength; if (size > maximumBytesArg) { await reader.cancel().catch(() => undefined); throw protocolErrorArg(); } chunks.push(value); } completed = true; } finally { signalArg?.removeEventListener('abort', onAbort); if (!completed) void reader.cancel().catch(() => undefined); reader.releaseLock(); } const body = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; } try { return JSON.parse(new TextDecoder().decode(body)) as unknown; } catch { throw protocolErrorArg(); } }; /** * Catalog efforts that select a Codex client mode instead of naming a Responses API reasoning effort. Codex * resolves them before it sends a request: `ultra` selects its multi-agent Ultra mode and sends the model's * multi-agent effort or `max`, and `persistent` selects its persistent mode and sends `disabled`. A caller * sends the effort it picks from `reasoningEfforts` as it is, so the catalog read leaves these out. */ const codexClientModeEfforts: ReadonlySet = new Set(['ultra', 'persistent']); /** The effort Codex sends for a client-mode effort, as its `ModelInfo::resolve_reasoning_effort` resolves it. */ const resolveCodexClientModeEffort = ( effortArg: string, effortsArg: readonly IOpenAiChatGptModelReasoningEffort[], multiAgentEffortArg: unknown, ): string => { if (effortArg === 'persistent') return 'disabled'; const isListed = (candidateArg: unknown): candidateArg is string => effortsArg.some((entry) => entry.effort === candidateArg); if (isListed(multiAgentEffortArg)) return multiAgentEffortArg; if (isListed('max')) return 'max'; return effortsArg.at(-1)?.effort ?? 'medium'; }; const projectCatalog = (valueArg: unknown): IOpenAiChatGptModel[] => { if (!isRecord(valueArg) || !Array.isArray(valueArg.models) || valueArg.models.length > maximumCatalogModels) { throw protocolError(); } const modelIds = new Set(); const entries = valueArg.models.map((rawModel, sourceIndex) => { if (!isRecord(rawModel)) throw protocolError(); const modelId = boundedString(rawModel.slug, 256); if (modelIds.has(modelId)) throw protocolError(); modelIds.add(modelId); const visibility = rawModel.visibility; if (visibility !== 'list' && visibility !== 'hide' && visibility !== 'none') { throw protocolError(); } if (!Number.isSafeInteger(rawModel.priority)) throw protocolError(); if (!Array.isArray(rawModel.supported_reasoning_levels) || rawModel.supported_reasoning_levels.length > 16) { throw protocolError(); } const reasoningEfforts = rawModel.supported_reasoning_levels .map((rawEffort) => { if (!isRecord(rawEffort)) throw protocolError(); return { effort: boundedString(rawEffort.effort, 128), description: boundedString(rawEffort.description, 1024, true), }; }) .filter((entry) => !codexClientModeEfforts.has(entry.effort)); const catalogDefaultEffort = rawModel.default_reasoning_level === null || rawModel.default_reasoning_level === undefined ? 'none' : boundedString(rawModel.default_reasoning_level, 128); const modalities = rawModel.input_modalities ?? ['text', 'image']; if ( !Array.isArray(modalities) || modalities.length > 3 || modalities.some((entry) => entry !== 'text' && entry !== 'image' && entry !== 'audio') || new Set(modalities).size !== modalities.length ) { throw protocolError(); } const rawServiceTiers = rawModel.service_tiers ?? []; if (!Array.isArray(rawServiceTiers) || rawServiceTiers.length > 16) { throw protocolError(); } const serviceTiers = rawServiceTiers.map((rawTier) => { if (!isRecord(rawTier)) throw protocolError(); return { id: boundedString(rawTier.id, 128), name: boundedString(rawTier.name, 256), description: boundedString(rawTier.description, 1024, true), }; }); const contextWindow = rawModel.context_window; if ( contextWindow !== null && contextWindow !== undefined && (!Number.isSafeInteger(contextWindow) || (contextWindow as number) < 1) ) { throw protocolError(); } const autoCompactTokenLimit = rawModel.auto_compact_token_limit; if ( autoCompactTokenLimit !== null && autoCompactTokenLimit !== undefined && (!Number.isSafeInteger(autoCompactTokenLimit) || (autoCompactTokenLimit as number) < 1) ) { throw protocolError(); } const modelMessages = isRecord(rawModel.model_messages) ? rawModel.model_messages : undefined; const variables = isRecord(modelMessages?.instructions_variables) ? modelMessages.instructions_variables : undefined; const supportsPersonality = typeof modelMessages?.instructions_template === 'string' && modelMessages.instructions_template.includes('{{ personality }}') && typeof variables?.personality_default === 'string' && typeof variables.personality_friendly === 'string' && typeof variables.personality_pragmatic === 'string'; return { priority: rawModel.priority as number, sourceIndex, model: { providerId: 'openai' as const, modelId, wireModel: modelId, displayName: boundedString(rawModel.display_name, 512), description: rawModel.description === null || rawModel.description === undefined ? '' : boundedString(rawModel.description, 4096, true), hidden: visibility !== 'list', reasoningEfforts, defaultReasoningEffort: codexClientModeEfforts.has(catalogDefaultEffort) ? resolveCodexClientModeEffort(catalogDefaultEffort, reasoningEfforts, rawModel.multi_agent_reasoning_effort) : catalogDefaultEffort, inputModalities: modalities as TOpenAiChatGptInputModality[], supportsPersonality, serviceTiers, ...(rawModel.default_service_tier === null || rawModel.default_service_tier === undefined ? {} : { defaultServiceTier: boundedString(rawModel.default_service_tier, 128) }), ...(contextWindow === null || contextWindow === undefined ? {} : { contextWindow: contextWindow as number }), ...(autoCompactTokenLimit === null || autoCompactTokenLimit === undefined ? {} : { autoCompactTokenLimit: autoCompactTokenLimit as number }), isDefault: false, }, }; }); entries.sort((left, right) => left.priority - right.priority || left.sourceIndex - right.sourceIndex); const models = entries.map((entry) => entry.model); const defaultModel = models.find((model) => !model.hidden) ?? models[0]; if (defaultModel) defaultModel.isDefault = true; return models; }; /** * Reads the Codex model catalog of one ChatGPT account with access alone. * * It returns every model, hidden ones included, in the catalog's priority order. A rejected access token * fails with an `OpenAiChatGptAuthError` whose `status` is 401, so a caller that holds a renewable access * resolves it again and repeats the read. An abort rejects with the signal's reason; every other failure * is an `OpenAiChatGptModelListError`. */ export async function listOpenAiChatGptModels( accessArg: IOpenAiChatGptReadAccess, optionsArg: IOpenAiChatGptModelListOptions = {}, ): Promise { if ( !accessArg || typeof accessArg.accessToken !== 'string' || accessArg.accessToken.length === 0 || (accessArg.accountId !== undefined && (typeof accessArg.accountId !== 'string' || accessArg.accountId.length === 0)) || typeof accessArg.isFedrampAccount !== 'boolean' ) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT access is invalid.'); } const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') { throw new OpenAiChatGptAuthError('fetch is not available for the OpenAI ChatGPT model catalog.'); } const clientVersion = optionsArg.clientVersion ?? OPENAI_CHATGPT_CATALOG_CLIENT_VERSION; if (typeof clientVersion !== 'string' || !clientVersionPattern.test(clientVersion)) { throw new TypeError('The Codex client version must be a release version such as 0.160.0.'); } const signal = optionsArg.signal; signal?.throwIfAborted(); const url = `${OPENAI_CHATGPT_CODEX_BASE_URL}/models?client_version=${encodeURIComponent(clientVersion)}`; let response: Response; let onAbort: (() => void) | undefined; try { const fetchPromise = transport(url, { method: 'GET', redirect: 'error', signal, headers: { Accept: 'application/json', ...createOpenAiChatGptAccessHeaders(accessArg, optionsArg.originator ?? OPENAI_CHATGPT_DEFAULT_ORIGINATOR), version: clientVersion, }, }); if (!signal) { response = await fetchPromise; } else { // A transport that ignores the signal must not hold the caller: the abort settles the read, and a // response that arrives later is released. void fetchPromise.then((lateResponse) => { if (signal.aborted) void lateResponse.body?.cancel().catch(() => undefined); }).catch(() => undefined); const aborted = new Promise((_resolve, reject) => { onAbort = () => reject(signal.reason); signal.addEventListener('abort', onAbort, { once: true }); }); response = await Promise.race([fetchPromise, aborted]); } } catch { if (signal?.aborted) throw signal.reason; throw new OpenAiChatGptModelListError('NETWORK_FAILED'); } finally { if (onAbort) signal?.removeEventListener('abort', onAbort); } if (!response.ok) { await response.body?.cancel().catch(() => undefined); if (response.status === 401) { throw new OpenAiChatGptAuthError('OpenAI ChatGPT rejected the access token.', { status: 401 }); } throw new OpenAiChatGptModelListError('HTTP_ERROR', response.status); } return projectCatalog(await readOpenAiBoundedJson(response, signal, maximumCatalogBytes, protocolError)); }