1// JSON with keys sorted at every level: {a:1,b:2} and {b:2,a:1} give the same text
2export function stableStringify(value: unknown): string {
3 if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
4 if (value && typeof value === 'object') {
5 const entries = Object.entries(value as Record<string, unknown>)
6 .filter(([, v]) => v !== undefined)
7 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
8 return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`
9 }
10 return JSON.stringify(value) ?? 'null'
11}
12
13export function idempotencyKey(requestId: string, tool: string, args: Record<string, unknown>) {
14 return `${requestId}|${tool}|${stableStringify(args)}`
15}
Exactly-once in a few lines: the same request, tool and arguments always make the same key, and the ledger's UNIQUE column refuses a second copy.