Skip to content

Self-improving AI Employees for everyone

32.8 KB
Raw Blame
"""Environment-driven configuration with Pydantic v2."""

from typing import List, Literal, Optional
from pathlib import Path
from pydantic import Field, field_validator, model_validator
from pydantic_settings import BaseSettings

from core.approot import env_file_path, env_template_path


# The dev placeholder secrets shipped in ``.env.template``. SSOT for these
# literals — ``company build`` scaffolds fresh values over the ``dev-``
# placeholders and ``company deploy`` mints per-deploy keys. Drift-locked
# against the template by ``tests/core_config/test_dev_secret_guard.py``.
DEV_SECRET_LITERALS: frozenset = frozenset(
    {
        "dev-secret-key-12345678901234567890123456789012",
        "dev-jwt-secret-key-12345678901234567890",
        "dev-encryption-key-12345678901234567890123456",
    }
)


def dev_secret_offenders(settings) -> list[str]:
    """Env-var names still carrying dev placeholder secrets, non-dev posture only.

    Dev posture = auth disabled (``VITE_AUTH_ENABLED == "false"``, matching
    ``middleware/auth.py``) AND ``deployment_mode == "local"`` — returns []
    there. Duck-typed: accepts any object with the three secret attrs plus
    ``vite_auth_enabled`` and ``deployment_mode``.
    """
    auth_disabled = (settings.vite_auth_enabled or "").lower() == "false"
    if auth_disabled and settings.deployment_mode == "local":
        return []
    offenders: list[str] = []
    for attr, env_name in (
        ("secret_key", "SECRET_KEY"),
        ("jwt_secret_key", "JWT_SECRET_KEY"),
        ("api_key_encryption_key", "API_KEY_ENCRYPTION_KEY"),
    ):
        if getattr(settings, attr, None) in DEV_SECRET_LITERALS:
            offenders.append(env_name)
    return offenders


def cookie_posture_warnings(settings) -> list[str]:
    """Human-readable warnings about a risky session-cookie configuration.

    Warnings, not failures. The defaults are deliberately permissive because
    `company deploy` reaches the VM over plain HTTP on its IP and explicitly
    sets ``JWT_COOKIE_SECURE=false``; flipping the default would break every
    LAN/IP deployment with the worst possible symptom -- login appearing to
    succeed and then immediately logging out.

    Duck-typed like ``dev_secret_offenders`` so tests can pass a stub.
    """
    warnings: list[str] = []

    if not getattr(settings, "jwt_cookie_secure", False) and getattr(settings, "deployment_mode", "local") != "local":
        warnings.append(
            "JWT_COOKIE_SECURE=false outside local deployment: the session cookie "
            "will travel over plaintext HTTP."
        )

    origins = getattr(settings, "cors_origins", []) or []
    if "*" in origins:
        warnings.append(
            "CORS_ORIGINS contains '*' while credentialed CORS is enabled: any "
            "origin can make authenticated requests."
        )

    return warnings


class Settings(BaseSettings):
    """Application settings driven entirely by environment variables."""

    # Service Ports (used by start.js, vite, and docker-compose, not hardcoded here)
    vite_client_port: Optional[int] = Field(default=None, env="VITE_CLIENT_PORT")
    python_backend_port: Optional[int] = Field(default=None, env="PYTHON_BACKEND_PORT")
    redis_port: Optional[int] = Field(default=None, env="REDIS_PORT")

    # Server Configuration
    host: str = Field(env="HOST")
    port: int = Field(env="PORT", ge=1024, le=65535)
    debug: bool = Field(default=False, env="DEBUG")
    workers: int = Field(default=1, env="WORKERS", ge=1, le=8)

    # Authentication
    auth_mode: Literal["single", "multi"] = Field(default="single", env="AUTH_MODE")
    jwt_secret_key: str = Field(env="JWT_SECRET_KEY", min_length=32)
    jwt_expire_minutes: int = Field(default=10080, env="JWT_EXPIRE_MINUTES", ge=60)  # 7 days
    jwt_cookie_name: str = Field(default="opencompany_token", env="JWT_COOKIE_NAME")
    jwt_cookie_secure: bool = Field(default=False, env="JWT_COOKIE_SECURE")  # True in production
    jwt_cookie_samesite: Literal["lax", "strict", "none"] = Field(default="lax", env="JWT_COOKIE_SAMESITE")

    # Login/registration throttling. Defaults are deliberately tighter than
    # the generic `rate_limit_*` fields below (100/60s), which are far too
    # loose for a password endpoint.
    auth_rate_limit_enabled: bool = Field(default=True, env="AUTH_RATE_LIMIT_ENABLED")
    auth_rate_limit_attempts: int = Field(default=10, env="AUTH_RATE_LIMIT_ATTEMPTS", ge=1)
    auth_rate_limit_window: int = Field(default=300, env="AUTH_RATE_LIMIT_WINDOW", ge=1)

    # Security
    secret_key: str = Field(env="SECRET_KEY", min_length=32)
    cors_origins: List[str] = Field(env="CORS_ORIGINS")

    # Database Configuration. ``database_url`` is a computed property
    # (see below) — the SQLite file name lives in ``WORKFLOW_DB_FILENAME``
    # and resolves under ``DATA_DIR`` like every other state path,
    # rather than being hardcoded inside a SQLAlchemy URL string.
    workflow_db_filename: str = Field(env="WORKFLOW_DB_FILENAME")
    database_url_override: Optional[str] = Field(default=None, validation_alias="DATABASE_URL")
    distributed_mode: bool = Field(default=False, validation_alias="DISTRIBUTED_MODE")
    browser_replica_id: Optional[str] = Field(default=None, max_length=120, validation_alias="BROWSER_REPLICA_ID")
    browser_machine_id: Optional[str] = Field(default=None, max_length=255, validation_alias="BROWSER_MACHINE_ID")
    browser_replica_url: Optional[str] = Field(default=None, validation_alias="BROWSER_REPLICA_URL")
    browser_router_secret: Optional[str] = Field(default=None, validation_alias="BROWSER_ROUTER_SECRET")
    onepassword_cli_path: Optional[str] = Field(default=None, validation_alias="ONEPASSWORD_CLI_PATH")
    onepassword_cli_version: str = Field(default="2.40.0", validation_alias="ONEPASSWORD_CLI_VERSION")
    onepassword_auth_mode: Literal["desktop", "service_account"] = Field(default="desktop", validation_alias="ONEPASSWORD_AUTH_MODE")
    onepassword_account: Optional[str] = Field(default=None, validation_alias="ONEPASSWORD_ACCOUNT")
    onepassword_read_timeout_seconds: float = Field(default=30, ge=1, le=300, validation_alias="ONEPASSWORD_READ_TIMEOUT_SECONDS")
    database_echo: bool = Field(default=False, env="DATABASE_ECHO")
    database_pool_size: int = Field(default=20, env="DATABASE_POOL_SIZE", ge=5, le=100)
    database_max_overflow: int = Field(default=30, env="DATABASE_MAX_OVERFLOW", ge=10, le=100)

    # Cache Configuration
    redis_url: Optional[str] = Field(default=None, env="REDIS_URL")
    redis_enabled: bool = Field(default=False, env="REDIS_ENABLED")
    cache_ttl: int = Field(default=3600, env="CACHE_TTL", ge=60)

    # Execution Engine
    dlq_enabled: bool = Field(default=False, env="DLQ_ENABLED")
    employee_teams_enabled: bool = Field(default=True, env="EMPLOYEE_TEAMS_ENABLED")
    employee_team_conversion_enabled: bool = Field(default=False, env="EMPLOYEE_TEAM_CONVERSION_ENABLED")
    employee_capability_updates_enabled: bool = Field(default=True, env="EMPLOYEE_CAPABILITY_UPDATES_ENABLED")
    employee_safe_apply_enabled: bool = Field(default=True, env="EMPLOYEE_SAFE_APPLY_ENABLED")

    # Temporal Configuration. All sourced from ``.env.template``
    # (canonical defaults live there); no Python-side fallbacks.
    temporal_enabled: bool = Field(env="TEMPORAL_ENABLED")
    coding_pi_admissions_enabled: bool = Field(default=True, validation_alias="CODING_PI_ADMISSIONS_ENABLED")
    temporal_server_address: str = Field(env="TEMPORAL_SERVER_ADDRESS")
    temporal_namespace: str = Field(env="TEMPORAL_NAMESPACE")
    temporal_task_queue: str = Field(env="TEMPORAL_TASK_QUEUE")
    # F4.A: per-type activity dispatch. When True, MachinaWorkflow.run() schedules
    # `node.{type}.v{version}` per plugin (with task_queue=cls.task_queue) instead
    # of the single `execute_node_activity` legacy name. Workers register per-type
    # activities alongside the legacy one. Default on as shipped in
    # .env.template; TEMPORAL_PER_TYPE_DISPATCH=false is the rollback.
    temporal_per_type_dispatch: bool = Field(env="TEMPORAL_PER_TYPE_DISPATCH")
    # F4.B: agent-as-child-workflow. When True, MachinaWorkflow.run() schedules
    # AgentWorkflow (child workflow) for the 15 migrating agent types
    # (aiAgent / chatAgent / 11 specialized agents / 2 team leads) instead of
    # an activity. Tool calls inside the agent become per-type Temporal
    # activities. `rlm_agent`, `claude_code_agent` continue to run as F4.A
    # per-type activities (NOT migrated -- their external session state would
    # break across activity boundaries). Default on as shipped in
    # .env.template; TEMPORAL_AGENT_WORKFLOW_ENABLED=false is the rollback.
    # Implies temporal_per_type_dispatch=True.
    temporal_agent_workflow_enabled: bool = Field(
        env="TEMPORAL_AGENT_WORKFLOW_ENABLED",
    )
    # Wave 12 A3: SIGTERM grace window for Temporal workers. Activities
    # mid-flight finish (or hand back to the server for retry) instead of
    # being killed mid-call. Default 30s matches the polling-trigger
    # heartbeat interval — a worker drain completes within one polling
    # cycle. Tune via env when SIGTERM-to-restart latency matters.
    temporal_graceful_shutdown_seconds: int = Field(
        env="TEMPORAL_GRACEFUL_SHUTDOWN_SECONDS",
        ge=1,
    )
    # Wave 12 canary-flag default flipped to True (2026-05-15).
    # The Temporal-native event dispatch path
    # (services/events/dispatch.py:emit) is production-default;
    # consumer fan-out + WS broadcast both fire.
    #
    # Rollback procedure: set EVENT_FRAMEWORK_ENABLED=false in the
    # .env (or process env) and restart. dispatch.emit() reverts to a
    # pass-through no-op; legacy event_waiter.dispatch path keeps
    # working unchanged for non-canary triggers. See
    # docs-internal/event_framework.md § Rollback procedure.
    event_framework_enabled: bool = Field(
        default=True,
        env="EVENT_FRAMEWORK_ENABLED",
    )
    # Wave 16: per-queue activity routing. When True, main.py starts a
    # TemporalWorkerPool (one activity-only Worker per plugin-declared
    # task queue) alongside the TemporalWorkerManager, and
    # MachinaWorkflow._resolve_activity returns cls.task_queue so
    # per-type activities land on their specialised pool worker.
    #
    # Wave 16.4: default flipped to True — per-queue routing is the
    # production default (LLM / browser / code-exec / REST workloads
    # get isolated slot pools instead of sharing one 100-slot queue).
    # Rollback: TEMPORAL_WORKER_POOL_ENABLED=false + restart — the pool
    # stops and every activity routes back to the single manager worker
    # on "machina-tasks". Opt out via the env var, never by reverting
    # this default (locked by test_task_queue_coverage.py).
    temporal_worker_pool_enabled: bool = Field(
        default=True,
        env="TEMPORAL_WORKER_POOL_ENABLED",
    )
    # Wave 17.4: deployment topology hint. Drives worker identity
    # strings (visible in Temporal Web UI -> Workers) and per-mode
    # concurrency defaults (local laptops get half the per-queue slots
    # of an always-on cloud VM; explicit TEMPORAL_<QUEUE>_CONCURRENCY
    # env vars always win).
    #   local       — developer machine; sleeps/hibernates; 4-8 cores
    #   cloud       — always-on server (company deploy)
    #   self_hosted — user-managed always-on box
    deployment_mode: Literal["local", "cloud", "self_hosted"] = Field(
        default="local",
        env="DEPLOYMENT_MODE",
    )

    # gRPC frontend port — the port ``temporal server start-dev``
    # exposes for clients + supervisor readiness probe. Sourced from
    # ``.env.template`` (canonical default lives there). Reference:
    # https://docs.temporal.io/references/configuration
    temporal_frontend_grpc_port: int = Field(
        env="TEMPORAL_FRONTEND_GRPC_PORT",
        ge=1024,
        le=65535,
    )
    # Web UI port. ``temporal server start-dev`` defaults this to
    # ``--port + 1000``; declared explicitly via ``--ui-port`` (5680 in
    # the serial 5678-block) so the binding is intentional and surfaces
    # in status snapshots.
    temporal_ui_port: int = Field(
        env="TEMPORAL_UI_PORT",
        ge=1024,
        le=65535,
    )
    # SQLite db path passed to ``temporal server start-dev
    # --db-filename ...``. Resolved relative to ``DATA_DIR``
    # (``Settings._resolve_under_data``) unless absolute. Sourced
    # from ``.env.template`` (canonical default lives there).
    temporal_sqlite_path: str = Field(env="TEMPORAL_SQLITE_PATH")
    # Debug-only escape hatch: terminate every workflow in ``Running``
    # state on server boot. MUST stay false in normal operation — the
    # durability guarantee is that running and paused deployments
    # survive backend restarts and keep executing for months. The
    # durable workflow-control plane reconciles active generations on
    # boot; a live control row in any active state also skips the sweep
    # entirely (``has_active_workflow_controls``).
    temporal_terminate_running_on_startup: bool = Field(
        env="TEMPORAL_TERMINATE_RUNNING_ON_STARTUP",
    )

    # Startup resilience (server-ready-before-workers). Unlike the core
    # temporal fields above, these carry Python defaults (matching
    # ``.env.template``) so an existing ``.env`` predating them keeps
    # booting — same convention as ``dlq_enabled`` / ``event_framework_enabled``.
    # Readiness gate: poll the WorkflowService gRPC health check until
    # SERVING before the worker / visibility sweep act.
    temporal_health_check_attempts: int = Field(
        default=5,
        env="TEMPORAL_HEALTH_CHECK_ATTEMPTS",
        ge=1,
    )
    temporal_health_check_delay_seconds: float = Field(
        default=0.5,
        env="TEMPORAL_HEALTH_CHECK_DELAY_SECONDS",
        ge=0,
    )
    temporal_health_check_timeout_seconds: float = Field(
        default=2.0,
        env="TEMPORAL_HEALTH_CHECK_TIMEOUT_SECONDS",
        gt=0,
    )
    # Boot-time terminate-running sweep: retry the Visibility query that
    # races shard acquisition ("shard status unknown") before giving up.
    temporal_sweep_attempts: int = Field(
        default=4,
        env="TEMPORAL_SWEEP_ATTEMPTS",
        ge=1,
    )
    temporal_sweep_backoff_seconds: float = Field(
        default=0.5,
        env="TEMPORAL_SWEEP_BACKOFF_SECONDS",
        ge=0,
    )
    # Embedded worker self-restart backoff (doubles from base to max)
    # when the Temporal worker shuts down on a transient poll failure.
    temporal_worker_restart_backoff_seconds: float = Field(
        default=1.0,
        env="TEMPORAL_WORKER_RESTART_BACKOFF_SECONDS",
        gt=0,
    )
    temporal_worker_restart_backoff_max_seconds: float = Field(
        default=30.0,
        env="TEMPORAL_WORKER_RESTART_BACKOFF_MAX_SECONDS",
        gt=0,
    )
    # Backend-owned dev-server health monitor: after startup the lifespan
    # keeps probing the Temporal dev server at this interval and respawns
    # it if the child process dies while the backend stays up. Loopback
    # (backend-owned) servers only; remote clusters are never touched.
    temporal_health_monitor_interval_seconds: float = Field(
        default=15.0,
        env="TEMPORAL_HEALTH_MONITOR_INTERVAL_SECONDS",
        gt=0,
    )

    # Workflow-control recovery policies (canonical defaults + full
    # semantics in .env.template; Python defaults keep pre-feature .env
    # files booting). All three are consumed by
    # services/deployment/handlers.py — see the normalizers there.
    # "pause" | "resume": posture for generations still running after an
    # UNCLEAN shutdown (kill / crash). Clean restarts always restore as-is.
    workflow_control_crash_recovery: str = Field(
        default="pause",
        env="WORKFLOW_CONTROL_CRASH_RECOVERY",
    )
    # "pause" | "fail": convergence for a live generation whose controller
    # execution vanished (terminated in the Temporal UI, killed, deleted).
    # "pause" keeps it user-resumable — Resume rebuilds the controller from
    # the durable row; "fail" preserves the legacy Reset-only behaviour.
    workflow_control_missing_controller: str = Field(
        default="pause",
        env="WORKFLOW_CONTROL_MISSING_CONTROLLER",
    )
    # Circuit breaker: a controlled run failing with an error pauses the
    # deployment (user fixes + resumes) instead of the trigger firing into
    # the same error indefinitely.
    workflow_control_pause_on_failure: bool = Field(
        default=True,
        env="WORKFLOW_CONTROL_PAUSE_ON_FAILURE",
    )
    # The breaker trips only after this many failed runs inside the rolling
    # window below — one node hiccup on one firing (missing config,
    # transient API error) never pauses a deployment. 1 = pause on the
    # first failure.
    workflow_control_pause_on_failure_threshold: int = Field(
        default=3,
        env="WORKFLOW_CONTROL_PAUSE_ON_FAILURE_THRESHOLD",
        ge=1,
    )
    workflow_control_pause_on_failure_window_seconds: float = Field(
        default=600.0,
        env="WORKFLOW_CONTROL_PAUSE_ON_FAILURE_WINDOW_SECONDS",
        gt=0,
    )

    # API Keys (all optional, injected at runtime)
    google_maps_api_key: Optional[str] = Field(default=None, env="GOOGLE_MAPS_API_KEY")
    openai_api_key: Optional[str] = Field(default=None, env="OPENAI_API_KEY")
    anthropic_api_key: Optional[str] = Field(default=None, env="ANTHROPIC_API_KEY")
    google_ai_api_key: Optional[str] = Field(default=None, env="GOOGLE_AI_API_KEY")

    # JS executor sidecar settings live in the plugin: nodes/code/_runtime.py
    # and _nodejs.py read the NODEJS_EXECUTOR_* env vars directly
    # (plugin-owned config, same as the WhatsApp runtime).

    # AI Proxy Configuration (Ollama-style proxy)
    ai_proxy_default_port: int = Field(default=11434, env="AI_PROXY_DEFAULT_PORT")

    # OpenCompany Gateway (hosted LiteLLM, gateway/): with a gateway key in
    # Connectors, LLM calls for a provider this install has no key of its
    # own for go through the gateway on the person's allowance. On by
    # default; false hides the card and turns the routing off.
    gateway_enabled: bool = Field(default=True, validation_alias="OPENCOMPANY_GATEWAY_ENABLED")
    gateway_url: str = Field(default="https://api.gw.opencompany.sh", validation_alias="OPENCOMPANY_GATEWAY_URL")

    # Residential Proxy Configuration
    proxy_enabled: bool = Field(default=False, env="PROXY_ENABLED")
    proxy_budget_daily_usd: float = Field(default=50.0, env="PROXY_BUDGET_DAILY_USD")
    proxy_default_country: str = Field(default="", env="PROXY_DEFAULT_COUNTRY")

    # WebSocket Configuration
    websocket_url: str = Field(default="", env="WEBSOCKET_URL")
    websocket_api_key: Optional[str] = Field(default=None, env="WEBSOCKET_API_KEY")

    # Android Relay Configuration (passed to Vite frontend)
    vite_android_relay_url: Optional[str] = Field(default=None, env="VITE_ANDROID_RELAY_URL")

    # Frontend Auth Configuration (passed to Vite frontend)
    vite_auth_enabled: Optional[str] = Field(default=None, env="VITE_AUTH_ENABLED")

    # API Key Security
    api_key_encryption_key: str = Field(env="API_KEY_ENCRYPTION_KEY", min_length=32)
    api_key_cache_ttl: int = Field(default=2592000, env="API_KEY_CACHE_TTL", ge=3600)

    # Data directory (base for all persistent storage: DBs, workspaces,
    # workflows, claude state). Default is the user's home dir
    # (``~/.opencompany``) — same convention claude code itself uses
    # (``~/.claude/``), Stripe (``~/.config/stripe/``), ngrok
    # (``~/.ngrok2/``). Survives ``rm -rf`` of the repo. Resolution
    # rules (``~``, absolute, repo-relative) live in
    # :func:`core.paths.opencompany_root`. The path resolver falls back to
    # an existing sibling ``.machina`` root so upgrades retain state.
    # pre-cutover ``data/`` + ``workflows/`` layout — operators
    # either set ``DATA_DIR=data`` to keep the old layout or move
    # the contents manually (see ``paths.py`` docstring).
    data_dir: str = Field(default="~/.opencompany", env="DATA_DIR")

    # Credentials Database (separate encrypted database for API keys and OAuth tokens)
    # Resolved relative to data_dir unless absolute
    credentials_db_path: str = Field(default="credentials.db", env="CREDENTIALS_DB_PATH")

    # Credential Backend Selection
    # Options: fernet (default), keyring (OS-native), aws (AWS Secrets Manager)
    credential_backend: Literal["fernet", "keyring", "aws"] = Field(default="fernet", env="CREDENTIAL_BACKEND")
    aws_secret_arn: Optional[str] = Field(default=None, env="AWS_SECRET_ARN")
    aws_region: Optional[str] = Field(default=None, env="AWS_REGION")

    # Logging
    log_level: str = Field(default="INFO", env="LOG_LEVEL")
    log_format: str = Field(default="json", env="LOG_FORMAT")
    log_file: Optional[str] = Field(default=None, env="LOG_FILE")
    # File-rotation knobs — only consulted when LOG_FILE is set.
    # Default ceiling = 10 MiB × 5 backups = ~50 MiB on disk.
    log_file_max_bytes: int = Field(
        default=10 * 1024 * 1024,
        env="LOG_FILE_MAX_BYTES",
        ge=1024,
    )
    log_file_backup_count: int = Field(
        default=5,
        env="LOG_FILE_BACKUP_COUNT",
        ge=0,
    )
    # OpenTelemetry console span export. Off unless explicitly enabled or
    # LOG_LEVEL=DEBUG (see ``tracing_console_spans_enabled``): the Temporal
    # SDK TracingInterceptor emits a span per Signal / Query / Update /
    # Activity on both the caller and handler side, which floods the
    # operator log at INFO with per-RPC lines.
    tracing_console_spans: bool = Field(default=False, env="TRACING_CONSOLE_SPANS")

    @property
    def tracing_console_spans_enabled(self) -> bool:
        """Console spans are debug output; DEBUG turns them on implicitly."""
        return self.tracing_console_spans or self.log_level.upper() == "DEBUG"

    # Rate Limiting
    rate_limit_enabled: bool = Field(default=True, env="RATE_LIMIT_ENABLED")
    rate_limit_requests: int = Field(default=100, env="RATE_LIMIT_REQUESTS", ge=10)
    rate_limit_window: int = Field(default=60, env="RATE_LIMIT_WINDOW", ge=10)

    # Service Timeouts
    ai_timeout: int = Field(default=30, env="AI_TIMEOUT", ge=5, le=300)
    ai_max_retries: int = Field(default=3, env="AI_MAX_RETRIES", ge=0, le=5)
    ai_retry_delay: float = Field(default=1.0, env="AI_RETRY_DELAY", ge=0.1, le=10.0)

    maps_timeout: int = Field(default=10, env="MAPS_TIMEOUT", ge=5, le=60)
    maps_max_requests_per_second: int = Field(default=50, env="MAPS_MAX_RPS", ge=1, le=1000)

    # Health Check
    health_check_interval: int = Field(default=30, env="HEALTH_CHECK_INTERVAL", ge=10)

    # Cleanup Configuration (for long-running daemon)
    cleanup_enabled: bool = Field(default=True, env="CLEANUP_ENABLED")
    cleanup_interval: int = Field(default=3600, env="CLEANUP_INTERVAL", ge=60)
    cleanup_logs_max_count: int = Field(default=1000, env="CLEANUP_LOGS_MAX_COUNT", ge=100)
    cleanup_cache_max_age_hours: int = Field(default=24, env="CLEANUP_CACHE_MAX_AGE_HOURS", ge=1)

    # Feature Toggles
    ws_logging_enabled: bool = Field(default=True, env="WS_LOGGING_ENABLED")

    # Workspace Configuration (per-workflow file storage for nodes and agents)
    # Workspace base -- relative to data_dir unless absolute
    workspace_base_dir: str = Field(default="workspaces", env="WORKSPACE_BASE_DIR")

    # WhatsApp runtime settings live in the plugin: nodes/whatsapp/_runtime.py
    # reads the WHATSAPP_* env vars directly (plugin-owned config).

    # Browser node (nodes/browser): OpenCompany launches a pinned Chrome for
    # Testing, one process per browser profile. Canonical values live in
    # .env.template (same pattern as COMPACTION_RATIO — the code default
    # only mirrors the template for bare Settings() construction, e.g.
    # pytest/CI without the CLI env layering). The instance cap stops the
    # least recently used idle profile before another would exceed it; the
    # idle timeout (ms) stops a profile's Chrome after that long with no
    # agent step, viewer or login; 0 disables. The install timeout bounds
    # the browser-use CLI install (and Chrome only in explicit testing mode). Sandbox:
    # auto disables Chrome's sandbox only as root on Linux, where it cannot
    # start. system discovers installed Chrome/Edge/Chromium; testing opts into
    # the pinned download. browser_family selects the browser by name;
    # chrome_path is an optional explicit executable override.
    # Render inside the workspace by default; a separate window is opt-in.
    # Downloads a page starts are
    # capped at download_max_mb each.
    browser_max_instances: int = Field(default=3, env="BROWSER_MAX_INSTANCES", ge=1, le=50)
    browser_idle_timeout_ms: int = Field(default=600_000, env="BROWSER_IDLE_TIMEOUT_MS", ge=0)
    browser_install_timeout_seconds: int = Field(default=900, env="BROWSER_INSTALL_TIMEOUT_SECONDS", ge=60)
    browser_sandbox: str = Field(default="auto", env="BROWSER_SANDBOX", pattern="^(auto|on|off)$")
    browser_chrome_path: str = Field(default="", env="BROWSER_CHROME_PATH")
    browser_family: str = Field(default="chrome", env="BROWSER_FAMILY", pattern="^(chrome|edge|chromium|auto)$")
    browser_runtime: str = Field(default="system", env="BROWSER_RUNTIME", pattern="^(system|testing)$")
    browser_headless: bool = Field(default=True, env="BROWSER_HEADLESS")
    browser_download_max_mb: int = Field(default=200, env="BROWSER_DOWNLOAD_MAX_MB", ge=1)

    # Compaction Configuration. Threshold = model context_length ×
    # compaction_ratio. Per-user UserSettings row overrides at runtime.
    compaction_enabled: bool = Field(default=True, env="COMPACTION_ENABLED")
    compaction_ratio: float = Field(default=0.8, env="COMPACTION_RATIO", ge=0.05, le=0.99)

    # Largest result, in characters, one external tool call may add to an
    # agent's conversation; longer results are cut with a note. 0 disables
    # the cap. Per-user UserSettings row overrides at runtime.
    tool_result_max_chars: int = Field(default=100_000, env="TOOL_RESULT_MAX_CHARS", ge=0)

    # Agent loop hard step cap. Per-user UserSettings row overrides
    # at runtime; per-agent-node ``parameters.max_iterations`` is the
    # innermost override.
    agent_recursion_limit: int = Field(default=200, env="AGENT_RECURSION_LIMIT", ge=1)

    # Multi-agent delegation guardrails. The concurrency cap applies to all
    # active descendants of one root execution (the root itself is excluded).
    # Team leads may delegate one additional level, but deeper trees are
    # rejected before a child workflow is scheduled.
    max_concurrent_subagents: int = Field(default=3, env="MAX_CONCURRENT_SUBAGENTS", ge=1, le=50)
    max_delegation_depth: int = Field(default=2, env="MAX_DELEGATION_DEPTH", ge=1, le=2)

    # Gunicorn Configuration (for production deployment)
    gunicorn_timeout: int = Field(default=120, env="GUNICORN_TIMEOUT", ge=30)
    gunicorn_graceful_timeout: int = Field(default=30, env="GUNICORN_GRACEFUL_TIMEOUT", ge=10)
    gunicorn_keepalive: int = Field(default=5, env="GUNICORN_KEEPALIVE", ge=1)
    gunicorn_max_requests: int = Field(default=10000, env="GUNICORN_MAX_REQUESTS", ge=0)
    gunicorn_max_requests_jitter: int = Field(default=1000, env="GUNICORN_MAX_REQUESTS_JITTER", ge=0)

    # Filesystem-path fields that may use ``~`` in ``.env``. Expanded
    # once at load time so every downstream consumer
    # (``core.paths.opencompany_root``, ``Settings._resolve_under_data``,
    # the Temporal SQLite path, WhatsApp runtime dir, ...) sees
    # a real path. ``Path.expanduser()`` is a no-op when ``~`` isn't
    # present, so we can run it unconditionally.
    @field_validator("data_dir", "log_file", mode="after")
    @classmethod
    def _expanduser_path(cls, v: Optional[str]) -> Optional[str]:
        return str(Path(v).expanduser()) if v else v

    @model_validator(mode="after")
    def _reject_unusable_cookie_combination(self):
        """Fail fast on `SameSite=None` without `Secure`.

        Every current browser rejects that cookie outright, so the app would
        boot fine and then silently refuse to keep anyone logged in. This is
        the one cookie misconfiguration worth failing on rather than warning
        about -- see `cookie_posture_warnings` for the rest.
        """
        if self.jwt_cookie_samesite == "none" and not self.jwt_cookie_secure:
            raise ValueError(
                "JWT_COOKIE_SAMESITE=none requires JWT_COOKIE_SECURE=true; "
                "browsers reject a SameSite=None cookie that is not Secure, "
                "which silently breaks login."
            )
        return self

    @property
    def database_url(self) -> str:
        """Explicit shared PostgreSQL URL, or the existing local SQLite path."""
        if self.database_url_override:
            value = self.database_url_override
            if value.startswith("postgresql://"):
                value = "postgresql+asyncpg://" + value[len("postgresql://"):]
            if not value.startswith(("postgresql+asyncpg://", "sqlite+aiosqlite://")):
                raise ValueError("DATABASE_URL must use PostgreSQL asyncpg or SQLite aiosqlite")
            return value
        db_path = Path(self._resolve_under_data(self.workflow_db_filename))
        db_path.parent.mkdir(parents=True, exist_ok=True)
        return f"sqlite+aiosqlite:///{db_path}"

    @model_validator(mode="after")
    def _validate_distributed_browser(self):
        if not self.distributed_mode:
            return self
        from urllib.parse import urlsplit

        if not self.database_url.startswith("postgresql+asyncpg://"):
            raise ValueError("DISTRIBUTED_MODE requires a shared PostgreSQL DATABASE_URL")
        if not self.temporal_enabled or not self.temporal_agent_workflow_enabled or not self.temporal_per_type_dispatch:
            raise ValueError("Distributed Browser tasks require Temporal native agent and per-type dispatch")
        host = self.temporal_server_address.rsplit(":", 1)[0].strip("[]")
        if host in {"localhost", "127.0.0.1", "::1"}:
            raise ValueError("DISTRIBUTED_MODE requires an external shared TEMPORAL_SERVER_ADDRESS")
        if not self.browser_replica_id or not self.browser_replica_url:
            raise ValueError("DISTRIBUTED_MODE requires BROWSER_REPLICA_ID and BROWSER_REPLICA_URL")
        url = urlsplit(self.browser_replica_url)
        if url.scheme not in {"http", "https"} or not url.hostname or url.username or url.password or url.query or url.fragment or url.path not in {"", "/"}:
            raise ValueError("BROWSER_REPLICA_URL must be a trusted backend HTTP(S) origin")
        if self.workers != 1:
            raise ValueError("Each distributed backend replica must run one browser-owner process (WORKERS=1)")
        if self.onepassword_auth_mode != "service_account":
            raise ValueError("DISTRIBUTED_MODE requires ONEPASSWORD_AUTH_MODE=service_account")
        return self

    @property
    def is_development(self) -> bool:
        """Check if running in development mode."""
        return self.debug

    @property
    def is_production(self) -> bool:
        """Check if running in production mode."""
        return not self.debug

    def _resolve_under_data(self, path: str) -> str:
        """Resolve ``path`` under ``data_dir``, returning an absolute path.

        Thin delegate to :func:`core.paths._resolve_data_path` so the
        single resolution algorithm lives in one place. Used by the
        ``credentials_db_resolved`` / ``workspace_base_resolved``
        properties and any plugin that needs a DATA_DIR-relative path
        without importing ``core.paths`` directly.
        """
        from core.paths import _resolve_data_path

        return str(_resolve_data_path(self.data_dir, path))

    @property
    def credentials_db_resolved(self) -> str:
        """Full credentials DB path, rooted under data_dir."""
        return self._resolve_under_data(self.credentials_db_path)

    @property
    def workspace_base_resolved(self) -> str:
        """Full workspace base path, rooted under data_dir."""
        return self._resolve_under_data(self.workspace_base_dir)

    model_config = {
        # Layered like ``cli.config.load_config``: the canonical template
        # supplies every default, the operator's ``.env`` overrides it, the
        # process environment wins over both. Resolved through
        # ``core.approot`` (absolute paths), so ``Settings()`` no longer
        # depends on the process cwd being ``server/`` — the desktop shell
        # spawns uvicorn from a relocated bundle and points
        # ``OPENCOMPANY_ENV_FILE`` at its writable data dir.
        "env_file": (str(env_template_path()), str(env_file_path())),
        "env_file_encoding": "utf-8",
        "case_sensitive": False,
        # ``ignore`` lets stale ``.env`` files survive obsolete vars
        # (e.g. the postgres-backend Temporal knobs stripped from the
        # supervised cluster path). Without this, existing installs
        # carrying ``TEMPORAL_BACKEND`` / ``TEMPORAL_BIND_LOCAL_ONLY`` /
        # etc. would raise ValidationError on startup.
        "extra": "ignore",
        "populate_by_name": True,
        "env_parse_none_str": "none",
        "env_nested_delimiter": "__",
    }