// --------------------------------------------------------------------------- // Per-request LLM credential context. // // Each visitor can run the app's AI features on their own (free) Hugging Face // token, supplied per request via the x-hf-token / x-hf-model headers. // withApiError() reads those headers and runs every route handler inside // runWithLlmConfig(), so the `claude` singleton (used unchanged at ~21 call // sites) transparently resolves the active request's credentials. // // This lives in its own module — separate from claude.ts — so that the many // route tests that `vi.mock("@/lib/claude")` keep working: withApiError pulls // the context primitives from here, not from the mocked claude module. // --------------------------------------------------------------------------- import { AsyncLocalStorage } from "node:async_hooks"; /** Per-request LLM credentials (typically derived from request headers). */ export interface LlmConfig { hfToken?: string; hfModel?: string; } const globalForLlm = globalThis as unknown as { __llmStore?: AsyncLocalStorage; }; // Singleton store so request context survives Next.js HMR module reloads. const llmStore: AsyncLocalStorage = globalForLlm.__llmStore ?? new AsyncLocalStorage(); globalForLlm.__llmStore = llmStore; /** Run `fn` with request-scoped LLM credentials visible to getClaude()/claude. */ export function runWithLlmConfig(config: LlmConfig, fn: () => T): T { return llmStore.run(config, fn); } /** The active request's LLM config, or undefined outside a request. */ export function getLlmConfig(): LlmConfig | undefined { return llmStore.getStore(); } function clean(v: string | null | undefined): string | undefined { const t = v?.trim(); return t ? t : undefined; } /** Build an LlmConfig from request headers (x-hf-token / x-hf-model). */ export function llmConfigFromHeaders(headers: Headers): LlmConfig { return { hfToken: clean(headers.get("x-hf-token")), hfModel: clean(headers.get("x-hf-model")), }; }