/**
 * AsyncLocalStorage-based correlation context for request/session/turn/run scoping.
 *
 * Seed at HTTP entry points and session/turn creation so downstream events can
 * automatically attach the correct IDs without explicit threading.
 *
 * Usage:
 * ```ts
 * // Seed at HTTP request entry:
 * correlationCtx.run({ requestId: crypto.randomUUID() }, () => handler(req));
 *
 * // Read anywhere downstream:
 * const { requestId, sessionId } = getCorrelationContext();
 * ```
 */
import { AsyncLocalStorage } from 'node:async_hooks';
/** The singleton AsyncLocalStorage instance for correlation context. */
export const correlationCtx = new AsyncLocalStorage();
/**
 * Get the current correlation context, or an empty object if none is active.
 * Safe to call from anywhere — returns {} when no context is running.
 */
export function getCorrelationContext() {
    return correlationCtx.getStore() ?? {};
}
/**
 * Run a function within a new correlation context that inherits the current
 * context and overrides the provided fields.
 */
export function withCorrelation(overrides, fn) {
    const current = correlationCtx.getStore() ?? {};
    return correlationCtx.run({ ...current, ...overrides }, fn);
}
/**
 * Run an async function within a new correlation context.
 */
export async function withCorrelationAsync(overrides, fn) {
    const current = correlationCtx.getStore() ?? {};
    return correlationCtx.run({ ...current, ...overrides }, fn);
}
