: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): expose content autopilot APIs (#91087)
Jordan Mryyan417091194c23
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 61044676e03c..ceb9adc8b0a4 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -607,6 +607,19 @@ class LlmsTxtFetchSustainedRateThrottle(_TeamBucketRateThrottle):rate = "200/hour"+# Site discovery can fetch several small public resources per request and holds the web worker for+# the complete chain. The project-wide API throttles do not cover session-authenticated requests,+# so this separate team bucket also limits browser callers.+class ContentAutopilotDiscoveryBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "content_autopilot_discovery_burst"+ rate = "10/minute"+++class ContentAutopilotDiscoverySustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "content_autopilot_discovery_sustained"+ rate = "100/hour"++# The batch session-context endpoint computes experiment context for up to 20 recordings per# call, in up to several per-day ClickHouse scan sets — heavier than most ClickHouse endpoints# — and its primary caller is the session-authenticated replay/experiment UI, which thediff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex c5350c53c883..181e1707800e 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -603,6 +603,7 @@ SPECTACULAR_SETTINGS = {"CITestRunnerEnum": "products.engineering_analytics.backend.facade.contracts.CITestRunner","UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES","DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",+ "LifecycleStatusEnum": "products.notebooks.backend.widget_models.WIDGET_LIFECYCLE_STATUS_CHOICES","SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES","SignalSourceType": "products.signals.backend.enums.SIGNAL_SOURCE_TYPE_VALUES","ErrorTrackingIssueSeverityRuleEnum": ["low", "medium", "high", "critical"],diff --git a/products/notebooks/backend/facade/widgets.py b/products/notebooks/backend/facade/widgets.pyindex 7b332e3b53df..7b76fa59d04a 100644--- a/products/notebooks/backend/facade/widgets.py+++ b/products/notebooks/backend/facade/widgets.py@@ -2,6 +2,7 @@ from products.notebooks.backend.widget_models import (DEFAULT_WIDGET_MODEL,MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,MAX_WIDGET_PROMPT_LENGTH,+ WIDGET_LIFECYCLE_STATUS_CHOICES,WIDGET_MODEL_CHOICES,)from products.notebooks.backend.widgets import (@@ -24,6 +25,7 @@ __all__ = ["DEFAULT_WIDGET_MODEL","MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH","MAX_WIDGET_PROMPT_LENGTH",+ "WIDGET_LIFECYCLE_STATUS_CHOICES","WIDGET_MODEL_CHOICES","WidgetConflictError","WidgetError",diff --git a/products/notebooks/backend/presentation/widget_serializers.py b/products/notebooks/backend/presentation/widget_serializers.pyindex 4ba210169881..07033a1eadb4 100644--- a/products/notebooks/backend/presentation/widget_serializers.py+++ b/products/notebooks/backend/presentation/widget_serializers.py@@ -6,6 +6,7 @@ from products.notebooks.backend.facade.widgets import (DEFAULT_WIDGET_MODEL,MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,MAX_WIDGET_PROMPT_LENGTH,+ WIDGET_LIFECYCLE_STATUS_CHOICES,WIDGET_MODEL_CHOICES,)@@ -89,7 +90,7 @@ class WidgetSecurityReviewSerializer(serializers.Serializer):class WidgetStatusSerializer(serializers.Serializer):lifecycle_status = serializers.ChoiceField(- choices=["awaiting_generation", "generating", "building", "ready", "failed", "incompatible"],+ choices=WIDGET_LIFECYCLE_STATUS_CHOICES,help_text="Current widget and preview state.",)error_detail = serializers.CharField(required=False, allow_null=True, help_text="Actionable failure detail.")diff --git a/products/notebooks/backend/widget_models.py b/products/notebooks/backend/widget_models.pyindex 33ca87cea97e..242bfe370648 100644--- a/products/notebooks/backend/widget_models.py+++ b/products/notebooks/backend/widget_models.py@@ -7,5 +7,14 @@ WIDGET_MODEL_CHOICES = (DEFAULT_WIDGET_MODEL = "claude-sonnet-4-6"+WIDGET_LIFECYCLE_STATUS_CHOICES = (+ "awaiting_generation",+ "generating",+ "building",+ "ready",+ "failed",+ "incompatible",+)+MAX_WIDGET_PROMPT_LENGTH = 20_000MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH = 50_000diff --git a/products/web_analytics/backend/content_autopilot/lifecycle.py b/products/web_analytics/backend/content_autopilot/lifecycle.pyindex 8f0ee25bcf2c..7997f0f4f5b5 100644--- a/products/web_analytics/backend/content_autopilot/lifecycle.py+++ b/products/web_analytics/backend/content_autopilot/lifecycle.py@@ -66,7 +66,7 @@ def start_run(*, team: Team, profile_id: str, triggered_by_id: int | None) -> Coraise ContentAutopilotLifecycleError("A content run is already in progress for this site.")return ContentAutopilotRun.objects.for_team(team_id, canonical=True).create(- team=team,+ team_id=team_id,profile=profile,run_status=ContentAutopilotRun.RunStatus.PENDING,input_snapshot={diff --git a/products/web_analytics/backend/content_autopilot/site_discovery.py b/products/web_analytics/backend/content_autopilot/site_discovery.pyindex 117f174966ce..168d139b10fb 100644--- a/products/web_analytics/backend/content_autopilot/site_discovery.py+++ b/products/web_analytics/backend/content_autopilot/site_discovery.py@@ -4,6 +4,7 @@ from html.parser import HTMLParserfrom typing import TypedDictfrom urllib.parse import urljoin, urlparse, urlunparse+import idnaimport defusedxml.ElementTree as ETfrom defusedxml.common import DefusedXmlExceptionfrom defusedxml.ElementTree import ParseError as DefusedParseError@@ -78,6 +79,22 @@ class _SiteNameParser(HTMLParser):self.title += data+def _canonical_host(hostname: str) -> str:+ """Return the host in the ASCII form the transport connects to.++ `requests` IDNA-encodes a non-ASCII host before it opens the connection, so the+ Unicode and the punycode spelling of one site must compare equal here too. An IP+ literal and every other ASCII host stay as they are.+ """+ host = hostname.lower().removesuffix(".")+ if host.isascii():+ return host+ try:+ return idna.encode(host, uts46=True).decode("ascii")+ except idna.IDNAError:+ return host++def normalize_site_origin(raw_url: str) -> str:invalid = ValueError("Enter a valid http or https site URL.")stripped = raw_url.strip()@@ -85,7 +102,7 @@ def normalize_site_origin(raw_url: str) -> str:raise invalidtry:parsed = urlparse(stripped)- hostname = (parsed.hostname or "").lower().removesuffix(".")+ hostname = _canonical_host(parsed.hostname or "")port = parsed.portexcept ValueError as error:raise invalid from error@@ -102,13 +119,13 @@ def _origin_key(url: str) -> str | None:try:parsed = urlparse(url)scheme = parsed.scheme.lower()- hostname = (parsed.hostname or "").lower()+ hostname = _canonical_host(parsed.hostname or "")port = parsed.portexcept ValueError:return Noneif scheme not in _DEFAULT_PORTS or not hostname or parsed.username or parsed.password:return None- return f"{scheme}://{hostname.removesuffix('.')}:{port if port is not None else _DEFAULT_PORTS[scheme]}"+ return f"{scheme}://{hostname}:{port if port is not None else _DEFAULT_PORTS[scheme]}"def has_same_public_origin(first_url: str, second_url: str) -> bool:@@ -120,7 +137,7 @@ def _public_host(url: str) -> str:try:parsed = urlparse(url)scheme = parsed.scheme.lower()- hostname = (parsed.hostname or "").lower().removesuffix(".")+ hostname = _canonical_host(parsed.hostname or "")except ValueError:return ""if scheme not in _DEFAULT_PORTS or not hostname or parsed.username or parsed.password:@@ -198,7 +215,9 @@ def _verified_sitemaps(candidates: list[str], *, deadline: float, budget: _Requeexcept PublicUrlFetchError:continueif _is_sitemap(fetched.text):- verified.append(fetched.url)+ # Record the candidate, not the redirect target: every candidate is already+ # same-origin with the profile domain, which is what profile creation accepts.+ verified.append(candidate)return list(dict.fromkeys(verified))diff --git a/products/web_analytics/backend/facade/__init__.py b/products/web_analytics/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/web_analytics/backend/facade/content_autopilot.py b/products/web_analytics/backend/facade/content_autopilot.pynew file mode 100644index 000000000000..6c570b33b6fd--- /dev/null+++ b/products/web_analytics/backend/facade/content_autopilot.py@@ -0,0 +1,32 @@+from products.web_analytics.backend.content_autopilot.export import ContentAutopilotExportError, export_proposal+from products.web_analytics.backend.content_autopilot.lifecycle import (+ MAX_PROPOSAL_MARKDOWN_CHARS,+ ContentAutopilotLifecycleError,+ cancel_run,+ edit_proposal,+ regenerate_proposal,+ reject_proposal,+ start_run,+)+from products.web_analytics.backend.content_autopilot.site_discovery import (+ discover_site,+ has_same_public_origin,+ normalize_site_origin,+)+from products.web_analytics.backend.public_url_fetch import PublicUrlFetchError++__all__ = [+ "MAX_PROPOSAL_MARKDOWN_CHARS",+ "ContentAutopilotExportError",+ "ContentAutopilotLifecycleError",+ "PublicUrlFetchError",+ "cancel_run",+ "discover_site",+ "edit_proposal",+ "export_proposal",+ "has_same_public_origin",+ "normalize_site_origin",+ "regenerate_proposal",+ "reject_proposal",+ "start_run",+]diff --git a/products/web_analytics/backend/facade/models.py b/products/web_analytics/backend/facade/models.pynew file mode 100644index 000000000000..c0a8ef576372--- /dev/null+++ b/products/web_analytics/backend/facade/models.py@@ -0,0 +1,11 @@+from products.web_analytics.backend.models import (+ ContentAutopilotProposal,+ ContentAutopilotRun,+ ContentAutopilotSiteProfile,+)++__all__ = [+ "ContentAutopilotProposal",+ "ContentAutopilotRun",+ "ContentAutopilotSiteProfile",+]diff --git a/products/web_analytics/backend/presentation/__init__.py b/products/web_analytics/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/web_analytics/backend/presentation/views/__init__.py b/products/web_analytics/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/web_analytics/backend/presentation/views/content_autopilot.py b/products/web_analytics/backend/presentation/views/content_autopilot.pynew file mode 100644index 000000000000..d8dda4726aa7--- /dev/null+++ b/products/web_analytics/backend/presentation/views/content_autopilot.py@@ -0,0 +1,553 @@+from collections.abc import Iterator+from contextlib import contextmanager+from typing import Any+from urllib.parse import urlparse++from django.db import IntegrityError, transaction+from django.db.models import QuerySet++from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_view+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import BaseThrottle++from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.permissions import posthog_feature_flag_enabled+from posthog.rate_limit import (+ ContentAutopilotDiscoveryBurstRateThrottle,+ ContentAutopilotDiscoverySustainedRateThrottle,+)+from posthog.security.url_validation import has_authority_bypass_chars++from products.web_analytics.backend.facade.content_autopilot import (+ MAX_PROPOSAL_MARKDOWN_CHARS,+ ContentAutopilotExportError,+ ContentAutopilotLifecycleError,+ PublicUrlFetchError,+ cancel_run,+ discover_site,+ edit_proposal,+ export_proposal,+ has_same_public_origin,+ normalize_site_origin,+ regenerate_proposal,+ reject_proposal,+ start_run,+)+from products.web_analytics.backend.facade.models import (+ ContentAutopilotProposal,+ ContentAutopilotRun,+ ContentAutopilotSiteProfile,+)++CONTENT_AUTOPILOT_FEATURE_FLAG = "web-analytics-content-autopilot"+DUPLICATE_DOMAIN_CONSTRAINT = "content_auto_profile_team_domain"+DUPLICATE_DOMAIN_MESSAGE = "This site is already configured for the project."+++@contextmanager+def duplicate_domain_as_validation_error() -> Iterator[None]:+ try:+ with transaction.atomic():+ yield+ except IntegrityError as error:+ if DUPLICATE_DOMAIN_CONSTRAINT in str(error):+ raise ValidationError({"domain": DUPLICATE_DOMAIN_MESSAGE}) from error+ raise+++class ContentAutopilotViewSetMixin(TeamAndOrgViewSetMixin):+ scope_object = "web_analytics"+ scope_object_read_actions = ["list", "retrieve"]++ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ distinct_id = getattr(request.user, "distinct_id", None)+ if not distinct_id or not posthog_feature_flag_enabled(+ CONTENT_AUTOPILOT_FEATURE_FLAG, distinct_id, organization_id=self.organization_id+ ):+ raise PermissionDenied("This feature is not available.")++ def _should_skip_parents_filter(self) -> bool:+ return True++ def handle_exception(self, exc: Exception) -> Response:+ if isinstance(exc, ContentAutopilotLifecycleError | ContentAutopilotExportError):+ exc = ValidationError(str(exc))+ return super().handle_exception(exc)++ def validated_query_params(self, serializer_class: type[serializers.Serializer]) -> dict[str, Any]:+ query = serializer_class(data=self.request.query_params)+ query.is_valid(raise_exception=True)+ return query.validated_data+++class ContentAutopilotEvidenceSerializer(serializers.Serializer):+ opportunity_kind = serializers.ChoiceField(+ choices=[+ ("poor_ctr", "Poor click-through rate"),+ ("content_gap", "Content gap"),+ ("organic_decline", "Organic decline"),+ ("ai_visibility_gap", "AI visibility gap"),+ ("site_hygiene", "Site hygiene"),+ ],+ help_text="Reason the opportunity was selected.",+ )+ explanation = serializers.CharField(help_text="Plain-language explanation of the supporting evidence.")+ page_url = serializers.URLField(required=False, allow_blank=True, help_text="Page supported by this evidence.")+ query = serializers.CharField(+ required=False, allow_blank=True, help_text="Search query supported by this evidence."+ )+++class ContentAutopilotSnapshotSerializer(serializers.Serializer):+ domain = serializers.URLField(required=False, help_text="Site domain used for the run.")+ confidence = serializers.ChoiceField(+ choices=[("standard", "Standard"), ("lower", "Lower")],+ required=False,+ help_text="Confidence level based on the available data sources.",+ )+ source_urls = serializers.ListField(+ child=serializers.URLField(), required=False, help_text="Public sources authorized for this run."+ )+ content_boundaries = serializers.ListField(+ child=serializers.CharField(), required=False, help_text="Site paths authorized for this run."+ )+ brand_rules = serializers.ListField(+ child=serializers.CharField(), required=False, help_text="Editorial rules captured for this run."+ )+++class ContentAutopilotErrorSerializer(serializers.Serializer):+ error_code = serializers.CharField(help_text="Stable machine-readable error code.")+ message = serializers.CharField(help_text="Error explanation suitable for the review workspace.")+++class ContentAutopilotValidationCheckSerializer(serializers.Serializer):+ check_key = serializers.CharField(help_text="Stable identifier for the validation gate.")+ label = serializers.CharField( # type: ignore[assignment] # API field intentionally shadows DRF Field.label.+ help_text="Human-readable validation name."+ )+ passed = serializers.BooleanField(help_text="Whether the proposal passed this validation.")+ message = serializers.CharField(help_text="Validation result and any action needed.")+ blocking = serializers.BooleanField(help_text="Whether failure prevents export.")+++class ContentAutopilotValidationReportSerializer(serializers.Serializer):+ passed = serializers.BooleanField(help_text="Whether every blocking validation passed.")+ checks = ContentAutopilotValidationCheckSerializer(+ many=True,+ help_text="Factual, brand, intent, originality, linking, crawlability, and schema checks.",+ )+++class ContentAutopilotFrontmatterEntrySerializer(serializers.Serializer):+ key = serializers.CharField(help_text="Frontmatter field name.")+ value = serializers.CharField(help_text="Serialized frontmatter value.")+++class ContentAutopilotPackageSerializer(serializers.Serializer):+ file_path = serializers.CharField(help_text="Repository-relative Markdown or MDX file path.")+ title = serializers.CharField(help_text="Content title.")+ description = serializers.CharField(help_text="Search description or summary.")+ slug = serializers.CharField(help_text="URL slug.")+ frontmatter = ContentAutopilotFrontmatterEntrySerializer(+ many=True,+ help_text="Ordered frontmatter entries.",+ )+ internal_links = serializers.ListField(+ child=serializers.URLField(),+ help_text="Validated same-origin internal links included in the content.",+ )+ source_notes = serializers.ListField(+ child=serializers.CharField(),+ help_text="Portable source notes included with the export.",+ )+++class ContentAutopilotSiteProfileSerializer(serializers.ModelSerializer):+ source_urls = serializers.ListField(+ child=serializers.URLField(),+ help_text="Public sitemap and factual source URLs used to build the site profile.",+ )+ content_boundaries = serializers.ListField(+ child=serializers.CharField(),+ help_text="Same-origin URL path prefixes allowed for research.",+ )+ brand_rules = serializers.ListField(+ child=serializers.CharField(),+ help_text="Brand, terminology, and editorial rules applied to every proposal.",+ )++ class Meta:+ model = ContentAutopilotSiteProfile+ fields = [+ "id",+ "name",+ "domain",+ "source_urls",+ "content_boundaries",+ "brand_rules",+ "search_console_enabled",+ "created_at",+ "updated_at",+ ]+ read_only_fields = ["id", "created_at", "updated_at"]+ extra_kwargs = {+ "name": {"help_text": "Name used to identify this site in the workspace."},+ "domain": {"help_text": "Authorized site origin for this profile."},+ "search_console_enabled": {"help_text": "Whether to use connected Google Search Console data."},+ }++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ def submitted(field: str, default: Any = "") -> Any:+ return attrs[field] if field in attrs else getattr(self.instance, field, default)++ try:+ domain = normalize_site_origin(submitted("domain"))+ except ValueError as error:+ raise ValidationError({"domain": str(error)}) from error++ attrs["domain"] = domain+ attrs["name"] = submitted("name").strip() or (urlparse(domain).hostname or domain).removeprefix("www.")++ for source_url in submitted("source_urls", []) or []:+ url = str(source_url)+ parsed_source = urlparse(url)+ if (+ parsed_source.fragment+ or parsed_source.path.startswith("//")+ or has_authority_bypass_chars(url)+ or not has_same_public_origin(url, domain)+ ):+ raise ValidationError(+ {"source_urls": "Use public same-origin source URLs without credentials or fragments."}+ )++ for boundary in submitted("content_boundaries", []) or []:+ path = str(boundary)+ if (+ not path.startswith("/")+ or path.startswith("//")+ or ".." in path.split("/")+ or any(character in path for character in "\\?#")+ ):+ raise ValidationError({"content_boundaries": "Use same-origin path prefixes beginning with '/'."})++ return attrs++ def create(self, validated_data: dict[str, Any]) -> ContentAutopilotSiteProfile:+ team = self.context["get_team"]()+ user_id = getattr(self.context["request"].user, "id", None)+ with duplicate_domain_as_validation_error():+ return ContentAutopilotSiteProfile.objects.for_team(team.id).create(+ team=team,+ created_by_id=user_id,+ updated_by_id=user_id,+ **validated_data,+ )++ def update(+ self, instance: ContentAutopilotSiteProfile, validated_data: dict[str, Any]+ ) -> ContentAutopilotSiteProfile:+ instance.updated_by_id = getattr(self.context["request"].user, "id", None)+ with duplicate_domain_as_validation_error():+ return super().update(instance, validated_data)+++class ContentAutopilotSiteDiscoveryRequestSerializer(serializers.Serializer):+ domain = serializers.URLField(help_text="Public site URL to inspect for onboarding defaults.")+++class ContentAutopilotSiteDiscoveryResponseSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Site name inferred from the homepage or hostname.")+ domain = serializers.URLField(help_text="Normalized site origin.")+ source_urls = serializers.ListField(+ child=serializers.URLField(), help_text="Detected sitemap URLs or an editable conventional suggestion."+ )+ content_boundaries = serializers.ListField(+ child=serializers.CharField(), help_text="Editable same-origin path boundaries."+ )+ sitemap_detected = serializers.BooleanField(help_text="Whether at least one sitemap was verified.")+ warnings = serializers.ListField(child=serializers.CharField(), help_text="Non-blocking discovery warnings.")+++class ContentAutopilotRunStartRequestSerializer(serializers.Serializer):+ profile_id = serializers.UUIDField(help_text="Site profile to research.")+++class ContentAutopilotRunListQuerySerializer(serializers.Serializer):+ profile_id = serializers.UUIDField(required=False, help_text="Only return runs for this site profile.")+++class ContentAutopilotRunSerializer(serializers.ModelSerializer):+ input_snapshot = ContentAutopilotSnapshotSerializer(help_text="Immutable inputs captured at run start.")+ errors = ContentAutopilotErrorSerializer( # type: ignore[assignment] # API field intentionally shadows Serializer.errors.+ many=True, help_text="Inspectable workflow errors from this run."+ )++ class Meta:+ model = ContentAutopilotRun+ fields = [+ "id",+ "profile_id",+ "run_status",+ "input_snapshot",+ "errors",+ "created_at",+ "updated_at",+ "completed_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "profile_id": {"help_text": "Site profile used by this run."},+ "run_status": {"help_text": "Current durable workflow status."},+ }+++class ContentAutopilotProposalBaseSerializer(serializers.ModelSerializer):+ evidence = ContentAutopilotEvidenceSerializer(many=True, help_text="Performance evidence for this proposal.")+ validation_report = ContentAutopilotValidationReportSerializer(+ help_text="Blocking and advisory validation results."+ )+++class ContentAutopilotProposalSerializer(ContentAutopilotProposalBaseSerializer):+ content_package = ContentAutopilotPackageSerializer(+ help_text="Structured package that accompanies the exported Markdown."+ )++ class Meta:+ model = ContentAutopilotProposal+ fields = [+ "id",+ "run_id",+ "proposal_type",+ "lifecycle_status",+ "title",+ "target_query",+ "target_url",+ "evidence",+ "validation_report",+ "content_package",+ "original_markdown",+ "proposed_markdown",+ "created_at",+ "updated_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "run_id": {"help_text": "Run that generated this proposal."},+ "proposal_type": {"help_text": "New article or bounded page improvement."},+ "lifecycle_status": {"help_text": "Review and export lifecycle status."},+ "title": {"help_text": "Review title for this proposal."},+ "target_query": {"help_text": "Primary query or topic targeted by this proposal."},+ "target_url": {"help_text": "Existing or intended public URL."},+ "original_markdown": {"help_text": "Existing content for page-improvement diffs."},+ "proposed_markdown": {"help_text": "Full proposed Markdown after edits."},+ }+++class ContentAutopilotProposalListSerializer(ContentAutopilotProposalBaseSerializer):+ file_path = serializers.SerializerMethodField(help_text="Repository-relative export path.")++ class Meta:+ model = ContentAutopilotProposal+ fields = [+ "id",+ "run_id",+ "proposal_type",+ "lifecycle_status",+ "title",+ "target_query",+ "evidence",+ "validation_report",+ "file_path",+ "created_at",+ "updated_at",+ ]+ read_only_fields = fields++ @extend_schema_field(serializers.CharField)+ def get_file_path(self, proposal: ContentAutopilotProposal) -> str:+ return proposal.content_package.get("file_path", "")+++class ContentAutopilotProposalListQuerySerializer(serializers.Serializer):+ run_id = serializers.UUIDField(required=False, help_text="Only return proposals from this content run.")+ profile_id = serializers.UUIDField(required=False, help_text="Only return proposals for this site profile.")+++class ContentAutopilotProposalEditRequestSerializer(serializers.Serializer):+ proposed_markdown = serializers.CharField(+ max_length=MAX_PROPOSAL_MARKDOWN_CHARS,+ trim_whitespace=False,+ help_text="Edited Markdown to save for review.",+ )+ content_package = ContentAutopilotPackageSerializer(+ help_text="Updated structured package to save with the proposal."+ )+++class ContentAutopilotExportResponseSerializer(serializers.Serializer):+ filename = serializers.CharField(help_text="Suggested export filename.")+ markdown = serializers.CharField(help_text="Validated Markdown content.")+ content_package = ContentAutopilotPackageSerializer(help_text="Structured JSON package for a CMS adapter.")+++class ContentAutopilotSiteProfileViewSet(ContentAutopilotViewSetMixin, viewsets.ModelViewSet):+ serializer_class = ContentAutopilotSiteProfileSerializer+ queryset = ContentAutopilotSiteProfile.objects.unscoped()+ http_method_names = ["get", "post", "patch", "head", "options"]++ def get_throttles(self) -> list[BaseThrottle]:+ if self.action == "discover":+ return [+ ContentAutopilotDiscoveryBurstRateThrottle(),+ ContentAutopilotDiscoverySustainedRateThrottle(),+ ]+ return super().get_throttles()++ def safely_get_queryset(+ self, queryset: QuerySet[ContentAutopilotSiteProfile]+ ) -> QuerySet[ContentAutopilotSiteProfile]:+ return ContentAutopilotSiteProfile.objects.for_team(self.team_id).order_by("created_at")++ @validated_request(+ request_serializer=ContentAutopilotSiteDiscoveryRequestSerializer,+ operation_id="web_analytics_content_autopilot_profiles_discover",+ summary="Discover content autopilot site settings",+ description="Inspects a public site for its canonical origin, name, and sitemap URLs.",+ responses={200: OpenApiResponse(response=ContentAutopilotSiteDiscoveryResponseSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=False, methods=["post"], required_scopes=["web_analytics:write"])+ def discover(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ try:+ result = discover_site(request.validated_data["domain"])+ except (ValueError, PublicUrlFetchError) as error:+ raise ValidationError({"domain": str(error)}) from error+ return Response(ContentAutopilotSiteDiscoveryResponseSerializer(instance=result).data)+++@extend_schema_view(list=extend_schema(parameters=[ContentAutopilotRunListQuerySerializer]))+class ContentAutopilotRunViewSet(ContentAutopilotViewSetMixin, viewsets.ReadOnlyModelViewSet):+ serializer_class = ContentAutopilotRunSerializer+ queryset = ContentAutopilotRun.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[ContentAutopilotRun]) -> QuerySet[ContentAutopilotRun]:+ queryset = ContentAutopilotRun.objects.for_team(self.team_id)+ if self.action == "list":+ filters = self.validated_query_params(ContentAutopilotRunListQuerySerializer)+ if profile_id := filters.get("profile_id"):+ queryset = queryset.filter(profile_id=profile_id)+ return queryset.order_by("-created_at")++ @validated_request(+ request_serializer=ContentAutopilotRunStartRequestSerializer,+ operation_id="web_analytics_content_autopilot_runs_start",+ summary="Start a content autopilot run",+ description="Captures the current profile and creates one pending on-demand content research run.",+ responses={202: OpenApiResponse(response=ContentAutopilotRunSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=False, methods=["post"], required_scopes=["web_analytics:write"])+ def start(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ run = start_run(+ team=self.team,+ profile_id=str(request.validated_data["profile_id"]),+ triggered_by_id=getattr(request.user, "id", None),+ )+ return Response(self.get_serializer(run).data, status=status.HTTP_202_ACCEPTED)++ @validated_request(+ operation_id="web_analytics_content_autopilot_runs_cancel",+ summary="Cancel a content autopilot run",+ description="Stops a pending or generating run without creating content writes.",+ responses={200: OpenApiResponse(response=ContentAutopilotRunSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def cancel(self, request: Request, **kwargs: Any) -> Response:+ run = cancel_run(team=self.team, run_id=str(self.get_object().id))+ return Response(self.get_serializer(run).data)+++@extend_schema_view(+ list=extend_schema(+ parameters=[ContentAutopilotProposalListQuerySerializer],+ responses=ContentAutopilotProposalListSerializer(many=True),+ )+)+class ContentAutopilotProposalViewSet(ContentAutopilotViewSetMixin, viewsets.ReadOnlyModelViewSet):+ serializer_class = ContentAutopilotProposalSerializer+ queryset = ContentAutopilotProposal.objects.unscoped()++ def get_serializer_class(self) -> type[serializers.BaseSerializer[Any]]:+ if self.action == "list":+ return ContentAutopilotProposalListSerializer+ return ContentAutopilotProposalSerializer++ def safely_get_queryset(self, queryset: QuerySet[ContentAutopilotProposal]) -> QuerySet[ContentAutopilotProposal]:+ queryset = ContentAutopilotProposal.objects.for_team(self.team_id)+ if self.action == "list":+ filters = self.validated_query_params(ContentAutopilotProposalListQuerySerializer)+ if run_id := filters.get("run_id"):+ queryset = queryset.filter(run_id=run_id)+ if profile_id := filters.get("profile_id"):+ queryset = queryset.filter(run__profile_id=profile_id)+ queryset = queryset.defer("original_markdown", "proposed_markdown")+ return queryset.order_by("-created_at")++ @validated_request(+ request_serializer=ContentAutopilotProposalEditRequestSerializer,+ operation_id="web_analytics_content_autopilot_proposals_edit",+ summary="Edit a content proposal",+ description="Saves reviewed Markdown and its structured package without publishing it.",+ responses={200: OpenApiResponse(response=ContentAutopilotProposalSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def edit(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ proposal = edit_proposal(team=self.team, proposal_id=str(self.get_object().id), **request.validated_data)+ return Response(self.get_serializer(proposal).data)++ @validated_request(+ operation_id="web_analytics_content_autopilot_proposals_reject",+ summary="Reject a content proposal",+ description="Rejects a proposal without changing the public site.",+ responses={200: OpenApiResponse(response=ContentAutopilotProposalSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def reject(self, request: Request, **kwargs: Any) -> Response:+ proposal = reject_proposal(team=self.team, proposal_id=str(self.get_object().id))+ return Response(self.get_serializer(proposal).data)++ @validated_request(+ operation_id="web_analytics_content_autopilot_proposals_regenerate",+ summary="Regenerate a content proposal",+ description="Returns a proposal to generation while keeping its previous result inspectable in history.",+ responses={202: OpenApiResponse(response=ContentAutopilotProposalSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def regenerate(self, request: Request, **kwargs: Any) -> Response:+ proposal = regenerate_proposal(team=self.team, proposal_id=str(self.get_object().id))+ return Response(self.get_serializer(proposal).data, status=status.HTTP_202_ACCEPTED)++ @validated_request(+ operation_id="web_analytics_content_autopilot_proposals_export",+ summary="Export a content proposal",+ description="Returns validated Markdown and structured JSON without publishing it.",+ responses={200: OpenApiResponse(response=ContentAutopilotExportResponseSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=True, methods=["post"], required_scopes=["web_analytics:write"])+ def export(self, request: Request, **kwargs: Any) -> Response:+ exported = export_proposal(team=self.team, proposal_id=str(self.get_object().id))+ return Response(ContentAutopilotExportResponseSerializer(instance=exported).data)diff --git a/products/web_analytics/backend/routes.py b/products/web_analytics/backend/routes.pyindex 8b933f6c0161..9e85afd7d269 100644--- a/products/web_analytics/backend/routes.py+++ b/products/web_analytics/backend/routes.py@@ -12,6 +12,11 @@ from products.web_analytics.backend.api.web_analytics_filter_preset import WebAnfrom products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions import (WebAnalyticsPathCleaningSuggestionViewSet,)+from products.web_analytics.backend.presentation.views.content_autopilot import (+ ContentAutopilotProposalViewSet,+ ContentAutopilotRunViewSet,+ ContentAutopilotSiteProfileViewSet,+)def register_routes(routers: RouterRegistry) -> None:@@ -28,6 +33,24 @@ def register_routes(routers: RouterRegistry) -> None:["team_id"],)routers.projects.register(r"web_analytics", WebAnalyticsViewSet, "project_web_analytics", ["team_id"])+ routers.projects.register(+ r"web_analytics_content_autopilot_profiles",+ ContentAutopilotSiteProfileViewSet,+ "project_web_analytics_content_autopilot_profiles",+ ["team_id"],+ )+ routers.projects.register(+ r"web_analytics_content_autopilot_runs",+ ContentAutopilotRunViewSet,+ "project_web_analytics_content_autopilot_runs",+ ["team_id"],+ )+ routers.projects.register(+ r"web_analytics_content_autopilot_proposals",+ ContentAutopilotProposalViewSet,+ "project_web_analytics_content_autopilot_proposals",+ ["team_id"],+ )routers.projects.register(r"web_analytics_achievements",WebAnalyticsAchievementsViewSet,diff --git a/products/web_analytics/backend/test/test_content_autopilot_api.py b/products/web_analytics/backend/test/test_content_autopilot_api.pynew file mode 100644index 000000000000..51ac54dff9a1--- /dev/null+++ b/products/web_analytics/backend/test/test_content_autopilot_api.py@@ -0,0 +1,334 @@+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.core.cache import cache++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team+from posthog.rate_limit import ContentAutopilotDiscoveryBurstRateThrottle++from products.web_analytics.backend.models import ContentAutopilotProposal, ContentAutopilotRun+from products.web_analytics.backend.presentation.views.content_autopilot import CONTENT_AUTOPILOT_FEATURE_FLAG+from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl, PublicUrlFetchError+from products.web_analytics.backend.test.content_autopilot_test_utils import (+ create_content_autopilot_profile,+ create_content_autopilot_proposal,+ create_content_autopilot_run,+)++DISCOVERED_SITE = {+ "name": "Example",+ "domain": "https://example.com",+ "source_urls": ["https://example.com/sitemap.xml"],+ "content_boundaries": ["/"],+ "sitemap_detected": True,+ "warnings": [],+}+++class TestContentAutopilotAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag_patcher = patch(+ "products.web_analytics.backend.presentation.views.content_autopilot.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.feature_enabled = flag_patcher.start()+ self.addCleanup(flag_patcher.stop)++ def _profiles_url(self, suffix: str = "") -> str:+ return f"/api/projects/{self.team.id}/web_analytics_content_autopilot_profiles/{suffix}"++ def _runs_url(self, suffix: str = "", *, team_id: int | None = None) -> str:+ return f"/api/projects/{team_id or self.team.id}/web_analytics_content_autopilot_runs/{suffix}"++ def _proposals_url(self, suffix: str = "") -> str:+ return f"/api/projects/{self.team.id}/web_analytics_content_autopilot_proposals/{suffix}"++ def _profile_payload(self, **overrides: object) -> dict[str, object]:+ payload: dict[str, object] = {+ "name": "Example",+ "domain": "https://example.com",+ "source_urls": ["https://example.com/sitemap.xml"],+ "content_boundaries": ["/blog"],+ "brand_rules": ["Use sentence case"],+ "search_console_enabled": False,+ }+ payload.update(overrides)+ return payload++ def test_requires_the_rollout_flag_with_user_and_organization_context(self) -> None:+ self.feature_enabled.return_value = False++ response = self.client.get(self._profiles_url())++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.feature_enabled.assert_called_once_with(+ CONTENT_AUTOPILOT_FEATURE_FLAG,+ self.user.distinct_id,+ organization_id=str(self.organization.id),+ )++ def test_requires_an_authenticated_project_member(self) -> None:+ self.client.logout()++ response = self.client.get(self._profiles_url())++ self.assertIn(response.status_code, {status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN})++ @parameterized.expand(+ [+ ("source_urls", {"source_urls": ["https://other.example/sitemap.xml"]}),+ ("content_boundaries", {"content_boundaries": ["/docs/../private"]}),+ ]+ )+ def test_profile_validates_site_boundaries(self, field: str, overrides: dict[str, object]) -> None:+ response = self.client.post(self._profiles_url(), self._profile_payload(**overrides), format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], field)++ def test_profile_accepts_same_origin_sources_with_queries_and_default_ports(self) -> None:+ response = self.client.post(+ self._profiles_url(),+ self._profile_payload(source_urls=["https://example.com:443/sitemap.xml?page=1"]),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(response.json()["source_urls"], ["https://example.com:443/sitemap.xml?page=1"])++ def test_project_can_configure_and_list_multiple_sites(self) -> None:+ first = self.client.post(self._profiles_url(), self._profile_payload(), format="json")+ second = self.client.post(+ self._profiles_url(),+ self._profile_payload(+ name="Docs",+ domain="https://docs.example.com/",+ source_urls=["https://docs.example.com/sitemap.xml"],+ ),+ format="json",+ )++ response = self.client.get(self._profiles_url())++ self.assertEqual(first.status_code, status.HTTP_201_CREATED, first.json())+ self.assertEqual(second.status_code, status.HTTP_201_CREATED, second.json())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ {profile["domain"] for profile in response.json()["results"]},+ {"https://example.com", "https://docs.example.com"},+ )++ def test_project_cannot_configure_the_same_domain_twice(self) -> None:+ create_content_autopilot_profile(self.team)++ response = self.client.post(self._profiles_url(), self._profile_payload(), format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "domain")++ @patch("products.web_analytics.backend.presentation.views.content_autopilot.discover_site")+ def test_discover_returns_editable_onboarding_defaults(self, discover_site: MagicMock) -> None:+ discover_site.return_value = DISCOVERED_SITE++ response = self.client.post(+ self._profiles_url("discover/"),+ {"domain": "https://example.com/blog"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["source_urls"], ["https://example.com/sitemap.xml"])++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_discovered_defaults_create_a_profile_when_the_sitemap_redirects(self, fetch_public_url: MagicMock) -> None:+ def response_for(url: str, **_kwargs: object) -> FetchedPublicUrl:+ if url == "https://example.com/sitemap.xml":+ return FetchedPublicUrl(+ status_code=301,+ headers={"location": "https://www.example.com/sitemap.xml"},+ body=b"",+ )+ if url == "https://www.example.com/sitemap.xml":+ return FetchedPublicUrl(status_code=200, headers={}, body=b"<urlset />")+ return FetchedPublicUrl(status_code=404, headers={}, body=b"")++ fetch_public_url.side_effect = response_for++ discovered = self.client.post(+ self._profiles_url("discover/"),+ {"domain": "https://example.com"},+ format="json",+ )+ created = self.client.post(+ self._profiles_url(),+ {**discovered.json(), "brand_rules": ["Use sentence case"]},+ format="json",+ )++ self.assertEqual(discovered.status_code, status.HTTP_200_OK, discovered.json())+ self.assertTrue(discovered.json()["sitemap_detected"])+ self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.json())+ self.assertEqual(created.json()["source_urls"], ["https://example.com/sitemap.xml"])++ @patch("products.web_analytics.backend.presentation.views.content_autopilot.discover_site")+ def test_discover_returns_a_validation_error_for_a_typed_fetch_failure(self, discover_site: MagicMock) -> None:+ discover_site.side_effect = PublicUrlFetchError("transport", "The site could not be inspected safely.")++ response = self.client.post(+ self._profiles_url("discover/"),+ {"domain": "https://example.com"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "domain")++ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ @patch("products.web_analytics.backend.presentation.views.content_autopilot.discover_site")+ def test_discover_is_throttled_for_the_session_authenticated_ui(+ self, discover_site: MagicMock, _rate_limit_enabled: MagicMock+ ) -> None:+ discover_site.return_value = DISCOVERED_SITE+ cache.clear()+ self.addCleanup(cache.clear)++ with patch.object(ContentAutopilotDiscoveryBurstRateThrottle, "rate", "2/minute"):+ statuses = [+ self.client.post(self._profiles_url("discover/"), {"domain": "https://example.com"}).status_code+ for _ in range(3)+ ]++ self.assertEqual(statuses, [status.HTTP_200_OK, status.HTTP_200_OK, status.HTTP_429_TOO_MANY_REQUESTS])++ def _child_environment(self) -> Team:+ return Team.objects.create(+ organization=self.organization,+ project=self.team.project,+ parent_team=self.team,+ name="Child environment",+ )++ @parameterized.expand([("root_project", False), ("child_environment", True)])+ def test_start_and_cancel_expose_durable_run_transitions(self, _name: str, through_child: bool) -> None:+ profile = create_content_autopilot_profile(self.team)+ team_id = self._child_environment().id if through_child else self.team.id++ started = self.client.post(+ self._runs_url("start/", team_id=team_id), {"profile_id": str(profile.id)}, format="json"+ )+ canceled = self.client.post(self._runs_url(f"{started.json()['id']}/cancel/", team_id=team_id), format="json")++ self.assertEqual(started.status_code, status.HTTP_202_ACCEPTED, started.json())+ self.assertEqual(started.json()["input_snapshot"]["confidence"], "lower")+ self.assertEqual(canceled.status_code, status.HTTP_200_OK, canceled.json())+ self.assertEqual(canceled.json()["run_status"], ContentAutopilotRun.RunStatus.CANCELED)++ def test_run_and_proposal_filters_are_validated_and_tenant_scoped(self) -> None:+ first_profile = create_content_autopilot_profile(self.team)+ second_profile = create_content_autopilot_profile(self.team, domain="https://docs.example.com")+ first_run = create_content_autopilot_run(self.team, first_profile)+ second_run = create_content_autopilot_run(self.team, second_profile)+ first_proposal = create_content_autopilot_proposal(self.team, first_run)+ create_content_autopilot_proposal(self.team, second_run)++ runs = self.client.get(self._runs_url(), {"profile_id": str(first_profile.id)})+ proposals = self.client.get(self._proposals_url(), {"run_id": str(first_run.id)})+ invalid_runs = self.client.get(self._runs_url(), {"profile_id": "not-a-uuid"})+ invalid_proposals = self.client.get(self._proposals_url(), {"run_id": "not-a-uuid"})++ self.assertEqual([run["id"] for run in runs.json()["results"]], [str(first_run.id)])+ self.assertEqual([proposal["id"] for proposal in proposals.json()["results"]], [str(first_proposal.id)])+ self.assertEqual(proposals.json()["results"][0]["file_path"], "content/guides/example.md")+ self.assertEqual(proposals.json()["results"][0]["evidence"][0]["opportunity_kind"], "poor_ctr")+ self.assertNotIn("proposed_markdown", proposals.json()["results"][0])+ self.assertNotIn("content_package", proposals.json()["results"][0])+ proposal_detail = self.client.get(self._proposals_url(f"{first_proposal.id}/"))+ self.assertIn("proposed_markdown", proposal_detail.json())+ self.assertIn("content_package", proposal_detail.json())+ self.assertEqual(invalid_runs.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(invalid_proposals.status_code, status.HTTP_400_BAD_REQUEST)++ def test_edit_reject_and_regenerate_expose_review_transitions(self) -> None:+ profile = create_content_autopilot_profile(self.team)+ run = create_content_autopilot_run(self.team, profile)+ edited_proposal = create_content_autopilot_proposal(self.team, run)+ rejected_proposal = create_content_autopilot_proposal(self.team, run)+ regenerated_proposal = create_content_autopilot_proposal(self.team, run)+ edited_package = {**edited_proposal.content_package, "title": "Reviewed guide", "markdown": "# Stale draft"}++ edited = self.client.post(+ self._proposals_url(f"{edited_proposal.id}/edit/"),+ {"proposed_markdown": "# Reviewed draft", "content_package": edited_package},+ format="json",+ )+ rejected = self.client.post(self._proposals_url(f"{rejected_proposal.id}/reject/"), format="json")+ regenerated = self.client.post(+ self._proposals_url(f"{regenerated_proposal.id}/regenerate/"),+ format="json",+ )++ self.assertEqual(edited.status_code, status.HTTP_200_OK, edited.json())+ self.assertFalse(edited.json()["validation_report"]["passed"])+ self.assertEqual(edited.json()["proposed_markdown"], "# Reviewed draft")+ self.assertEqual(edited.json()["content_package"]["title"], "Reviewed guide")+ self.assertNotIn("markdown", edited.json()["content_package"])+ self.assertEqual(rejected.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.REJECTED)+ self.assertEqual(regenerated.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.GENERATING)++ def test_edit_stores_markdown_whitespace_exactly(self) -> None:+ proposal = self._reviewable_proposal()+ markdown = " indented code block\n\n# Reviewed draft\n\nUseful content.\n"++ edited = self.client.post(+ self._proposals_url(f"{proposal.id}/edit/"),+ {"proposed_markdown": markdown, "content_package": proposal.content_package},+ format="json",+ )++ self.assertEqual(edited.status_code, status.HTTP_200_OK, edited.json())+ self.assertEqual(edited.json()["proposed_markdown"], markdown)+ proposal.refresh_from_db()+ self.assertEqual(proposal.proposed_markdown, markdown)++ def _reviewable_proposal(self, *, validation_passed: bool = True) -> ContentAutopilotProposal:+ run = create_content_autopilot_run(self.team, create_content_autopilot_profile(self.team))+ return create_content_autopilot_proposal(self.team, run, validation_passed=validation_passed)++ def test_export_returns_markdown_and_marks_the_proposal_exported(self) -> None:+ proposal = self._reviewable_proposal()++ response = self.client.post(self._proposals_url(f"{proposal.id}/export/"), format="json")+ body = response.json()++ self.assertEqual(response.status_code, status.HTTP_200_OK, body)+ self.assertEqual(body["filename"], "example.md")+ self.assertEqual(body["markdown"], proposal.proposed_markdown)+ self.assertNotIn("markdown", body["content_package"])+ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.EXPORTED)++ def test_export_refuses_a_proposal_that_failed_validation(self) -> None:+ proposal = self._reviewable_proposal(validation_passed=False)++ response = self.client.post(self._proposals_url(f"{proposal.id}/export/"), format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ proposal.refresh_from_db()+ self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)++ def test_other_team_records_are_not_exposed(self) -> None:+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other"))+ other_profile = create_content_autopilot_profile(other_team, domain="https://other.example")+ other_run = create_content_autopilot_run(other_team, other_profile)+ other_proposal = create_content_autopilot_proposal(other_team, other_run)++ proposal_response = self.client.get(self._proposals_url(f"{other_proposal.id}/"))+ runs_response = self.client.get(self._runs_url())++ self.assertEqual(proposal_response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(runs_response.status_code, status.HTTP_200_OK)+ self.assertEqual(runs_response.json()["results"], [])diff --git a/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.pyindex 17ab5e9dc0e9..c41c8912ec79 100644--- a/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py+++ b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py@@ -7,6 +7,8 @@ from parameterized import parameterizedfrom products.web_analytics.backend.content_autopilot.site_discovery import (_MAX_DISCOVERY_REQUESTS,discover_site,+ has_same_public_origin,+ has_same_public_site,normalize_site_origin,)from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl, PublicUrlFetchError@@ -23,11 +25,20 @@ class TestContentAutopilotSiteDiscovery(SimpleTestCase):("default_port", "https://example.com:443/path", "https://example.com"),("custom_port", "http://example.com:8080/path", "http://example.com:8080"),("fully_qualified_dot", "https://example.com./path", "https://example.com"),+ ("unicode_host", "https://ПРИМЕР.РФ/guides?q=1", "https://xn--e1afmkfd.xn--p1ai"),+ ("punycode_host", "https://xn--e1afmkfd.xn--p1ai", "https://xn--e1afmkfd.xn--p1ai"),+ ("ipv6_host", "https://[::1]:8443/path", "https://[::1]:8443"),])def test_normalizes_site_origin(self, _name: str, raw_url: str, expected: str) -> None:self.assertEqual(normalize_site_origin(raw_url), expected)+ def test_matches_one_site_across_unicode_and_punycode_spellings(self) -> None:+ punycode_sitemap = "https://xn--e1afmkfd.xn--p1ai/sitemap.xml"++ self.assertTrue(has_same_public_origin(punycode_sitemap, normalize_site_origin("https://пример.рф")))+ self.assertTrue(has_same_public_site(punycode_sitemap, "https://пример.рф"))+@parameterized.expand([("unsupported_scheme", "ftp://example.com"),@@ -101,7 +112,7 @@ class TestContentAutopilotSiteDiscovery(SimpleTestCase):])@patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")- def test_records_a_sitemap_redirect_only_when_it_stays_on_the_site(+ def test_keeps_a_redirected_sitemap_url_on_the_profile_origin(self, _name: str, redirect_target: str, stays_on_site: bool, fetch_public_url: MagicMock) -> None:def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:@@ -116,9 +127,8 @@ class TestContentAutopilotSiteDiscovery(SimpleTestCase):result = discover_site("https://example.com")self.assertEqual(result["sitemap_detected"], stays_on_site)- self.assertEqual(- result["source_urls"], [redirect_target] if stays_on_site else ["https://example.com/sitemap.xml"]- )+ self.assertEqual(result["source_urls"], ["https://example.com/sitemap.xml"])+ self.assertEqual(result["domain"], "https://example.com")@patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")def test_caps_the_requests_one_discovery_sends(self, fetch_public_url: MagicMock) -> None:diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 7dfdcaec7b76..4659a40190f8 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -691,6 +691,365 @@ export interface RecordVisitResponseApi {recorded: boolean}+export interface ContentAutopilotSiteProfileApi {+ readonly id: string+ /**+ * Name used to identify this site in the workspace.+ * @maxLength 255+ */+ name?: string+ /**+ * Authorized site origin for this profile.+ * @maxLength 2048+ */+ domain: string+ /** Public sitemap and factual source URLs used to build the site profile. */+ source_urls: string[]+ /** Same-origin URL path prefixes allowed for research. */+ content_boundaries: string[]+ /** Brand, terminology, and editorial rules applied to every proposal. */+ brand_rules: string[]+ /** Whether to use connected Google Search Console data. */+ search_console_enabled?: boolean+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedContentAutopilotSiteProfileListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ContentAutopilotSiteProfileApi[]+}++export interface PatchedContentAutopilotSiteProfileApi {+ readonly id?: string+ /**+ * Name used to identify this site in the workspace.+ * @maxLength 255+ */+ name?: string+ /**+ * Authorized site origin for this profile.+ * @maxLength 2048+ */+ domain?: string+ /** Public sitemap and factual source URLs used to build the site profile. */+ source_urls?: string[]+ /** Same-origin URL path prefixes allowed for research. */+ content_boundaries?: string[]+ /** Brand, terminology, and editorial rules applied to every proposal. */+ brand_rules?: string[]+ /** Whether to use connected Google Search Console data. */+ search_console_enabled?: boolean+ readonly created_at?: string+ readonly updated_at?: string+}++export interface ContentAutopilotSiteDiscoveryRequestApi {+ /** Public site URL to inspect for onboarding defaults. */+ domain: string+}++export interface ContentAutopilotSiteDiscoveryResponseApi {+ /** Site name inferred from the homepage or hostname. */+ name: string+ /** Normalized site origin. */+ domain: string+ /** Detected sitemap URLs or an editable conventional suggestion. */+ source_urls: string[]+ /** Editable same-origin path boundaries. */+ content_boundaries: string[]+ /** Whether at least one sitemap was verified. */+ sitemap_detected: boolean+ /** Non-blocking discovery warnings. */+ warnings: string[]+}++/**+ * * `new_content` - New content+ * * `page_improvement` - Page improvement+ */+export type ContentAutopilotProposalProposalTypeEnumApi =+ (typeof ContentAutopilotProposalProposalTypeEnumApi)[keyof typeof ContentAutopilotProposalProposalTypeEnumApi]++export const ContentAutopilotProposalProposalTypeEnumApi = {+ NewContent: 'new_content',+ PageImprovement: 'page_improvement',+} as const++/**+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `rejected` - Rejected+ * * `exported` - Exported+ * * `failed` - Failed+ */+export type ContentAutopilotProposalLifecycleStatusEnumApi =+ (typeof ContentAutopilotProposalLifecycleStatusEnumApi)[keyof typeof ContentAutopilotProposalLifecycleStatusEnumApi]++export const ContentAutopilotProposalLifecycleStatusEnumApi = {+ Generating: 'generating',+ ReadyForReview: 'ready_for_review',+ Rejected: 'rejected',+ Exported: 'exported',+ Failed: 'failed',+} as const++/**+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene+ */+export type OpportunityKindEnumApi = (typeof OpportunityKindEnumApi)[keyof typeof OpportunityKindEnumApi]++export const OpportunityKindEnumApi = {+ PoorCtr: 'poor_ctr',+ ContentGap: 'content_gap',+ OrganicDecline: 'organic_decline',+ AiVisibilityGap: 'ai_visibility_gap',+ SiteHygiene: 'site_hygiene',+} as const++export interface ContentAutopilotEvidenceApi {+ /** Reason the opportunity was selected.+ *+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene */+ opportunity_kind: OpportunityKindEnumApi+ /** Plain-language explanation of the supporting evidence. */+ explanation: string+ /** Page supported by this evidence. */+ page_url?: string+ /** Search query supported by this evidence. */+ query?: string+}++export interface ContentAutopilotValidationCheckApi {+ /** Stable identifier for the validation gate. */+ check_key: string+ /** Human-readable validation name. */+ label: string+ /** Whether the proposal passed this validation. */+ passed: boolean+ /** Validation result and any action needed. */+ message: string+ /** Whether failure prevents export. */+ blocking: boolean+}++export interface ContentAutopilotValidationReportApi {+ /** Whether every blocking validation passed. */+ passed: boolean+ /** Factual, brand, intent, originality, linking, crawlability, and schema checks. */+ checks: ContentAutopilotValidationCheckApi[]+}++export interface ContentAutopilotProposalListApi {+ readonly id: string+ readonly run_id: string+ readonly proposal_type: ContentAutopilotProposalProposalTypeEnumApi+ readonly lifecycle_status: ContentAutopilotProposalLifecycleStatusEnumApi+ readonly title: string+ readonly target_query: string+ /** Performance evidence for this proposal. */+ evidence: ContentAutopilotEvidenceApi[]+ /** Blocking and advisory validation results. */+ validation_report: ContentAutopilotValidationReportApi+ /** Repository-relative export path. */+ readonly file_path: string+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedContentAutopilotProposalListListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ContentAutopilotProposalListApi[]+}++export interface ContentAutopilotFrontmatterEntryApi {+ /** Frontmatter field name. */+ key: string+ /** Serialized frontmatter value. */+ value: string+}++export interface ContentAutopilotPackageApi {+ /** Repository-relative Markdown or MDX file path. */+ file_path: string+ /** Content title. */+ title: string+ /** Search description or summary. */+ description: string+ /** URL slug. */+ slug: string+ /** Ordered frontmatter entries. */+ frontmatter: ContentAutopilotFrontmatterEntryApi[]+ /** Validated same-origin internal links included in the content. */+ internal_links: string[]+ /** Portable source notes included with the export. */+ source_notes: string[]+}++export interface ContentAutopilotProposalApi {+ readonly id: string+ /** Run that generated this proposal. */+ readonly run_id: string+ /** New article or bounded page improvement.+ *+ * * `new_content` - New content+ * * `page_improvement` - Page improvement */+ readonly proposal_type: ContentAutopilotProposalProposalTypeEnumApi+ /** Review and export lifecycle status.+ *+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `rejected` - Rejected+ * * `exported` - Exported+ * * `failed` - Failed */+ readonly lifecycle_status: ContentAutopilotProposalLifecycleStatusEnumApi+ /** Review title for this proposal. */+ readonly title: string+ /** Primary query or topic targeted by this proposal. */+ readonly target_query: string+ /** Existing or intended public URL. */+ readonly target_url: string+ /** Performance evidence for this proposal. */+ evidence: ContentAutopilotEvidenceApi[]+ /** Blocking and advisory validation results. */+ validation_report: ContentAutopilotValidationReportApi+ /** Structured package that accompanies the exported Markdown. */+ content_package: ContentAutopilotPackageApi+ /** Existing content for page-improvement diffs. */+ readonly original_markdown: string+ /** Full proposed Markdown after edits. */+ readonly proposed_markdown: string+ readonly created_at: string+ readonly updated_at: string+}++export interface ContentAutopilotProposalEditRequestApi {+ /**+ * Edited Markdown to save for review.+ * @maxLength 500000+ */+ proposed_markdown: string+ /** Updated structured package to save with the proposal. */+ content_package: ContentAutopilotPackageApi+}++export interface ContentAutopilotExportResponseApi {+ /** Suggested export filename. */+ filename: string+ /** Validated Markdown content. */+ markdown: string+ /** Structured JSON package for a CMS adapter. */+ content_package: ContentAutopilotPackageApi+}++/**+ * * `pending` - Pending+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `completed` - Completed+ * * `canceled` - Canceled+ * * `failed` - Failed+ */+export type ContentAutopilotRunRunStatusEnumApi =+ (typeof ContentAutopilotRunRunStatusEnumApi)[keyof typeof ContentAutopilotRunRunStatusEnumApi]++export const ContentAutopilotRunRunStatusEnumApi = {+ Pending: 'pending',+ Generating: 'generating',+ ReadyForReview: 'ready_for_review',+ Completed: 'completed',+ Canceled: 'canceled',+ Failed: 'failed',+} as const++/**+ * * `standard` - Standard+ * * `lower` - Lower+ */+export type ContentAutopilotSnapshotConfidenceEnumApi =+ (typeof ContentAutopilotSnapshotConfidenceEnumApi)[keyof typeof ContentAutopilotSnapshotConfidenceEnumApi]++export const ContentAutopilotSnapshotConfidenceEnumApi = {+ Standard: 'standard',+ Lower: 'lower',+} as const++export interface ContentAutopilotSnapshotApi {+ /** Site domain used for the run. */+ domain?: string+ /** Confidence level based on the available data sources.+ *+ * * `standard` - Standard+ * * `lower` - Lower */+ confidence?: ContentAutopilotSnapshotConfidenceEnumApi+ /** Public sources authorized for this run. */+ source_urls?: string[]+ /** Site paths authorized for this run. */+ content_boundaries?: string[]+ /** Editorial rules captured for this run. */+ brand_rules?: string[]+}++export interface ContentAutopilotErrorApi {+ /** Stable machine-readable error code. */+ error_code: string+ /** Error explanation suitable for the review workspace. */+ message: string+}++export interface ContentAutopilotRunApi {+ readonly id: string+ /** Site profile used by this run. */+ readonly profile_id: string+ /** Current durable workflow status.+ *+ * * `pending` - Pending+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `completed` - Completed+ * * `canceled` - Canceled+ * * `failed` - Failed */+ readonly run_status: ContentAutopilotRunRunStatusEnumApi+ /** Immutable inputs captured at run start. */+ input_snapshot: ContentAutopilotSnapshotApi+ /** Inspectable workflow errors from this run. */+ errors: ContentAutopilotErrorApi[]+ readonly created_at: string+ readonly updated_at: string+ /** @nullable */+ readonly completed_at: string | null+}++export interface PaginatedContentAutopilotRunListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ContentAutopilotRunApi[]+}++export interface ContentAutopilotRunStartRequestApi {+ /** Site profile to research. */+ profile_id: string+}+export interface WebAnalyticsFilterPresetApi {readonly id: stringreadonly short_id: string@@ -1022,6 +1381,51 @@ export type WebAnalyticsWeeklyDigestParams = {days?: number}+export type WebAnalyticsContentAutopilotProfilesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type WebAnalyticsContentAutopilotProposalsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Only return proposals for this site profile.+ */+ profile_id?: string+ /**+ * Only return proposals from this content run.+ */+ run_id?: string+}++export type WebAnalyticsContentAutopilotRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Only return runs for this site profile.+ */+ profile_id?: string+}+export type WebAnalyticsFilterPresetsListParams = {created_by?: number/**diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 02856b7e66b8..d85864cc7ea0 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -13,6 +13,14 @@ import type {AcknowledgeCelebrationRequestApi,AcknowledgeCelebrationResponseApi,ApplyPathCleaningSuggestionResponseApi,+ ContentAutopilotExportResponseApi,+ ContentAutopilotProposalApi,+ ContentAutopilotProposalEditRequestApi,+ ContentAutopilotRunApi,+ ContentAutopilotRunStartRequestApi,+ ContentAutopilotSiteDiscoveryRequestApi,+ ContentAutopilotSiteDiscoveryResponseApi,+ ContentAutopilotSiteProfileApi,GeneratePathCleaningSuggestionResponseApi,HeatmapEventsResponseApi,HeatmapPreflightRequestApi,@@ -25,7 +33,11 @@ import type {HeatmapsResponseApi,LlmsTxtFetchRequestApi,LlmsTxtFetchResponseApi,+ PaginatedContentAutopilotProposalListListApi,+ PaginatedContentAutopilotRunListApi,+ PaginatedContentAutopilotSiteProfileListApi,PaginatedWebAnalyticsFilterPresetListApi,+ PatchedContentAutopilotSiteProfileApi,PatchedSavedHeatmapRequestApi,PatchedWebAnalyticsFilterPresetApi,PreviewPathCleaningSuggestionResponseApi,@@ -36,6 +48,9 @@ import type {SavedHeatmapListResponseApi,SavedHeatmapRequestApi,SavedListParams,+ WebAnalyticsContentAutopilotProfilesListParams,+ WebAnalyticsContentAutopilotProposalsListParams,+ WebAnalyticsContentAutopilotRunsListParams,WebAnalyticsFilterPresetApi,WebAnalyticsFilterPresetsListParams,WebAnalyticsRecapParams,@@ -562,6 +577,340 @@ export const webAnalyticsAchievementsRecordVisit = async (})}+export const getWebAnalyticsContentAutopilotProfilesListUrl = (+ projectId: string,+ params?: WebAnalyticsContentAutopilotProfilesListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/?${stringifiedParams}`+ : `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/`+}++export const webAnalyticsContentAutopilotProfilesList = async (+ projectId: string,+ params?: WebAnalyticsContentAutopilotProfilesListParams,+ options?: RequestInit+): Promise<PaginatedContentAutopilotSiteProfileListApi> => {+ return apiMutator<PaginatedContentAutopilotSiteProfileListApi>(+ getWebAnalyticsContentAutopilotProfilesListUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotProfilesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/`+}++export const webAnalyticsContentAutopilotProfilesCreate = async (+ projectId: string,+ contentAutopilotSiteProfileApi: NonReadonly<ContentAutopilotSiteProfileApi>,+ options?: RequestInit+): Promise<ContentAutopilotSiteProfileApi> => {+ return apiMutator<ContentAutopilotSiteProfileApi>(getWebAnalyticsContentAutopilotProfilesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(contentAutopilotSiteProfileApi),+ })+}++export const getWebAnalyticsContentAutopilotProfilesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/${id}/`+}++export const webAnalyticsContentAutopilotProfilesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotSiteProfileApi> => {+ return apiMutator<ContentAutopilotSiteProfileApi>(+ getWebAnalyticsContentAutopilotProfilesRetrieveUrl(projectId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotProfilesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/${id}/`+}++export const webAnalyticsContentAutopilotProfilesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedContentAutopilotSiteProfileApi?: NonReadonly<PatchedContentAutopilotSiteProfileApi>,+ options?: RequestInit+): Promise<ContentAutopilotSiteProfileApi> => {+ return apiMutator<ContentAutopilotSiteProfileApi>(+ getWebAnalyticsContentAutopilotProfilesPartialUpdateUrl(projectId, id),+ {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedContentAutopilotSiteProfileApi),+ }+ )+}++export const getWebAnalyticsContentAutopilotProfilesDiscoverUrl = (projectId: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/discover/`+}++/**+ * Inspects a public site for its canonical origin, name, and sitemap URLs.+ * @summary Discover content autopilot site settings+ */+export const webAnalyticsContentAutopilotProfilesDiscover = async (+ projectId: string,+ contentAutopilotSiteDiscoveryRequestApi: ContentAutopilotSiteDiscoveryRequestApi,+ options?: RequestInit+): Promise<ContentAutopilotSiteDiscoveryResponseApi> => {+ return apiMutator<ContentAutopilotSiteDiscoveryResponseApi>(+ getWebAnalyticsContentAutopilotProfilesDiscoverUrl(projectId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(contentAutopilotSiteDiscoveryRequestApi),+ }+ )+}++export const getWebAnalyticsContentAutopilotProposalsListUrl = (+ projectId: string,+ params?: WebAnalyticsContentAutopilotProposalsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/?${stringifiedParams}`+ : `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/`+}++export const webAnalyticsContentAutopilotProposalsList = async (+ projectId: string,+ params?: WebAnalyticsContentAutopilotProposalsListParams,+ options?: RequestInit+): Promise<PaginatedContentAutopilotProposalListListApi> => {+ return apiMutator<PaginatedContentAutopilotProposalListListApi>(+ getWebAnalyticsContentAutopilotProposalsListUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotProposalsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/${id}/`+}++export const webAnalyticsContentAutopilotProposalsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotProposalApi> => {+ return apiMutator<ContentAutopilotProposalApi>(getWebAnalyticsContentAutopilotProposalsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWebAnalyticsContentAutopilotProposalsEditUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/${id}/edit/`+}++/**+ * Saves reviewed Markdown and its structured package without publishing it.+ * @summary Edit a content proposal+ */+export const webAnalyticsContentAutopilotProposalsEdit = async (+ projectId: string,+ id: string,+ contentAutopilotProposalEditRequestApi: ContentAutopilotProposalEditRequestApi,+ options?: RequestInit+): Promise<ContentAutopilotProposalApi> => {+ return apiMutator<ContentAutopilotProposalApi>(getWebAnalyticsContentAutopilotProposalsEditUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(contentAutopilotProposalEditRequestApi),+ })+}++export const getWebAnalyticsContentAutopilotProposalsExportUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/${id}/export/`+}++/**+ * Returns validated Markdown and structured JSON without publishing it.+ * @summary Export a content proposal+ */+export const webAnalyticsContentAutopilotProposalsExport = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotExportResponseApi> => {+ return apiMutator<ContentAutopilotExportResponseApi>(+ getWebAnalyticsContentAutopilotProposalsExportUrl(projectId, id),+ {+ ...options,+ method: 'POST',+ }+ )+}++export const getWebAnalyticsContentAutopilotProposalsRegenerateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/${id}/regenerate/`+}++/**+ * Returns a proposal to generation while keeping its previous result inspectable in history.+ * @summary Regenerate a content proposal+ */+export const webAnalyticsContentAutopilotProposalsRegenerate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotProposalApi> => {+ return apiMutator<ContentAutopilotProposalApi>(+ getWebAnalyticsContentAutopilotProposalsRegenerateUrl(projectId, id),+ {+ ...options,+ method: 'POST',+ }+ )+}++export const getWebAnalyticsContentAutopilotProposalsRejectUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_proposals/${id}/reject/`+}++/**+ * Rejects a proposal without changing the public site.+ * @summary Reject a content proposal+ */+export const webAnalyticsContentAutopilotProposalsReject = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotProposalApi> => {+ return apiMutator<ContentAutopilotProposalApi>(getWebAnalyticsContentAutopilotProposalsRejectUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getWebAnalyticsContentAutopilotRunsListUrl = (+ projectId: string,+ params?: WebAnalyticsContentAutopilotRunsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/web_analytics_content_autopilot_runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/web_analytics_content_autopilot_runs/`+}++export const webAnalyticsContentAutopilotRunsList = async (+ projectId: string,+ params?: WebAnalyticsContentAutopilotRunsListParams,+ options?: RequestInit+): Promise<PaginatedContentAutopilotRunListApi> => {+ return apiMutator<PaginatedContentAutopilotRunListApi>(+ getWebAnalyticsContentAutopilotRunsListUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWebAnalyticsContentAutopilotRunsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_runs/${id}/`+}++export const webAnalyticsContentAutopilotRunsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotRunApi> => {+ return apiMutator<ContentAutopilotRunApi>(getWebAnalyticsContentAutopilotRunsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWebAnalyticsContentAutopilotRunsCancelUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_runs/${id}/cancel/`+}++/**+ * Stops a pending or generating run without creating content writes.+ * @summary Cancel a content autopilot run+ */+export const webAnalyticsContentAutopilotRunsCancel = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ContentAutopilotRunApi> => {+ return apiMutator<ContentAutopilotRunApi>(getWebAnalyticsContentAutopilotRunsCancelUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getWebAnalyticsContentAutopilotRunsStartUrl = (projectId: string) => {+ return `/api/projects/${projectId}/web_analytics_content_autopilot_runs/start/`+}++/**+ * Captures the current profile and creates one pending on-demand content research run.+ * @summary Start a content autopilot run+ */+export const webAnalyticsContentAutopilotRunsStart = async (+ projectId: string,+ contentAutopilotRunStartRequestApi: ContentAutopilotRunStartRequestApi,+ options?: RequestInit+): Promise<ContentAutopilotRunApi> => {+ return apiMutator<ContentAutopilotRunApi>(getWebAnalyticsContentAutopilotRunsStartUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(contentAutopilotRunStartRequestApi),+ })+}+export const getWebAnalyticsFilterPresetsListUrl = (projectId: string,params?: WebAnalyticsFilterPresetsListParamsdiff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex 9afa969ec87f..320f051e2f87 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -256,6 +256,107 @@ export const WebAnalyticsAchievementsRecordInteractionBody = /* @__PURE__ */ zod),})+export const webAnalyticsContentAutopilotProfilesCreateBodyNameMax = 255++export const webAnalyticsContentAutopilotProfilesCreateBodyDomainMax = 2048++export const WebAnalyticsContentAutopilotProfilesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(webAnalyticsContentAutopilotProfilesCreateBodyNameMax)+ .optional()+ .describe('Name used to identify this site in the workspace.'),+ domain: zod+ .url()+ .max(webAnalyticsContentAutopilotProfilesCreateBodyDomainMax)+ .describe('Authorized site origin for this profile.'),+ source_urls: zod+ .array(zod.url())+ .describe('Public sitemap and factual source URLs used to build the site profile.'),+ content_boundaries: zod.array(zod.string()).describe('Same-origin URL path prefixes allowed for research.'),+ brand_rules: zod.array(zod.string()).describe('Brand, terminology, and editorial rules applied to every proposal.'),+ search_console_enabled: zod.boolean().optional().describe('Whether to use connected Google Search Console data.'),+})++export const webAnalyticsContentAutopilotProfilesPartialUpdateBodyNameMax = 255++export const webAnalyticsContentAutopilotProfilesPartialUpdateBodyDomainMax = 2048++export const WebAnalyticsContentAutopilotProfilesPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(webAnalyticsContentAutopilotProfilesPartialUpdateBodyNameMax)+ .optional()+ .describe('Name used to identify this site in the workspace.'),+ domain: zod+ .url()+ .max(webAnalyticsContentAutopilotProfilesPartialUpdateBodyDomainMax)+ .optional()+ .describe('Authorized site origin for this profile.'),+ source_urls: zod+ .array(zod.url())+ .optional()+ .describe('Public sitemap and factual source URLs used to build the site profile.'),+ content_boundaries: zod+ .array(zod.string())+ .optional()+ .describe('Same-origin URL path prefixes allowed for research.'),+ brand_rules: zod+ .array(zod.string())+ .optional()+ .describe('Brand, terminology, and editorial rules applied to every proposal.'),+ search_console_enabled: zod.boolean().optional().describe('Whether to use connected Google Search Console data.'),+})++/**+ * Inspects a public site for its canonical origin, name, and sitemap URLs.+ * @summary Discover content autopilot site settings+ */+export const WebAnalyticsContentAutopilotProfilesDiscoverBody = /* @__PURE__ */ zod.object({+ domain: zod.url().describe('Public site URL to inspect for onboarding defaults.'),+})++/**+ * Saves reviewed Markdown and its structured package without publishing it.+ * @summary Edit a content proposal+ */+export const webAnalyticsContentAutopilotProposalsEditBodyProposedMarkdownMax = 500000++export const WebAnalyticsContentAutopilotProposalsEditBody = /* @__PURE__ */ zod.object({+ proposed_markdown: zod+ .string()+ .max(webAnalyticsContentAutopilotProposalsEditBodyProposedMarkdownMax)+ .describe('Edited Markdown to save for review.'),+ content_package: zod+ .object({+ file_path: zod.string().describe('Repository-relative Markdown or MDX file path.'),+ title: zod.string().describe('Content title.'),+ description: zod.string().describe('Search description or summary.'),+ slug: zod.string().describe('URL slug.'),+ frontmatter: zod+ .array(+ zod.object({+ key: zod.string().describe('Frontmatter field name.'),+ value: zod.string().describe('Serialized frontmatter value.'),+ })+ )+ .describe('Ordered frontmatter entries.'),+ internal_links: zod+ .array(zod.url())+ .describe('Validated same-origin internal links included in the content.'),+ source_notes: zod.array(zod.string()).describe('Portable source notes included with the export.'),+ })+ .describe('Updated structured package to save with the proposal.'),+})++/**+ * Captures the current profile and creates one pending on-demand content research run.+ * @summary Start a content autopilot run+ */+export const WebAnalyticsContentAutopilotRunsStartBody = /* @__PURE__ */ zod.object({+ profile_id: zod.uuid().describe('Site profile to research.'),+})+export const webAnalyticsFilterPresetsCreateBodyNameMax = 400export const WebAnalyticsFilterPresetsCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex f6d6599960e6..cb0a9dd5e0cc 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -168,6 +168,51 @@ tools:web-analytics-achievements-update-preferences:operation: web_analytics_achievements_update_preferencesenabled: false+ web-analytics-content-autopilot-profiles-create:+ operation: web_analytics_content_autopilot_profiles_create+ enabled: false+ web-analytics-content-autopilot-profiles-discover:+ operation: web_analytics_content_autopilot_profiles_discover+ enabled: false+ web-analytics-content-autopilot-profiles-list:+ operation: web_analytics_content_autopilot_profiles_list+ enabled: false+ web-analytics-content-autopilot-profiles-partial-update:+ operation: web_analytics_content_autopilot_profiles_partial_update+ enabled: false+ web-analytics-content-autopilot-profiles-retrieve:+ operation: web_analytics_content_autopilot_profiles_retrieve+ enabled: false+ web-analytics-content-autopilot-proposals-edit:+ operation: web_analytics_content_autopilot_proposals_edit+ enabled: false+ web-analytics-content-autopilot-proposals-export:+ operation: web_analytics_content_autopilot_proposals_export+ enabled: false+ web-analytics-content-autopilot-proposals-list:+ operation: web_analytics_content_autopilot_proposals_list+ enabled: false+ web-analytics-content-autopilot-proposals-regenerate:+ operation: web_analytics_content_autopilot_proposals_regenerate+ enabled: false+ web-analytics-content-autopilot-proposals-reject:+ operation: web_analytics_content_autopilot_proposals_reject+ enabled: false+ web-analytics-content-autopilot-proposals-retrieve:+ operation: web_analytics_content_autopilot_proposals_retrieve+ enabled: false+ web-analytics-content-autopilot-runs-cancel:+ operation: web_analytics_content_autopilot_runs_cancel+ enabled: false+ web-analytics-content-autopilot-runs-list:+ operation: web_analytics_content_autopilot_runs_list+ enabled: false+ web-analytics-content-autopilot-runs-retrieve:+ operation: web_analytics_content_autopilot_runs_retrieve+ enabled: false+ web-analytics-content-autopilot-runs-start:+ operation: web_analytics_content_autopilot_runs_start+ enabled: falseweb-analytics-fetch-llms-txt:operation: web_analytics_fetch_llms_txtenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 05b92d51151b..f362e663f194 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18734,6 +18734,315 @@ export namespace Schemas {token: string;}+ export interface ContentAutopilotError {+ /** Stable machine-readable error code. */+ error_code: string;+ /** Error explanation suitable for the review workspace. */+ message: string;+ }++ /**+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene+ */+ export type OpportunityKindEnum = typeof OpportunityKindEnum[keyof typeof OpportunityKindEnum];+++ export const OpportunityKindEnum = {+ PoorCtr: 'poor_ctr',+ ContentGap: 'content_gap',+ OrganicDecline: 'organic_decline',+ AiVisibilityGap: 'ai_visibility_gap',+ SiteHygiene: 'site_hygiene',+ } as const;++ export interface ContentAutopilotEvidence {+ /** Reason the opportunity was selected.+ *+ * * `poor_ctr` - Poor click-through rate+ * * `content_gap` - Content gap+ * * `organic_decline` - Organic decline+ * * `ai_visibility_gap` - AI visibility gap+ * * `site_hygiene` - Site hygiene */+ opportunity_kind: OpportunityKindEnum;+ /** Plain-language explanation of the supporting evidence. */+ explanation: string;+ /** Page supported by this evidence. */+ page_url?: string;+ /** Search query supported by this evidence. */+ query?: string;+ }++ export interface ContentAutopilotFrontmatterEntry {+ /** Frontmatter field name. */+ key: string;+ /** Serialized frontmatter value. */+ value: string;+ }++ export interface ContentAutopilotPackage {+ /** Repository-relative Markdown or MDX file path. */+ file_path: string;+ /** Content title. */+ title: string;+ /** Search description or summary. */+ description: string;+ /** URL slug. */+ slug: string;+ /** Ordered frontmatter entries. */+ frontmatter: ContentAutopilotFrontmatterEntry[];+ /** Validated same-origin internal links included in the content. */+ internal_links: string[];+ /** Portable source notes included with the export. */+ source_notes: string[];+ }++ export interface ContentAutopilotExportResponse {+ /** Suggested export filename. */+ filename: string;+ /** Validated Markdown content. */+ markdown: string;+ /** Structured JSON package for a CMS adapter. */+ content_package: ContentAutopilotPackage;+ }++ /**+ * * `new_content` - New content+ * * `page_improvement` - Page improvement+ */+ export type ContentAutopilotProposalProposalTypeEnum = typeof ContentAutopilotProposalProposalTypeEnum[keyof typeof ContentAutopilotProposalProposalTypeEnum];+++ export const ContentAutopilotProposalProposalTypeEnum = {+ NewContent: 'new_content',+ PageImprovement: 'page_improvement',+ } as const;++ /**+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `rejected` - Rejected+ * * `exported` - Exported+ * * `failed` - Failed+ */+ export type ContentAutopilotProposalLifecycleStatusEnum = typeof ContentAutopilotProposalLifecycleStatusEnum[keyof typeof ContentAutopilotProposalLifecycleStatusEnum];+++ export const ContentAutopilotProposalLifecycleStatusEnum = {+ Generating: 'generating',+ ReadyForReview: 'ready_for_review',+ Rejected: 'rejected',+ Exported: 'exported',+ Failed: 'failed',+ } as const;++ export interface ContentAutopilotValidationCheck {+ /** Stable identifier for the validation gate. */+ check_key: string;+ /** Human-readable validation name. */+ label: string;+ /** Whether the proposal passed this validation. */+ passed: boolean;+ /** Validation result and any action needed. */+ message: string;+ /** Whether failure prevents export. */+ blocking: boolean;+ }++ export interface ContentAutopilotValidationReport {+ /** Whether every blocking validation passed. */+ passed: boolean;+ /** Factual, brand, intent, originality, linking, crawlability, and schema checks. */+ checks: ContentAutopilotValidationCheck[];+ }++ export interface ContentAutopilotProposal {+ readonly id: string;+ /** Run that generated this proposal. */+ readonly run_id: string;+ /** New article or bounded page improvement.+ *+ * * `new_content` - New content+ * * `page_improvement` - Page improvement */+ readonly proposal_type: ContentAutopilotProposalProposalTypeEnum;+ /** Review and export lifecycle status.+ *+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `rejected` - Rejected+ * * `exported` - Exported+ * * `failed` - Failed */+ readonly lifecycle_status: ContentAutopilotProposalLifecycleStatusEnum;+ /** Review title for this proposal. */+ readonly title: string;+ /** Primary query or topic targeted by this proposal. */+ readonly target_query: string;+ /** Existing or intended public URL. */+ readonly target_url: string;+ /** Performance evidence for this proposal. */+ evidence: ContentAutopilotEvidence[];+ /** Blocking and advisory validation results. */+ validation_report: ContentAutopilotValidationReport;+ /** Structured package that accompanies the exported Markdown. */+ content_package: ContentAutopilotPackage;+ /** Existing content for page-improvement diffs. */+ readonly original_markdown: string;+ /** Full proposed Markdown after edits. */+ readonly proposed_markdown: string;+ readonly created_at: string;+ readonly updated_at: string;+ }++ export interface ContentAutopilotProposalEditRequest {+ /**+ * Edited Markdown to save for review.+ * @maxLength 500000+ */+ proposed_markdown: string;+ /** Updated structured package to save with the proposal. */+ content_package: ContentAutopilotPackage;+ }++ export interface ContentAutopilotProposalList {+ readonly id: string;+ readonly run_id: string;+ readonly proposal_type: ContentAutopilotProposalProposalTypeEnum;+ readonly lifecycle_status: ContentAutopilotProposalLifecycleStatusEnum;+ readonly title: string;+ readonly target_query: string;+ /** Performance evidence for this proposal. */+ evidence: ContentAutopilotEvidence[];+ /** Blocking and advisory validation results. */+ validation_report: ContentAutopilotValidationReport;+ /** Repository-relative export path. */+ readonly file_path: string;+ readonly created_at: string;+ readonly updated_at: string;+ }++ /**+ * * `pending` - Pending+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `completed` - Completed+ * * `canceled` - Canceled+ * * `failed` - Failed+ */+ export type ContentAutopilotRunRunStatusEnum = typeof ContentAutopilotRunRunStatusEnum[keyof typeof ContentAutopilotRunRunStatusEnum];+++ export const ContentAutopilotRunRunStatusEnum = {+ Pending: 'pending',+ Generating: 'generating',+ ReadyForReview: 'ready_for_review',+ Completed: 'completed',+ Canceled: 'canceled',+ Failed: 'failed',+ } as const;++ /**+ * * `standard` - Standard+ * * `lower` - Lower+ */+ export type ContentAutopilotSnapshotConfidenceEnum = typeof ContentAutopilotSnapshotConfidenceEnum[keyof typeof ContentAutopilotSnapshotConfidenceEnum];+++ export const ContentAutopilotSnapshotConfidenceEnum = {+ Standard: 'standard',+ Lower: 'lower',+ } as const;++ export interface ContentAutopilotSnapshot {+ /** Site domain used for the run. */+ domain?: string;+ /** Confidence level based on the available data sources.+ *+ * * `standard` - Standard+ * * `lower` - Lower */+ confidence?: ContentAutopilotSnapshotConfidenceEnum;+ /** Public sources authorized for this run. */+ source_urls?: string[];+ /** Site paths authorized for this run. */+ content_boundaries?: string[];+ /** Editorial rules captured for this run. */+ brand_rules?: string[];+ }++ export interface ContentAutopilotRun {+ readonly id: string;+ /** Site profile used by this run. */+ readonly profile_id: string;+ /** Current durable workflow status.+ *+ * * `pending` - Pending+ * * `generating` - Generating+ * * `ready_for_review` - Ready for review+ * * `completed` - Completed+ * * `canceled` - Canceled+ * * `failed` - Failed */+ readonly run_status: ContentAutopilotRunRunStatusEnum;+ /** Immutable inputs captured at run start. */+ input_snapshot: ContentAutopilotSnapshot;+ /** Inspectable workflow errors from this run. */+ errors: ContentAutopilotError[];+ readonly created_at: string;+ readonly updated_at: string;+ /** @nullable */+ readonly completed_at: string | null;+ }++ export interface ContentAutopilotRunStartRequest {+ /** Site profile to research. */+ profile_id: string;+ }++ export interface ContentAutopilotSiteDiscoveryRequest {+ /** Public site URL to inspect for onboarding defaults. */+ domain: string;+ }++ export interface ContentAutopilotSiteDiscoveryResponse {+ /** Site name inferred from the homepage or hostname. */+ name: string;+ /** Normalized site origin. */+ domain: string;+ /** Detected sitemap URLs or an editable conventional suggestion. */+ source_urls: string[];+ /** Editable same-origin path boundaries. */+ content_boundaries: string[];+ /** Whether at least one sitemap was verified. */+ sitemap_detected: boolean;+ /** Non-blocking discovery warnings. */+ warnings: string[];+ }++ export interface ContentAutopilotSiteProfile {+ readonly id: string;+ /**+ * Name used to identify this site in the workspace.+ * @maxLength 255+ */+ name?: string;+ /**+ * Authorized site origin for this profile.+ * @maxLength 2048+ */+ domain: string;+ /** Public sitemap and factual source URLs used to build the site profile. */+ source_urls: string[];+ /** Same-origin URL path prefixes allowed for research. */+ content_boundaries: string[];+ /** Brand, terminology, and editorial rules applied to every proposal. */+ brand_rules: string[];+ /** Whether to use connected Google Search Console data. */+ search_console_enabled?: boolean;+ readonly created_at: string;+ readonly updated_at: string;+ }+/*** * `utf-8` - utf-8* * `base64` - base64@@ -54784,6 +55093,33 @@ export namespace Schemas {results: CommunitySkillList[];}+ export interface PaginatedContentAutopilotProposalListList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ContentAutopilotProposalList[];+ }++ export interface PaginatedContentAutopilotRunList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ContentAutopilotRun[];+ }++ export interface PaginatedContentAutopilotSiteProfileList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ContentAutopilotSiteProfile[];+ }+export interface PaginatedConversationMinimalList {count: number;/** @nullable */@@ -61462,6 +61798,30 @@ export namespace Schemas {source_comment?: string | null;}+ export interface PatchedContentAutopilotSiteProfile {+ readonly id?: string;+ /**+ * Name used to identify this site in the workspace.+ * @maxLength 255+ */+ name?: string;+ /**+ * Authorized site origin for this profile.+ * @maxLength 2048+ */+ domain?: string;+ /** Public sitemap and factual source URLs used to build the site profile. */+ source_urls?: string[];+ /** Same-origin URL path prefixes allowed for research. */+ content_boundaries?: string[];+ /** Brand, terminology, and editorial rules applied to every proposal. */+ brand_rules?: string[];+ /** Whether to use connected Google Search Console data. */+ search_console_enabled?: boolean;+ readonly created_at?: string;+ readonly updated_at?: string;+ }+export type PatchedConversationMessagesItem = { [key: string]: unknown };export type PatchedConversationPendingApprovalsItem = { [key: string]: unknown };@@ -102115,6 +102475,51 @@ export namespace Schemas {days?: number;};+ export type WebAnalyticsContentAutopilotProfilesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type WebAnalyticsContentAutopilotProposalsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Only return proposals for this site profile.+ */+ profile_id?: string;+ /**+ * Only return proposals from this content run.+ */+ run_id?: string;+ };++ export type WebAnalyticsContentAutopilotRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Only return runs for this site profile.+ */+ profile_id?: string;+ };+export type WebAnalyticsFilterPresetsListParams = {created_by?: number;/**