import type * as plugins from './plugins.js'; // Only transports owned here and known not to change the request body may retain // native policy confirmation. Arbitrary custom fetch middleware is opaque. const transparentTransports = new WeakSet>(); export function registerAnthropicCacheTransparentTransport( transport: NonNullable, ): void { transparentTransports.add(transport); } export function isAnthropicCacheTransparentTransport( transport: plugins.AnthropicProviderSettings['fetch'], ): boolean { return transport === undefined || transparentTransports.has(transport); } const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); /** Read the serialized native Messages request, after SDK cache validation/conversion. */ export function readAnthropicEffectiveCachePolicy( url: string, body: unknown, ): plugins.ISmartAiEffectiveCachePolicy | undefined { const endpoint = new URL(url); if (endpoint.origin !== 'https://api.anthropic.com' || endpoint.pathname !== '/v1/messages' || endpoint.username !== '' || endpoint.password !== '' || typeof body !== 'string') return undefined; let request: unknown; try { request = JSON.parse(body); } catch { return undefined; } if (!isRecord(request) || !Array.isArray(request.messages)) return undefined; const controls: unknown[] = []; const collect = (part: unknown) => { if (isRecord(part) && Object.prototype.hasOwnProperty.call(part, 'cache_control')) { controls.push(part.cache_control); } }; collect(request); for (const key of ['system', 'tools']) { const parts = request[key]; if (Array.isArray(parts)) parts.forEach(collect); } for (const message of request.messages) { if (isRecord(message) && Array.isArray(message.content)) message.content.forEach(collect); } return { provider: 'anthropic', controls }; }