Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.0 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.browserbase._config import BrowserbaseSourceConfig
from products.warehouse_sources.sources.browserbase.browserbase import (
    browserbase_source,
    validate_credentials as validate_browserbase_credentials,
)
from products.warehouse_sources.sources.browserbase.settings import BROWSERBASE_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    SimpleSource,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class BrowserbaseSource(SimpleSource[BrowserbaseSourceConfig]):
    codebase_detection = detect(
        env=("^BROWSERBASE_",),
        npm=("@browserbasehq/sdk", "@browserbasehq/stagehand"),
        pypi=("browserbase", "stagehand"),
        go=("github.com/browserbase/stagehand-go",),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://docs.browserbase.com/reference/api/overview"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.BROWSERBASE

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.BROWSERBASE,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Browserbase",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Browserbase API key to sync your Browserbase sessions and projects into the PostHog Data warehouse.

You can find your project API key in your [Browserbase dashboard](https://www.browserbase.com/settings). API keys are scoped to a single project.""",
            iconPath="/static/services/browserbase.svg",
            docsUrl="https://posthog.com/docs/cdp/sources/browserbase",
            keywords=["browser", "automation", "agents", "sessions"],
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="bb_...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.browserbase.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # An invalid or revoked key surfaces as an HTTPError from `raise_for_status()`. Retrying
            # can never satisfy a credential problem, so stop the sync. Match the stable status text
            # and base host, not the per-request path.
            "401 Client Error: Unauthorized for url: https://api.browserbase.com": "Your Browserbase API key is invalid or has been revoked. Create a new key in your Browserbase project settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.browserbase.com": "Your Browserbase API key does not have access to this data. Check the key's project scope, then reconnect.",
        }

    def get_schemas(
        self,
        config: BrowserbaseSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Every Browserbase endpoint is full refresh: either no server-side timestamp filter exists,
        # or the only one on offer filters on creation time over rows that keep changing after they
        # are created (see settings.py).
        return build_endpoint_schemas(
            ENDPOINTS,
            INCREMENTAL_FIELDS,
            names,
            should_sync_default={name: config.should_sync_default for name, config in BROWSERBASE_ENDPOINTS.items()},
        )

    def validate_credentials(
        self,
        config: BrowserbaseSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_browserbase_credentials(config.api_key):
            return True, None

        return False, "Invalid Browserbase API key"

    def source_for_pipeline(self, config: BrowserbaseSourceConfig, inputs: SourceInputs) -> SourceResponse:
        return browserbase_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
        )