import type * as plugins from './plugins.js'; import { OPENAI_CHATGPT_CODEX_BASE_URL } from './smartai.chatgpt.openai.js'; // Only transports owned here and known not to change the request body may retain // native policy confirmation on OpenAI's API. Arbitrary custom fetch middleware is opaque. const transparentTransports = new WeakSet>(); export function registerOpenAiCacheTransparentTransport( transport: NonNullable, ): void { transparentTransports.add(transport); } /** Whether a connection's transport sends the body the adapter serialized: the global fetch, or a registered one. */ export function isOpenAiCacheTransparentTransport( transport: plugins.OpenAIProviderSettings['fetch'], ): boolean { return transport === undefined || transparentTransports.has(transport); } const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const apiPaths = new Set(['/v1/responses', '/v1/chat/completions']); /** * Read the serialized request, after the adapter's own transforms. OpenAI's API counts only * through a transport known not to change the body; the ChatGPT backend counts through any, since * its budget is already the shortest one OpenAI documents. */ export function readOpenAiEffectiveCachePolicy( url: string, body: unknown, transparentTransport: boolean, ): plugins.ISmartAiOpenAiEffectiveCachePolicy | undefined { const endpointUrl = new URL(url); if (endpointUrl.username !== '' || endpointUrl.password !== '' || typeof body !== 'string') return undefined; const endpoint = endpointUrl.href.startsWith(`${OPENAI_CHATGPT_CODEX_BASE_URL}/`) ? 'chatgpt' : transparentTransport && endpointUrl.origin === 'https://api.openai.com' && apiPaths.has(endpointUrl.pathname) ? 'api' : undefined; if (!endpoint) return undefined; let request: unknown; try { request = JSON.parse(body); } catch { return undefined; } if (!isRecord(request) || typeof request.model !== 'string') return undefined; const options = request.prompt_cache_options; return { provider: 'openai', endpoint, model: request.model, ...(request.prompt_cache_retention === undefined ? {} : { retention: request.prompt_cache_retention }), ...(isRecord(options) && options.ttl !== undefined ? { ttl: options.ttl } : {}), }; }