/**
 * Session Context — AsyncLocalStorage for MCP session ID propagation
 *
 * Provides transparent session tracking through async call chains without
 * modifying function signatures. Every tool handler call from the MCP SDK
 * inherits the session context set by the transport layer.
 *
 * DESIGN: getActiveSessionId() returns STDIO_SESSION_ID when no session
 * context is active — NOT null. This is fail-safe: there is always a valid
 * session ID. No null checks needed downstream.
 *
 * Usage:
 *   HTTP mode: withSession(sessionId, () => handler(request))
 *   Stdio mode: withSession(STDIO_SESSION_ID, () => server.connect(transport))
 *
 * CRITICAL: NEVER use console.log() — stdout is JSON-RPC (IMM-02).
 *
 * @module server/session-context
 */
import { AsyncLocalStorage } from 'node:async_hooks';
// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════
/**
 * Default session ID for stdio mode (single client, single process).
 * Used as the fallback when no session context is active.
 */
const STDIO_SESSION_ID = '__stdio__';
// ═══════════════════════════════════════════════════════════════════════════════
// ASYNC LOCAL STORAGE
// ═══════════════════════════════════════════════════════════════════════════════
/**
 * AsyncLocalStorage instance for session ID propagation.
 * Node.js stable API since v16 — propagates through async/await, timers,
 * event emitters, and Promises without manual threading.
 */
const sessionStore = new AsyncLocalStorage();
// ═══════════════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════
/**
 * Execute a function within a session context.
 *
 * All code running inside `fn` (including nested async calls, timers, and
 * Promises) will see `sessionId` when calling `getActiveSessionId()`.
 *
 * @param sessionId - The MCP session identifier
 * @param fn - Function to execute within the session context
 * @returns The return value of fn
 */
function withSession(sessionId, fn) {
    return sessionStore.run(sessionId, fn);
}
/**
 * Get the active session ID for the current async context.
 *
 * Returns STDIO_SESSION_ID when called outside a session context (e.g.,
 * stdio mode, process exit handlers, background timers). This ensures
 * downstream code always has a valid session ID — no null checks needed.
 *
 * @returns The current session ID, or STDIO_SESSION_ID if none is active
 */
function getActiveSessionId() {
    return sessionStore.getStore() ?? STDIO_SESSION_ID;
}
// ═══════════════════════════════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════════════════════════════
export { withSession, getActiveSessionId, STDIO_SESSION_ID };
//# sourceMappingURL=session-context.js.map