import { createHash } from 'node:crypto'; import type { PromptCacheContext, PromptCacheMode } from '../types.js'; const SCOPE_VERSION = 'minimal-agent:prompt-cache:v1'; /** Build a provider-safe cache routing key without exposing local identity. */ export function createPromptCacheContext( conversationKey: string, namespace = 'main', ): PromptCacheContext { const scopeKey = createHash('sha256') .update(SCOPE_VERSION) .update('\0') .update(namespace) .update('\0') .update(conversationKey) .digest('hex'); return { scopeKey, conversationKey }; } export function derivePromptCacheContext( parent: PromptCacheContext | undefined, namespace: string, role: PromptCacheContext['role'] = parent?.role ?? 'main', traceLane?: string, ): PromptCacheContext | undefined { return parent ? { ...createPromptCacheContext(parent.conversationKey, namespace), role, traceLane } : undefined; } export function normalizePromptCacheMode(value: unknown): PromptCacheMode { return value === 'session-key' || value === 'disabled' ? value : 'auto'; } export function shortCacheScope(scopeKey: string | undefined): string | undefined { return scopeKey?.slice(0, 12); } /** Diagnostic fingerprint only; callers must never log the source material. */ export function promptMaterialHash(value: unknown): string { const serialized = typeof value === 'string' ? value : JSON.stringify(value); return createHash('sha256').update(serialized ?? '').digest('hex').slice(0, 12); }