: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(aio): add access control to evaluations (#81376)
Reece Jones24400ed39b9d
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex 10fb2a27e01c..7f585a2bc6df 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -93,6 +93,7 @@ export const getStorybookAppContext = (): AppContext => ({activity_log: 'viewer',customer_analytics: 'manager',llm_analytics: 'manager',+ evaluation: 'manager',llm_playground: 'manager',mcp_analytics: 'manager',tagger: 'manager',diff --git a/ee/api/rbac/access_control_settings.py b/ee/api/rbac/access_control_settings.pyindex 3a900c4bbc65..2702c717df24 100644--- a/ee/api/rbac/access_control_settings.py+++ b/ee/api/rbac/access_control_settings.py@@ -73,6 +73,7 @@ class _ResourceDisplayModel:# resource, since ENTITY_MAP is consulted first and the entry goes dead. A resource in neither place# and with no derivable name field is left out of the picker and falls back to the raw id._MODELS_NOT_IN_ENTITY_MAP: dict[str, _ResourceDisplayModel] = {+ "evaluation": _ResourceDisplayModel(app_label="ai_observability", model_name="evaluation", name_field="name"),"warehouse_view": _ResourceDisplayModel(app_label="data_modeling", model_name="datawarehousesavedquery", name_field="name"),diff --git a/ee/api/rbac/test/__snapshots__/test_access_control.ambr b/ee/api/rbac/test/__snapshots__/test_access_control.ambrindex b9d597e9b29f..6afcef36e6c4 100644--- a/ee/api/rbac/test/__snapshots__/test_access_control.ambr+++ b/ee/api/rbac/test/__snapshots__/test_access_control.ambr@@ -7,6 +7,7 @@'dataset','early_access_feature','endpoint',+ 'evaluation','experiment','experiment_saved_metric','external_data_source',diff --git a/ee/api/rbac/test/test_access_control.py b/ee/api/rbac/test/test_access_control.pyindex 4a17501d9d54..27792db9dacf 100644--- a/ee/api/rbac/test/test_access_control.py+++ b/ee/api/rbac/test/test_access_control.py@@ -20,6 +20,7 @@ from posthog.session_recordings.models.session_recording import SessionRecordingfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom posthog.utils import render_template+from products.ai_observability.backend.models.evaluations import Evaluationfrom products.cohorts.backend.models.cohort import Cohortfrom products.conversations.backend.models import Ticketfrom products.dashboards.backend.models.dashboard import Dashboard@@ -2366,6 +2367,20 @@ class TestAccessControlSubjectRulesEndpoints(BaseAccessControlTest):# A bare number doesn't read as an object, so the label matches the ticket page's own titleassert [(r["id"], r["name"]) for r in res.json()["results"]] == [(str(ticket.id), "Ticket: 66184")]+ def test_object_search_labels_an_evaluation_by_name(self):+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Helpful evaluator",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ )++ res = self.client.get("/api/projects/@current/access_control_object_search?resource=evaluation&search=Helpful")++ assert res.status_code == status.HTTP_200_OK+ assert [(r["id"], r["name"]) for r in res.json()["results"]] == [(str(evaluation.id), "Helpful evaluator")]+def test_object_search_finds_objects_whose_deleted_flag_is_null(self):# SessionRecording.deleted has no default, so rows carry NULL, which filter(deleted=False)# drops: the picker returned nothing at all for the resourcediff --git a/ee/migrations/0060_backfill_evaluation_access_control.py b/ee/migrations/0060_backfill_evaluation_access_control.pynew file mode 100644index 000000000000..ab22e436e300--- /dev/null+++ b/ee/migrations/0060_backfill_evaluation_access_control.py@@ -0,0 +1,39 @@+from django.db import migrations++CHUNK_SIZE = 200+++def backfill_evaluation_access_control(apps, schema_editor):+ # Evaluations used to inherit their access level from llm_analytics; now that it's an+ # independent resource, mirror every resource-wide llm_analytics grant onto a matching+ # evaluation row so existing permissions keep working instead of silently defaulting to+ # editor. Rows with a resource_id are per-object grants on other llm_analytics+ # sub-resources (datasets, provider keys, ...) and aren't evaluation-related, so they're excluded.+ # Reads the same resource-wide llm_analytics rows as ee/migrations/0053, so this is similarly near-instant.+ AccessControl = apps.get_model("ee", "AccessControl")++ for row in AccessControl.objects.filter(resource="llm_analytics", resource_id__isnull=True).iterator(+ chunk_size=CHUNK_SIZE+ ):+ AccessControl.objects.get_or_create(+ resource="evaluation",+ resource_id=None,+ team_id=row.team_id,+ organization_member_id=row.organization_member_id,+ role_id=row.role_id,+ defaults={"access_level": row.access_level, "created_by_id": row.created_by_id},+ )+++def reverse_func(apps, schema_editor):+ pass+++class Migration(migrations.Migration):+ dependencies = [+ ("ee", "0059_scimprovisioneduser_unique_config"),+ ]++ operations = [+ migrations.RunPython(backfill_evaluation_access_control, reverse_func),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex 612f9b628861..f5a8d9017c15 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0059_scimprovisioneduser_unique_config+0060_backfill_evaluation_access_controldiff --git a/ee/migrations/test/test_migration_0060.py b/ee/migrations/test/test_migration_0060.pynew file mode 100644index 000000000000..0075148a11ae--- /dev/null+++ b/ee/migrations/test/test_migration_0060.py@@ -0,0 +1,118 @@+import importlib++from posthog.test.base import BaseTest++from django.apps import apps++from parameterized import parameterized++from ee.models.rbac.access_control import AccessControl+from ee.models.rbac.role import Role++migration_module = importlib.import_module("ee.migrations.0060_backfill_evaluation_access_control")+backfill_evaluation_access_control = migration_module.backfill_evaluation_access_control+++class TestBackfillEvaluationAccessControl(BaseTest):+ def _scope_kwargs(self, case):+ role = (+ Role.objects.create(name="Engineering", organization=self.organization) if case == "role_scoped" else None+ )+ return {+ "organization_member": self.organization_membership if case == "member_scoped" else None,+ "role": role,+ }++ @parameterized.expand(+ [+ ("member_scoped",),+ ("role_scoped",),+ ("org_default",),+ ]+ )+ def test_backfills_resource_wide_row(self, case):+ scope_kwargs = self._scope_kwargs(case)++ AccessControl.objects.create(+ team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs+ )++ backfill_evaluation_access_control(apps, None)++ backfilled = AccessControl.objects.filter(resource="evaluation", team=self.team, **scope_kwargs).first()+ assert backfilled is not None+ assert backfilled.access_level == "viewer"++ def test_does_not_touch_other_resources(self):+ AccessControl.objects.create(+ team=self.team,+ resource="dataset",+ resource_id=None,+ access_level="editor",+ organization_member=self.organization_membership,+ )++ backfill_evaluation_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="evaluation").exists()++ def test_ignores_object_scoped_llm_analytics_rows(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id="123",+ access_level="editor",+ organization_member=self.organization_membership,+ )++ backfill_evaluation_access_control(apps, None)++ assert not AccessControl.objects.filter(resource="evaluation").exists()++ def test_does_not_overwrite_existing_row(self):+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id=None,+ access_level="editor",+ organization_member=self.organization_membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=None,+ access_level="none",+ organization_member=self.organization_membership,+ )++ backfill_evaluation_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="evaluation", organization_member=self.organization_membership)++ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.access_level == "none"++ @parameterized.expand(+ [+ ("member_scoped",),+ ("role_scoped",),+ ("org_default",),+ ]+ )+ def test_idempotent_on_repeat_run(self, case):+ # organization_member/role are nullable, and Postgres unique constraints treat NULLs as+ # distinct, so the org_default (both-None) case would silently duplicate on a second run+ # if the migration ever stopped looking up the existing row before creating one.+ scope_kwargs = self._scope_kwargs(case)++ AccessControl.objects.create(+ team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer", **scope_kwargs+ )++ backfill_evaluation_access_control(apps, None)+ backfill_evaluation_access_control(apps, None)++ rows = AccessControl.objects.filter(resource="evaluation", team=self.team, **scope_kwargs)+ assert rows.count() == 1diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f25755d81593..4e0f2a33e923 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7637,9 +7637,9 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--light:hash: v1.k794b7964.826b954e1c03e3156d0c10598975c3fd43583672372c163fa08264506f929cd7.C22X_4g68JpmDtmjwe33M24AQZ4CTTIwW2cMZPL0JCoscenes-app-settings-environment--settings-environment-access-control--dark:- hash: v1.k794b7964.accdd9c00d468382dda33761da2f7edc1a086c418561fcb24274aea3bffa6905.kPKTpBwOGrFJWYZFgEQa0LVY9ymopIu_8QgbuRa9-sg+ hash: v1.k794b7964.aaa5cfaf171ff03f70b661188ff1929c429d4869f42447b613e3187c0f64676d.0FKBKOrxXxrhUqI7snoVtWkkOiBcQiq5PyBDkeVhtywscenes-app-settings-environment--settings-environment-access-control--light:- hash: v1.k794b7964.8d23c1f36b33b296b50f8c50564d62c94d70df0548062d233f7f21a17a0c2350.Qj-t7gHYmg3GAb-GLs_F_cMzF69W1tLdJwOggJBy8e0+ hash: v1.k794b7964.186fbf23227d2d6dc06649434978123a3fb9bd1bf1b2199124397879059bacc6.tT3nI1FldKPItDCHz00NZgrH3dQJIseYExoZD9D51Usscenes-app-settings-environment--settings-environment-autocapture--dark:hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4scenes-app-settings-environment--settings-environment-autocapture--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsxindex a5baf5f7b6b7..28314aef2ca1 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/ScopeIcon.tsx@@ -12,6 +12,7 @@ import {IconFlask,IconHome,IconList,+ IconListCheck,IconLive,IconListTree,IconLlmAnalytics,@@ -66,6 +67,8 @@ export function ScopeIcon(props: { scope: APIScopeObject }): JSX.Element | nullreturn <IconWarning />case 'event_definition':return <IconApps />+ case 'evaluation':+ return <IconListCheck />case 'experiment':return <IconFlask />case 'export':diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.tsindex ea1158150607..d1ed3e27157a 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts@@ -181,6 +181,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(AccessControlResourceType.Heatmap,AccessControlResourceType.Insight,AccessControlResourceType.LlmAnalytics,+ AccessControlResourceType.Evaluation,AccessControlResourceType.McpAnalytics,AccessControlResourceType.Tagger,AccessControlResourceType.LlmSkill,diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.tsindex 1fc2e45f80d4..15bd31f242a3 100644--- a/frontend/src/lib/utils/accessControlUtils.ts+++ b/frontend/src/lib/utils/accessControlUtils.ts@@ -364,5 +364,8 @@ export const getAccessControlTooltip = (resource: APIScopeObject): string | nullif (resource === AccessControlResourceType.Metrics) {return 'Controls access to the metrics product and its API. It does not restrict querying the underlying metrics tables with SQL.'}+ if (resource === AccessControlResourceType.LlmAnalytics) {+ return 'Covers traces, datasets, provider keys, and the model picker.'+ }return null}diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 5d9b7740d803..09cd269c80f5 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -214,6 +214,7 @@ export enum Scene {AIObservabilityDatasets = 'AIObservabilityDatasets',AIObservabilityEvaluation = 'AIObservabilityEvaluation',AIObservabilityEvaluations = 'AIObservabilityEvaluations',+ AIObservabilityEvaluationTemplates = 'AIObservabilityEvaluationTemplates',AIObservabilityPlayground = 'AIObservabilityPlayground',AIObservabilityTag = 'AIObservabilityTag',AIObservabilityTags = 'AIObservabilityTags',@@ -440,8 +441,9 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.AIObservabilityClusters]: AccessControlResourceType.AiObservabilityClusters,[Scene.AIObservabilityDataset]: AccessControlResourceType.LlmAnalytics,[Scene.AIObservabilityDatasets]: AccessControlResourceType.LlmAnalytics,- [Scene.AIObservabilityEvaluation]: AccessControlResourceType.LlmAnalytics,- [Scene.AIObservabilityEvaluations]: AccessControlResourceType.LlmAnalytics,+ [Scene.AIObservabilityEvaluation]: AccessControlResourceType.Evaluation,+ [Scene.AIObservabilityEvaluations]: AccessControlResourceType.Evaluation,+ [Scene.AIObservabilityEvaluationTemplates]: AccessControlResourceType.Evaluation,[Scene.AIObservabilityPlayground]: AccessControlResourceType.LlmPlayground,[Scene.AIObservabilityTag]: AccessControlResourceType.Tagger,[Scene.AIObservabilityTags]: AccessControlResourceType.Tagger,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a3db95ccdfeb..6e8a6d53b088 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -294,6 +294,7 @@ export enum AccessControlResourceType {Dashboard = 'dashboard',DashboardTemplate = 'dashboard_template',LlmAnalytics = 'llm_analytics',+ Evaluation = 'evaluation',Tagger = 'tagger',LlmSkill = 'llm_skill',LlmPlayground = 'llm_playground',diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.pyindex d5c192a3f75d..a42ecedeadf0 100644--- a/posthog/rbac/user_access_control.py+++ b/posthog/rbac/user_access_control.py@@ -73,6 +73,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("hog_flow","insight","llm_analytics",+ "evaluation","tagger","llm_skill","ai_observability_clusters",@@ -103,7 +104,6 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {"session_recording_playlist": "session_recording","warehouse_table": "warehouse_objects","warehouse_view": "warehouse_objects",- "evaluation": "llm_analytics","dataset": "llm_analytics","llm_provider_key": "llm_analytics","llm_prompt": "llm_analytics",diff --git a/products/ai_observability/backend/api/evaluation_config.py b/products/ai_observability/backend/api/evaluation_config.pyindex 5b1c54d3e15e..4f658caf8da0 100644--- a/products/ai_observability/backend/api/evaluation_config.py+++ b/products/ai_observability/backend/api/evaluation_config.py@@ -11,6 +11,7 @@ from posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_actionfrom posthog.permissions import AccessControlPermission+from posthog.scopes import APIScopeObjectOrNotSupportedfrom ..models.evaluation_config import EvaluationConfigfrom ..models.provider_keys import LLMProviderKey@@ -53,17 +54,29 @@ class EvaluationConfigSetActiveKeyRequestSerializer(serializers.Serializer):)+class EvaluationConfigAccessControlPermission(AccessControlPermission):+ def _get_scope_object(self, request: Request, view: viewsets.ViewSet) -> APIScopeObjectOrNotSupported:+ return "evaluation" if view.action == "set_active_key" else "llm_analytics"++class EvaluationConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""Team-level evaluation configuration"""- scope_object = "evaluation"+ # Reads are shared by evaluations, taggers, and the playground model picker.+ scope_object = "llm_analytics"+ requires_resource_level_access = True# `set_active_key` is a custom @action and `list` lives on a plain ViewSet, so neither maps to# ScopeBasePermission's default action lists. Spell them out explicitly — without this, every# personal-API-key request 403s with "This action does not support Personal API Key access".scope_object_read_actions = ["list"]scope_object_write_actions = ["set_active_key"]serializer_class = _FallbackSerializer- permission_classes = [IsAuthenticated, AccessControlPermission]+ permission_classes = [IsAuthenticated, EvaluationConfigAccessControlPermission]++ def dangerously_get_required_scopes(self, request: Request, view: viewsets.ViewSet) -> list[str] | None:+ if self.action == "set_active_key":+ return ["evaluation:write"]+ return None@extend_schema(operation_id="llm_analytics_evaluation_config_retrieve",diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.pyindex 1c25ed9f0339..60fd8f5a930c 100644--- a/products/ai_observability/backend/api/evaluation_reports.py+++ b/products/ai_observability/backend/api/evaluation_reports.py@@ -1,7 +1,8 @@"""API endpoints for evaluation report configuration and report run history."""import datetime as dt-from typing import Any, cast+from typing import Any, Protocol, cast+from uuid import UUIDfrom django.conf import settingsfrom django.db.models import Count, Max, QuerySet@@ -12,14 +13,23 @@ from asgiref.sync import async_to_syncfrom drf_spectacular.utils import extend_schema, extend_schema_fieldfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.permissions import BasePermission, IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.views import APIViewfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import InternalAPIAuthenticationfrom posthog.event_usage import report_user_actionfrom posthog.models.integration import Integration-from posthog.permissions import AccessControlPermission+from posthog.permissions import (+ AccessControlPermission,+ APIScopePermission,+ TeamMemberAccessPermission,+ get_authenticator_scopes,+ is_service_auth,+)from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (EvalReportGenerationStatus,normalize_metrics_payload,@@ -33,7 +43,7 @@ from products.ai_observability.backend.models.evaluation_reports import (EvaluationReportQuerySet,EvaluationReportRun,)-from products.ai_observability.backend.models.evaluations import EvaluationTarget+from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTargetfrom products.workflows.backend.utils.rrule_utils import validate_rrulelogger = structlog.get_logger(__name__)@@ -567,14 +577,53 @@ class EvaluationReportRunSerializer(serializers.ModelSerializer):}+class _EvaluationReportPermissionView(Protocol):+ action: str+ team_id: int+++class EvaluationReportAccessControlPermission(AccessControlPermission):+ def has_permission(self, request: Request, view: APIView) -> bool:+ report_view = cast(_EvaluationReportPermissionView, view)+ if report_view.action != "create":+ return super().has_permission(request, view)++ # Scoped tokens must pass the standard scope and resource checks. Session users can be+ # authorized against the submitted parent before the generic create check rejects them.+ if get_authenticator_scopes(request.successful_authenticator) is not None:+ return super().has_permission(request, view)++ try:+ evaluation_id = UUID(str(request.data.get("evaluation")))+ evaluation = Evaluation.objects.filter(team_id=report_view.team_id, id=evaluation_id).first()+ except (TypeError, ValueError):+ return False+ return evaluation is not None and self.has_object_permission(request, view, evaluation)++ def has_object_permission(self, request: Request, view: APIView, obj: object) -> bool:+ if not isinstance(obj, (EvaluationReport, Evaluation)):+ return False+ evaluation = obj.evaluation if isinstance(obj, EvaluationReport) else obj+ return super().has_object_permission(request, view, evaluation)++class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):"""CRUD for evaluation report configurations + report run history."""- scope_object = "llm_analytics"- permission_classes = [AccessControlPermission]+ scope_object = "evaluation"serializer_class = EvaluationReportSerializerqueryset = EvaluationReport.objects.all()+ def dangerously_get_permissions(self) -> list[BasePermission]:+ if isinstance(self.request.successful_authenticator, InternalAPIAuthentication):+ return [IsAuthenticated()]+ return [+ IsAuthenticated(),+ APIScopePermission(),+ EvaluationReportAccessControlPermission(),+ TeamMemberAccessPermission(),+ ]+@staticmethoddef _is_mcp_request(request: Request) -> bool:return request.META.get("HTTP_X_POSTHOG_CLIENT") == "mcp"@@ -596,6 +645,11 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse).order_by("-created_at"),)+ if not is_service_auth(self.request):+ visible_evaluation_ids = self.user_access_control.filter_queryset_by_access_level(+ Evaluation.objects.filter(team_id=self.team_id, deleted=False)+ ).values("id")+ report_queryset = report_queryset.filter(evaluation_id__in=visible_evaluation_ids)# Generate validates eligibility explicitly so unsupported legacy rows return a useful 400.if self.action != "generate":report_queryset = report_queryset.reportable()@@ -619,6 +673,7 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsedef create(self, request: Request, *args, **kwargs) -> Response:serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)+ self.check_object_permissions(request, serializer.validated_data["evaluation"])self.perform_create(serializer)headers = self.get_success_headers(serializer.data)status_code = status.HTTP_201_CREATED if getattr(serializer, "created_instance", True) else status.HTTP_200_OK@@ -712,7 +767,7 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse)@extend_schema(responses=EvaluationReportRunSerializer(many=True))- @action(detail=True, methods=["get"], url_path="runs", required_scopes=["llm_analytics:read"])+ @action(detail=True, methods=["get"], url_path="runs", required_scopes=["evaluation:read"])@llma_track_latency("llma_evaluation_report_runs_list")def runs(self, request: Request, **kwargs) -> Response:"""List report runs (history) for this report."""@@ -726,7 +781,7 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsereturn Response(serializer.data)@extend_schema(request=None, responses={202: None})- @action(detail=True, methods=["post"], url_path="generate", required_scopes=["llm_analytics:write"])+ @action(detail=True, methods=["post"], url_path="generate", required_scopes=["evaluation:write"])@llma_track_latency("llma_evaluation_report_generate")def generate(self, request: Request, **kwargs) -> Response:"""Trigger immediate report generation."""diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.pyindex 4ecf9eb3c3c2..95eea3a81cec 100644--- a/products/ai_observability/backend/api/evaluation_runs.py+++ b/products/ai_observability/backend/api/evaluation_runs.py@@ -88,6 +88,8 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):except Evaluation.DoesNotExist:return Response({"error": f"Evaluation {evaluation_id} not found"}, status=404)+ self.check_object_permissions(request, evaluation)+# This endpoint runs one $ai_generation through the generation workflow. Without this check# a trace- or session-target evaluation is accepted and run as a generation, emitting a# verdict with $ai_target_type "generation_uuid" under that evaluation's name — which thendiff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 180a189f3360..b21d7a26b8cf 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -8,7 +8,7 @@ import structlogimport django_filtersfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_field-from rest_framework import serializers, viewsets+from rest_framework import exceptions, serializers, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.generics import get_object_or_404@@ -31,6 +31,7 @@ from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_propefrom posthog.models.team import Teamfrom posthog.permissions import AccessControlPermissionfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin+from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.model_resolution import active_key_fallbackfrom posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_eval@@ -271,7 +272,9 @@ class EvaluationConditionSerializer(serializers.Serializer):)-class EvaluationSerializer(serializers.ModelSerializer):+class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):+ """An evaluation that scores LLM generations, traces, or sessions."""+created_by = UserBasicSerializer(read_only=True,allow_null=True,@@ -357,6 +360,7 @@ class EvaluationSerializer(serializers.ModelSerializer):"updated_at","created_by","deleted",+ "user_access_level",]# status / status_reason are server-managed (coerced from enabled on user writes, set directly by# system transitions). Clients toggle `enabled`; the model's save() keeps the status fields consistent.@@ -1174,6 +1178,9 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi@action(detail=False, methods=["post"], url_path="test_hog", required_scopes=["evaluation:read"])def test_hog(self, request: Request, **kwargs) -> Response:"""Test Hog evaluation code against sample events without saving."""+ if not self.user_access_control.check_access_level_for_resource("evaluation", "viewer"):+ raise exceptions.PermissionDenied()+serializer = TestHogRequestSerializer(data=request.data)if not serializer.is_valid():return Response({"error": serializer.errors}, status=400)diff --git a/products/ai_observability/backend/api/models.py b/products/ai_observability/backend/api/models.pyindex 37436de7cdcf..a38f0bb58c56 100644--- a/products/ai_observability/backend/api/models.py+++ b/products/ai_observability/backend/api/models.py@@ -64,7 +64,9 @@ class LLMModelsListResponseSerializer(serializers.Serializer):class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""List available models, for one provider or for every supported provider."""- scope_object = "evaluation"+ # Shared by the evaluations, taggers, and playground model pickers, so it sits on the+ # product-wide llm_analytics resource rather than any one of their resources.+ scope_object = "llm_analytics"serializer_class = _FallbackSerializerpermission_classes = [IsAuthenticated, AccessControlPermission]diff --git a/products/ai_observability/backend/api/offline_evaluations.py b/products/ai_observability/backend/api/offline_evaluations.pyindex 87179523d0f4..c608d12740c2 100644--- a/products/ai_observability/backend/api/offline_evaluations.py+++ b/products/ai_observability/backend/api/offline_evaluations.py@@ -128,8 +128,9 @@ class OfflineExperimentItemsResponseSerializer(serializers.Serializer):class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- scope_object = "llm_analytics"+ scope_object = "evaluation"scope_object_read_actions = ["experiment_items"]+ requires_resource_level_access = Truepermission_classes = [AccessControlPermission]@extend_schema(diff --git a/products/ai_observability/backend/api/provider_keys.py b/products/ai_observability/backend/api/provider_keys.pyindex 0a2fe17cfffb..1473117a758c 100644--- a/products/ai_observability/backend/api/provider_keys.py+++ b/products/ai_observability/backend/api/provider_keys.py@@ -7,7 +7,7 @@ from django.db.models import QuerySetfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema-from rest_framework import serializers, status, viewsets+from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -17,7 +17,7 @@ from posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action-from posthog.permissions import TeamMemberStrictManagementPermission+from posthog.permissions import TeamMemberStrictManagementPermission, is_service_authfrom posthog.plugins.plugin_server_api import reload_evaluations_on_workers, reload_taggers_on_workersfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -276,7 +276,26 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vdef safely_get_queryset(self, queryset: QuerySet[LLMProviderKey]) -> QuerySet[LLMProviderKey]:return queryset.filter(team_id=self.team_id).select_related("created_by").order_by("-created_at")+ def _require_evaluation_write_access(self) -> None:+ if not is_service_auth(self.request) and not self.user_access_control.check_access_level_for_resource(+ "evaluation", "editor"+ ):+ raise exceptions.PermissionDenied("You do not have editor access to evaluations.")++ def _require_write_access_to_evaluations(self, evaluations: list[Evaluation]) -> None:+ if is_service_auth(self.request):+ return++ if any(+ not self.user_access_control.check_access_level_for_object(evaluation, "editor")+ for evaluation in evaluations+ ):+ raise exceptions.PermissionDenied("You do not have editor access to all affected evaluations.")+def perform_create(self, serializer):+ if serializer.validated_data.get("set_as_active", False):+ self._require_evaluation_write_access()+instance = serializer.save()report_user_action(self.request.user,@@ -428,6 +447,18 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vinstance = self.get_object()replacement_key_id = request.query_params.get("replacement_key_id")+ if EvaluationConfig.objects.filter(team_id=self.team_id, active_provider_key=instance).exists():+ self._require_evaluation_write_access()++ affected_evaluations = list(+ Evaluation.objects.filter(+ team_id=self.team_id,+ model_configuration__provider_key=instance,+ deleted=False,+ )+ )+ self._require_write_access_to_evaluations(affected_evaluations)+if replacement_key_id:try:replacement_key = LLMProviderKey.objects.get(id=replacement_key_id, team_id=self.team_id)diff --git a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py b/products/ai_observability/backend/api/test/test_ai_observability_access_control.pyindex cdaabc14ccbb..8eae6da62a28 100644--- a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py+++ b/products/ai_observability/backend/api/test/test_ai_observability_access_control.py@@ -11,7 +11,6 @@ from posthog.models.user import Userfrom products.ai_observability.backend.dataset_service import archive_dataset, create_dataset, create_dataset_itemfrom products.ai_observability.backend.models.clustering_job import ClusteringJob-from products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom products.ai_observability.backend.models.review_queues import ReviewQueue, ReviewQueueItemfrom products.ai_observability.backend.models.trace_reviews import TraceReview@@ -64,16 +63,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):self.editor_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")self.no_access_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")- self.evaluation = Evaluation.objects.create(- team=self.team,- name="Test Evaluation",- evaluation_type="llm_judge",- evaluation_config={"prompt": "Test prompt"},- output_type="boolean",- output_config={},- created_by=self.user,- )-self.dataset = create_dataset(team=self.team,name="Test Dataset",@@ -170,7 +159,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):@parameterized.expand([- ("evaluations", "evaluation"),("datasets", "dataset"),("llm_analytics/provider_keys", "provider_key"),]@@ -204,7 +192,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):@parameterized.expand([- ("evaluations", "evaluation"),("datasets", "dataset"),("llm_analytics/provider_keys", "provider_key"),]@@ -306,24 +293,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):# -- Viewer cannot create/update/delete --- def test_viewer_cannot_create_evaluation(self):- self._set_access_level(self.viewer_user, access_level="viewer")- self.client.force_login(self.viewer_user)-- response = self.client.post(- f"/api/environments/{self.team.id}/evaluations/",- {- "name": "New Evaluation",- "evaluation_type": "llm_judge",- "model_configuration": _DEFAULT_MODEL_CONFIGURATION,- "evaluation_config": {"prompt": "prompt"},- "output_type": "boolean",- "output_config": {},- },- format="json",- )- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)-def test_viewer_cannot_create_dataset(self):self._set_access_level(self.viewer_user, access_level="viewer")self.client.force_login(self.viewer_user)@@ -335,17 +304,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)- def test_viewer_cannot_update_evaluation(self):- self._set_access_level(self.viewer_user, access_level="viewer")- self.client.force_login(self.viewer_user)-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{self.evaluation.id}/",- {"name": "Updated"},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)-def test_viewer_cannot_delete_provider_key(self):self._set_access_level(self.viewer_user, access_level="viewer")self.client.force_login(self.viewer_user)@@ -522,24 +480,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):# -- Editor can create/update/delete --- def test_editor_can_create_evaluation(self):- self._set_access_level(self.editor_user, access_level="editor")- self.client.force_login(self.editor_user)-- response = self.client.post(- f"/api/environments/{self.team.id}/evaluations/",- {- "name": "Editor Evaluation",- "evaluation_type": "llm_judge",- "model_configuration": _DEFAULT_MODEL_CONFIGURATION,- "evaluation_config": {"prompt": "prompt"},- "output_type": "boolean",- "output_config": {},- },- format="json",- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)-def test_editor_can_create_dataset(self):self._set_access_level(self.editor_user, access_level="editor")self.client.force_login(self.editor_user)@@ -709,17 +649,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):).exists())- def test_editor_can_update_evaluation(self):- self._set_access_level(self.editor_user, access_level="editor")- self.client.force_login(self.editor_user)-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{self.evaluation.id}/",- {"name": "Updated by editor"},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-@parameterized.expand([("create", status.HTTP_403_FORBIDDEN),@@ -926,7 +855,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):@parameterized.expand([- ("evaluations",),("datasets",),("llm_analytics/provider_keys",),("llm_analytics/review_queues",),@@ -966,7 +894,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):@parameterized.expand([- ("evaluations", "evaluation"),("datasets", "dataset"),("llm_analytics/provider_keys", "provider_key"),]@@ -980,7 +907,6 @@ class TestAIObservabilityAccessControl(APIBaseTest):@parameterized.expand([- ("evaluations", "evaluation"),("datasets", "dataset"),("llm_analytics/provider_keys", "provider_key"),]@@ -1010,8 +936,8 @@ class TestAIObservabilityAccessControl(APIBaseTest):clustering_response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/clustering_jobs/")self.assertEqual(clustering_response.status_code, status.HTTP_200_OK)- evaluations_response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")- self.assertEqual(evaluations_response.status_code, status.HTTP_403_FORBIDDEN)+ datasets_response = self.client.get(f"/api/environments/{self.team.id}/datasets/")+ self.assertEqual(datasets_response.status_code, status.HTTP_403_FORBIDDEN)# -- Org admin has full access without explicit permissions --diff --git a/products/ai_observability/backend/api/test/test_evaluation_config.py b/products/ai_observability/backend/api/test/test_evaluation_config.pyindex 89bbdf5600ae..abaa1247a501 100644--- a/products/ai_observability/backend/api/test/test_evaluation_config.py+++ b/products/ai_observability/backend/api/test/test_evaluation_config.py@@ -4,11 +4,15 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import Organization, Project, Team, User+from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Project, Team, Userfrom products.ai_observability.backend.models.evaluation_config import EvaluationConfig+from products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey+from ee.models.rbac.access_control import AccessControl+def _setup_team():org = Organization.objects.create(name="test")@@ -206,3 +210,53 @@ class TestEvaluationConfigViewSet(APIBaseTest):self.assertEqual(active_key["provider"], "openai")self.assertEqual(active_key["state"], "ok")self.assertIn("api_key_masked", active_key)++ def test_evaluation_restrictions_only_allow_read_only_shared_model_config(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ limited_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=limited_user, organization=self.organization)+ visible_evaluation = Evaluation.objects.create(+ team=self.team,+ name="Visible Evaluation",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ )+ key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Team Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ created_by=self.user,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ access_level="none",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(visible_evaluation.id),+ access_level="editor",+ organization_member=membership,+ )+ self.client.force_login(limited_user)++ get_response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")++ set_active_key_response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/set_active_key/",+ {"key_id": str(key.id)},+ format="json",+ )++ assert get_response.status_code == status.HTTP_200_OK+ assert set_active_key_response.status_code == status.HTTP_403_FORBIDDEN+ assert not EvaluationConfig.objects.filter(team=self.team, active_provider_key=key).exists()diff --git a/products/ai_observability/backend/api/test/test_evaluation_directories.py b/products/ai_observability/backend/api/test/test_evaluation_directories.pyindex cd5d049fb0e5..02e05efbf0ac 100644--- a/products/ai_observability/backend/api/test/test_evaluation_directories.py+++ b/products/ai_observability/backend/api/test/test_evaluation_directories.py@@ -150,7 +150,7 @@ class TestEvaluationDirectoriesApi(APIBaseTest):membership = OrganizationMembership.objects.get(user=limited_user, organization=self.organization)AccessControl.objects.create(team=self.team,- resource="llm_analytics",+ resource="evaluation",access_level="none",organization_member=membership,)diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.pyindex e94e60a00d93..3ed6267f3756 100644--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py@@ -11,14 +11,18 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models.integration import Integration-from posthog.models.organization import Organization+from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom products.ai_observability.backend.api.evaluation_reports import EvaluationReportRunSerializerfrom products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRunfrom products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTarget+from ee.models.rbac.access_control import AccessControl+class TestEvaluationReportRunSerializer(SimpleTestCase):def test_normalizes_legacy_metrics_without_backfilling_stored_json(self) -> None:@@ -787,7 +791,7 @@ class TestEvaluationReportApi(APIBaseTest):# requests are rejected with "This action does not support Personal API Key access".@parameterized.expand([- ("read_scope_allowed", ["llm_analytics:read"], status.HTTP_200_OK),+ ("read_scope_allowed", ["evaluation:read"], status.HTTP_200_OK),("wrong_scope_denied", ["insight:read"], status.HTTP_403_FORBIDDEN),])@@ -801,8 +805,8 @@ class TestEvaluationReportApi(APIBaseTest):@parameterized.expand([- ("write_scope_allowed", ["llm_analytics:write"], status.HTTP_202_ACCEPTED),- ("wrong_scope_denied", ["llm_analytics:read"], status.HTTP_403_FORBIDDEN),+ ("write_scope_allowed", ["evaluation:write"], status.HTTP_202_ACCEPTED),+ ("wrong_scope_denied", ["evaluation:read"], status.HTTP_403_FORBIDDEN),])@patch("products.ai_observability.backend.api.evaluation_reports.async_to_sync")@@ -849,3 +853,133 @@ class TestEvaluationReportApi(APIBaseTest):response = self.client.patch(f"{self.base_url}{report.id}/", {"deleted": True}, format="json")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)mock_report.assert_not_called()+++class TestEvaluationReportAccessControl(APIBaseTest):+ # Reports moved from the coarse `llm_analytics` resource onto `evaluation`, which owns them.+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ self.evaluation = Evaluation.objects.create(+ team=self.team,+ name="Test Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test"},+ output_type="boolean",+ created_by=self.user,+ )+ self.report = EvaluationReport.objects.create(+ team=self.team,+ evaluation=self.evaluation,+ frequency=EvaluationReport.Frequency.EVERY_N,+ trigger_threshold=100,+ delivery_targets=[{"type": "email", "value": "[email protected]"}],+ )+ self.base_url = f"/api/environments/{self.team.id}/llm_analytics/evaluation_reports/"+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ def _grant(self, resource: str, access_level: str, resource_id: str | None = None) -> None:+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ access_level=access_level,+ organization_member=OrganizationMembership.objects.get(+ user=self.other_user, organization=self.organization+ ),+ )++ def test_evaluation_viewer_can_read_runs_but_not_generate(self):+ self._grant("evaluation", "viewer")+ self.client.force_login(self.other_user)++ runs_response = self.client.get(f"{self.base_url}{self.report.id}/runs/")+ assert runs_response.status_code == status.HTTP_200_OK++ generate_response = self.client.post(f"{self.base_url}{self.report.id}/generate/")+ assert generate_response.status_code == status.HTTP_403_FORBIDDEN++ def test_llm_analytics_grant_alone_does_not_reach_reports(self):+ self._grant("evaluation", "none")+ self._grant("llm_analytics", "editor")+ self.client.force_login(self.other_user)++ response = self.client.get(self.base_url)++ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_evaluation_specific_editor_cannot_redirect_another_evaluations_report(self) -> None:+ visible_evaluation = Evaluation.objects.create(+ team=self.team,+ name="Visible Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test"},+ output_type="boolean",+ created_by=self.user,+ )+ self._grant("evaluation", "none")+ self._grant("evaluation", "editor", resource_id=str(visible_evaluation.id))+ self.client.force_login(self.other_user)++ response = self.client.patch(+ f"{self.base_url}{self.report.id}/",+ {"delivery_targets": [{"type": "email", "value": "[email protected]"}]},+ format="json",+ )++ assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)+ self.report.refresh_from_db()+ assert self.report.delivery_targets == [{"type": "email", "value": "[email protected]"}]++ def test_evaluation_specific_editor_cannot_upsert_another_evaluations_report(self) -> None:+ visible_evaluation = Evaluation.objects.create(+ team=self.team,+ name="Visible Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test"},+ output_type="boolean",+ created_by=self.user,+ )+ self._grant("evaluation", "none")+ self._grant("evaluation", "editor", resource_id=str(visible_evaluation.id))+ self.client.force_login(self.other_user)++ response = self.client.post(+ self.base_url,+ {+ "evaluation": str(self.evaluation.id),+ "frequency": EvaluationReport.Frequency.EVERY_N,+ "trigger_threshold": 100,+ "delivery_targets": [{"type": "email", "value": "[email protected]"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ self.report.refresh_from_db()+ assert self.report.delivery_targets == [{"type": "email", "value": "[email protected]"}]++ def test_evaluation_specific_editor_can_upsert_its_report(self) -> None:+ self._grant("evaluation", "none")+ self._grant("evaluation", "editor", resource_id=str(self.evaluation.id))+ self.client.force_login(self.other_user)++ response = self.client.post(+ self.base_url,+ {+ "evaluation": str(self.evaluation.id),+ "frequency": EvaluationReport.Frequency.EVERY_N,+ "trigger_threshold": 100,+ "delivery_targets": [{"type": "email", "value": "[email protected]"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ self.report.refresh_from_db()+ assert self.report.delivery_targets == [{"type": "email", "value": "[email protected]"}]diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.pyindex 1233954b083b..f5779cd01bb1 100644--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py@@ -11,6 +11,11 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags+from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User++from ee.models.rbac.access_control import AccessControlfrom ...api.evaluation_runs import _evaluation_workflow_prefixfrom ...models.evaluations import Evaluation@@ -46,6 +51,37 @@ class TestEvaluationRunViewSet(APIBaseTest):enabled=True,)+ def test_create_requires_access_to_requested_evaluation(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=other_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team, resource="evaluation", access_level="editor", organization_member=membership+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(self.evaluation.id),+ access_level="none",+ organization_member=membership,+ )+ self.client.force_login(other_user)++ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluation_runs/",+ {+ "evaluation_id": str(self.evaluation.id),+ "target_event_id": str(uuid.uuid4()),+ "timestamp": datetime.now().isoformat(),+ },+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+@patch("products.ai_observability.backend.api.evaluation_runs.query_with_columns")@patch("products.ai_observability.backend.api.evaluation_runs.sync_connect")def test_create_evaluation_run_success(self, mock_connect, mock_query):diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 96cfe8c864f0..b70f2d794247 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -11,8 +11,9 @@ from drf_spectacular.plumbing import get_overridefrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY-from posthog.models import Organization, Project, Team, User+from posthog.models import Organization, OrganizationMembership, Project, Team, Userfrom products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer, _TargetConfigFieldfrom products.ai_observability.backend.models.evaluation_config import EvaluationConfig@@ -22,6 +23,8 @@ from products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.model_configuration import LLMModelConfigurationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey+from ee.models.rbac.access_control import AccessControl+_DEFAULT_MODEL_CONFIGURATION = {"provider": "openai","model": "gpt-5-mini",@@ -1754,3 +1757,175 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):eval_obj.refresh_from_db()self.assertTrue(eval_obj.enabled)self.assertIsNone(eval_obj.status_reason)+++class TestEvaluationsAccessControl(APIBaseTest):+ # Evaluations have their own access control resource (see ACCESS_CONTROL_RESOURCES in+ # posthog/rbac/user_access_control.py). They used to inherit from `llm_analytics`.+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ self.viewer_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.editor_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.no_access_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")++ self._grant(self.viewer_user, "viewer")+ self._grant(self.editor_user, "editor")+ self._grant(self.no_access_user, "none")++ def _grant(+ self, user: User, access_level: str, resource: str = "evaluation", resource_id: str | None = None+ ) -> AccessControl:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ return AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ access_level=access_level,+ organization_member=membership,+ )++ def _create_evaluation(self, name: str = "Existing Evaluation") -> Evaluation:+ return Evaluation.objects.create(+ team=self.team,+ name=name,+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ created_by=self.user,+ )++ def _create_payload(self, name: str = "New Evaluation") -> dict:+ return {+ "name": name,+ "evaluation_type": "hog",+ "evaluation_config": {"source": "return true"},+ "output_type": "boolean",+ }++ def test_no_access_user_cannot_list_or_create_evaluations(self):+ self.client.force_login(self.no_access_user)++ list_response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")+ assert list_response.status_code == status.HTTP_403_FORBIDDEN++ create_response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/", self._create_payload(), format="json"+ )+ assert create_response.status_code == status.HTTP_403_FORBIDDEN+ assert Evaluation.objects.count() == 0++ def test_viewer_user_can_read_but_not_write_evaluations(self):+ evaluation = self._create_evaluation()+ self.client.force_login(self.viewer_user)++ list_response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")+ assert list_response.status_code == status.HTTP_200_OK+ assert len(list_response.json()["results"]) == 1++ retrieve_response = self.client.get(f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/")+ assert retrieve_response.status_code == status.HTTP_200_OK++ create_response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/", self._create_payload(), format="json"+ )+ assert create_response.status_code == status.HTTP_403_FORBIDDEN+ assert Evaluation.objects.count() == 1++ edit_response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",+ {"name": "Renamed by viewer"},+ format="json",+ )+ assert edit_response.status_code == status.HTTP_403_FORBIDDEN+ evaluation.refresh_from_db()+ assert evaluation.name == "Existing Evaluation"++ def test_editor_user_can_create_and_edit_evaluations(self):+ self.client.force_login(self.editor_user)++ create_response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/", self._create_payload(), format="json"+ )+ assert create_response.status_code == status.HTTP_201_CREATED+ evaluation_id = create_response.json()["id"]++ edit_response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{evaluation_id}/",+ {"name": "Renamed by editor"},+ format="json",+ )+ assert edit_response.status_code == status.HTTP_200_OK+ assert edit_response.json()["name"] == "Renamed by editor"++ def test_viewer_cannot_soft_delete_evaluation(self):+ # DELETE is 405 (ForbidDestroyModel), so deletion goes through a `deleted` patch.+ evaluation = self._create_evaluation()+ self.client.force_login(self.viewer_user)++ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/", {"deleted": True}, format="json"+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ evaluation.refresh_from_db()+ assert evaluation.deleted is False++ def test_retrieve_exposes_user_access_level(self):+ evaluation = self._create_evaluation()+ self.client.force_login(self.viewer_user)++ response = self.client.get(f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["user_access_level"] == "viewer"++ def test_object_level_grant_scopes_list_to_that_evaluation(self):+ visible = self._create_evaluation("Visible")+ self._create_evaluation("Hidden")+ self._grant(self.no_access_user, "viewer", resource_id=str(visible.id))+ self.client.force_login(self.no_access_user)++ response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert [result["name"] for result in results] == ["Visible"]++ @patch("products.ai_observability.backend.api.evaluations.query_ai_events")+ def test_object_level_grant_does_not_authorize_team_wide_hog_preview(self, mock_query) -> None:+ visible = self._create_evaluation("Visible")+ self._grant(self.no_access_user, "viewer", resource_id=str(visible.id))+ self.client.force_login(self.no_access_user)++ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/test_hog/",+ {"source": "return true"},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_query.assert_not_called()++ def test_llm_analytics_grant_no_longer_implies_evaluation_access(self):+ # Regression guard for removing "evaluation" from RESOURCE_INHERITANCE_MAP.+ self._grant(self.no_access_user, "editor", resource="llm_analytics")+ self.client.force_login(self.no_access_user)++ response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")++ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_model_picker_stays_on_llm_analytics_resource(self):+ # LLMModelsViewSet is shared with the taggers and playground pickers, so it must not+ # require evaluation access.+ self._grant(self.no_access_user, "viewer", resource="llm_analytics")+ self.client.force_login(self.no_access_user)++ response = self.client.get(f"/api/projects/{self.team.id}/llm_analytics/models/?provider=openai")++ assert response.status_code == status.HTTP_200_OKdiff --git a/products/ai_observability/backend/api/test/test_offline_evaluations.py b/products/ai_observability/backend/api/test/test_offline_evaluations.pyindex ddb45c8c3a5f..d5050110abb0 100644--- a/products/ai_observability/backend/api/test/test_offline_evaluations.py+++ b/products/ai_observability/backend/api/test/test_offline_evaluations.py@@ -7,6 +7,14 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User++from products.ai_observability.backend.models.evaluations import Evaluation++from ee.models.rbac.access_control import AccessControl+class TestOfflineEvaluationItemsEndpoint(APIBaseTest):URL: str = ""@@ -20,6 +28,38 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):response.results = rowsreturn response+ def test_requires_resource_level_evaluation_access(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Visible Eval",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test"},+ output_type="boolean",+ created_by=self.user,+ )+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=other_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team, resource="evaluation", access_level="none", organization_member=membership+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(evaluation.id),+ access_level="viewer",+ organization_member=membership,+ )+ self.client.force_login(other_user)++ response = self.client.post(self.URL, {"experiment_id": "unrelated"}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN+def _preflight_row(self,item_id: str = "item-1",diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.pyindex 95af100235b3..e965c287d73e 100644--- a/products/ai_observability/backend/api/test/test_provider_keys.py+++ b/products/ai_observability/backend/api/test/test_provider_keys.py@@ -6,8 +6,10 @@ from unittest.mock import patchfrom django.core.cache import cachefrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import status+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, OrganizationMembership, Project, Team, Userfrom products.ai_observability.backend.api.proxy import models_cache_key@@ -18,6 +20,8 @@ from products.ai_observability.backend.models.model_configuration import LLMModefrom products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom products.ai_observability.backend.models.taggers import Tagger+from ee.models.rbac.access_control import AccessControl+def _setup_team():org = Organization.objects.create(name="test")@@ -41,6 +45,36 @@ def _setup_team():return team+def _grant_provider_key_management_without_evaluation_access(team: Team, membership: OrganizationMembership) -> None:+ organization = membership.organization+ organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ organization.save()+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()+ AccessControl.objects.create(+ team=team,+ resource="project",+ resource_id=str(team.id),+ access_level="admin",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=team,+ resource="llm_analytics",+ access_level="editor",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=team,+ resource="evaluation",+ access_level="none",+ organization_member=membership,+ )++class TestLLMProviderKeyViewSet(APIBaseTest):def setUp(self):super().setUp()@@ -91,6 +125,20 @@ class TestLLMProviderKeyViewSet(APIBaseTest):config = EvaluationConfig.objects.get(team=self.team)self.assertEqual(config.active_provider_key, key)+ @patch("products.ai_observability.backend.api.provider_keys.validate_provider_key")+ def test_cannot_create_active_provider_key_without_evaluation_access(self, mock_validate):+ mock_validate.return_value = (LLMProviderKey.State.OK, None)+ _grant_provider_key_management_without_evaluation_access(self.team, self.organization_membership)++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/provider_keys/",+ {"provider": "openai", "name": "My Key", "api_key": "sk-test-key-12345", "set_as_active": True},+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertFalse(LLMProviderKey.objects.exists())+ self.assertFalse(EvaluationConfig.objects.exists())+def test_api_key_required_on_create(self):response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/provider_keys/",@@ -1071,6 +1119,162 @@ class TestLLMProviderKeyDependentConfigs(APIBaseTest):config.refresh_from_db()self.assertEqual(config.active_provider_key, key2)+ def test_cannot_replace_active_key_without_evaluation_access(self):+ _grant_provider_key_management_without_evaluation_access(self.team, self.organization_membership)+ active_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Active Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-active"},+ created_by=self.user,+ )+ replacement_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Replacement Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-replacement"},+ created_by=self.user,+ )+ config = EvaluationConfig.objects.create(team=self.team, active_provider_key=active_key)++ response = self.client.delete(+ f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{active_key.id}/"+ f"?replacement_key_id={replacement_key.id}"+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ config.refresh_from_db()+ self.assertEqual(config.active_provider_key, active_key)+ self.assertTrue(LLMProviderKey.objects.filter(id=active_key.id).exists())++ @parameterized.expand([(False,), (True,)])+ def test_cannot_delete_active_key_pinned_to_denied_evaluation(self, use_replacement: bool):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="admin",+ organization_member=self.organization_membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ access_level="editor",+ organization_member=self.organization_membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ access_level="editor",+ organization_member=self.organization_membership,+ )+ active_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Active Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-active"},+ created_by=self.user,+ )+ replacement_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Replacement Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-replacement"},+ created_by=self.user,+ )+ model_config = LLMModelConfiguration.objects.create(+ team=self.team,+ provider="openai",+ model="gpt-5-mini",+ provider_key=active_key,+ )+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Restricted Evaluation",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "Is this good?"},+ output_type="boolean",+ model_configuration=model_config,+ enabled=True,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(evaluation.id),+ access_level="none",+ organization_member=self.organization_membership,+ )+ config = EvaluationConfig.objects.create(team=self.team, active_provider_key=active_key)+ url = f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{active_key.id}/"+ if use_replacement:+ url = f"{url}?replacement_key_id={replacement_key.id}"++ response = self.client.delete(url)++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ config.refresh_from_db()+ model_config.refresh_from_db()+ evaluation.refresh_from_db()+ self.assertEqual(config.active_provider_key, active_key)+ self.assertEqual(model_config.provider_key, active_key)+ self.assertEqual(evaluation.status, "active")+ self.assertTrue(LLMProviderKey.objects.filter(id=active_key.id).exists())++ def test_cannot_replace_key_pinned_to_denied_evaluation(self):+ _grant_provider_key_management_without_evaluation_access(self.team, self.organization_membership)+ pinned_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Pinned Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-pinned"},+ created_by=self.user,+ )+ replacement_key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Replacement Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-replacement"},+ created_by=self.user,+ )+ model_config = LLMModelConfiguration.objects.create(+ team=self.team,+ provider="openai",+ model="gpt-5-mini",+ provider_key=pinned_key,+ )+ Evaluation.objects.create(+ team=self.team,+ name="Restricted Evaluation",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "Is this good?"},+ output_type="boolean",+ model_configuration=model_config,+ enabled=True,+ )++ response = self.client.delete(+ f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{pinned_key.id}/"+ f"?replacement_key_id={replacement_key.id}"+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ model_config.refresh_from_db()+ self.assertEqual(model_config.provider_key, pinned_key)+ self.assertTrue(LLMProviderKey.objects.filter(id=pinned_key.id).exists())+def test_delete_non_active_key_with_replacement_keeps_active_key(self):active_key = LLMProviderKey.objects.create(team=self.team,diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 6eea8235e252..51cb437333a2 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -324,8 +324,9 @@ export function AIObservabilityEvaluation(): JSX.Element {</LemonButton>{activeTab !== 'runs' && (<AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={evaluation.user_access_level ?? undefined}><LemonButtontype="primary"@@ -450,6 +451,7 @@ export function AIObservabilityEvaluation(): JSX.Element {content: (<EvaluationReportsTabevaluationId={evaluation.id}+ userAccessLevel={evaluation.user_access_level ?? undefined}onConfigureClick={() => setActiveTab('configuration')}/>),diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsxindex 11396888c358..7364581649fe 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx@@ -203,10 +203,12 @@ function AIObservabilityEvaluationsContent(): JSX.Element {const { searchParams } = useValues(router)const evaluationUrl = (id: string): string => combineUrl(urls.aiObservabilityEvaluation(id), searchParams).urlconst settingsUrl = urls.settings('project-ai-observability', 'ai-observability-byok')- const moveEvaluationDisabledReason = getAccessControlDisabledReason(- AccessControlResourceType.LlmAnalytics,- AccessControlLevel.Editor- )+ const moveEvaluationDisabledReason = (evaluation: EvaluationConfig): string | null =>+ getAccessControlDisabledReason(+ AccessControlResourceType.Evaluation,+ AccessControlLevel.Editor,+ evaluation.user_access_level ?? undefined+ )const filteredEvaluationsWithMetrics = evaluationsWithMetrics.filter((evaluation: EvaluationConfig) =>displayedEvaluations.some((filtered) => filtered.id === evaluation.id)@@ -286,8 +288,9 @@ function AIObservabilityEvaluationsContent(): JSX.Element {return (<div className="flex items-center gap-2"><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={evaluation.user_access_level ?? undefined}><Tooltip title={isBlocked ? blockedReason : undefined}><span>@@ -441,12 +444,13 @@ function AIObservabilityEvaluationsContent(): JSX.Element {icon={<IconFolder />}tooltip="Move evaluation"loading={movingEvaluationId === evaluation.id}- disabledReason={moveEvaluationDisabledReason}+ disabledReason={moveEvaluationDisabledReason(evaluation)}/></LemonMenu><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={evaluation.user_access_level ?? undefined}><LemonButtonsize="small"@@ -456,8 +460,9 @@ function AIObservabilityEvaluationsContent(): JSX.Element {/></AccessControlAction><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={evaluation.user_access_level ?? undefined}><LemonButtonsize="small"@@ -518,7 +523,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {render: (_, directory) => (<div className="flex justify-end gap-1"><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -530,7 +535,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {/></AccessControlAction><AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -615,7 +620,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {<div className="flex shrink-0 items-center gap-2">{!selectedDirectoryId && (<AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}><LemonButton@@ -629,7 +634,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {</AccessControlAction>)}<AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}+ resourceType={AccessControlResourceType.Evaluation}minAccessLevel={AccessControlLevel.Editor}><LemonButtondiff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsxindex 9a687d1450b5..bc956d26a711 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx@@ -3,14 +3,18 @@ import { useActions, useValues } from 'kea'import { IconInfo } from '@posthog/icons'import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { evaluationReportLogic } from '../evaluationReportLogic'import type { EvaluationReportRun } from '../types'import { EvaluationReportViewer, summarizeEvaluationReportResults } from './EvaluationReportViewer'interface EvaluationReportsTabProps {evaluationId: string+ userAccessLevel?: AccessControlLevel/** Called when the user clicks the "Set up scheduled reports" CTA in the empty state. */onConfigureClick: () => void}@@ -26,7 +30,11 @@ const STATUS_STYLES: Record<failed: { label: 'Failed', type: 'danger' },}-export function EvaluationReportsTab({ evaluationId, onConfigureClick }: EvaluationReportsTabProps): JSX.Element {+export function EvaluationReportsTab({+ evaluationId,+ userAccessLevel,+ onConfigureClick,+}: EvaluationReportsTabProps): JSX.Element {const logic = evaluationReportLogic({ evaluationId })const { reportRuns, reportRunsLoading, reportsLoading, activeReport, generateResultLoading } = useValues(logic)const { generateReport, loadReportRuns } = useActions(logic)@@ -68,14 +76,20 @@ export function EvaluationReportsTab({ evaluationId, onConfigureClick }: Evaluat>Refresh</LemonButton>- <LemonButton- type="primary"- size="small"- onClick={() => generateReport(activeReport.id)}- loading={generateResultLoading}+ <AccessControlAction+ resourceType={AccessControlResourceType.Evaluation}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}>- Generate now- </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => generateReport(activeReport.id)}+ loading={generateResultLoading}+ >+ Generate now+ </LemonButton>+ </AccessControlAction></div>)}</div>diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.test.tsindex e981ee28140d..60161ae1b8da 100644--- a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts@@ -38,6 +38,7 @@ const evaluationApi = (id: string): EvaluationApi => ({hedgehog_config: null,},deleted: false,+ user_access_level: 'editor',})const evaluationReportApi = (id: string, evaluation: string): EvaluationReportApi => ({diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex 01f4f9941301..a42b07a05972 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -5,6 +5,7 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { ActivityScope } from '~/types'import type { TestHogResponseApi } from '../generated/api.schemas'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'@@ -603,6 +604,31 @@ return result`,})})+ describe('sidePanelContext', () => {+ it('scopes the side panel to this evaluation once it loads', async () => {+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ await expectLogic(logic).toMatchValues({+ sidePanelContext: {+ activity_scope: ActivityScope.EVALUATION,+ activity_item_id: 'eval-123',+ access_control_resource: 'evaluation',+ access_control_resource_id: 'eval-123',+ },+ })+ })++ it('stays null while creating a new evaluation', async () => {+ logic = llmEvaluationLogic({ evaluationId: 'new' })+ logic.mount()++ await expectLogic(logic).toMatchValues({ sidePanelContext: null })+ })+ })+describe('modelSelectionRequired', () => {beforeEach(() => {logic = llmEvaluationLogic({ evaluationId: 'eval-123' })diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 5265bd1b5888..a4a69fa684c0 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -8,8 +8,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { MaxContextInput, createMaxContextHelpers } from '~/scenes/max/maxTypes'-import { Breadcrumb } from '~/types'+import { ActivityScope, Breadcrumb } from '~/types'import {evaluationsCreate,@@ -253,6 +254,7 @@ export interface llmEvaluationLogicValues {} | nullselectedModel: stringselectedPickerProviderKeyId: string | null+ sidePanelContext: SidePanelSceneContext | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -433,6 +435,10 @@ export interface llmEvaluationLogicMeta {searchParams: Record<string, any>) => Breadcrumb[]maxContext: (evaluation: EvaluationConfig | null) => MaxContextInput[]+ sidePanelContext: (+ evaluation: EvaluationConfig | null,+ isNewEvaluation: boolean+ ) => SidePanelSceneContext | null}}@@ -1205,6 +1211,19 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([]},],++ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.evaluation, s.isNewEvaluation],+ (evaluation: EvaluationConfig | null, isNewEvaluation: boolean): SidePanelSceneContext | null =>+ evaluation?.id && !isNewEvaluation+ ? {+ activity_scope: ActivityScope.EVALUATION,+ activity_item_id: evaluation.id,+ access_control_resource: 'evaluation',+ access_control_resource_id: evaluation.id,+ }+ : null,+ ],}),urlToAction(({ actions, props, values }) => ({diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex ec3c2ab6dde3..5fc8f8daf41f 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -1,4 +1,4 @@-import { AnyPropertyFilter, UserBasicType } from '~/types'+import { AccessControlLevel, AnyPropertyFilter, UserBasicType } from '~/types'import type {EvaluationReportCitationApi,@@ -86,6 +86,7 @@ export interface BaseEvaluationConfig {updated_at: stringcreated_by?: UserBasicType | nulldeleted?: boolean+ user_access_level?: AccessControlLevel | null}export interface LLMJudgeEvaluation extends BaseEvaluationConfig {diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex ae71c91285ea..aabba7489166 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -863,6 +863,9 @@ export type EvaluationApiTargetConfig =max_age_seconds?: number}+/**+ * An evaluation that scores LLM generations, traces, or sessions.+ */export interface EvaluationApi {readonly id: string/**@@ -919,6 +922,11 @@ export interface EvaluationApi {readonly created_by: UserBasicApi | null/** Set to true to soft-delete the evaluation. */deleted?: boolean+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null}export interface PaginatedEvaluationListApi {@@ -992,6 +1000,9 @@ export type PatchedEvaluationApiTargetConfig =max_age_seconds?: number}+/**+ * An evaluation that scores LLM generations, traces, or sessions.+ */export interface PatchedEvaluationApi {readonly id?: string/**@@ -1048,6 +1059,11 @@ export interface PatchedEvaluationApi {readonly created_by?: UserBasicApi | null/** Set to true to soft-delete the evaluation. */deleted?: boolean+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null}export type TestHogRequestApiConditionsItem = { [key: string]: unknown }diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 09fa62559d15..f3453f2a2027 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -249,179 +249,181 @@ export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 604800export const evaluationsCreateBodyModelConfigurationOneModelMax = 100-export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),- description: zod.string().optional().describe('Optional description of what this evaluation checks.'),- directory_id: zod- .uuid()- .nullish()- .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),- enabled: zod- .boolean()- .optional()- .describe('Whether the evaluation runs automatically on new $ai_generation events.'),- evaluation_type: zod- .enum(['llm_judge', 'hog', 'sentiment'])- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')- .describe(- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"- ),- evaluation_config: zod- .union([- zod.object({- prompt: zod- .string()- .min(1)- .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),- }),- zod.object({- source: zod- .string()- .min(1)- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),- }),- zod.object({- source: zod- .enum(['user_messages'])- .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault)- .describe(- "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."- ),- }),- ])- .optional()- .describe(- "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."- ),- output_type: zod- .enum(['boolean', 'sentiment'])- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')- .describe(- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"- ),- output_config: zod- .object({- allows_na: zod- .boolean()- .default(evaluationsCreateBodyOutputConfigAllowsNaDefault)- .describe('Whether the evaluation can return N\/A for non-applicable generations.'),- })- .optional()- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),- conditions: zod- .array(- zod- .object({- id: zod+export const EvaluationsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),+ description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the evaluation runs automatically on new $ai_generation events.'),+ evaluation_type: zod+ .enum(['llm_judge', 'hog', 'sentiment'])+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')+ .describe(+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"+ ),+ evaluation_config: zod+ .union([+ zod.object({+ prompt: zod.string()- .max(evaluationsCreateBodyConditionsItemIdMax)- .describe('Stable identifier for this condition set.'),- rollout_percentage: zod- .number()- .min(evaluationsCreateBodyConditionsItemRolloutPercentageMin)- .max(evaluationsCreateBodyConditionsItemRolloutPercentageMax)- .default(evaluationsCreateBodyConditionsItemRolloutPercentageDefault)+ .min(1)+ .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),+ }),+ zod.object({+ source: zod+ .string()+ .min(1)+ .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),+ }),+ zod.object({+ source: zod+ .enum(['user_messages'])+ .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault).describe(- 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."),- properties: zod- .array(zod.record(zod.string(), zod.unknown()))+ }),+ ])+ .optional()+ .describe(+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."+ ),+ output_type: zod+ .enum(['boolean', 'sentiment'])+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')+ .describe(+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"+ ),+ output_config: zod+ .object({+ allows_na: zod+ .boolean()+ .default(evaluationsCreateBodyOutputConfigAllowsNaDefault)+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),+ })+ .optional()+ .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsCreateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsCreateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsCreateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsCreateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe(+ 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'+ ),+ target: zod+ .enum(['generation', 'trace', 'session'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"+ ),+ target_config: zod+ .union([+ zod.object({+ strategy: zod+ .enum(['fixed_window'])+ .describe('Wait a fixed window after the first matching generation, then evaluate.'),+ window_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax).optional().describe(- 'Property filters (event or person) that scope which generations match this condition set.'+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- })- .describe('A trigger condition set controlling which generations an evaluation runs on.')- )- .optional()- .describe(- 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'- ),- target: zod- .enum(['generation', 'trace', 'session'])- .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')- .optional()- .describe(- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"- ),- target_config: zod- .union([- zod.object({- strategy: zod- .enum(['fixed_window'])- .describe('Wait a fixed window after the first matching generation, then evaluate.'),- window_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)- .max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax)- .optional()- .describe(- "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- zod.object({- strategy: zod- .enum(['inactivity'])- .describe('Evaluate once the unit has had no new activity for the quiet period.'),- quiet_period_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)- .max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)- .optional()- .describe(- "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- max_age_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)- .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)- .optional()- .describe(- "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- ])- .optional()- .describe(- "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."- ),- model_configuration: zod- .union([- zod- .object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])+ }),+ zod.object({+ strategy: zod+ .enum(['inactivity'])+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),+ quiet_period_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)+ .max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)+ .optional().describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."),- model: zod.string().max(evaluationsCreateBodyModelConfigurationOneModelMax),- provider_key_id: zod- .uuid()- .nullish()+ max_age_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)+ .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)+ .optional().describe(- 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- provider_key_name: zod.string().nullable(),- })- .describe('Nested serializer for model configuration.'),- zod.null(),- ])- .optional()- .describe(- 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'- ),- deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),-})+ }),+ ])+ .optional()+ .describe(+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."+ ),+ model_configuration: zod+ .union([+ zod+ .object({+ provider: zod+ .enum([+ 'openai',+ 'anthropic',+ 'gemini',+ 'openrouter',+ 'fireworks',+ 'azure_openai',+ 'together_ai',+ 'minimax',+ 'zeabur',+ ])+ .describe(+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ ),+ model: zod.string().max(evaluationsCreateBodyModelConfigurationOneModelMax),+ provider_key_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ ),+ provider_key_name: zod.string().nullable(),+ })+ .describe('Nested serializer for model configuration.'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'+ ),+ deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),+ })+ .describe('An evaluation that scores LLM generations, traces, or sessions.')export const evaluationsUpdateBodyNameMax = 400@@ -444,179 +446,181 @@ export const evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 604800export const evaluationsUpdateBodyModelConfigurationOneModelMax = 100-export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(evaluationsUpdateBodyNameMax).describe('Name of the evaluation.'),- description: zod.string().optional().describe('Optional description of what this evaluation checks.'),- directory_id: zod- .uuid()- .nullish()- .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),- enabled: zod- .boolean()- .optional()- .describe('Whether the evaluation runs automatically on new $ai_generation events.'),- evaluation_type: zod- .enum(['llm_judge', 'hog', 'sentiment'])- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')- .describe(- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"- ),- evaluation_config: zod- .union([- zod.object({- prompt: zod- .string()- .min(1)- .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),- }),- zod.object({- source: zod- .string()- .min(1)- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),- }),- zod.object({- source: zod- .enum(['user_messages'])- .default(evaluationsUpdateBodyEvaluationConfigThreeSourceDefault)- .describe(- "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."- ),- }),- ])- .optional()- .describe(- "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."- ),- output_type: zod- .enum(['boolean', 'sentiment'])- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')- .describe(- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"- ),- output_config: zod- .object({- allows_na: zod- .boolean()- .default(evaluationsUpdateBodyOutputConfigAllowsNaDefault)- .describe('Whether the evaluation can return N\/A for non-applicable generations.'),- })- .optional()- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),- conditions: zod- .array(- zod- .object({- id: zod+export const EvaluationsUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(evaluationsUpdateBodyNameMax).describe('Name of the evaluation.'),+ description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the evaluation runs automatically on new $ai_generation events.'),+ evaluation_type: zod+ .enum(['llm_judge', 'hog', 'sentiment'])+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')+ .describe(+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"+ ),+ evaluation_config: zod+ .union([+ zod.object({+ prompt: zod.string()- .max(evaluationsUpdateBodyConditionsItemIdMax)- .describe('Stable identifier for this condition set.'),- rollout_percentage: zod- .number()- .min(evaluationsUpdateBodyConditionsItemRolloutPercentageMin)- .max(evaluationsUpdateBodyConditionsItemRolloutPercentageMax)- .default(evaluationsUpdateBodyConditionsItemRolloutPercentageDefault)+ .min(1)+ .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),+ }),+ zod.object({+ source: zod+ .string()+ .min(1)+ .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),+ }),+ zod.object({+ source: zod+ .enum(['user_messages'])+ .default(evaluationsUpdateBodyEvaluationConfigThreeSourceDefault).describe(- 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."),- properties: zod- .array(zod.record(zod.string(), zod.unknown()))+ }),+ ])+ .optional()+ .describe(+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."+ ),+ output_type: zod+ .enum(['boolean', 'sentiment'])+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')+ .describe(+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"+ ),+ output_config: zod+ .object({+ allows_na: zod+ .boolean()+ .default(evaluationsUpdateBodyOutputConfigAllowsNaDefault)+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),+ })+ .optional()+ .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsUpdateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsUpdateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsUpdateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsUpdateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe(+ 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'+ ),+ target: zod+ .enum(['generation', 'trace', 'session'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"+ ),+ target_config: zod+ .union([+ zod.object({+ strategy: zod+ .enum(['fixed_window'])+ .describe('Wait a fixed window after the first matching generation, then evaluate.'),+ window_seconds: zod+ .number()+ .min(evaluationsUpdateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsUpdateBodyTargetConfigOneWindowSecondsMax).optional().describe(- 'Property filters (event or person) that scope which generations match this condition set.'+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- })- .describe('A trigger condition set controlling which generations an evaluation runs on.')- )- .optional()- .describe(- 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'- ),- target: zod- .enum(['generation', 'trace', 'session'])- .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')- .optional()- .describe(- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"- ),- target_config: zod- .union([- zod.object({- strategy: zod- .enum(['fixed_window'])- .describe('Wait a fixed window after the first matching generation, then evaluate.'),- window_seconds: zod- .number()- .min(evaluationsUpdateBodyTargetConfigOneWindowSecondsMin)- .max(evaluationsUpdateBodyTargetConfigOneWindowSecondsMax)- .optional()- .describe(- "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- zod.object({- strategy: zod- .enum(['inactivity'])- .describe('Evaluate once the unit has had no new activity for the quiet period.'),- quiet_period_seconds: zod- .number()- .min(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)- .max(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)- .optional()- .describe(- "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- max_age_seconds: zod- .number()- .min(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin)- .max(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax)- .optional()- .describe(- "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- ])- .optional()- .describe(- "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."- ),- model_configuration: zod- .union([- zod- .object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])+ }),+ zod.object({+ strategy: zod+ .enum(['inactivity'])+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),+ quiet_period_seconds: zod+ .number()+ .min(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)+ .max(evaluationsUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)+ .optional().describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."),- model: zod.string().max(evaluationsUpdateBodyModelConfigurationOneModelMax),- provider_key_id: zod- .uuid()- .nullish()+ max_age_seconds: zod+ .number()+ .min(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMin)+ .max(evaluationsUpdateBodyTargetConfigTwoMaxAgeSecondsMax)+ .optional().describe(- 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- provider_key_name: zod.string().nullable(),- })- .describe('Nested serializer for model configuration.'),- zod.null(),- ])- .optional()- .describe(- 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'- ),- deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),-})+ }),+ ])+ .optional()+ .describe(+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."+ ),+ model_configuration: zod+ .union([+ zod+ .object({+ provider: zod+ .enum([+ 'openai',+ 'anthropic',+ 'gemini',+ 'openrouter',+ 'fireworks',+ 'azure_openai',+ 'together_ai',+ 'minimax',+ 'zeabur',+ ])+ .describe(+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ ),+ model: zod.string().max(evaluationsUpdateBodyModelConfigurationOneModelMax),+ provider_key_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ ),+ provider_key_name: zod.string().nullable(),+ })+ .describe('Nested serializer for model configuration.'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'+ ),+ deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),+ })+ .describe('An evaluation that scores LLM generations, traces, or sessions.')export const evaluationsPartialUpdateBodyNameMax = 400@@ -639,181 +643,183 @@ export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 60480export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100-export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),- description: zod.string().optional().describe('Optional description of what this evaluation checks.'),- directory_id: zod- .uuid()- .nullish()- .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),- enabled: zod- .boolean()- .optional()- .describe('Whether the evaluation runs automatically on new $ai_generation events.'),- evaluation_type: zod- .enum(['llm_judge', 'hog', 'sentiment'])- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')- .optional()- .describe(- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"- ),- evaluation_config: zod- .union([- zod.object({- prompt: zod- .string()- .min(1)- .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),- }),- zod.object({- source: zod- .string()- .min(1)- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),- }),- zod.object({- source: zod- .enum(['user_messages'])- .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault)- .describe(- "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."- ),- }),- ])- .optional()- .describe(- "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."- ),- output_type: zod- .enum(['boolean', 'sentiment'])- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')- .optional()- .describe(- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"- ),- output_config: zod- .object({- allows_na: zod- .boolean()- .default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)- .describe('Whether the evaluation can return N\/A for non-applicable generations.'),- })- .optional()- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),- conditions: zod- .array(- zod- .object({- id: zod+export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),+ description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the evaluation runs automatically on new $ai_generation events.'),+ evaluation_type: zod+ .enum(['llm_judge', 'hog', 'sentiment'])+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')+ .optional()+ .describe(+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"+ ),+ evaluation_config: zod+ .union([+ zod.object({+ prompt: zod.string()- .max(evaluationsPartialUpdateBodyConditionsItemIdMax)- .describe('Stable identifier for this condition set.'),- rollout_percentage: zod- .number()- .min(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin)- .max(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax)- .default(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault)+ .min(1)+ .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),+ }),+ zod.object({+ source: zod+ .string()+ .min(1)+ .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),+ }),+ zod.object({+ source: zod+ .enum(['user_messages'])+ .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault).describe(- 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."),- properties: zod- .array(zod.record(zod.string(), zod.unknown()))+ }),+ ])+ .optional()+ .describe(+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."+ ),+ output_type: zod+ .enum(['boolean', 'sentiment'])+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')+ .optional()+ .describe(+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"+ ),+ output_config: zod+ .object({+ allows_na: zod+ .boolean()+ .default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),+ })+ .optional()+ .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsPartialUpdateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe(+ 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'+ ),+ target: zod+ .enum(['generation', 'trace', 'session'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"+ ),+ target_config: zod+ .union([+ zod.object({+ strategy: zod+ .enum(['fixed_window'])+ .describe('Wait a fixed window after the first matching generation, then evaluate.'),+ window_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax).optional().describe(- 'Property filters (event or person) that scope which generations match this condition set.'+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- })- .describe('A trigger condition set controlling which generations an evaluation runs on.')- )- .optional()- .describe(- 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'- ),- target: zod- .enum(['generation', 'trace', 'session'])- .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')- .optional()- .describe(- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"- ),- target_config: zod- .union([- zod.object({- strategy: zod- .enum(['fixed_window'])- .describe('Wait a fixed window after the first matching generation, then evaluate.'),- window_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax)- .optional()- .describe(- "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- zod.object({- strategy: zod- .enum(['inactivity'])- .describe('Evaluate once the unit has had no new activity for the quiet period.'),- quiet_period_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)- .optional()- .describe(- "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- max_age_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)- .optional()- .describe(- "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- ])- .optional()- .describe(- "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."- ),- model_configuration: zod- .union([- zod- .object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])+ }),+ zod.object({+ strategy: zod+ .enum(['inactivity'])+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),+ quiet_period_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)+ .optional().describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."),- model: zod.string().max(evaluationsPartialUpdateBodyModelConfigurationOneModelMax),- provider_key_id: zod- .uuid()- .nullish()+ max_age_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)+ .optional().describe(- 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- provider_key_name: zod.string().nullable(),- })- .describe('Nested serializer for model configuration.'),- zod.null(),- ])- .optional()- .describe(- 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'- ),- deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),-})+ }),+ ])+ .optional()+ .describe(+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."+ ),+ model_configuration: zod+ .union([+ zod+ .object({+ provider: zod+ .enum([+ 'openai',+ 'anthropic',+ 'gemini',+ 'openrouter',+ 'fireworks',+ 'azure_openai',+ 'together_ai',+ 'minimax',+ 'zeabur',+ ])+ .describe(+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ ),+ model: zod.string().max(evaluationsPartialUpdateBodyModelConfigurationOneModelMax),+ provider_key_id: zod+ .uuid()+ .nullish()+ .describe(+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ ),+ provider_key_name: zod.string().nullable(),+ })+ .describe('Nested serializer for model configuration.'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'+ ),+ deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),+ })+ .describe('An evaluation that scores LLM generations, traces, or sessions.')/*** Test Hog evaluation code against sample events without saving.diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsxindex a980b5dad963..19f2e1dcc568 100644--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx@@ -127,6 +127,7 @@ describe('AIObservabilitySelfDriving', () => {updated_at: '2024-01-01T00:00:00Z',created_by: null,deleted: false,+ user_access_level: 'editor',},{id: 'evaluation-disabled',@@ -147,6 +148,7 @@ describe('AIObservabilitySelfDriving', () => {updated_at: '2024-01-02T00:00:00Z',created_by: null,deleted: false,+ user_access_level: 'editor',},],})diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex ad1e318adf3e..f33b31299907 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -640,7 +640,7 @@ tools:operation: llm_analytics_evaluation_reports_createenabled: truescopes:- - llm_analytics:write+ - evaluation:writeannotations:readOnly: falsedestructive: false@@ -680,7 +680,7 @@ tools:operation: llm_analytics_evaluation_reports_generate_createenabled: truescopes:- - llm_analytics:write+ - evaluation:writeannotations:readOnly: falsedestructive: false@@ -695,7 +695,7 @@ tools:operation: llm_analytics_evaluation_reports_retrieveenabled: truescopes:- - llm_analytics:read+ - evaluation:readannotations:readOnly: truedestructive: false@@ -708,7 +708,7 @@ tools:operation: llm_analytics_evaluation_reports_listenabled: truescopes:- - llm_analytics:read+ - evaluation:readannotations:readOnly: truedestructive: false@@ -722,7 +722,7 @@ tools:operation: llm_analytics_evaluation_reports_runs_listenabled: truescopes:- - llm_analytics:read+ - evaluation:readannotations:readOnly: truedestructive: false@@ -736,7 +736,7 @@ tools:operation: llm_analytics_evaluation_reports_partial_updateenabled: truescopes:- - llm_analytics:write+ - evaluation:writeannotations:readOnly: falsedestructive: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 75284dc080e7..012780a5072e 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6157,7 +6157,7 @@"feature": "llm_analytics","summary": "Create evaluation report config","title": "Create evaluation report config",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6171,7 +6171,7 @@"feature": "llm_analytics","summary": "Trigger evaluation report generation","title": "Trigger evaluation report generation",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -6185,7 +6185,7 @@"feature": "llm_analytics","summary": "Get evaluation report config","title": "Get evaluation report config",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6199,7 +6199,7 @@"feature": "llm_analytics","summary": "List evaluation report configs","title": "List evaluation report configs",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6213,7 +6213,7 @@"feature": "llm_analytics","summary": "List evaluation report runs","title": "List evaluation report runs",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6227,7 +6227,7 @@"feature": "llm_analytics","summary": "Update evaluation report config","title": "Update evaluation report config",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": true,diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f68018408bd7..3501ec3f7266 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6354,7 +6354,7 @@"feature": "llm_analytics","summary": "Create evaluation report config","title": "Create evaluation report config",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6368,7 +6368,7 @@"feature": "llm_analytics","summary": "Trigger evaluation report generation","title": "Trigger evaluation report generation",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -6382,7 +6382,7 @@"feature": "llm_analytics","summary": "Get evaluation report config","title": "Get evaluation report config",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6396,7 +6396,7 @@"feature": "llm_analytics","summary": "List evaluation report configs","title": "List evaluation report configs",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6410,7 +6410,7 @@"feature": "llm_analytics","summary": "List evaluation report runs","title": "List evaluation report runs",- "required_scopes": ["llm_analytics:read"],+ "required_scopes": ["evaluation:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -6424,7 +6424,7 @@"feature": "llm_analytics","summary": "Update evaluation report config","title": "Update evaluation report config",- "required_scopes": ["llm_analytics:write"],+ "required_scopes": ["evaluation:write"],"annotations": {"destructiveHint": false,"idempotentHint": true,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a7d8d69538f5..9cd04248a134 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31474,6 +31474,9 @@ export namespace Schemas {readonly provider_key_name: string | null;}+ /**+ * An evaluation that scores LLM generations, traces, or sessions.+ */export interface Evaluation {readonly id: string;/**@@ -31530,6 +31533,11 @@ export namespace Schemas {readonly created_by: UserBasic | null;/** Set to true to soft-delete the evaluation. */deleted?: boolean;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level: string | null;}/**@@ -58979,6 +58987,9 @@ export namespace Schemas {max_age_seconds?: number;};+ /**+ * An evaluation that scores LLM generations, traces, or sessions.+ */export interface PatchedEvaluation {readonly id?: string;/**@@ -59035,6 +59046,11 @@ export namespace Schemas {readonly created_by?: UserBasic | null;/** Set to true to soft-delete the evaluation. */deleted?: boolean;+ /**+ * The effective access level the user has for this object+ * @nullable+ */+ readonly user_access_level?: string | null;}export interface PatchedEvaluationDirectory {diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 0ae60fa3693b..7bc393a1aff8 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -579,179 +579,181 @@ export const evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax = 604800export const evaluationsCreateBodyModelConfigurationOneModelMax = 100-export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),- description: zod.string().optional().describe('Optional description of what this evaluation checks.'),- directory_id: zod- .string()- .nullish()- .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),- enabled: zod- .boolean()- .optional()- .describe('Whether the evaluation runs automatically on new $ai_generation events.'),- evaluation_type: zod- .enum(['llm_judge', 'hog', 'sentiment'])- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')- .describe(- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"- ),- evaluation_config: zod- .union([- zod.object({- prompt: zod- .string()- .min(1)- .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),- }),- zod.object({- source: zod- .string()- .min(1)- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),- }),- zod.object({- source: zod- .enum(['user_messages'])- .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault)- .describe(- "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."- ),- }),- ])- .optional()- .describe(- "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."- ),- output_type: zod- .enum(['boolean', 'sentiment'])- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')- .describe(- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"- ),- output_config: zod- .object({- allows_na: zod- .boolean()- .default(evaluationsCreateBodyOutputConfigAllowsNaDefault)- .describe('Whether the evaluation can return N\/A for non-applicable generations.'),- })- .optional()- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),- conditions: zod- .array(- zod- .object({- id: zod+export const EvaluationsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),+ description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .string()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the evaluation runs automatically on new $ai_generation events.'),+ evaluation_type: zod+ .enum(['llm_judge', 'hog', 'sentiment'])+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')+ .describe(+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"+ ),+ evaluation_config: zod+ .union([+ zod.object({+ prompt: zod.string()- .max(evaluationsCreateBodyConditionsItemIdMax)- .describe('Stable identifier for this condition set.'),- rollout_percentage: zod- .number()- .min(evaluationsCreateBodyConditionsItemRolloutPercentageMin)- .max(evaluationsCreateBodyConditionsItemRolloutPercentageMax)- .default(evaluationsCreateBodyConditionsItemRolloutPercentageDefault)+ .min(1)+ .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),+ }),+ zod.object({+ source: zod+ .string()+ .min(1)+ .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),+ }),+ zod.object({+ source: zod+ .enum(['user_messages'])+ .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault).describe(- 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."),- properties: zod- .array(zod.record(zod.string(), zod.unknown()))+ }),+ ])+ .optional()+ .describe(+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."+ ),+ output_type: zod+ .enum(['boolean', 'sentiment'])+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')+ .describe(+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"+ ),+ output_config: zod+ .object({+ allows_na: zod+ .boolean()+ .default(evaluationsCreateBodyOutputConfigAllowsNaDefault)+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),+ })+ .optional()+ .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsCreateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsCreateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsCreateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsCreateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe(+ 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'+ ),+ target: zod+ .enum(['generation', 'trace', 'session'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"+ ),+ target_config: zod+ .union([+ zod.object({+ strategy: zod+ .enum(['fixed_window'])+ .describe('Wait a fixed window after the first matching generation, then evaluate.'),+ window_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax).optional().describe(- 'Property filters (event or person) that scope which generations match this condition set.'+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- })- .describe('A trigger condition set controlling which generations an evaluation runs on.')- )- .optional()- .describe(- 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'- ),- target: zod- .enum(['generation', 'trace', 'session'])- .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')- .optional()- .describe(- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"- ),- target_config: zod- .union([- zod.object({- strategy: zod- .enum(['fixed_window'])- .describe('Wait a fixed window after the first matching generation, then evaluate.'),- window_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigOneWindowSecondsMin)- .max(evaluationsCreateBodyTargetConfigOneWindowSecondsMax)- .optional()- .describe(- "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- zod.object({- strategy: zod- .enum(['inactivity'])- .describe('Evaluate once the unit has had no new activity for the quiet period.'),- quiet_period_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)- .max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)- .optional()- .describe(- "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- max_age_seconds: zod- .number()- .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)- .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)- .optional()- .describe(- "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- ])- .optional()- .describe(- "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."- ),- model_configuration: zod- .union([- zod- .object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])+ }),+ zod.object({+ strategy: zod+ .enum(['inactivity'])+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),+ quiet_period_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMin)+ .max(evaluationsCreateBodyTargetConfigTwoQuietPeriodSecondsMax)+ .optional().describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."),- model: zod.string().max(evaluationsCreateBodyModelConfigurationOneModelMax),- provider_key_id: zod- .string()- .nullish()+ max_age_seconds: zod+ .number()+ .min(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMin)+ .max(evaluationsCreateBodyTargetConfigTwoMaxAgeSecondsMax)+ .optional().describe(- 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- provider_key_name: zod.string().nullish(),- })- .describe('Nested serializer for model configuration.'),- zod.null(),- ])- .optional()- .describe(- 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'- ),- deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),-})+ }),+ ])+ .optional()+ .describe(+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."+ ),+ model_configuration: zod+ .union([+ zod+ .object({+ provider: zod+ .enum([+ 'openai',+ 'anthropic',+ 'gemini',+ 'openrouter',+ 'fireworks',+ 'azure_openai',+ 'together_ai',+ 'minimax',+ 'zeabur',+ ])+ .describe(+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ ),+ model: zod.string().max(evaluationsCreateBodyModelConfigurationOneModelMax),+ provider_key_id: zod+ .string()+ .nullish()+ .describe(+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ ),+ provider_key_name: zod.string().nullish(),+ })+ .describe('Nested serializer for model configuration.'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'+ ),+ deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),+ })+ .describe('An evaluation that scores LLM generations, traces, or sessions.')export const EvaluationsRetrieveParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this evaluation.'),@@ -792,181 +794,183 @@ export const evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax = 60480export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100-export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),- description: zod.string().optional().describe('Optional description of what this evaluation checks.'),- directory_id: zod- .string()- .nullish()- .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),- enabled: zod- .boolean()- .optional()- .describe('Whether the evaluation runs automatically on new $ai_generation events.'),- evaluation_type: zod- .enum(['llm_judge', 'hog', 'sentiment'])- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')- .optional()- .describe(- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"- ),- evaluation_config: zod- .union([- zod.object({- prompt: zod- .string()- .min(1)- .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),- }),- zod.object({- source: zod- .string()- .min(1)- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),- }),- zod.object({- source: zod- .enum(['user_messages'])- .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault)- .describe(- "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."- ),- }),- ])- .optional()- .describe(- "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."- ),- output_type: zod- .enum(['boolean', 'sentiment'])- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')- .optional()- .describe(- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"- ),- output_config: zod- .object({- allows_na: zod- .boolean()- .default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)- .describe('Whether the evaluation can return N\/A for non-applicable generations.'),- })- .optional()- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),- conditions: zod- .array(- zod- .object({- id: zod+export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),+ description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .string()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),+ enabled: zod+ .boolean()+ .optional()+ .describe('Whether the evaluation runs automatically on new $ai_generation events.'),+ evaluation_type: zod+ .enum(['llm_judge', 'hog', 'sentiment'])+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')+ .optional()+ .describe(+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment (trained on English, so use 'llm_judge' for multilingual agents).\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"+ ),+ evaluation_config: zod+ .union([+ zod.object({+ prompt: zod.string()- .max(evaluationsPartialUpdateBodyConditionsItemIdMax)- .describe('Stable identifier for this condition set.'),- rollout_percentage: zod- .number()- .min(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin)- .max(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax)- .default(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault)+ .min(1)+ .describe('Evaluation criteria for the LLM judge. Describe what makes a good vs bad response.'),+ }),+ zod.object({+ source: zod+ .string()+ .min(1)+ .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),+ }),+ zod.object({+ source: zod+ .enum(['user_messages'])+ .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault).describe(- 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ "Classify sentiment from user messages in the generation input. The classifier is trained on English, so labels are unreliable for other languages; use an 'llm_judge' evaluation for multilingual agents."),- properties: zod- .array(zod.record(zod.string(), zod.unknown()))+ }),+ ])+ .optional()+ .describe(+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."+ ),+ output_type: zod+ .enum(['boolean', 'sentiment'])+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')+ .optional()+ .describe(+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"+ ),+ output_config: zod+ .object({+ allows_na: zod+ .boolean()+ .default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),+ })+ .optional()+ .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),+ conditions: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(evaluationsPartialUpdateBodyConditionsItemIdMax)+ .describe('Stable identifier for this condition set.'),+ rollout_percentage: zod+ .number()+ .min(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMin)+ .max(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageMax)+ .default(evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault)+ .describe(+ 'Percentage (0-100) of matching events to sample for this evaluation. Defaults to 100.'+ ),+ properties: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe(+ 'Property filters (event or person) that scope which generations match this condition set.'+ ),+ })+ .describe('A trigger condition set controlling which generations an evaluation runs on.')+ )+ .optional()+ .describe(+ 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'+ ),+ target: zod+ .enum(['generation', 'trace', 'session'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')+ .optional()+ .describe(+ "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"+ ),+ target_config: zod+ .union([+ zod.object({+ strategy: zod+ .enum(['fixed_window'])+ .describe('Wait a fixed window after the first matching generation, then evaluate.'),+ window_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax).optional().describe(- 'Property filters (event or person) that scope which generations match this condition set.'+ "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- })- .describe('A trigger condition set controlling which generations an evaluation runs on.')- )- .optional()- .describe(- 'Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.'- ),- target: zod- .enum(['generation', 'trace', 'session'])- .describe('\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session')- .optional()- .describe(- "What the evaluation runs on. 'generation' evaluates each matching $ai_generation event individually. 'trace' evaluates the whole trace once and 'session' the whole $ai_session_id session once: the first matching generation schedules a run that waits for the unit to settle, then evaluates all of its events together. Condition filters still match individual generations — a unit is evaluated when any of its generations matches, and sampling applies per unit. A 'session' evaluation only fires for generations that carry $ai_session_id. When and how the run fires is controlled by target_config's settle strategy.\n\n\* `generation` - Generation\n\* `trace` - Trace\n\* `session` - Session"- ),- target_config: zod- .union([- zod.object({- strategy: zod- .enum(['fixed_window'])- .describe('Wait a fixed window after the first matching generation, then evaluate.'),- window_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigOneWindowSecondsMax)- .optional()- .describe(- "Seconds to wait after the first matching generation before evaluating the whole unit. Captured when the run is scheduled — editing it does not change runs already in flight. The accepted range depends on `target`: 10–7200 for 'trace', 10–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- zod.object({- strategy: zod- .enum(['inactivity'])- .describe('Evaluate once the unit has had no new activity for the quiet period.'),- quiet_period_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)- .optional()- .describe(- "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- max_age_seconds: zod- .number()- .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)- .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)- .optional()- .describe(- "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."- ),- }),- ])- .optional()- .describe(- "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."- ),- model_configuration: zod- .union([- zod- .object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])+ }),+ zod.object({+ strategy: zod+ .enum(['inactivity'])+ .describe('Evaluate once the unit has had no new activity for the quiet period.'),+ quiet_period_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigTwoQuietPeriodSecondsMax)+ .optional().describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ "Seconds without new activity before the unit counts as settled. The accepted range depends on `target`: 10–1800 for 'trace', 10–86400 for 'session'. The default also depends on `target`; see the field-level help_text."),- model: zod.string().max(evaluationsPartialUpdateBodyModelConfigurationOneModelMax),- provider_key_id: zod- .string()- .nullish()+ max_age_seconds: zod+ .number()+ .min(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMin)+ .max(evaluationsPartialUpdateBodyTargetConfigTwoMaxAgeSecondsMax)+ .optional().describe(- 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ "Hard cap in seconds on the total wait from the first matching generation, even if the unit stays active. Must be at least quiet_period_seconds. The accepted range depends on `target`: 60–7200 for 'trace', 60–604800 for 'session'. The default also depends on `target`; see the field-level help_text."),- provider_key_name: zod.string().nullish(),- })- .describe('Nested serializer for model configuration.'),- zod.null(),- ])- .optional()- .describe(- 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'- ),- deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),-})+ }),+ ])+ .optional()+ .describe(+ "Target-specific config. For 'trace' and 'session' targets: a settle config discriminated on `strategy`, either 'fixed_window' {window_seconds} or 'inactivity' {quiet_period_seconds, max_age_seconds}. Send `strategy` explicitly. The server fills in any other field you omit, using per-target defaults, and the accepted bounds also depend on `target`. Empty for 'generation'."+ ),+ model_configuration: zod+ .union([+ zod+ .object({+ provider: zod+ .enum([+ 'openai',+ 'anthropic',+ 'gemini',+ 'openrouter',+ 'fireworks',+ 'azure_openai',+ 'together_ai',+ 'minimax',+ 'zeabur',+ ])+ .describe(+ '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'+ ),+ model: zod.string().max(evaluationsPartialUpdateBodyModelConfigurationOneModelMax),+ provider_key_id: zod+ .string()+ .nullish()+ .describe(+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'+ ),+ provider_key_name: zod.string().nullish(),+ })+ .describe('Nested serializer for model configuration.'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'+ ),+ deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),+ })+ .describe('An evaluation that scores LLM generations, traces, or sessions.')/*** Hard delete of this model is not allowed. Use a patch API call to set "deleted" to truediff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.jsonindex 2763f8ba56fd..b0c4e6283648 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json@@ -1,5 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "An evaluation that scores LLM generations, traces, or sessions.","properties": {"conditions": {"description": "Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads.",