"""Authentication — single token source via ContextVar + env mirror. The ContextVar ``hf_token`` is the authoritative token source for storage sync and HF Hub upload code. BAML's ``env.HF_TOKEN`` reads from the process environment, so ``_install_active_token()`` also writes ``os.environ["HF_TOKEN"]``. In CLI/Jobs contexts the env var is set first and copied into the ContextVar. """ from __future__ import annotations import os from contextvars import ContextVar hf_token: ContextVar[str | None] = ContextVar("hf_token", default=None) """HF OAuth token for the current request. Set via ``_install_active_token()`` which keeps both the ContextVar and ``os.environ["HF_TOKEN"]`` in sync — the latter is required by BAML. """ def install_token(token_str: str) -> None: """Install the token as the single source of truth. Writes the ContextVar (for storage sync / HF Hub) and os.environ (for BAML's ``env.HF_TOKEN``). """ hf_token.set(token_str) os.environ["HF_TOKEN"] = token_str