File size: 2,060 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// ---------------------------------------------------------------------------
// 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<LlmConfig>;
};

// Singleton store so request context survives Next.js HMR module reloads.
const llmStore: AsyncLocalStorage<LlmConfig> =
  globalForLlm.__llmStore ?? new AsyncLocalStorage<LlmConfig>();
globalForLlm.__llmStore = llmStore;

/** Run `fn` with request-scoped LLM credentials visible to getClaude()/claude. */
export function runWithLlmConfig<T>(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")),
  };
}