import { createHmac, randomBytes } from 'node:crypto'; import { appendFileSync } from 'node:fs'; import type { PromptCacheContext, LlmStreamEvent } from '../types.js'; type Role = NonNullable; type Terminal = Extract; const salt = randomBytes(32); const hash = (value: unknown) => createHmac('sha256', salt).update(JSON.stringify(value)).digest('base64url'); const samples = new Map< string, { head: string; items: string[]; count: number } >(); const noop = () => {}; const count = (n: unknown): number | null => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 ? n : null; /** Separate from general debug logs: only counters and opaque fingerprints cross this boundary. */ export function beginCacheTrace( url: string, model: string, format: string, body: string, ctx?: PromptCacheContext, role: Role = ctx?.role ?? 'main', sink?: (record: Record) => void, ): (outcome: string, ev?: Terminal) => void { const file = process.env.MINIMAL_AGENT_CACHE_TRACE; if (!file && !sink) return noop; try { const started = Date.now(); const { origin, pathname } = new URL(url); const { messages, input, requestId: _id, ...header } = JSON.parse(body); const items = messages ?? input ?? []; if (!Array.isArray(items)) return noop; const key = hash([url, model, format, role, ctx?.scopeKey, ctx?.traceLane]); const previous = ctx && samples.get(key); const sample = { head: hash(header), items: items.slice(0, 2048).map(hash), count: items.length, }; let matched = 0; if (previous) { while ( matched < sample.items.length && sample.items[matched] === previous.items[matched] ) matched++; } const partial = matched === 2048 && Math.min(previous?.count ?? 0, items.length) > matched; const sameMessages = !!previous && matched === items.length && matched === previous.count; const identical = sameMessages && previous.head === sample.head; if (ctx) { samples.delete(key); samples.set(key, sample); if (samples.size > 64) samples.delete(samples.keys().next().value!); } let emitted = false; return (outcome, ev) => { if (emitted) return; emitted = true; const done = ev?.type === 'done' ? ev : undefined; const usage = ev?.promptCacheUsage; const writeByTtl = Object.fromEntries( (['5m', '1h', '30m', '12h'] as const).flatMap((ttl) => { const n = count(usage?.cacheWritesByTtl?.[ttl]); return n !== null ? [[ttl, n]] : []; }), ); const record = { role, started, elapsedMs: Math.max(0, Date.now() - started), endpoint: origin, route: hash(pathname).slice(0, 12), model, format, lane: key.slice(0, 12), prefix: sample.head.slice(0, 12), messages: sample.count, comparison: !previous ? 'first' : partial ? 'bounded' : identical ? 'same' : 'changed', headerChanged: previous ? previous.head !== sample.head : null, firstChanged: previous && !partial && !sameMessages ? matched : null, outcome, input: count(ev?.promptTokens ?? usage?.promptTokens), read: count(usage?.cacheReadTokens ?? done?.cachedPromptTokens), write: count(usage?.cacheWriteTokens ?? done?.cacheWriteTokens), writeByTtl: Object.keys(writeByTtl).length ? writeByTtl : undefined, reported: usage?.reported ?? (done?.cachedPromptTokens !== undefined || done?.cacheWriteTokens !== undefined), }; try { if (sink) sink(record); else appendFileSync(file!, JSON.stringify(record) + '\n', { mode: 0o600 }); } catch { /* diagnostics must not disrupt inference */ } }; } catch { return noop; } }