"""Application settings, loaded from environment variables (prefix ``WP_``) or ``.env``.""" from __future__ import annotations from functools import lru_cache from pydantic import Field, SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="WP_", env_file=".env", extra="ignore") env: str = "dev" # Runtime connection: non-owner role without BYPASSRLS (see docs/adr/0003-tenancy-rls.md) database_url: str = "postgresql+psycopg://workpilot_app:workpilot_app@localhost:5432/workpilot" # Migration connection: owner of all tables. Never used by the running app. owner_database_url: str = ( "postgresql+psycopg://workpilot_owner:workpilot_owner@localhost:5432/workpilot" ) jwt_secret: SecretStr = SecretStr("dev-only-change-me-0123456789abcdef") jwt_algorithm: str = "HS256" access_token_minutes: int = 15 refresh_token_days: int = 14 # Gateway limits (OWASP AI Agent Security Cheat Sheet example thresholds) max_tool_calls_per_minute: int = 30 max_consecutive_failures: int = 5 max_run_cost_usd: float = 10.0 # Model calls per tenant per UTC day (0 = unlimited). For public demos (deploy/hf). max_llm_calls_per_tenant_per_day: int = 0 # Phase 15 (ADR-0009 G7): T0 reads have their own bucket; schedule-triggered runs get a # per-run batch allowance instead of the interactive tenant bucket. 0 disables either # (back to one shared bucket). max_read_calls_per_minute: int = 120 max_scheduled_run_calls_per_minute: int = 300 approval_ttl_minutes: int = 60 * 24 # Model tiers. Any LangChain ``init_chat_model`` string, e.g. "anthropic:claude-haiku-5-5". model_router: str = "anthropic:claude-haiku-5-5" model_worker: str = "anthropic:claude-sonnet-5-5" model_planner: str = "anthropic:claude-opus-5-5" model_fallbacks: list[str] = Field(default_factory=list) langfuse_host: str | None = None # Phase 15: observability. Traces go to OTLP/HTTP: ``otel_exporter_endpoint`` if set, # else Langfuse's OTLP endpoint (``/api/public/otel/v1/traces``, basic auth # with the key pair). Neither configured: tracing is a no-op. langfuse_public_key: str | None = None langfuse_secret_key: SecretStr | None = None otel_exporter_endpoint: str | None = None otel_exporter_headers: dict[str, str] = Field(default_factory=dict) otel_service_name: str = "workpilot" # USD per 1M tokens, [input, output], by model-name prefix; overrides/extends the built-in # table in core.observability.costs (whose values are unverified placeholders). model_prices: dict[str, list[float]] = Field(default_factory=dict) # Prompt management: "local" (prompt_versions table) or "langfuse" (needs the keys above). prompt_registry: str = "local" # Online LLM-judge evaluation: share of finished runs sampled (0 disables). judge_sample_rate: float = 0.0 # PII analyzer: "regex" (default) or "presidio" (optional; falls back to regex). pii_analyzer: str = "regex" # Alerts (core.observability.alerts): DBOS cron sweep; "" disables. alerts_cron: str = "0 */5 * * * *" alerts_webhook_url: str | None = None alerts_webhook_secret: SecretStr | None = None alerts_window_minutes: int = 60 alerts_circuit_breaker_threshold: int = 3 # trips per window per tenant alerts_quota_threshold: int = 20 alerts_injection_threshold: int = 5 # injection signals per window per tenant alerts_cost_anomaly_factor: float = 3.0 # last 24h vs daily mean of the 7 days before alerts_cost_min_usd: float = 1.0 # ignore anomalies below this daily spend # Browser origins allowed to call the API (the web dashboard). JSON list in the env var, # e.g. WP_CORS_ORIGINS='["https://app.example.com"]'. Empty list disables CORS. cors_origins: list[str] = Field( default_factory=lambda: ["http://localhost:3000", "http://127.0.0.1:3000"] ) # Phase 5: durable event dispatch (DBOS). The system database holds DBOS's own workflow # state, not tenant data; default: "_dbos_sys" with the owner credentials. dbos_system_database_url: str | None = None dbos_app_name: str = "workpilot" events_tenant_concurrency: int = 2 # max concurrent dispatches per tenant (all workers) events_worker_concurrency: int = 20 # max concurrent dispatches per worker process events_max_attempts: int = 4 # then the event is dead-lettered events_retry_interval_s: float = 2.0 # first retry delay; doubles each attempt events_queue_poll_s: float = 1.0 events_stale_after_s: int = 60 # re-enqueue persisted-but-undispatched events schedule_tick_cron: str = "*/10 * * * * *" # 6 fields: seconds first approval_sweep_cron: str = "0 * * * * *" # Chat runs left 'running' by a dead API process are continued from their checkpoint by # the approval sweep once this old (0 disables). Must exceed the longest legitimate run. stranded_run_after_s: int = 900 # Phase 7: channels (WhatsApp Cloud API, email via Nango). Secrets are NOT settings: # channel accounts name them (secret_ref) and they resolve from WP_SECRET_. channels_delivery_cron: str = "*/5 * * * * *" # outbox delivery sweep ("" disables) channels_inbox_poll_cron: str = "0 * * * * *" # email inbox poll ("" disables) channels_batch_size: int = 50 # messages claimed per tenant per outbox per sweep channels_max_attempts: int = 5 # transient failures before a message is failed channels_retry_base_s: float = 30.0 # first retry delay; doubles each attempt channels_sending_lease_s: int = 300 # 'sending' longer than this -> failed (unknown) channels_inbox_lookback_s: int = 3600 # first poll of a new mailbox looks back this far nango_base_url: str = "https://api.nango.dev" whatsapp_api_base_url: str = "https://graph.facebook.com" # Phase 16: runtime extensibility (tenant tools from OpenAPI / MCP / connectors, NL rules). # Tenant-supplied URLs are checked before every request (SSRF guard): https only and no # private/loopback hosts unless these are relaxed (local development only). ext_allow_http: bool = False ext_allow_private_hosts: bool = False ext_http_timeout_s: float = 15.0 ext_max_response_bytes: int = 256_000 # tool responses are truncated beyond this ext_max_spec_bytes: int = 2_000_000 # uploaded/fetched OpenAPI documents ext_max_tools_per_import: int = 100 ext_tool_cache_size: int = 512 # built tenant tools kept in memory per process # Phase 12: memory and knowledge (core/memory). OWASP-style limits on every memory write. memory_max_bytes: int = 4096 # serialized value size cap per memory item memory_default_ttl_days: int = 180 # every item expires; prefs/cases alike memory_max_ttl_days: int = 365 knowledge_max_upload_bytes: int = 10_000_000 knowledge_chunk_words: int = 180 knowledge_chunk_overlap: int = 40 knowledge_url_fetch_enabled: bool = True # URL ingestion (SSRF-guarded fetcher) # Phase 13: multilingual (core/i18n). Roman Urdu the system may have misunderstood goes # to a human instead of an automatic reply (tenants may override in settings["i18n"]). i18n_review_min_coverage: float = 0.6 # share of words the lexicon knows i18n_review_min_confidence: float = 0.35 # language-detection confidence i18n_review_min_transcript_confidence: float = 0.8 i18n_normalization_enabled: bool = True # off only for eval ablations # Voice notes: off by default; "pkg.module:factory" returning a core.i18n Transcriber. voice_transcription_enabled: bool = False voice_transcriber: str = "none" # Phase 18: deployment and production readiness (docs/deployment.md). # Worker identity for DBOS recovery when --executor-id is not passed: a STABLE id per # replica (Fly sets FLY_MACHINE_ID, Railway RAILWAY_REPLICA_ID; ECS uses one service per id). worker_executor_id: str | None = None # Seconds uvicorn waits for open requests after SIGTERM (in-flight runs are drained first). graceful_shutdown_s: int = 25 # Retention (python -m core.cli purge-retention). Tenants override with # settings["retention"] = {"audit_log_days": N, "messages_days": N}; 0 keeps forever. # Tenant values below the floor are raised to it (audit evidence cannot be shortened). retention_audit_log_days: int = 730 retention_audit_log_min_days: int = 90 retention_messages_days: int = 365 # Pack message tables whose old, finished rows are redacted (not deleted: other pack rows # reference them). Names only: core never imports packs. retention_message_tables: list[str] = Field( default_factory=lambda: ["ecom_messages", "appt_messages"] ) # Public demo tenant (python -m core.cli seed-demo). The password is public by design: # the demo user is a MANAGER (cannot configure channels), and channel accounts are off. demo_email: str = "demo@workpilot.dev" demo_password: SecretStr = SecretStr("try-workpilot-demo") demo_business_name: str = "WorkPilot Demo Store" demo_seeders: list[str] = Field( default_factory=lambda: ["demo", "ecommerce/ops-full", "appointments"] ) @lru_cache def get_settings() -> Settings: return Settings()