assembly-fingerprint.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { createHash } from 'node:crypto';
  2. const FINGERPRINT_LENGTH = 16;
  3. export interface AssemblyFingerprintContext {
  4. readonly systemPrompt?: string;
  5. readonly tools?: readonly {
  6. readonly name: string;
  7. readonly description: string;
  8. readonly parameters: unknown;
  9. }[];
  10. }
  11. export interface AssemblyFingerprint {
  12. readonly systemPrompt: string;
  13. readonly tools: string;
  14. }
  15. /**
  16. * Fingerprint only the provider-visible, cache-relevant assembly surfaces.
  17. * Message history is intentionally excluded so normal loop growth does not
  18. * look like system/tool assembly churn.
  19. */
  20. export function fingerprintAssembly(context: AssemblyFingerprintContext): AssemblyFingerprint {
  21. const toolInterfaces = (context.tools ?? []).map((tool) => ({
  22. name: tool.name,
  23. description: tool.description,
  24. parameters: tool.parameters,
  25. }));
  26. return {
  27. // Preserve whitespace exactly: prompt caches observe it even when humans do not.
  28. systemPrompt: fingerprint(context.systemPrompt ?? ''),
  29. // Preserve tool order but canonicalize object keys inside each definition.
  30. tools: fingerprint(canonicalStringify(toolInterfaces)),
  31. };
  32. }
  33. function fingerprint(value: string): string {
  34. return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, FINGERPRINT_LENGTH);
  35. }
  36. function canonicalStringify(value: unknown): string {
  37. return JSON.stringify(canonicalize(value, new Set())) ?? 'null';
  38. }
  39. function canonicalize(value: unknown, ancestors: Set<object>): unknown {
  40. if (Array.isArray(value)) {
  41. if (ancestors.has(value)) throw new TypeError('Cannot fingerprint cyclic assembly data');
  42. ancestors.add(value);
  43. try {
  44. return value.map((item) => canonicalize(item, ancestors));
  45. } finally {
  46. ancestors.delete(value);
  47. }
  48. }
  49. if (!value || typeof value !== 'object') return value;
  50. if (ancestors.has(value)) throw new TypeError('Cannot fingerprint cyclic assembly data');
  51. ancestors.add(value);
  52. try {
  53. const result: Record<string, unknown> = {};
  54. for (const key of Object.keys(value).sort()) {
  55. const item = (value as Record<string, unknown>)[key];
  56. if (item === undefined || typeof item === 'function' || typeof item === 'symbol') continue;
  57. result[key] = canonicalize(item, ancestors);
  58. }
  59. return result;
  60. } finally {
  61. ancestors.delete(value);
  62. }
  63. }