from __future__ import annotations import ipaddress import os from dataclasses import dataclass, field from urllib.parse import urlsplit DEFAULT_ORIGINS = ( "https://2b-entertainment.com", "https://www.2b-entertainment.com", ) DEFAULT_MODEL = "minimax/minimax-m3:free" DEFAULT_FALLBACK_MODELS = ( "minimax/minimax-m2.7:free", "openrouter/free", ) PRIVATE_DEVELOPMENT_NETWORKS = ( ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16"), ipaddress.ip_network("::1/128"), ipaddress.ip_network("fc00::/7"), ipaddress.ip_network("fe80::/10"), ) IpNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network def _csv(value: str) -> tuple[str, ...]: return tuple(item.strip() for item in value.split(",") if item.strip()) def _integer(name: str, default: int, minimum: int, maximum: int) -> int: raw = os.getenv(name) value = default if raw is None else int(raw) if not minimum <= value <= maximum: raise ValueError(f"{name} must be between {minimum} and {maximum}.") return value def _number(name: str, default: float, minimum: float, maximum: float) -> float: raw = os.getenv(name) value = default if raw is None else float(raw) if not minimum <= value <= maximum: raise ValueError(f"{name} must be between {minimum} and {maximum}.") return value def _boolean(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None: return default normalized = raw.strip().lower() if normalized in {"1", "true", "yes", "on"}: return True if normalized in {"0", "false", "no", "off"}: return False raise ValueError(f"{name} must be a boolean.") def _development_origin(origin: str) -> bool: parsed = urlsplit(origin) structurally_valid = ( parsed.scheme in {"http", "https"} and bool(parsed.hostname) and not parsed.username and not parsed.password and parsed.path in {"", "/"} and not parsed.query and not parsed.fragment ) if not structurally_valid or parsed.hostname is None: return False if parsed.hostname == "localhost": return True try: address = ipaddress.ip_address(parsed.hostname) except ValueError: return False return any(address in network for network in PRIVATE_DEVELOPMENT_NETWORKS) @dataclass(frozen=True, slots=True) class Settings: openrouter_api_key: str = field(default="", repr=False) primary_model: str = DEFAULT_MODEL fallback_models: tuple[str, ...] = DEFAULT_FALLBACK_MODELS environment: str = "production" localhost_origins: tuple[str, ...] = () rate_limit_requests: int = 15 rate_limit_window_seconds: int = 60 max_body_bytes: int = 24_576 max_message_characters: int = 2_000 max_history_messages: int = 12 max_history_message_characters: int = 1_200 max_history_characters: int = 6_000 upstream_timeout_seconds: float = 25.0 max_output_tokens: int = 700 max_output_characters: int = 12_000 trust_proxy_headers: bool = False trusted_proxy_networks: tuple[IpNetwork, ...] = ( ipaddress.ip_network("127.0.0.1/32"), ipaddress.ip_network("::1/128"), ) openrouter_site_url: str = "https://2b-entertainment.com" web_search_enabled: bool = False web_search_engine: str = "exa" web_search_max_results: int = 4 web_search_max_uses: int = 1 web_search_max_characters: int = 4_000 market_research_enabled: bool = False market_research_database_path: str = "data/private/fuugi_research.sqlite3" market_research_retention_days: int = 90 memory_enabled: bool = False memory_database_path: str = "data/fuugi_memory.sqlite3" memory_session_pepper: str = field(default="", repr=False) memory_retention_days: int = 90 memory_max_items: int = 50 memory_max_item_characters: int = 500 memory_max_context_characters: int = 4_000 fuugi_worker_url: str = "" fuugi_worker_token: str = field(default="", repr=False) fuugi_worker_timeout_seconds: float = 45.0 @classmethod def from_env(cls) -> Settings: environment = os.getenv("ENVIRONMENT", "production").strip().lower() if environment not in {"production", "development", "test"}: raise ValueError("ENVIRONMENT must be production, development, or test.") fallback_models = _csv( os.getenv("OPENROUTER_FALLBACK_MODELS", ",".join(DEFAULT_FALLBACK_MODELS)) ) proxy_networks = tuple( ipaddress.ip_network(value, strict=False) for value in _csv(os.getenv("TRUSTED_PROXY_NETWORKS", "127.0.0.1/32,::1/128")) ) web_search_engine = os.getenv("WEB_SEARCH_ENGINE", "exa").strip().lower() if web_search_engine not in {"exa", "parallel", "perplexity"}: raise ValueError("WEB_SEARCH_ENGINE must be exa, parallel, or perplexity.") settings = cls( openrouter_api_key=os.getenv("OPENROUTER_API_KEY", "").strip(), primary_model=os.getenv("OPENROUTER_MODEL", DEFAULT_MODEL).strip() or DEFAULT_MODEL, fallback_models=fallback_models, environment=environment, localhost_origins=_csv(os.getenv("CORS_LOCALHOST_ORIGINS", "")), rate_limit_requests=_integer("RATE_LIMIT_REQUESTS", 15, 1, 10_000), rate_limit_window_seconds=_integer("RATE_LIMIT_WINDOW_SECONDS", 60, 1, 86_400), max_body_bytes=_integer("MAX_BODY_BYTES", 24_576, 1_024, 1_048_576), max_message_characters=_integer("MAX_MESSAGE_CHARACTERS", 2_000, 1, 8_000), max_history_messages=_integer("MAX_HISTORY_MESSAGES", 12, 0, 50), max_history_message_characters=_integer( "MAX_HISTORY_MESSAGE_CHARACTERS", 1_200, 1, 8_000 ), max_history_characters=_integer("MAX_HISTORY_CHARACTERS", 6_000, 1, 50_000), upstream_timeout_seconds=_number("UPSTREAM_TIMEOUT_SECONDS", 25.0, 1.0, 120.0), max_output_tokens=_integer("MAX_OUTPUT_TOKENS", 700, 1, 4_096), max_output_characters=_integer("MAX_OUTPUT_CHARACTERS", 12_000, 100, 50_000), trust_proxy_headers=_boolean("TRUST_PROXY_HEADERS", False), trusted_proxy_networks=proxy_networks, openrouter_site_url=os.getenv( "OPENROUTER_SITE_URL", "https://2b-entertainment.com" ).strip(), web_search_enabled=_boolean("WEB_SEARCH_ENABLED", False), web_search_engine=web_search_engine, web_search_max_results=_integer("WEB_SEARCH_MAX_RESULTS", 4, 1, 10), web_search_max_uses=_integer("WEB_SEARCH_MAX_USES", 1, 1, 2), web_search_max_characters=_integer( "WEB_SEARCH_MAX_CHARACTERS", 4_000, 500, 8_000 ), market_research_enabled=_boolean("MARKET_RESEARCH_ENABLED", False), market_research_database_path=os.getenv( "MARKET_RESEARCH_DATABASE_PATH", "data/private/fuugi_research.sqlite3" ).strip(), market_research_retention_days=_integer( "MARKET_RESEARCH_RETENTION_DAYS", 90, 1, 365 ), memory_enabled=_boolean("MEMORY_ENABLED", False), memory_database_path=os.getenv( "MEMORY_DATABASE_PATH", "data/fuugi_memory.sqlite3" ).strip(), memory_session_pepper=os.getenv("MEMORY_SESSION_PEPPER", "").strip(), memory_retention_days=_integer("MEMORY_RETENTION_DAYS", 90, 1, 365), memory_max_items=_integer("MEMORY_MAX_ITEMS", 50, 1, 100), memory_max_item_characters=_integer( "MEMORY_MAX_ITEM_CHARACTERS", 500, 20, 1_000 ), memory_max_context_characters=_integer( "MEMORY_MAX_CONTEXT_CHARACTERS", 4_000, 100, 10_000 ), fuugi_worker_url=os.getenv("FUUGI_WORKER_URL", "").strip(), fuugi_worker_token=os.getenv("FUUGI_WORKER_TOKEN", "").strip(), fuugi_worker_timeout_seconds=_number( "FUUGI_WORKER_TIMEOUT_SECONDS", 45.0, 5.0, 90.0 ), ) if settings.memory_enabled: if len(settings.memory_session_pepper) < 32: raise ValueError( "MEMORY_SESSION_PEPPER must contain at least 32 characters " "when memory is enabled." ) if not settings.memory_database_path: raise ValueError("MEMORY_DATABASE_PATH is required when memory is enabled.") if settings.market_research_enabled and not settings.market_research_database_path: raise ValueError( "MARKET_RESEARCH_DATABASE_PATH is required when market research is enabled." ) return settings @property def models(self) -> tuple[str, ...]: return tuple(dict.fromkeys((self.primary_model, *self.fallback_models))) @property def allowed_origins(self) -> tuple[str, ...]: if self.environment != "development": return DEFAULT_ORIGINS invalid = [origin for origin in self.localhost_origins if not _development_origin(origin)] if invalid: raise ValueError( "CORS_LOCALHOST_ORIGINS may contain localhost or private LAN origins only." ) return tuple(dict.fromkeys((*DEFAULT_ORIGINS, *self.localhost_origins)))