import type { LocalProvider, PromptCacheUsage } from '../types.js'; /** Endpoint contracts are not inherited by a proxy serving the same model name. */ export function cacheCapabilities(p: LocalProvider) { const format = p.apiFormat ?? 'openai'; let endpoint: URL | undefined; try { endpoint = new URL(p.baseURL); } catch { /* generic compatible endpoint */ } const origin = endpoint?.origin; const path = endpoint?.pathname.replace(/\/+$/, '') ?? ''; const claude = origin === 'https://api.anthropic.com' && ['', '/v1', '/v1/messages'].includes(path) && format === 'anthropic' && /^claude-/.test(p.model); const modern = origin === 'https://api.openai.com' && ['', '/v1', '/v1/responses'].includes(path) && format === 'openai-responses' && /^gpt-(?:5\.(?:[6-9]|[1-9]\d+)|6(?:\.\d+)?)(?:-|$)/.test(p.model); const ark = origin === 'https://ark.cn-beijing.volces.com' && ['/api/v3', '/api/v3/responses'].includes(path) && format === 'openai-responses' && [ 'doubao-seed-2-1-pro-260915', 'doubao-seed-2-1-lite-260915', 'doubao-seed-2-1-turbo-260628', ].includes(p.model); return { routingKey: format !== 'anthropic', // opt-in on compatible proxies; retains existing rejection fallback breakpoint: claude ? 'cache_control' : modern ? 'prompt_cache_breakpoint' : undefined, ttl: claude ? ['5m', '1h'] : modern ? ['30m', '12h'] : [], arkSession: ark, arkPrefix: ark, }; } export function configuredCacheTtl(p: LocalProvider) { const ttl = process.env.MINIMAL_AGENT_CACHE_TTL; return p.promptCache?.mode !== 'disabled' && ttl && cacheCapabilities(p).ttl.includes(ttl) ? ttl : undefined; } export function cacheWrites( details: unknown, ): Pick { if (!details || typeof details !== 'object') return {}; const d = details as Record; const valid = (n: unknown): n is number => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0; const split = d.cache_write_tokens_details as | Record | undefined; const byTtl = Object.fromEntries( Object.entries({ '30m': split?.ttl_30m_tokens, '12h': split?.ttl_12h_tokens, '5m': d.ephemeral_5m_input_tokens, '1h': d.ephemeral_1h_input_tokens, }).filter(([, v]) => valid(v)), ); return { ...(valid(d.cache_write_tokens) ? { cacheWriteTokens: d.cache_write_tokens } : {}), ...(Object.keys(byTtl).length ? { cacheWritesByTtl: byTtl } : {}), }; }