: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
chore(skills): split the API module by concern (#98597)
posthog[bot]9afb7014a9aa
diff --git a/products/skills/backend/api/skill_analytics.py b/products/skills/backend/api/skill_analytics.pynew file mode 100644index 000000000000..c385d6592dfa--- /dev/null+++ b/products/skills/backend/api/skill_analytics.py@@ -0,0 +1,84 @@+"""The analytics events every skill write reports, and the properties they carry."""++from typing import Any++import structlog+from rest_framework.request import Request++from posthog.event_usage import report_user_action+from posthog.models import Team, User++from ..models.skills import LLMSkill++logger = structlog.get_logger(__name__)+++def record_skill_event(+ *,+ log_event: str,+ action: str,+ user: User,+ team: Team,+ request: Request,+ props: dict[str, Any],+) -> None:+ """Log a skill write and report it as a product event, with the same properties on both."""+ logger.info(log_event, team_id=team.id, user_id=user.id, **props)+ report_user_action(user, action, props, team=team, request=request)+++def file_extension(path: str) -> str:+ return path.rsplit(".", 1)[1].lower() if "." in path else ""+++def skill_analytics_props(skill: LLMSkill) -> dict[str, Any]:+ """Properties shared by every skill report_user_action event.++ These power the internal LLMA skills adoption/usage dashboards — keep stable+ and additive (renaming a key here will rename it on every dashboard).+ """+ file_count = skill.files.count() if skill.pk else 0+ body = skill.body or ""+ description = skill.description or ""+ allowed_tools = skill.allowed_tools or []+ return {+ "skill_id": str(skill.id),+ "skill_name": skill.name,+ "skill_version": skill.version,+ "skill_is_latest": skill.is_latest,+ "skill_body_length": len(body),+ "skill_description_length": len(description),+ "skill_file_count": file_count,+ "skill_has_files": file_count > 0,+ "skill_has_license": bool(skill.license),+ "skill_has_compatibility": bool(skill.compatibility),+ "skill_has_allowed_tools": bool(allowed_tools),+ "skill_allowed_tools_count": len(allowed_tools),+ }+++def publish_analytics_props(+ published_skill: LLMSkill, validated_data: dict[str, Any], *, owners_changed: bool+) -> dict[str, Any]:+ """Which parts of a publish the caller actually sent, alongside the new version's own properties."""+ edits_value = validated_data.get("edits")+ file_edits_value = validated_data.get("file_edits")+ files_value = validated_data.get("files")+ return {+ **skill_analytics_props(published_skill),+ "base_version": validated_data["base_version"],+ "body_changed": validated_data.get("body") is not None or edits_value is not None,+ "files_replaced": files_value is not None,+ "files_replaced_count": len(files_value) if files_value is not None else 0,+ "edits_used": edits_value is not None,+ "edits_count": len(edits_value) if edits_value is not None else 0,+ "file_edits_used": file_edits_value is not None,+ "file_edits_count": len(file_edits_value) if file_edits_value is not None else 0,+ "description_changed": validated_data.get("description") is not None,+ "license_changed": validated_data.get("license") is not None,+ "compatibility_changed": validated_data.get("compatibility") is not None,+ "allowed_tools_changed": validated_data.get("allowed_tools") is not None,+ "metadata_changed": validated_data.get("metadata") is not None,+ "owners_changed": owners_changed,+ "version_description_set": validated_data.get("version_description") is not None,+ }diff --git a/products/skills/backend/api/skill_catalog.py b/products/skills/backend/api/skill_catalog.pynew file mode 100644index 000000000000..b0fcd642b14f--- /dev/null+++ b/products/skills/backend/api/skill_catalog.py@@ -0,0 +1,61 @@+"""The filters and orderings the skill list endpoint offers."""++from typing import Any++from django.db.models import Q, QuerySet+from django.http import QueryDict++from posthog.models import Team++from products.access_control.backend.facade.user_access_control import UserAccessControl++from ..models.skills import LLMSkill+from .skill_services import get_active_skill_queryset, skill_names_owned_by++ALLOWED_LIST_ORDERINGS = frozenset(+ {+ "name",+ "-name",+ "created_at",+ "-created_at",+ "updated_at",+ "-updated_at",+ "version",+ "-version",+ "latest_version",+ "-latest_version",+ "version_count",+ "-version_count",+ }+)+++def list_queryset(+ *, team: Team, user_access_control: UserAccessControl, params: dict[str, Any], query_params: QueryDict+) -> QuerySet[LLMSkill]:+ queryset = user_access_control.filter_queryset_by_access_level(+ get_active_skill_queryset(team), resource="llm_skill"+ ).filter(is_latest=True)++ search = params.get("search", "").strip()+ if search:+ queryset = queryset.filter(Q(name__icontains=search) | Q(description__icontains=search))++ created_by_id = params.get("created_by_id")+ if created_by_id:+ queryset = queryset.filter(created_by_id=created_by_id)++ # Owners are keyed on the logical skill name, not on a version row, so the filter matches by+ # name across every version the queryset could surface.+ owner_id = params.get("owner_id")+ if owner_id:+ queryset = queryset.filter(name__in=skill_names_owned_by(team, owner_id))++ # Presence of the param — even as an empty string — is a filter: `?category=` returns only+ # uncategorized skills, `?category=scout` only scouts. Omitting it returns every category.+ if "category" in query_params:+ queryset = queryset.filter(category=params.get("category") or "")++ order_by = query_params.get("order_by", "-created_at")+ queryset = queryset.order_by(order_by if order_by in ALLOWED_LIST_ORDERINGS else "-created_at", "-id")+ return querysetdiff --git a/products/skills/backend/api/skill_error_responses.py b/products/skills/backend/api/skill_error_responses.pynew file mode 100644index 000000000000..4266bae6f269--- /dev/null+++ b/products/skills/backend/api/skill_error_responses.py@@ -0,0 +1,94 @@+"""The error responses more than one skill endpoint answers with.++Every skill write funnels its service-layer errors through ``skill_write_error_response``, so a+given failure reads the same whichever endpoint hit it.+"""++from collections.abc import Callable+from typing import Any++from rest_framework import status+from rest_framework.response import Response++from .skill_services import (+ LLMSkillDescriptionTooLongError,+ LLMSkillEditError,+ LLMSkillFileLimitError,+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+)+++def skill_not_found_response(skill_name: str) -> Response:+ return Response(+ {"detail": f"Skill with name '{skill_name}' not found."},+ status=status.HTTP_404_NOT_FOUND,+ )+++def version_conflict_response(current_version: int) -> Response:+ return Response(+ {+ "detail": "The skill changed since you opened it. Reload the latest version and try again.",+ "current_version": current_version,+ },+ status=status.HTTP_409_CONFLICT,+ )+++def skill_write_error_response(+ err: Exception,+ skill_name: str,+ *,+ not_found_response: Callable[[str], Response] | None = None,+) -> Response | None:+ """Render a service-layer write error. Returns None for an error with no shared rendering.++ A caller only reaches this for the errors it catches itself, so returning None means the caller+ caught something it has no response for and must re-raise.+ """+ if isinstance(err, LLMSkillNotFoundError):+ return (+ not_found_response(skill_name) if not_found_response is not None else skill_not_found_response(skill_name)+ )+ if isinstance(err, LLMSkillVersionConflictError):+ return version_conflict_response(err.current_version)+ if isinstance(err, LLMSkillVersionLimitError):+ return Response(+ {+ "detail": (+ f"Skill has reached the maximum of {err.max_version} versions. "+ "Archive and recreate the skill to continue publishing."+ ),+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ if isinstance(err, LLMSkillFileLimitError):+ return Response(+ {"detail": f"Skill has reached the maximum of {err.max_count} files."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if isinstance(err, LLMSkillDescriptionTooLongError):+ return Response(+ {+ "detail": (+ f"Shorten the skill description to {err.max_length} characters before creating a new version."+ )+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ if isinstance(err, LLMSkillEditError):+ error_body: dict[str, Any] = {"detail": err.message}+ if err.edit_index is not None:+ error_body["edit_index"] = err.edit_index+ if err.file_path is not None:+ error_body["file_path"] = err.file_path+ return Response(error_body, status=status.HTTP_400_BAD_REQUEST)+ return None+++def spec_problems_detail(lead: str, problems: list[str], next_step: str) -> str:+ # Clients such as the app toast show only `detail`, so the specific problems must live there too.+ sentences = ". ".join((problem[:1].upper() + problem[1:]).removesuffix(".") for problem in problems)+ return f"{lead} {sentences}. {next_step}"diff --git a/products/skills/backend/api/skill_import.py b/products/skills/backend/api/skill_import.pynew file mode 100644index 000000000000..f0538578e72c--- /dev/null+++ b/products/skills/backend/api/skill_import.py@@ -0,0 +1,89 @@+"""The limits an uploaded skill zip must clear before it becomes a skill."""++from collections.abc import Callable, Sequence+from typing import Any++from rest_framework import serializers++from ..marketplace.packaging import SkillExport, SkillFileExport+from .skill_serializers import (+ MAX_SKILL_FILE_BYTES,+ validate_allowed_tool,+ validate_new_skill_name_value,+ validate_skill_body_size,+)+from .skill_services import compute_spec_problems, skill_name_is_well_formed++# Generous ceiling for an uploaded skill zip — per-skill content (body, 200 files × 1 MB) is+# already bounded by create_skill, this just caps the upload before we read it into memory.+MAX_IMPORT_ZIP_BYTES = 10_000_000+++def import_problems(skill_export: SkillExport) -> list[str]:+ """Every reason this zip cannot be imported, as sentences for the caller. Empty == importable.++ The import path calls create_skill directly, so it must re-apply the same size/shape limits the+ create/edit serializers enforce — otherwise a spec-valid zip could persist content (oversized+ body/files, whitespace-bearing tools) the rest of the system assumes is bounded.+ The shared spec rules cover the description, name shape, and bundled-file paths.+ """+ return [+ *_spec_problem_messages(skill_export),+ *_metadata_problems(skill_export),+ *_file_problems(skill_export.files),+ ]+++def _spec_problem_messages(skill_export: SkillExport) -> list[str]:+ """Render the shared packaging problems in the flat format used by API responses."""+ return [+ f"file '{problem.file_path}': {problem.message}" if problem.file_path else problem.message+ for problem in compute_spec_problems(+ skill_export.name,+ skill_export.description,+ [skill_file.path for skill_file in skill_export.files],+ )+ ]+++def _metadata_problems(skill_export: SkillExport) -> list[str]:+ problems: list[str] = []+ # The reserved-name and bundled-name rules are all this adds on top of the shape rules above,+ # so calling it for a malformed name would report that defect twice.+ if skill_name_is_well_formed(skill_export.name):+ problems += _validation_problem("name", validate_new_skill_name_value, skill_export.name)+ problems += _validation_problem("body", validate_skill_body_size, skill_export.body)+ for tool in skill_export.allowed_tools:+ problems += _validation_problem(f"allowed-tools '{tool}'", validate_allowed_tool, tool)+ if len(skill_export.license) > 255:+ problems.append("license must be 255 characters or fewer")+ if len(skill_export.compatibility) > 500:+ problems.append("compatibility must be 500 characters or fewer")+ return problems+++def _file_problems(files: Sequence[SkillFileExport]) -> list[str]:+ problems: list[str] = []+ for skill_file in files:+ # create_skill inserts the files with bulk_create, which runs no model validation, so a+ # path the column cannot hold reaches Postgres as a DataError and fails the request.+ if len(skill_file.path) > 500:+ problems.append(f"file '{skill_file.path}': path must be 500 characters or fewer")+ if len(skill_file.content.encode("utf-8")) > MAX_SKILL_FILE_BYTES:+ problems.append(f"file '{skill_file.path}': content must be {MAX_SKILL_FILE_BYTES} bytes or fewer")+ return problems+++def _validation_problem(label: str, validate: Callable[[Any], Any], value: Any) -> list[str]:+ try:+ validate(value)+ except serializers.ValidationError as err:+ return [f"{label}: {_first_error(err)}"]+ return []+++def _first_error(err: serializers.ValidationError) -> str:+ detail = err.detail+ if isinstance(detail, list) and detail:+ return str(detail[0])+ return str(detail)diff --git a/products/skills/backend/api/skill_permissions.py b/products/skills/backend/api/skill_permissions.pynew file mode 100644index 000000000000..f66ccd62ebf0--- /dev/null+++ b/products/skills/backend/api/skill_permissions.py@@ -0,0 +1,76 @@+"""Permissions that gate publishing a skill to the community marketplace."""++from typing import TYPE_CHECKING, cast++from rest_framework.exceptions import NotFound+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.views import APIView++from .community_skills import CommunitySkillFeatureFlagPermission+from .skill_services import get_skill_by_name_from_db, resolve_skill_owners++if TYPE_CHECKING:+ from .skills import LLMSkillViewSet+++class CommunityPublishFeatureFlagPermission(CommunitySkillFeatureFlagPermission):+ """Gates publishing to the community marketplace, and nothing else on this viewset.++ The Skills product is GA and the marketplace is not, so the flag can only bind to the one action —+ otherwise the whole product goes dark, and without it publish goes live everywhere the moment the+ GitHub App is installed and the 503 fail-safe stops firing.+ """++ def has_permission(self, request, view) -> bool:+ if getattr(view, "action", None) != "publish_to_community":+ return True+ return super().has_permission(request, view)+++class CommunityPublishOwnerPermission(BasePermission):+ """Restricts publishing to the community to the skill's own owners, and gates nothing else here.++ Publishing writes the skill into a public repository, so it asks for a stronger claim on the skill+ than editing it does. The claim must also be per skill. `AccessControlPermission.has_permission`+ passes a member who holds an object-level grant on any one skill, and the `name/<slug>` actions+ then load whichever skill the URL names, so edit access alone reaches every skill in the project.++ A skill with no current owners is publishable by nobody. Owners leave the set when a member loses+ project access, and a skill can be created with an explicit empty owner list, so the alternative is+ a fallback to edit access for exactly the skills that have nobody to answer for them. Adding an+ owner is the remedy, and the message says so.+ """++ NO_OWNERS_MESSAGE = "This skill has no owners. Add an owner to publish it."+ NOT_OWNER_MESSAGE = (+ "Only an owner can publish this skill to the community. Ask an owner to publish it, or to add you as one."+ )++ def has_permission(self, request: Request, view: APIView) -> bool:+ if getattr(view, "action", None) != "publish_to_community":+ return True++ user = request.user+ if not user or not user.is_authenticated:+ return False++ skill_view = cast("LLMSkillViewSet", view)+ try:+ team = skill_view.team+ except (ValueError, KeyError, AttributeError):+ return False++ skill_name = skill_view.kwargs.get("skill_name") or ""+ owners = resolve_skill_owners(team, skill_name)+ if any(owner.pk == user.pk for owner in owners):+ return True++ # A slug that names no skill answers 404, the way every other `name/<slug>` action answers it,+ # because a skill that does not exist has no owners either. Raising here rather than passing+ # keeps the action from loading a skill another request creates in between.+ if get_skill_by_name_from_db(team, skill_name) is None:+ raise NotFound(f"Skill with name '{skill_name}' not found.")++ self.message = self.NO_OWNERS_MESSAGE if not owners else self.NOT_OWNER_MESSAGE+ return Falsediff --git a/products/skills/backend/api/skill_search.py b/products/skills/backend/api/skill_search.pynew file mode 100644index 000000000000..98142aae24b5--- /dev/null+++ b/products/skills/backend/api/skill_search.py@@ -0,0 +1,316 @@+"""The bounded full-text search over a team's skills, and the excerpts it reports."""++import re+from collections.abc import Sequence+from typing import Any, Literal, Protocol, cast++from django.db import OperationalError+from django.db.models import Case, Exists, Expression, IntegerField, OuterRef, Q, QuerySet, Subquery, Value, When+from django.db.models.functions import Coalesce++import psycopg++from posthog.models import Team+from posthog.models.utils import execute_with_timeout++from products.access_control.backend.facade.user_access_control import UserAccessControl++from ..models.skills import LLMSkill, LLMSkillFile++SKILL_SEARCH_RESULT_LIMIT = 10+SKILL_SEARCH_MATCH_LIMIT = 2+SKILL_SEARCH_EXCERPT_LENGTH = 300+SKILL_SEARCH_TIMEOUT_MS = 5_000+SKILL_SEARCH_EXACT_NAME_BONUS = 5_000+SKILL_SEARCH_MAX_TOKENS = 8+SKILL_SEARCH_MIN_TOKEN_LENGTH = 2+SKILL_SEARCH_MIN_STEM_LENGTH = 5+SKILL_SEARCH_DERIVATIONAL_SUFFIXES = ("ations", "ation", "tions", "tion", "ings", "ing", "ed")+SKILL_SEARCH_SIBILANT_ES_ENDINGS = ("ches", "shes", "sses", "xes", "zes")+SkillSearchField = Literal["name", "description", "body", "path", "content"]+SKILL_SEARCH_FIELD_LOOKUPS: dict[SkillSearchField, str] = {+ "name": "name__icontains",+ "description": "description__icontains",+ "body": "body__icontains",+ "path": "path__icontains",+ "content": "content__icontains",+}+++class _ScoredSkill(Protocol):+ search_score: int+++class SkillSearchTimeout(Exception):+ """The search exceeded SKILL_SEARCH_TIMEOUT_MS in the database."""+++def search_skills(team: Team, user_access_control: UserAccessControl, query: str) -> list[dict[str, Any]]:+ """Every readable skill matching the query, best match first, with excerpts.++ Raises SkillSearchTimeout when the query outruns its database timeout. The search spans skill+ bodies and bundled file contents, so a broad query on a large team can reach it.+ """+ try:+ with execute_with_timeout(SKILL_SEARCH_TIMEOUT_MS):+ return [+ {+ "name": skill.name,+ "description": skill.description,+ "score": cast(_ScoredSkill, skill).search_score,+ "matches": search_matches(skill, query),+ }+ for skill in search_queryset(team, user_access_control, query)+ ]+ except OperationalError as err:+ if not isinstance(err.__cause__, psycopg.errors.QueryCanceled):+ raise+ raise SkillSearchTimeout from err+++def search_queryset(team: Team, user_access_control: UserAccessControl, query: str) -> QuerySet[LLMSkill]:+ skill_files = LLMSkillFile.objects.filter(skill_id=OuterRef("pk"))+ tokens = _skill_search_tokens(query)+ matching_skill_files = skill_files.filter(+ _skill_search_field_query("path", query, tokens)+ | (markdown_file_query() & _skill_search_field_query("content", query, tokens))+ )+ file_path_score = Coalesce(+ Subquery(+ skill_files.annotate(score=_skill_search_field_score("path", query, tokens, 120))+ .order_by("-score")+ .values("score")[:1],+ output_field=IntegerField(),+ ),+ Value(0),+ )+ file_content_score = Coalesce(+ Subquery(+ skill_files.filter(markdown_file_query())+ .annotate(score=_skill_search_field_score("content", query, tokens, 40))+ .order_by("-score")+ .values("score")[:1],+ output_field=IntegerField(),+ ),+ Value(0),+ )++ queryset = LLMSkill.objects.filter(+ team=team,+ deleted=False,+ is_latest=True,+ category="",+ )+ queryset = user_access_control.filter_queryset_by_access_level(queryset, resource="llm_skill")+ queryset = queryset.filter(+ _skill_search_field_query("name", query, tokens)+ | _skill_search_field_query("description", query, tokens)+ | _skill_search_field_query("body", query, tokens)+ | Q(Exists(matching_skill_files))+ )++ exact_name_score = Case(+ When(name__iexact=query, then=Value(SKILL_SEARCH_EXACT_NAME_BONUS)),+ default=Value(0),+ output_field=IntegerField(),+ )+ score = (+ exact_name_score+ + _skill_search_field_score("name", query, tokens, 1_000)+ + _skill_search_field_score("description", query, tokens, 300)+ + _skill_search_field_score("body", query, tokens, 80)+ + file_path_score+ + file_content_score+ )+ return queryset.annotate(search_score=score).order_by("-search_score", "name", "id")[:SKILL_SEARCH_RESULT_LIMIT]+++def search_matches(skill: LLMSkill, query: str) -> list[dict[str, Any]]:+ matches: list[dict[str, Any]] = []+ tokens = _skill_search_tokens(query)++ if _skill_search_match_term(skill.name, query, tokens) is not None:+ matches.append({"matched_field": "name", "excerpt": skill.name})+ description_match = _skill_search_match_term(skill.description, query, tokens)+ if description_match is not None:+ match_index = skill.description.lower().find(description_match.lower())+ excerpt_start = max(0, match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)+ matches.append(+ {+ "matched_field": "description",+ "excerpt": skill.description[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH],+ }+ )+ body_match_term = _skill_search_match_term(skill.body, query, tokens)+ body_match = (+ _content_search_match(skill.body, body_match_term, matched_field="body", path="SKILL.md")+ if body_match_term is not None+ else None+ )+ if body_match is not None:+ matches.append(body_match)++ if len(matches) < SKILL_SEARCH_MATCH_LIMIT:+ remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)+ matching_paths = (+ skill.files.filter(_skill_search_field_query("path", query, tokens))+ .annotate(search_match_score=_skill_search_field_score("path", query, tokens, 120))+ .order_by("-search_match_score", "path")+ .values_list("path", flat=True)[:remaining_match_count]+ )+ for path in matching_paths:+ matches.append({"matched_field": "file_path", "path": path, "excerpt": path})++ if len(matches) < SKILL_SEARCH_MATCH_LIMIT:+ remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)+ file_content_query = Q(content__icontains=query)+ for variants in tokens:+ file_content_query |= _skill_search_variant_query("content", variants)+ content_files = (+ skill.files.filter(markdown_file_query(), file_content_query)+ .annotate(search_match_score=_skill_search_field_score("content", query, tokens, 40))+ .order_by("-search_match_score", "path")+ .values_list("path", "content")+ )[:remaining_match_count]+ for path, content in content_files:+ match_term = _skill_search_match_term(content, query, tokens)+ if match_term is None:+ continue+ match = _content_search_match(+ content,+ match_term,+ matched_field="file_content",+ path=path,+ )+ if match is not None:+ matches.append(match)++ return matches[:SKILL_SEARCH_MATCH_LIMIT]+++def _skill_search_tokens(query: str) -> list[tuple[str, ...]]:+ raw_tokens = list(dict.fromkeys(re.findall(r"[^\W_]+", query.lower())))+ informative_tokens = [token for token in raw_tokens if len(token) >= SKILL_SEARCH_MIN_TOKEN_LENGTH]+ bounded_tokens = sorted(informative_tokens, key=len, reverse=True)[:SKILL_SEARCH_MAX_TOKENS] or raw_tokens[:1]+ return [_skill_search_variants(token) for token in bounded_tokens]+++def _skill_search_variants(token: str) -> tuple[str, ...]:+ if len(token) < 6 or not token.isascii() or not token.isalpha():+ return (token,)++ stems: list[str] = []+ suffix = next(+ (+ candidate+ for candidate in SKILL_SEARCH_DERIVATIONAL_SUFFIXES+ if len(token) > len(candidate) and token.endswith(candidate)+ ),+ None,+ )+ if suffix is not None:+ stems.append(token[: -len(suffix)])+ elif token.endswith("ies"):+ stems.append(f"{token[:-3]}y")+ elif token.endswith(SKILL_SEARCH_SIBILANT_ES_ENDINGS):+ stems.append(token[:-2])+ elif token.endswith("es"):+ stems.extend((token[:-1], token[:-2]))+ elif token.endswith("s") and token != "status" and not token.endswith(("is", "ss")):+ stems.append(token[:-1])+ else:+ return (token,)++ variants = [token]+ for stem in stems:+ variants.append(stem)+ if len(stem) >= 2 and stem[-1] == stem[-2]:+ variants.append(stem[:-1])+ return tuple(dict.fromkeys(variant for variant in variants if len(variant) >= SKILL_SEARCH_MIN_STEM_LENGTH))+++def _skill_search_variant_query(field: SkillSearchField, variants: Sequence[str]) -> Q:+ lookup = SKILL_SEARCH_FIELD_LOOKUPS[field]+ query = Q()+ for variant in variants:+ query |= Q(**{lookup: variant})+ return query+++def _skill_search_all_tokens_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:+ query = Q()+ for variants in tokens:+ query &= _skill_search_variant_query(field, variants)+ return query+++def _skill_search_any_token_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:+ query = Q()+ for variants in tokens:+ query |= _skill_search_variant_query(field, variants)+ return query+++def _skill_search_field_query(field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]]) -> Q:+ return Q(**{SKILL_SEARCH_FIELD_LOOKUPS[field]: phrase}) | _skill_search_any_token_query(field, tokens)+++def _skill_search_field_score(+ field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]], weight: int+) -> Expression:+ phrase_score = Case(+ When(_skill_search_field_query(field, phrase, ()), then=Value(weight * 2)),+ default=Value(0),+ output_field=IntegerField(),+ )+ if not tokens:+ return phrase_score++ partial_weight = max(1, weight // len(tokens) // 4)+ partial_score: Expression = Value(0, output_field=IntegerField())+ for variants in tokens:+ partial_score += Case(+ When(_skill_search_variant_query(field, variants), then=Value(partial_weight)),+ default=Value(0),+ output_field=IntegerField(),+ )+ token_score = Case(+ When(_skill_search_all_tokens_query(field, tokens), then=Value(weight)),+ default=partial_score,+ output_field=IntegerField(),+ )+ return phrase_score + token_score+++def _skill_search_match_term(content: str, phrase: str, tokens: Sequence[Sequence[str]]) -> str | None:+ lowered = content.lower()+ if phrase.lower() in lowered:+ return phrase+ return next((variant for variants in tokens for variant in variants if variant in lowered), None)+++def _content_search_match(content: str, query: str, *, matched_field: str, path: str) -> dict[str, Any] | None:+ match_index = content.lower().find(query.lower())+ if match_index == -1:+ return None++ line = content.count("\n", 0, match_index) + 1+ line_start = content.rfind("\n", 0, match_index) + 1+ line_end = content.find("\n", match_index)+ if line_end == -1:+ line_end = len(content)+ line_content = content[line_start:line_end].strip()+ excerpt_source = line_content or content+ excerpt_match_index = excerpt_source.lower().find(query.lower())+ excerpt_start = max(0, excerpt_match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)+ excerpt = excerpt_source[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH]+ return {+ "matched_field": matched_field,+ "path": path,+ "line": line,+ "excerpt": excerpt[:SKILL_SEARCH_EXCERPT_LENGTH],+ }+++def markdown_file_query() -> Q:+ return Q(path__iendswith=".md") | Q(content_type__icontains="markdown")diff --git a/products/skills/backend/api/skill_throttles.py b/products/skills/backend/api/skill_throttles.pynew file mode 100644index 000000000000..f611bb41358e--- /dev/null+++ b/products/skills/backend/api/skill_throttles.py@@ -0,0 +1,83 @@+"""Rate limits for the skill endpoints that cost more than a plain read."""++from rest_framework.request import Request+from rest_framework.views import APIView++from posthog.auth import PersonalAPIKeyAuthentication+from posthog.rate_limit import BurstRateThrottle, PersonalApiKeyOrUserRateThrottle, SustainedRateThrottle+++class _CommunityPublishThrottle(PersonalApiKeyOrUserRateThrottle):+ # Publishing opens a pull request in a public repo, so the ceiling is "a handful, by hand", not+ # the API-shaped hundreds-per-minute of BurstRateThrottle. That one also extends+ # PersonalApiKeyRateThrottle, which ignores session traffic.+ def get_cache_key(self, request, view):+ # Per team, not per credential. The inherited key prefers the personal API key hash, so one+ # member holding several keys would get a fresh budget with each of them — and the skill+ # being published belongs to the team either way.+ team_id = self.safely_get_team_id_from_view(view)+ if team_id is None:+ return super().get_cache_key(request, view)+ return self.cache_format % {"scope": self.scope, "ident": f"team-{team_id}"}+++class CommunityPublishBurstThrottle(_CommunityPublishThrottle):+ scope = "community_skill_publish_burst"+ rate = "6/hour"+++class CommunityPublishSustainedThrottle(_CommunityPublishThrottle):+ scope = "community_skill_publish_sustained"+ rate = "20/day"+++class _SkillUserThrottle(PersonalApiKeyOrUserRateThrottle):+ """Per-credential throttling for skill endpoints, including OAuth and sessions.++ The general BurstRateThrottle/SustainedRateThrottle only count personal-API-key traffic, so an+ OAuth or session caller would reach expensive skill operations unthrottled.+ PersonalApiKeyOrUserRateThrottle counts every auth method, but its inherited key identifies+ session and OAuth callers by project, so one user's burst would 429 every other user in the+ project. Those callers get a per-user bucket instead; a personal API key keeps its own.+ """++ def get_cache_key(self, request: Request, view: APIView) -> str:+ if not request.user.is_authenticated or isinstance(+ request.successful_authenticator, PersonalAPIKeyAuthentication+ ):+ return super().get_cache_key(request, view)+ return self.cache_format % {"scope": self.scope, "ident": f"user:{request.user.pk}"}+++class SkillBundleBurstThrottle(_SkillUserThrottle):+ # A sandbox fetches the bundle once at session start, so 30/minute clears a burst of concurrent+ # starts for one user while still catching a scripted loop hammering the zip build.+ scope = "skills_bundle_burst"+ rate = "30/minute"+++class SkillBundleSustainedThrottle(_SkillUserThrottle):+ # A few hundred session starts an hour per user is well beyond normal use and short of what+ # sustained abuse of the 5 MB zip build could cost unthrottled.+ scope = "skills_bundle_sustained"+ rate = "300/hour"+++class SkillSearchBurstThrottle(_SkillUserThrottle):+ scope = "skills_search_burst"+ rate = "60/minute"+++class SkillSearchSustainedThrottle(_SkillUserThrottle):+ scope = "skills_search_sustained"+ rate = "600/hour"+++class SkillListBurstThrottle(_SkillUserThrottle):+ scope = "skills_list_burst"+ rate = BurstRateThrottle.rate+++class SkillListSustainedThrottle(_SkillUserThrottle):+ scope = "skills_list_sustained"+ rate = SustainedRateThrottle.ratediff --git a/products/skills/backend/api/skill_view_access.py b/products/skills/backend/api/skill_view_access.pynew file mode 100644index 000000000000..f9e03635c7de--- /dev/null+++ b/products/skills/backend/api/skill_view_access.py@@ -0,0 +1,200 @@+"""What a caller may reach, and how a skill is serialized back to them.++Every skill endpoint mixin builds on ``SkillAccessMixin``: the object-level check the shared+``name/<slug>`` URLs need, the web-auth gate the write endpoints need, and the two serialization+helpers whose context has to match across endpoints.+"""++from difflib import get_close_matches+from functools import cached_property+from typing import TYPE_CHECKING, Any, cast++from django.db.models import QuerySet++from rest_framework import serializers, status+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.auth import (+ JwtAuthentication,+ OAuthAccessTokenAuthentication,+ PersonalAPIKeyAuthentication,+ SessionAuthentication,+)+from posthog.models import Organization, Team++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.signals.backend.facade.api import get_scout_trial_skill_override++from ..models.skills import LLMSkill+from .skill_serializers import LLMSkillSerializer, LLMSkillVersionSummarySerializer+from .skill_services import get_active_skill_queryset, get_skill_by_name_from_db++if TYPE_CHECKING:+ from rest_framework.viewsets import GenericViewSet++ from products.signals.backend.facade.api import ScoutTrialSkill++ class _SkillViewBase(GenericViewSet[LLMSkill]):+ @property+ def team(self) -> Team: ...+ @property+ def organization(self) -> Organization: ...+ @property+ def user_access_control(self) -> UserAccessControl: ...++else:+ _SkillViewBase = object+++# A 404 offers a few near-miss names, not a listing: `skill-list` is still the way to browse.+MAX_SKILL_NAME_SUGGESTIONS = 3+SKILL_NAME_SUGGESTION_CUTOFF = 0.6+# Ceiling on the names one miss compares against, so a large store cannot make a 404 expensive.+MAX_SKILL_NAME_MATCH_CANDIDATES = 500+++# Keep this class and every endpoint mixin free of a class docstring. drf-spectacular resolves the+# viewset's docstring through its MRO, so a docstring here becomes the published OpenAPI description+# of every skill endpoint at once. The module docstring carries the description instead.+class SkillAccessMixin(_SkillViewBase):+ def _ensure_web_authenticated(self, request: Request) -> Response | None:+ if not isinstance(+ request.successful_authenticator,+ SessionAuthentication | JwtAuthentication | PersonalAPIKeyAuthentication | OAuthAccessTokenAuthentication,+ ):+ return Response(+ {"detail": "This endpoint is only available to web-authenticated users."},+ status=status.HTTP_403_FORBIDDEN,+ )+ return None++ def _load_skill_with_object_access(+ self,+ request: Request,+ skill_name: str,+ version: int | None = None,+ version_id: str | None = None,+ ) -> LLMSkill | None:+ # has_permission passes anyone with a grant on any one skill, so the loaded row is checked here.+ skill = get_skill_by_name_from_db(self.team, skill_name, version, version_id)+ if skill is not None:+ self.check_object_permissions(request, skill)+ skill = self._apply_trial_skill(request, skill)+ return skill++ @cached_property+ def _trial_skill(self) -> "ScoutTrialSkill | None":+ authenticator = self.request.successful_authenticator+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):+ return None+ token = authenticator.access_token+ if "scout_experiment_internal:read" not in (token.scope or "").split():+ return None+ if token.sandbox_task_id is None:+ raise PermissionDenied()+ trial_skill = get_scout_trial_skill_override(+ team_id=self.team.id, task_id=token.sandbox_task_id, token_id=token.pk+ )+ if trial_skill is None:+ raise PermissionDenied()+ return trial_skill++ def _apply_trial_skill(self, request: Request, skill: LLMSkill) -> LLMSkill:+ trial_skill = self._trial_skill+ if trial_skill is None or trial_skill.name != skill.name:+ return skill+ pinned = get_skill_by_name_from_db(self.team, skill.name, trial_skill.version)+ if pinned is None:+ raise NotFound()+ self.check_object_permissions(request, pinned)+ pinned.body = trial_skill.body+ pinned.stamp_digest()+ return pinned++ def _guard_object_access(self, request: Request, skill_name: str) -> Response | None:+ if self._load_skill_with_object_access(request, skill_name) is None:+ return self._skill_not_found_response(skill_name)+ return None++ def _guard_write(self, request: Request, skill_name: str) -> Response | None:+ """The gate every by-name write passes, or None when the caller may proceed.++ Web auth is checked before the skill is looked up, so a caller who may not reach this+ endpoint at all cannot use the 403/404 split to learn which skill names exist.+ """+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error+ return self._guard_object_access(request, skill_name)++ def _visible_skills_queryset(self) -> QuerySet[LLMSkill]:+ """Every active skill row this caller may read. `list` and every by-name read share it, so+ a name the list returned can never be denied by a read as if it did not exist."""+ return self.user_access_control.filter_queryset_by_access_level(+ get_active_skill_queryset(self.team), resource="llm_skill"+ )++ def _skill_not_found_response(self, skill_name: str, version: int | None = None) -> Response:+ """A 404 that answers from the same rows `list` returns.++ An agent that lists a skill and then cannot read it concludes the store is inconsistent+ and abandons the skill, so a miss has to say which of the two lookups it is: an unknown+ name (near-miss names the caller can actually read) or a known name at an absent version+ (the versions it does hold).+ """+ visible = self._visible_skills_queryset()+ if version is not None:+ available_versions = list(+ visible.filter(name=skill_name).order_by("version").values_list("version", flat=True)+ )+ if available_versions:+ return Response(+ {+ "detail": (+ f"Skill with name '{skill_name}' has no version {version}. "+ f"Available versions: {', '.join(str(v) for v in available_versions)}."+ ),+ "type": "skill_version_not_found",+ "skill_name": skill_name,+ "available_versions": available_versions,+ },+ status=status.HTTP_404_NOT_FOUND,+ )++ suggestions = get_close_matches(+ skill_name,+ visible.filter(is_latest=True).values_list("name", flat=True)[:MAX_SKILL_NAME_MATCH_CANDIDATES],+ n=MAX_SKILL_NAME_SUGGESTIONS,+ cutoff=SKILL_NAME_SUGGESTION_CUTOFF,+ )+ detail = f"Skill with name '{skill_name}' not found."+ if suggestions:+ detail += " Did you mean " + ", ".join(f"'{name}'" for name in suggestions) + "?"+ return Response(+ {+ "detail": detail,+ "type": "skill_not_found",+ "skill_name": skill_name,+ "suggestions": suggestions,+ },+ status=status.HTTP_404_NOT_FOUND,+ )++ def _serialize_skill(+ self, skill: LLMSkill, *, body_offset: int | None = None, body_length: int | None = None+ ) -> dict[str, Any]:+ context = self.get_serializer_context()+ if body_offset is not None or body_length is not None:+ context = {**context, "body_offset": body_offset, "body_length": body_length}+ return cast(dict[str, Any], LLMSkillSerializer(skill, context=context).data)++ def _serialize_version_summaries(self, skills: list[LLMSkill]) -> list[dict[str, Any]]:+ return cast(list[dict[str, Any]], LLMSkillVersionSummarySerializer(skills, many=True).data)++ def _validated_query(self, serializer_class: type[serializers.Serializer], request: Request) -> dict[str, Any]:+ """The request's query params, validated by `serializer_class`. 400s on a bad one."""+ serializer = serializer_class(data=request.query_params)+ serializer.is_valid(raise_exception=True)+ return cast(dict[str, Any], serializer.validated_data)diff --git a/products/skills/backend/api/skill_view_community.py b/products/skills/backend/api/skill_view_community.pynew file mode 100644index 000000000000..29b2d8aba4cd--- /dev/null+++ b/products/skills/backend/api/skill_view_community.py@@ -0,0 +1,154 @@+"""Publishing a skill to the public community marketplace."""++from typing import cast++import structlog+from drf_spectacular.utils import extend_schema+from rest_framework import status+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.models import User++from products.ai_observability.backend.api.metrics import llma_track_latency++from ..models.community_skills import CommunitySkillKind+from ..models.skills import SCOUT_SKILL_CATEGORY+from .community_publish_services import (+ CommunitySkillPublishError,+ CommunitySkillPublishNotConfiguredError,+ CommunitySkillPublishValidationError,+ publish_skill_to_community,+ publishable_tags,+)+from .skill_analytics import record_skill_event, skill_analytics_props+from .skill_serializers import (+ CommunitySkillPublishResultSerializer,+ LLMSkillPublishConflictSerializer,+ LLMSkillPublishToCommunitySerializer,+)+from .skill_view_access import SkillAccessMixin++logger = structlog.get_logger(__name__)+++# Reachable only through CommunityPublishOwnerPermission and the publish throttles, which live in+# skill_permissions and skill_throttles.+class SkillCommunityPublishMixin(SkillAccessMixin):+ @extend_schema(+ request=LLMSkillPublishToCommunitySerializer,+ responses={201: CommunitySkillPublishResultSerializer, 409: LLMSkillPublishConflictSerializer},+ )+ # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/publish-community",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_publish_community")+ @monitor(feature=None, endpoint="llma_skills_publish_community", method="POST")+ def publish_to_community(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error++ skill = self._load_skill_with_object_access(request, skill_name)+ if skill is None:+ return self._skill_not_found_response(skill_name)++ payload = LLMSkillPublishToCommunitySerializer(data=request.data)+ payload.is_valid(raise_exception=True)++ # Category rides along with id and version because registering a skill as a scout stamps+ # `category` without raising the version: on version alone, a skill reviewed as an ordinary+ # one could publish as a scout, carrying a schedule its publisher never consented to.+ expected_category = payload.validated_data.get("expected_category")+ if (+ skill.id != payload.validated_data["expected_skill_id"]+ or skill.version != payload.validated_data["expected_version"]+ or (expected_category is not None and skill.category != expected_category)+ ):+ return Response(+ {+ "detail": "This skill changed after you reviewed it. Reopen the dialog and review the latest version."+ },+ status=status.HTTP_409_CONFLICT,+ )++ files = [{"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill.files.all()]+ supplied_tags = payload.validated_data.get("tags")+ # An explicit empty list means "publish with no tags", so fall back to the skill's own tags+ # only when the caller omitted the field. Those are unvalidated metadata, unlike the ones the+ # serializer checked, so they go through publishable_tags first.+ if supplied_tags is None:+ supplied_tags = publishable_tags((skill.metadata or {}).get("tags"))+ # The LLMSkill name is the kebab slug; default the community display name to a title-cased form.+ display_name = payload.validated_data.get("display_name") or skill.name.replace("-", " ").title()++ # Derived, not caller-supplied: a scout published as a plain skill is exactly the entry the+ # catalog can't tell apart, and it lands in another project inert.+ kind = (+ CommunitySkillKind.SCOUT.value if skill.category == SCOUT_SKILL_CATEGORY else CommunitySkillKind.SKILL.value+ )++ try:+ result = publish_skill_to_community(+ slug=skill.name,+ # Scopes the publish branch to this team, so one team cannot rewrite another team's+ # open pull request for the same slug.+ publisher_id=str(self.team.uuid),+ name=display_name,+ description=skill.description,+ body=skill.body,+ files=files or None,+ tags=supplied_tags,+ allowed_tools=skill.allowed_tools or [],+ license=skill.license or "",+ compatibility=skill.compatibility or "",+ author_handle=payload.validated_data.get("author_handle", ""),+ metadata=skill.metadata,+ kind=kind,+ scout_config=payload.validated_data.get("scout_config"),+ )+ except CommunitySkillPublishNotConfiguredError:+ # The fail-safe is otherwise silent, so an instance that meant to have publishing on+ # looks like one that never configured it until somebody reports the toast.+ logger.warning(+ "llma_skill_publish_to_community_not_configured",+ team_id=self.team.id,+ user_id=cast(User, request.user).id,+ skill_name=skill.name,+ )+ return Response(+ {"detail": "Publishing to the community is not available on this instance."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ except CommunitySkillPublishValidationError as err:+ # Nothing reached GitHub, and republishing the same skill fails the same way — the+ # publisher has to edit it. That is a 400, not the 502 an unreachable GitHub gets.+ return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)+ except CommunitySkillPublishError as err:+ # The client sees the reason once; without this the server keeps no record of a publish+ # that failed against GitHub.+ logger.warning(+ "llma_skill_publish_to_community_failed",+ team_id=self.team.id,+ user_id=cast(User, request.user).id,+ skill_name=skill.name,+ error=str(err),+ )+ return Response({"detail": str(err)}, status=status.HTTP_502_BAD_GATEWAY)++ props = {**skill_analytics_props(skill), "community_pr_number": result["pr_number"]}+ record_skill_event(+ log_event="llma_skill_published_to_community",+ action="llma skill published to community",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(result, status=status.HTTP_201_CREATED)diff --git a/products/skills/backend/api/skill_view_files.py b/products/skills/backend/api/skill_view_files.pynew file mode 100644index 000000000000..4f7ef33cf29a--- /dev/null+++ b/products/skills/backend/api/skill_view_files.py@@ -0,0 +1,280 @@+"""The bundled files inside a skill: read one, add one, delete one, rename one.++Every write here publishes a new version of the skill, so they share the version-conflict and+version-limit contract of a publish.+"""++from typing import cast++from drf_spectacular.utils import extend_schema+from rest_framework import status+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.models import User++from products.ai_observability.backend.api.metrics import llma_track_latency++from ..models.skills import LLMSkillFile+from .skill_analytics import file_extension, record_skill_event, skill_analytics_props+from .skill_error_responses import skill_write_error_response+from .skill_serializers import (+ LLMSkillFetchQuerySerializer,+ LLMSkillFileCreateSerializer,+ LLMSkillFileDeleteQuerySerializer,+ LLMSkillFileRenameSerializer,+ LLMSkillFileSerializer,+ LLMSkillSerializer,+)+from .skill_services import (+ LLMSkillDescriptionTooLongError,+ LLMSkillFileLimitError,+ LLMSkillFileNotFoundError,+ LLMSkillFilePathConflictError,+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ create_skill_file,+ delete_skill_file,+ rename_skill_file,+)+from .skill_view_access import SkillAccessMixin+++def _safe_file_path(file_path: str) -> str | None:+ """The path without its trailing slashes, or None when it tries to escape the skill."""+ file_path = file_path.rstrip("/")+ normalized = file_path.replace("\\", "/")+ if ".." in normalized.split("/") or normalized.startswith("/"):+ return None+ return file_path+++class SkillFileActionsMixin(SkillAccessMixin):+ @extend_schema(+ parameters=[LLMSkillFetchQuerySerializer],+ responses={200: LLMSkillFileSerializer},+ )+ # NOTE: `required_scopes` is intentionally not set on @action here. delete_file is registered+ # below via @get_file.mapping.delete and shares this URL pattern's initkwargs — setting+ # required_scopes here would short-circuit ScopeBasePermission._get_required_scopes for DELETE+ # too, granting llm_skill:read access to a destructive operation. Scopes are resolved per-method+ # in dangerously_get_required_scopes instead.+ @action(+ methods=["GET"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/files/(?P<file_path>.+)",+ )+ @llma_track_latency("llma_skills_get_file")+ @monitor(feature=None, endpoint="llma_skills_get_file", method="GET")+ def get_file(self, request: Request, skill_name: str = "", file_path: str = "", **kwargs) -> Response:+ version_params = self._validated_query(LLMSkillFetchQuerySerializer, request)+ version = cast(int | None, version_params.get("version"))+ skill = self._load_skill_with_object_access(request, skill_name, version)+ if skill is None:+ return self._skill_not_found_response(skill_name, version)++ safe_path = _safe_file_path(file_path)+ if safe_path is None:+ return Response({"detail": "Invalid file path."}, status=status.HTTP_400_BAD_REQUEST)+ file_path = safe_path+ skill_file = LLMSkillFile.objects.filter(skill=skill, path=file_path).first()+ if skill_file is None:+ return Response(+ {"detail": f"File '{file_path}' not found in skill '{skill_name}'."},+ status=status.HTTP_404_NOT_FOUND,+ )++ return Response(LLMSkillFileSerializer(skill_file).data)++ @extend_schema(request=LLMSkillFileCreateSerializer, responses={201: LLMSkillSerializer})+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/files",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_create_file")+ @monitor(feature=None, endpoint="llma_skills_create_file", method="POST")+ def create_file(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ payload = LLMSkillFileCreateSerializer(data=request.data)+ payload.is_valid(raise_exception=True)++ try:+ published_skill = create_skill_file(+ self.team,+ user=cast(User, request.user),+ skill_name=skill_name,+ path=payload.validated_data["path"],+ content=payload.validated_data["content"],+ content_type=payload.validated_data.get("content_type", "text/plain"),+ base_version=payload.validated_data.get("base_version"),+ )+ except (+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ LLMSkillFileLimitError,+ LLMSkillDescriptionTooLongError,+ ) as err:+ response = skill_write_error_response(err, skill_name, not_found_response=self._skill_not_found_response)+ if response is None:+ raise+ return response+ except LLMSkillFilePathConflictError as err:+ return Response(+ {"detail": f"File '{err.path}' already exists in skill '{skill_name}'."},+ status=status.HTTP_409_CONFLICT,+ )++ path_value = payload.validated_data["path"]+ content_value = payload.validated_data["content"]+ props = {+ **skill_analytics_props(published_skill),+ "path": path_value,+ "content_type": payload.validated_data.get("content_type", "text/plain"),+ "file_content_length": len(content_value),+ "file_extension": file_extension(path_value),+ }+ record_skill_event(+ log_event="llma_skill_file_created",+ action="llma skill file created",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(published_skill), status=status.HTTP_201_CREATED)++ @extend_schema(parameters=[LLMSkillFileDeleteQuerySerializer], responses={200: LLMSkillSerializer})+ @get_file.mapping.delete+ @llma_track_latency("llma_skills_delete_file")+ @monitor(feature=None, endpoint="llma_skills_delete_file", method="DELETE")+ def delete_file(self, request: Request, skill_name: str = "", file_path: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ safe_path = _safe_file_path(file_path)+ if safe_path is None:+ return Response({"detail": "Invalid file path."}, status=status.HTTP_400_BAD_REQUEST)+ file_path = safe_path++ query_params = self._validated_query(LLMSkillFileDeleteQuerySerializer, request)++ try:+ published_skill = delete_skill_file(+ self.team,+ user=cast(User, request.user),+ skill_name=skill_name,+ path=file_path,+ base_version=query_params.get("base_version"),+ )+ except (+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ LLMSkillFileLimitError,+ LLMSkillDescriptionTooLongError,+ ) as err:+ response = skill_write_error_response(err, skill_name, not_found_response=self._skill_not_found_response)+ if response is None:+ raise+ return response+ except LLMSkillFileNotFoundError as err:+ return Response(+ {"detail": f"File '{err.path}' not found in skill '{skill_name}'."},+ status=status.HTTP_404_NOT_FOUND,+ )++ props = {+ **skill_analytics_props(published_skill),+ "path": file_path,+ "file_extension": file_extension(file_path),+ }+ record_skill_event(+ log_event="llma_skill_file_deleted",+ action="llma skill file deleted",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(published_skill))++ @extend_schema(request=LLMSkillFileRenameSerializer, responses={200: LLMSkillSerializer})+ # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/files-rename",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_rename_file")+ @monitor(feature=None, endpoint="llma_skills_rename_file", method="POST")+ def rename_file(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ payload = LLMSkillFileRenameSerializer(data=request.data)+ payload.is_valid(raise_exception=True)++ try:+ published_skill = rename_skill_file(+ self.team,+ user=cast(User, request.user),+ skill_name=skill_name,+ old_path=payload.validated_data["old_path"],+ new_path=payload.validated_data["new_path"],+ base_version=payload.validated_data.get("base_version"),+ )+ except (+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ LLMSkillFileLimitError,+ LLMSkillDescriptionTooLongError,+ ) as err:+ response = skill_write_error_response(err, skill_name, not_found_response=self._skill_not_found_response)+ if response is None:+ raise+ return response+ except LLMSkillFileNotFoundError as err:+ return Response(+ {"detail": f"File '{err.path}' not found in skill '{skill_name}'."},+ status=status.HTTP_404_NOT_FOUND,+ )+ except LLMSkillFilePathConflictError as err:+ return Response(+ {"detail": f"File '{err.path}' already exists in skill '{skill_name}'."},+ status=status.HTTP_409_CONFLICT,+ )++ old_path_value = payload.validated_data["old_path"]+ new_path_value = payload.validated_data["new_path"]+ old_extension = file_extension(old_path_value)+ new_extension = file_extension(new_path_value)+ props = {+ **skill_analytics_props(published_skill),+ "old_path": old_path_value,+ "new_path": new_path_value,+ "old_file_extension": old_extension,+ "new_file_extension": new_extension,+ "extension_changed": old_extension != new_extension,+ }+ record_skill_event(+ log_event="llma_skill_file_renamed",+ action="llma skill file renamed",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(published_skill))diff --git a/products/skills/backend/api/skill_view_lifecycle.py b/products/skills/backend/api/skill_view_lifecycle.pynew file mode 100644index 000000000000..5c17c76f730c--- /dev/null+++ b/products/skills/backend/api/skill_view_lifecycle.py@@ -0,0 +1,208 @@+"""The whole-skill operations: archive it, duplicate it, rename it."""++from typing import cast++from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import serializers, status+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.models import User++from products.ai_observability.backend.api.metrics import llma_track_latency++from .archive_guards import SkillArchiveRefused, SkillRenameConflict, SkillRenameRefused+from .skill_analytics import record_skill_event, skill_analytics_props+from .skill_serializers import LLMSkillDuplicateSerializer, LLMSkillRenameSerializer, LLMSkillSerializer+from .skill_services import (+ LLMSkillDescriptionTooLongError,+ LLMSkillDuplicateNameConflictError,+ LLMSkillNotFoundError,+ LLMSkillRenameNotAllowedError,+ archive_skill,+ duplicate_skill,+ rename_skill,+)+from .skill_view_access import SkillAccessMixin+++class SkillLifecycleActionsMixin(SkillAccessMixin):+ @extend_schema(+ request=None,+ responses={+ 204: None,+ 403: OpenApiResponse(+ description="Another product owns what this skill runs and refuses this caller's archive."+ ),+ },+ )+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/archive",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_archive")+ @monitor(feature=None, endpoint="llma_skills_archive", method="POST")+ def archive(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ try:+ skill_versions = archive_skill(+ self.team,+ skill_name,+ acting_user=cast(User, request.user),+ authenticator=request.successful_authenticator,+ )+ except SkillArchiveRefused as err:+ # A sibling product owns what this skill runs and says this caller may not remove it.+ return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)+ except LLMSkillNotFoundError:+ return self._skill_not_found_response(skill_name)++ props = {+ "skill_name": skill_name,+ "skill_versions": skill_versions,+ "skill_version_count": len(skill_versions),+ "skill_latest_version": max(skill_versions) if skill_versions else None,+ }+ record_skill_event(+ log_event="llma_skill_archived",+ action="llma skill archived",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(status=status.HTTP_204_NO_CONTENT)++ @extend_schema(request=LLMSkillDuplicateSerializer, responses={201: LLMSkillSerializer})+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/duplicate",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_duplicate")+ @monitor(feature=None, endpoint="llma_skills_duplicate", method="POST")+ def duplicate(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ payload = LLMSkillDuplicateSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ new_name = payload.validated_data["new_name"]++ try:+ new_skill = duplicate_skill(+ self.team,+ user=cast(User, request.user),+ source_name=skill_name,+ new_name=new_name,+ )+ except LLMSkillNotFoundError:+ return self._skill_not_found_response(skill_name)+ except LLMSkillDuplicateNameConflictError:+ # nosemgrep: api-response-must-match-schema (DRF's error envelope, not a data payload)+ return Response(+ {"attr": "new_name", "detail": "A skill with this name already exists."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ except LLMSkillDescriptionTooLongError as err:+ return Response(+ {+ "detail": (+ f"Shorten the source skill description to {err.max_length} characters before duplicating it."+ )+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ props = {+ **skill_analytics_props(new_skill),+ "source_skill_name": skill_name,+ }+ record_skill_event(+ log_event="llma_skill_duplicated",+ action="llma skill duplicated",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(new_skill), status=status.HTTP_201_CREATED)++ @extend_schema(+ request=LLMSkillRenameSerializer,+ responses={+ 200: LLMSkillSerializer,+ 403: OpenApiResponse(+ description="Another product owns what this skill runs and refuses this caller's rename."+ ),+ },+ )+ @action(+ methods=["POST"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/rename",+ required_scopes=["llm_skill:write"],+ )+ @llma_track_latency("llma_skills_rename")+ @monitor(feature=None, endpoint="llma_skills_rename", method="POST")+ def rename(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ payload = LLMSkillRenameSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ new_name = payload.validated_data["new_name"]++ try:+ renamed_skill = rename_skill(+ self.team,+ skill_name=skill_name,+ new_name=new_name,+ acting_user=cast(User, request.user),+ authenticator=request.successful_authenticator,+ )+ except SkillRenameRefused as err:+ return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)+ except SkillRenameConflict as err:+ raise serializers.ValidationError({"new_name": str(err)}, code="unique")+ except LLMSkillNotFoundError:+ return self._skill_not_found_response(skill_name)+ except LLMSkillDuplicateNameConflictError:+ raise serializers.ValidationError(+ {"new_name": "A skill with this name already exists."},+ code="unique",+ )+ except LLMSkillRenameNotAllowedError as err:+ raise serializers.ValidationError(+ {+ "new_name": (+ f"Names starting with '{err.prefix}' keep product settings under the skill name, "+ "so a skill can't be renamed into or out of them. Duplicate the skill instead."+ )+ },+ code="reserved_prefix",+ )++ props = {+ **skill_analytics_props(renamed_skill),+ "previous_skill_name": skill_name,+ }+ record_skill_event(+ log_event="llma_skill_renamed",+ action="llma skill renamed",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(renamed_skill))diff --git a/products/skills/backend/api/skill_view_marketplace.py b/products/skills/backend/api/skill_view_marketplace.pynew file mode 100644index 000000000000..56a69deb24af--- /dev/null+++ b/products/skills/backend/api/skill_view_marketplace.py@@ -0,0 +1,108 @@+"""The per-user credential a client needs to install this team's skills marketplace."""++from typing import Any, cast++from drf_spectacular.utils import extend_schema+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.models import User++from products.ai_observability.backend.api.metrics import llma_track_latency++from ..marketplace.adapters import MARKETPLACE_NAME, PLUGIN_NAME+from ..marketplace.credentials import (+ build_codex_install_command,+ build_install_command,+ get_marketplace_credential,+ issue_marketplace_credential,+ marketplace_credential_label,+ marketplace_repo_url,+)+from .skill_analytics import record_skill_event+from .skill_serializers import LLMSkillMarketplaceCommandSerializer, LLMSkillMarketplaceIssueSerializer+from .skill_view_access import SkillAccessMixin+++class SkillMarketplaceActionsMixin(SkillAccessMixin):+ def _marketplace_command_payload(self, key, token: str | None, status_str: str) -> dict[str, Any]:+ """Shape the marketplace-command response from a credential (or absence of one)."""+ team_id = self.team.id++ def claude(tok: str | None) -> str:+ return build_install_command(team_id, tok, plugin_name=PLUGIN_NAME, marketplace_name=MARKETPLACE_NAME)++ def codex(tok: str | None) -> str:+ return build_codex_install_command(team_id, tok, plugin_name=PLUGIN_NAME, marketplace_name=MARKETPLACE_NAME)++ return {+ "status": status_str,+ "connected": key is not None,+ "plugin_name": PLUGIN_NAME,+ "marketplace_name": MARKETPLACE_NAME,+ "label": marketplace_credential_label(team_id),+ "repo_url": marketplace_repo_url(team_id),+ "command": claude(token) if token else None,+ "command_template": claude(None),+ "codex_command": codex(token) if token else None,+ "codex_command_template": codex(None),+ "token": token,+ "mask_value": key.mask_value if key is not None else None,+ "created_at": key.created_at if key is not None else None,+ "last_rolled_at": key.last_rolled_at if key is not None else None,+ }++ @extend_schema(responses={200: LLMSkillMarketplaceCommandSerializer})+ # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients+ @action(methods=["GET"], detail=False, url_path="marketplace/install-command")+ @llma_track_latency("llma_skills_marketplace_command")+ @monitor(feature=None, endpoint="llma_skills_marketplace_command", method="GET")+ def marketplace_command(self, request: Request, **kwargs) -> Response:+ """Report whether the user already has a marketplace credential, without minting one.++ The token is unrecoverable, so an existing credential returns its mask only — the UI shows+ "already connected, existing setups keep working" and offers an explicit rotate.+ """+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error++ key = get_marketplace_credential(self.team, cast(User, request.user))+ payload = self._marketplace_command_payload(key, None, "exists" if key is not None else "absent")+ return Response(LLMSkillMarketplaceCommandSerializer(payload).data)++ @extend_schema(request=LLMSkillMarketplaceIssueSerializer, responses={200: LLMSkillMarketplaceCommandSerializer})+ @marketplace_command.mapping.post+ @llma_track_latency("llma_skills_marketplace_issue")+ @monitor(feature=None, endpoint="llma_skills_marketplace_issue", method="POST")+ def issue_marketplace_command(self, request: Request, **kwargs) -> Response:+ """Mint the user's read-only marketplace credential (or rotate it) and return the install command.++ Per-user: rotating only ever invalidates this user's own credential, never a teammate's.+ """+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error++ payload = LLMSkillMarketplaceIssueSerializer(data=request.data)+ payload.is_valid(raise_exception=True)++ issued = issue_marketplace_credential(+ self.team, cast(User, request.user), rotate=payload.validated_data["rotate"]+ )++ if issued.status in ("created", "rotated"):+ props = {"status": issued.status, "plugin_name": PLUGIN_NAME}+ record_skill_event(+ log_event="llma_skill_marketplace_credential_issued",+ action="llma skill marketplace credential issued",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )++ result = self._marketplace_command_payload(issued.key, issued.token, issued.status)+ return Response(LLMSkillMarketplaceCommandSerializer(result).data)diff --git a/products/skills/backend/api/skill_view_transfer.py b/products/skills/backend/api/skill_view_transfer.pynew file mode 100644index 000000000000..e41b9dd21d09--- /dev/null+++ b/products/skills/backend/api/skill_view_transfer.py@@ -0,0 +1,258 @@+"""Moving a skill in and out of PostHog as a zip: export, bundle, and import."""++from typing import Any, cast++from django.http import HttpResponse++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import status+from rest_framework.decorators import action+from rest_framework.exceptions import PermissionDenied+from rest_framework.parsers import FormParser, MultiPartParser+from rest_framework.renderers import BaseRenderer+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.auth import OAuthAccessTokenAuthentication+from posthog.models import User+from posthog.permissions import posthog_feature_flag_value+from posthog.renderers import SafeJSONRenderer++from products.ai_observability.backend.api.metrics import llma_track_latency++from ..marketplace.adapters import (+ SANDBOX_SKILLS_FEATURE_FLAG,+ build_skill_bundle,+ load_skill_export,+ sandbox_skills_flag_distinct_id,+)+from ..marketplace.packaging import SkillImportError, build_skill_zip, parse_skill_zip+from ..models.skills import LLMSkill+from .skill_analytics import record_skill_event, skill_analytics_props+from .skill_error_responses import spec_problems_detail+from .skill_import import (+ MAX_IMPORT_ZIP_BYTES,+ _spec_problem_messages as spec_problem_messages,+ import_problems,+)+from .skill_serializers import (+ LLMSkillBundleQuerySerializer,+ LLMSkillFetchQuerySerializer,+ LLMSkillImportSerializer,+ LLMSkillSerializer,+)+from .skill_services import (+ LLMSkillDuplicateNameConflictError,+ LLMSkillFileLimitError,+ LLMSkillFilePathConflictError,+ create_skill,+)+from .skill_view_access import SkillAccessMixin+++class ZipRenderer(BaseRenderer):+ """Lets ``Accept: application/zip`` through content negotiation on the zip actions.++ DRF negotiates before the action runs, so with the JSON-only default a client that asks for the+ zip it was promised gets 406. The zip itself is a raw HttpResponse and never reaches a renderer;+ only the actions' error Responses do, and those stay JSON so the client can read them.+ """++ media_type = "application/zip"+ format = "zip"++ def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:+ if renderer_context is not None:+ renderer_context["response"]["Content-Type"] = "application/json"+ return SafeJSONRenderer().render(data, "application/json", renderer_context)+++ZIP_ACTIONS = ("bundle", "export")+# With two renderers on an action, drf-spectacular advertises DRF's ``?format=`` override as a query+# parameter. Clients select the zip with ``Accept``; keep the generated types free of it.+FORMAT_QUERY_PARAM_EXCLUDED = OpenApiParameter(name="format", location=OpenApiParameter.QUERY, exclude=True)+++class SkillTransferActionsMixin(SkillAccessMixin):+ @extend_schema(+ parameters=[LLMSkillFetchQuerySerializer, FORMAT_QUERY_PARAM_EXCLUDED],+ responses={(200, "application/zip"): OpenApiTypes.BINARY},+ )+ @action(methods=["GET"], detail=False, url_path=r"name/(?P<skill_name>[^/]+)/export")+ @llma_track_latency("llma_skills_export")+ @monitor(feature=None, endpoint="llma_skills_export", method="GET")+ def export(self, request: Request, skill_name: str = "", **kwargs) -> Response | HttpResponse:+ version_params = self._validated_query(LLMSkillFetchQuerySerializer, request)+ version = cast(int | None, version_params.get("version"))+ skill = self._load_skill_with_object_access(request, skill_name, version)+ if skill is None:+ return self._skill_not_found_response(skill_name, version)++ export = load_skill_export(skill)+ problems = spec_problem_messages(export)+ if problems:+ return Response(+ {+ "detail": spec_problems_detail(+ "Couldn't download this skill because it doesn't meet the Agent Skills spec.",+ problems,+ "Edit the skill to fix this, then try again.",+ ),+ "problems": problems,+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ zip_bytes = build_skill_zip(export)+ response = HttpResponse(zip_bytes, content_type="application/zip")+ response["Content-Disposition"] = f'attachment; filename="{skill.name}.zip"'+ return response++ @extend_schema(+ parameters=[LLMSkillBundleQuerySerializer, FORMAT_QUERY_PARAM_EXCLUDED],+ responses={(200, "application/zip"): OpenApiTypes.BINARY},+ )+ @action(methods=["GET"], detail=False, url_path="bundle", required_scopes=["llm_skill:read"])+ @llma_track_latency("llma_skills_bundle")+ @monitor(feature=None, endpoint="llma_skills_bundle", method="GET")+ def bundle(self, request: Request, **kwargs) -> Response | HttpResponse:+ """One zip of the requesting user's store skills, for unpacking into a skills directory."""+ query_params = self._validated_query(LLMSkillBundleQuerySerializer, request)+ authenticator = request.successful_authenticator+ if (+ query_params["content"] == "full"+ and isinstance(authenticator, OAuthAccessTokenAuthentication)+ and "scout_experiment_internal:read" in (authenticator.access_token.scope or "").split()+ ):+ # Full bundles load rows independently and cannot apply a run's pinned candidate.+ raise PermissionDenied(+ "Scout trials must fetch individual skills or use a stub bundle instead of a full bundle."+ )+ user = cast(User, request.user)+ flag_value = posthog_feature_flag_value(+ SANDBOX_SKILLS_FEATURE_FLAG,+ sandbox_skills_flag_distinct_id(user),+ organization_id=self.organization.id,+ team_id=self.team.id,+ )+ # None means the flag service did not answer. A sandbox treats 404 as "not enabled", so+ # do not hand it that on an outage; 503 lets the caller tell the two apart.+ if flag_value is None:+ return Response(+ {"detail": "Feature flag evaluation is unavailable."}, status=status.HTTP_503_SERVICE_UNAVAILABLE+ )+ # A plain 404 Response, not NotFound: @monitor counts raised exceptions as endpoint errors,+ # and every sandbox in a non-flagged project hits this path once per run.+ if not flag_value:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)++ # Same object-level filter the list endpoint applies, so the bundle never carries a skill the+ # list would hide from this user.+ readable_skills = self.user_access_control.filter_queryset_by_access_level(+ LLMSkill.objects.filter(team=self.team), resource="llm_skill"+ )+ bundle = build_skill_bundle(+ self.team,+ user,+ readable_skills,+ content=query_params["content"],+ limit=query_params["limit"],+ )+ response = HttpResponse(bundle.zip_bytes, content_type="application/zip")+ response["Content-Disposition"] = 'attachment; filename="skills-bundle.zip"'+ # Counts only: names are unbounded and would blow past proxy header limits for heavy users.+ response["X-Skills-Included"] = str(len(bundle.included))+ response["X-Skills-Dropped"] = str(bundle.dropped_count)+ response["X-Skills-Skipped"] = str(bundle.skipped_count)+ return response++ @extend_schema(request=LLMSkillImportSerializer, responses={201: LLMSkillSerializer})+ @action(+ methods=["POST"],+ detail=False,+ url_path="import",+ required_scopes=["llm_skill:write"],+ parser_classes=[MultiPartParser, FormParser],+ )+ @llma_track_latency("llma_skills_import")+ @monitor(feature=None, endpoint="llma_skills_import", method="POST")+ def import_skill(self, request: Request, **kwargs) -> Response:+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error++ upload = request.FILES.get("file")+ if upload is None:+ return Response(+ {"detail": "Attach the skill .zip as multipart form field 'file'."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ # Bound the read by bytes (read one past the cap) — upload.size is not always reliable, so+ # don't trust it as the only guard against buffering an oversized body into memory.+ raw = upload.read(MAX_IMPORT_ZIP_BYTES + 1)+ if len(raw) > MAX_IMPORT_ZIP_BYTES:+ return Response(+ {"detail": f"Zip must be {MAX_IMPORT_ZIP_BYTES} bytes or fewer."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ try:+ skill_export = parse_skill_zip(raw)+ except SkillImportError as err:+ return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)++ problems = import_problems(skill_export)+ if problems:+ return Response(+ {+ "detail": spec_problems_detail(+ "Couldn't import this zip because it doesn't meet the Agent Skills spec.",+ problems,+ "Fix the skill files, then try again.",+ ),+ "problems": problems,+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ try:+ skill = create_skill(+ self.team,+ user=cast(User, request.user),+ name=skill_export.name,+ description=skill_export.description,+ body=skill_export.body,+ license=skill_export.license,+ compatibility=skill_export.compatibility,+ allowed_tools=skill_export.allowed_tools,+ metadata=skill_export.metadata,+ files=[+ {"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill_export.files+ ],+ )+ except LLMSkillDuplicateNameConflictError:+ # nosemgrep: api-response-must-match-schema (DRF's error envelope, not a data payload)+ return Response(+ {"attr": "name", "detail": f"A skill named '{skill_export.name}' already exists."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ except LLMSkillFilePathConflictError:+ return Response({"detail": "Duplicate bundled file paths in the zip."}, status=status.HTTP_400_BAD_REQUEST)+ except LLMSkillFileLimitError as err:+ return Response(+ {"detail": f"Skill exceeds the maximum of {err.max_count} bundled files."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ props = {**skill_analytics_props(skill), "imported": True}+ record_skill_event(+ log_event="llma_skill_imported",+ action="llma skill imported",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=props,+ )+ return Response(self._serialize_skill(skill), status=status.HTTP_201_CREATED)diff --git a/products/skills/backend/api/skill_view_versions.py b/products/skills/backend/api/skill_view_versions.pynew file mode 100644index 000000000000..5c07b8edc826--- /dev/null+++ b/products/skills/backend/api/skill_view_versions.py@@ -0,0 +1,321 @@+"""Reading a skill by name, publishing a new version of it, and listing its history."""++from typing import Any, cast+from uuid import UUID++from django.db import IntegrityError, transaction++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, status+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.monitoring import monitor+from posthog.models import User++from products.ai_observability.backend.api.metrics import llma_track_latency++from ..marketplace.packaging import frontmatter_document, render_skill_md+from ..models.skills import LLMSkill+from .skill_analytics import publish_analytics_props, record_skill_event+from .skill_error_responses import skill_write_error_response, version_conflict_response+from .skill_serializers import (+ DEFAULT_BODY_PAGE_LENGTH,+ PUBLISH_CONTENT_FIELDS,+ LLMSkillBodyFetchQuerySerializer,+ LLMSkillFetchQuerySerializer,+ LLMSkillMarkdownSerializer,+ LLMSkillPublishSerializer,+ LLMSkillResolveQuerySerializer,+ LLMSkillResolveResponseSerializer,+ LLMSkillSerializer,+)+from .skill_services import (+ LLMSkillDescriptionTooLongError,+ LLMSkillEditError,+ LLMSkillNotFoundError,+ LLMSkillOwnerNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ get_active_skill_queryset,+ get_skill_by_name_from_db,+ publish_skill_version,+ resolve_owner_users,+ resolve_versions_page,+ set_skill_owners,+)+from .skill_view_access import SkillAccessMixin+++def _is_uuid(value: str) -> bool:+ try:+ UUID(value)+ return True+ except ValueError:+ return False+++class SkillVersionActionsMixin(SkillAccessMixin):+ @extend_schema(+ parameters=[LLMSkillBodyFetchQuerySerializer],+ responses={200: LLMSkillSerializer},+ )+ @action(methods=["GET"], detail=False, url_path=r"name/(?P<skill_name>[^/]+)")+ @llma_track_latency("llma_skills_get_by_name")+ @monitor(feature=None, endpoint="llma_skills_get_by_name", method="GET")+ def get_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ version_params = self._validated_query(LLMSkillBodyFetchQuerySerializer, request)+ version = cast(int | None, version_params.get("version"))+ skill = self._load_skill_with_object_access(request, skill_name, version)++ if skill is None and _is_uuid(skill_name):+ redirect = self._redirect_to_name(request, skill_name)+ if redirect is not None:+ return redirect++ if skill is None:+ return self._skill_not_found_response(skill_name, version)++ # Cap the first page when the caller doesn't page explicitly, so body_next_offset is a+ # valid continuation offset even when the full body would be truncated in transit.+ body_length = cast(int | None, version_params.get("body_length"))+ if body_length is None:+ body_length = DEFAULT_BODY_PAGE_LENGTH++ return Response(+ self._serialize_skill(+ skill,+ body_offset=cast(int | None, version_params.get("body_offset")),+ body_length=body_length,+ )+ )++ def _redirect_to_name(self, request: Request, skill_name: str) -> Response | None:+ skill_by_id = get_active_skill_queryset(self.team).filter(id=skill_name).first()+ if skill_by_id is None:+ return None+ self.check_object_permissions(request, skill_by_id)+ # Use a relative path (no build_absolute_uri) to avoid embedding the+ # Host header in the Location value — prevents host-header open-redirect.+ redirect_url = request.get_full_path().replace(skill_name, skill_by_id.name, 1)+ response = Response(status=status.HTTP_302_FOUND)+ response["Location"] = redirect_url+ return response++ @extend_schema(request=LLMSkillPublishSerializer, responses={200: LLMSkillSerializer})+ @get_by_name.mapping.patch+ @llma_track_latency("llma_skills_publish_by_name")+ @monitor(feature=None, endpoint="llma_skills_publish_by_name", method="PATCH")+ def update_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ guard_error = self._guard_write(request, skill_name)+ if guard_error is not None:+ return guard_error++ payload = LLMSkillPublishSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ validated_data = payload.validated_data++ # Resolve owners before publishing so a bad UUID 400s without minting a version. `owner_uuids`+ # is None when omitted (owners left untouched), [] when the caller clears them.+ owner_uuids = validated_data.get("owners")+ owner_users = self._resolve_publish_owners(owner_uuids)++ if owner_uuids is not None and all(validated_data.get(p) is None for p in PUBLISH_CONTENT_FIELDS):+ return self._replace_owners_only(skill_name, validated_data, cast(list, owner_users))++ try:+ published_skill = self._publish_version(request, skill_name, validated_data, owner_users)+ except (+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ LLMSkillDescriptionTooLongError,+ LLMSkillEditError,+ ) as err:+ error_response = skill_write_error_response(+ err, skill_name, not_found_response=self._skill_not_found_response+ )+ if error_response is None:+ raise+ return error_response++ record_skill_event(+ log_event="llma_skill_version_published",+ action="llma skill version published",+ user=cast(User, request.user),+ team=self.team,+ request=request,+ props=publish_analytics_props(published_skill, validated_data, owners_changed=owner_uuids is not None),+ )+ return Response(self._serialize_skill(published_skill))++ def _resolve_publish_owners(self, owner_uuids: list[UUID] | None) -> list[User] | None:+ """The users the caller named as owners, or None when they left ownership alone."""+ if owner_uuids is None:+ return None+ try:+ return resolve_owner_users(self.team, [str(u) for u in owner_uuids])+ except LLMSkillOwnerNotFoundError as err:+ raise serializers.ValidationError(+ {"owners": f"User '{err.user_uuid}' is not a member of this project."},+ code="invalid_owner",+ )++ def _replace_owners_only(+ self, skill_name: str, validated_data: dict[str, Any], owner_users: list[User]+ ) -> Response:+ """Replace the skill's owners without publishing a version.++ Owners live on the logical skill, not a version row, so minting an identical version would+ rewrite version-history authorship, bump marketplace/update timestamps, and burn toward+ MAX_SKILL_VERSION for a no-op body. Same optimistic-concurrency contract as a publish when+ `base_version` is supplied: a stale value still 409s. It may be omitted (the generated PATCH+ schema marks it optional), which skips the version check — ownership isn't version-keyed, so+ the replace is still exact.+ """+ base_version = validated_data.get("base_version")+ # Lock the latest row for the check + replace (mirrors publish_skill_version): requests+ # run autocommit, so without the lock an owner update racing a publish from the same+ # base_version could pass a stale check and 200 where the contract advertises 409.+ with transaction.atomic():+ current_latest = (+ LLMSkill.objects.select_for_update()+ .filter(team=self.team, name=skill_name, deleted=False, is_latest=True)+ .order_by("-version", "-created_at", "-id")+ .first()+ )+ if current_latest is None:+ return self._skill_not_found_response(skill_name)+ if base_version is not None and base_version != current_latest.version:+ return version_conflict_response(current_latest.version)+ set_skill_owners(self.team, skill_name, owner_users)+ # Reread outside the transaction, so an archive landing in between can leave nothing to+ # serialize. Answer that the same way every other `name/<slug>` action answers it.+ refreshed = get_skill_by_name_from_db(self.team, skill_name=skill_name)+ if refreshed is None:+ return self._skill_not_found_response(skill_name)+ return Response(self._serialize_skill(refreshed))++ def _publish_version(+ self,+ request: Request,+ skill_name: str,+ validated_data: dict[str, Any],+ owner_users: list[User] | None,+ ) -> LLMSkill:+ """Publish a new version, and replace owners in the same transaction when asked to.++ If setting owners fails, the published version rolls back with it — otherwise the new+ body/files would be live while ownership stayed stale, and a retry with the original+ base_version would 409.+ """+ try:+ with transaction.atomic():+ published_skill = publish_skill_version(+ self.team,+ user=cast(User, request.user),+ skill_name=skill_name,+ body=validated_data.get("body"),+ edits=validated_data.get("edits"),+ description=validated_data.get("description"),+ license=validated_data.get("license"),+ compatibility=validated_data.get("compatibility"),+ allowed_tools=validated_data.get("allowed_tools"),+ metadata=validated_data.get("metadata"),+ files=validated_data.get("files"),+ file_edits=validated_data.get("file_edits"),+ base_version=validated_data["base_version"],+ version_description=validated_data.get("version_description"),+ )+ # Owners are keyed on the logical skill, so this runs only when the caller passed+ # `owners` — a plain body edit never touches ownership.+ if owner_users is not None:+ set_skill_owners(self.team, skill_name, owner_users)+ except IntegrityError as err:+ if "unique_skill_file_path" in str(err):+ raise serializers.ValidationError({"files": "Duplicate file paths are not allowed."}, code="unique")+ raise+ return published_skill++ @extend_schema(parameters=[LLMSkillResolveQuerySerializer], responses={200: LLMSkillResolveResponseSerializer})+ @action(+ methods=["GET"],+ detail=False,+ url_path=r"resolve/name/(?P<skill_name>[^/]+)",+ required_scopes=["llm_skill:read"],+ )+ @llma_track_latency("llma_skills_resolve_by_name")+ @monitor(feature=None, endpoint="llma_skills_resolve_by_name", method="GET")+ def resolve_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ auth_error = self._ensure_web_authenticated(request)+ if auth_error is not None:+ return auth_error++ query_params = self._validated_query(LLMSkillResolveQuerySerializer, request)+ version = cast(int | None, query_params.get("version"))+ version_id = query_params.get("version_id")+ skill = self._load_skill_with_object_access(+ request,+ skill_name,+ version,+ str(version_id) if version_id else None,+ )+ if skill is None:+ return self._skill_not_found_response(skill_name, version)++ limit = cast(int, query_params["limit"])+ offset = cast(int | None, query_params.get("offset"))+ before_version = cast(int | None, query_params.get("before_version"))+ versions, has_more = resolve_versions_page(+ self.team,+ skill_name=skill_name,+ limit=limit,+ offset=offset,+ before_version=before_version,+ )+ # nosemgrep: api-response-must-match-schema (these keys are exactly LLMSkillResolveResponseSerializer's fields)+ return Response(+ {+ "skill": self._serialize_skill(skill),+ "versions": self._serialize_version_summaries(versions),+ "has_more": has_more,+ }+ )++ @extend_schema(+ parameters=[LLMSkillFetchQuerySerializer],+ responses={200: LLMSkillMarkdownSerializer},+ )+ # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients+ @action(+ methods=["GET"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/skill-md",+ required_scopes=["llm_skill:read"],+ )+ @llma_track_latency("llma_skills_skill_md")+ @monitor(feature=None, endpoint="llma_skills_skill_md", method="GET")+ def skill_md(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ """The rendered SKILL.md plus its frontmatter as JSON, for a host that serves the file.++ Both halves come from one renderer, so a digest a client takes over ``content`` still+ describes the fields it reads from ``frontmatter``.+ """+ version_params = self._validated_query(LLMSkillFetchQuerySerializer, request)+ version = cast(int | None, version_params.get("version"))+ skill = self._load_skill_with_object_access(request, skill_name, version)+ if skill is None:+ return self._skill_not_found_response(skill_name, version)++ # SKILL.md never carries the bundled files, so don't load them just to render it.+ export = skill.to_export()+ payload = LLMSkillMarkdownSerializer(+ instance={+ "name": skill.name,+ "version": skill.version,+ "content": render_skill_md(export),+ "frontmatter": frontmatter_document(export),+ }+ )+ return Response(payload.data)diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 6d017cd72354..ca5bac4abaff 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,160 +1,72 @@-import re+"""The skills API: the catalog endpoints, and the viewset that composes the rest.++Each group of endpoints lives in its own module as a mixin: versions, lifecycle, files, transfer,+marketplace, and community. This module wires them together with the DRF plumbing that has to sit on+the concrete viewset, which is the renderers, throttles, scopes and serializer context.+"""+import hashlibfrom collections.abc import Sequence-from difflib import get_close_matches-from functools import cached_property-from typing import TYPE_CHECKING, Any, Literal, Protocol, cast+from typing import Any, castfrom urllib.parse import urlencode-from uuid import UUID-from django.db import IntegrityError, OperationalError, transaction-from django.db.models import Case, Exists, Expression, IntegerField, OuterRef, Q, QuerySet, Subquery, Value, When-from django.db.models.functions import Coalesce-from django.http import HttpResponse, HttpResponseBase+from django.db import IntegrityError+from django.db.models import QuerySet+from django.http import HttpResponseBasefrom django.utils.cache import get_conditional_response, patch_cache_control, patch_vary_headers-import psycopg-import structlog-from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import NotFound, PermissionDenied-from rest_framework.parsers import FormParser, MultiPartParser-from rest_framework.permissions import BasePermissionfrom rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializerfrom rest_framework.throttling import BaseThrottle-from rest_framework.views import APIViewfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.auth import (- JwtAuthentication,- OAuthAccessTokenAuthentication,- PersonalAPIKeyAuthentication,- SessionAuthentication,-)from posthog.dataclasses import frozen-from posthog.event_usage import report_user_actionfrom posthog.git import get_git_commit_shortfrom posthog.models import User-from posthog.models.utils import execute_with_timeout-from posthog.permissions import AccessControlPermission, is_scout_sandbox_request, posthog_feature_flag_value-from posthog.rate_limit import BurstRateThrottle, PersonalApiKeyOrUserRateThrottle, SustainedRateThrottle+from posthog.permissions import AccessControlPermission, is_scout_sandbox_request+from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottlefrom posthog.renderers import SafeJSONRendererfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.ai_observability.backend.api.metrics import llma_track_latency-from products.signals.backend.facade.api import get_scout_trial_skill_override-from ..marketplace.adapters import (- MARKETPLACE_NAME,- PLUGIN_NAME,- SANDBOX_SKILLS_FEATURE_FLAG,- build_skill_bundle,- load_skill_export,- sandbox_skills_flag_distinct_id,-)-from ..marketplace.credentials import (- build_codex_install_command,- build_install_command,- get_marketplace_credential,- issue_marketplace_credential,- marketplace_credential_label,- marketplace_repo_url,-)-from ..marketplace.packaging import (- SkillExport,- SkillImportError,- build_skill_zip,- frontmatter_document,- parse_skill_zip,- render_skill_md,-)-from ..models.community_skills import CommunitySkillKind-from ..models.skills import SCOUT_SKILL_CATEGORY, LLMSkill, LLMSkillFile-from .archive_guards import SkillArchiveRefused, SkillRenameConflict, SkillRenameRefused-from .community_publish_services import (- CommunitySkillPublishError,- CommunitySkillPublishNotConfiguredError,- CommunitySkillPublishValidationError,- publish_skill_to_community,- publishable_tags,-)-from .community_skills import CommunitySkillFeatureFlagPermission+from ..models.skills import LLMSkill, LLMSkillFile+from .skill_analytics import record_skill_event, skill_analytics_props+from .skill_catalog import list_queryset+from .skill_permissions import CommunityPublishFeatureFlagPermission, CommunityPublishOwnerPermission+from .skill_search import SkillSearchTimeout, search_skillsfrom .skill_serializers import (- DEFAULT_BODY_PAGE_LENGTH,- MAX_SKILL_FILE_BYTES,- PUBLISH_CONTENT_FIELDS,- CommunitySkillPublishResultSerializer,- LLMSkillBodyFetchQuerySerializer,- LLMSkillBundleQuerySerializer,LLMSkillCreateSerializer,- LLMSkillDuplicateSerializer,- LLMSkillFetchQuerySerializer,- LLMSkillFileCreateSerializer,- LLMSkillFileDeleteQuerySerializer,- LLMSkillFileRenameSerializer,- LLMSkillFileSerializer,- LLMSkillImportSerializer,LLMSkillListQuerySerializer,LLMSkillListSerializer,- LLMSkillMarkdownSerializer,- LLMSkillMarketplaceCommandSerializer,- LLMSkillMarketplaceIssueSerializer,- LLMSkillPublishConflictSerializer,- LLMSkillPublishSerializer,- LLMSkillPublishToCommunitySerializer,- LLMSkillRenameSerializer,- LLMSkillResolveQuerySerializer,- LLMSkillResolveResponseSerializer,LLMSkillSearchErrorSerializer,LLMSkillSearchQuerySerializer,LLMSkillSearchResponseSerializer,LLMSkillSerializer,- LLMSkillVersionSummarySerializer,- validate_allowed_tool,- validate_new_skill_name_value,- validate_skill_body_size,)-from .skill_services import (- LLMSkillDescriptionTooLongError,- LLMSkillDuplicateNameConflictError,- LLMSkillEditError,- LLMSkillFileLimitError,- LLMSkillFileNotFoundError,- LLMSkillFilePathConflictError,- LLMSkillNotFoundError,- LLMSkillOwnerNotFoundError,- LLMSkillRenameNotAllowedError,- LLMSkillVersionConflictError,- LLMSkillVersionLimitError,- archive_skill,- compute_spec_problems,- create_skill,- create_skill_file,- delete_skill_file,- duplicate_skill,- get_active_skill_queryset,- get_skill_by_name_from_db,- publish_skill_version,- rename_skill,- rename_skill_file,- resolve_owner_users,- resolve_skill_owners,- resolve_skill_owners_for_names,- resolve_versions_page,- set_skill_owners,- skill_name_is_well_formed,- skill_names_owned_by,- team_skills_version,+from .skill_services import get_active_skill_queryset, resolve_skill_owners_for_names, team_skills_version+from .skill_throttles import (+ CommunityPublishBurstThrottle,+ CommunityPublishSustainedThrottle,+ SkillBundleBurstThrottle,+ SkillBundleSustainedThrottle,+ SkillListBurstThrottle,+ SkillListSustainedThrottle,+ SkillSearchBurstThrottle,+ SkillSearchSustainedThrottle,)--if TYPE_CHECKING:- from products.signals.backend.facade.api import ScoutTrialSkill+from .skill_view_community import SkillCommunityPublishMixin+from .skill_view_files import SkillFileActionsMixin+from .skill_view_lifecycle import SkillLifecycleActionsMixin+from .skill_view_marketplace import SkillMarketplaceActionsMixin+from .skill_view_transfer import ZIP_ACTIONS, SkillTransferActionsMixin, ZipRenderer+from .skill_view_versions import SkillVersionActionsMixin@frozen@@ -163,405 +75,15 @@ class SkillsListValidators:etag: str-logger = structlog.get_logger(__name__)--# Generous ceiling for an uploaded skill zip — per-skill content (body, 200 files × 1 MB) is-# already bounded by create_skill, this just caps the upload before we read it into memory.-MAX_IMPORT_ZIP_BYTES = 10_000_000-SKILL_SEARCH_RESULT_LIMIT = 10-SKILL_SEARCH_MATCH_LIMIT = 2-SKILL_SEARCH_EXCERPT_LENGTH = 300-SKILL_SEARCH_TIMEOUT_MS = 5_000-SKILL_SEARCH_EXACT_NAME_BONUS = 5_000-SKILL_SEARCH_MAX_TOKENS = 8-SKILL_SEARCH_MIN_TOKEN_LENGTH = 2-SKILL_SEARCH_MIN_STEM_LENGTH = 5-SKILL_SEARCH_DERIVATIONAL_SUFFIXES = ("ations", "ation", "tions", "tion", "ings", "ing", "ed")-SKILL_SEARCH_SIBILANT_ES_ENDINGS = ("ches", "shes", "sses", "xes", "zes")-SkillSearchField = Literal["name", "description", "body", "path", "content"]-SKILL_SEARCH_FIELD_LOOKUPS: dict[SkillSearchField, str] = {- "name": "name__icontains",- "description": "description__icontains",- "body": "body__icontains",- "path": "path__icontains",- "content": "content__icontains",-}-# A 404 offers a few near-miss names, not a listing: `skill-list` is still the way to browse.-MAX_SKILL_NAME_SUGGESTIONS = 3-SKILL_NAME_SUGGESTION_CUTOFF = 0.6-# Ceiling on the names one miss compares against, so a large store cannot make a 404 expensive.-MAX_SKILL_NAME_MATCH_CANDIDATES = 500---def _content_search_match(content: str, query: str, *, matched_field: str, path: str) -> dict[str, Any] | None:- match_index = content.lower().find(query.lower())- if match_index == -1:- return None-- line = content.count("\n", 0, match_index) + 1- line_start = content.rfind("\n", 0, match_index) + 1- line_end = content.find("\n", match_index)- if line_end == -1:- line_end = len(content)- line_content = content[line_start:line_end].strip()- excerpt_source = line_content or content- excerpt_match_index = excerpt_source.lower().find(query.lower())- excerpt_start = max(0, excerpt_match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)- excerpt = excerpt_source[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH]- return {- "matched_field": matched_field,- "path": path,- "line": line,- "excerpt": excerpt[:SKILL_SEARCH_EXCERPT_LENGTH],- }---def _skill_search_tokens(query: str) -> list[tuple[str, ...]]:- raw_tokens = list(dict.fromkeys(re.findall(r"[^\W_]+", query.lower())))- informative_tokens = [token for token in raw_tokens if len(token) >= SKILL_SEARCH_MIN_TOKEN_LENGTH]- bounded_tokens = sorted(informative_tokens, key=len, reverse=True)[:SKILL_SEARCH_MAX_TOKENS] or raw_tokens[:1]- return [_skill_search_variants(token) for token in bounded_tokens]---def _skill_search_variants(token: str) -> tuple[str, ...]:- if len(token) < 6 or not token.isascii() or not token.isalpha():- return (token,)-- stems: list[str] = []- suffix = next(- (- candidate- for candidate in SKILL_SEARCH_DERIVATIONAL_SUFFIXES- if len(token) > len(candidate) and token.endswith(candidate)- ),- None,- )- if suffix is not None:- stems.append(token[: -len(suffix)])- elif token.endswith("ies"):- stems.append(f"{token[:-3]}y")- elif token.endswith(SKILL_SEARCH_SIBILANT_ES_ENDINGS):- stems.append(token[:-2])- elif token.endswith("es"):- stems.extend((token[:-1], token[:-2]))- elif token.endswith("s") and token != "status" and not token.endswith(("is", "ss")):- stems.append(token[:-1])- else:- return (token,)-- variants = [token]- for stem in stems:- variants.append(stem)- if len(stem) >= 2 and stem[-1] == stem[-2]:- variants.append(stem[:-1])- return tuple(dict.fromkeys(variant for variant in variants if len(variant) >= SKILL_SEARCH_MIN_STEM_LENGTH))---def _skill_search_variant_query(field: SkillSearchField, variants: Sequence[str]) -> Q:- lookup = SKILL_SEARCH_FIELD_LOOKUPS[field]- query = Q()- for variant in variants:- query |= Q(**{lookup: variant})- return query---def _skill_search_all_tokens_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:- query = Q()- for variants in tokens:- query &= _skill_search_variant_query(field, variants)- return query---def _skill_search_any_token_query(field: SkillSearchField, tokens: Sequence[Sequence[str]]) -> Q:- query = Q()- for variants in tokens:- query |= _skill_search_variant_query(field, variants)- return query---def _skill_search_field_query(field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]]) -> Q:- return Q(**{SKILL_SEARCH_FIELD_LOOKUPS[field]: phrase}) | _skill_search_any_token_query(field, tokens)---def _skill_search_field_score(- field: SkillSearchField, phrase: str, tokens: Sequence[Sequence[str]], weight: int-) -> Expression:- phrase_score = Case(- When(_skill_search_field_query(field, phrase, ()), then=Value(weight * 2)),- default=Value(0),- output_field=IntegerField(),- )- if not tokens:- return phrase_score-- partial_weight = max(1, weight // len(tokens) // 4)- partial_score: Expression = Value(0, output_field=IntegerField())- for variants in tokens:- partial_score += Case(- When(_skill_search_variant_query(field, variants), then=Value(partial_weight)),- default=Value(0),- output_field=IntegerField(),- )- token_score = Case(- When(_skill_search_all_tokens_query(field, tokens), then=Value(weight)),- default=partial_score,- output_field=IntegerField(),- )- return phrase_score + token_score---class _ScoredSkill(Protocol):- search_score: int---def _skill_search_match_term(content: str, phrase: str, tokens: Sequence[Sequence[str]]) -> str | None:- lowered = content.lower()- if phrase.lower() in lowered:- return phrase- return next((variant for variants in tokens for variant in variants if variant in lowered), None)---def _is_markdown_file_query() -> Q:- return Q(path__iendswith=".md") | Q(content_type__icontains="markdown")---def _file_extension(path: str) -> str:- return path.rsplit(".", 1)[1].lower() if "." in path else ""---def _is_uuid(value: str) -> bool:- try:- UUID(value)- return True- except ValueError:- return False---def _skill_analytics_props(skill: LLMSkill) -> dict[str, Any]:- """Properties shared by every skill report_user_action event.-- These power the internal LLMA skills adoption/usage dashboards — keep stable- and additive (renaming a key here will rename it on every dashboard).- """- file_count = skill.files.count() if skill.pk else 0- body = skill.body or ""- description = skill.description or ""- allowed_tools = skill.allowed_tools or []- return {- "skill_id": str(skill.id),- "skill_name": skill.name,- "skill_version": skill.version,- "skill_is_latest": skill.is_latest,- "skill_body_length": len(body),- "skill_description_length": len(description),- "skill_file_count": file_count,- "skill_has_files": file_count > 0,- "skill_has_license": bool(skill.license),- "skill_has_compatibility": bool(skill.compatibility),- "skill_has_allowed_tools": bool(allowed_tools),- "skill_allowed_tools_count": len(allowed_tools),- }---ALLOWED_LIST_ORDERINGS = frozenset(- {- "name",- "-name",- "created_at",- "-created_at",- "updated_at",- "-updated_at",- "version",- "-version",- "latest_version",- "-latest_version",- "version_count",- "-version_count",- }-)---class CommunityPublishFeatureFlagPermission(CommunitySkillFeatureFlagPermission):- """Gates publishing to the community marketplace, and nothing else on this viewset.-- The Skills product is GA and the marketplace is not, so the flag can only bind to the one action —- otherwise the whole product goes dark, and without it publish goes live everywhere the moment the- GitHub App is installed and the 503 fail-safe stops firing.- """-- def has_permission(self, request, view) -> bool:- if getattr(view, "action", None) != "publish_to_community":- return True- return super().has_permission(request, view)---class CommunityPublishOwnerPermission(BasePermission):- """Restricts publishing to the community to the skill's own owners, and gates nothing else here.-- Publishing writes the skill into a public repository, so it asks for a stronger claim on the skill- than editing it does. The claim must also be per skill. `AccessControlPermission.has_permission`- passes a member who holds an object-level grant on any one skill, and the `name/<slug>` actions- then load whichever skill the URL names, so edit access alone reaches every skill in the project.-- A skill with no current owners is publishable by nobody. Owners leave the set when a member loses- project access, and a skill can be created with an explicit empty owner list, so the alternative is- a fallback to edit access for exactly the skills that have nobody to answer for them. Adding an- owner is the remedy, and the message says so.- """-- NO_OWNERS_MESSAGE = "This skill has no owners. Add an owner to publish it."- NOT_OWNER_MESSAGE = (- "Only an owner can publish this skill to the community. Ask an owner to publish it, or to add you as one."- )-- def has_permission(self, request: Request, view: APIView) -> bool:- if getattr(view, "action", None) != "publish_to_community":- return True-- user = request.user- if not user or not user.is_authenticated:- return False-- skill_view = cast("LLMSkillViewSet", view)- try:- team = skill_view.team- except (ValueError, KeyError, AttributeError):- return False-- skill_name = skill_view.kwargs.get("skill_name") or ""- owners = resolve_skill_owners(team, skill_name)- if any(owner.pk == user.pk for owner in owners):- return True-- # A slug that names no skill answers 404, the way every other `name/<slug>` action answers it,- # because a skill that does not exist has no owners either. Raising here rather than passing- # keeps the action from loading a skill another request creates in between.- if get_skill_by_name_from_db(team, skill_name) is None:- raise NotFound(f"Skill with name '{skill_name}' not found.")-- self.message = self.NO_OWNERS_MESSAGE if not owners else self.NOT_OWNER_MESSAGE- return False---class _CommunityPublishThrottle(PersonalApiKeyOrUserRateThrottle):- # Publishing opens a pull request in a public repo, so the ceiling is "a handful, by hand", not- # the API-shaped hundreds-per-minute of BurstRateThrottle. That one also extends- # PersonalApiKeyRateThrottle, which ignores session traffic.- def get_cache_key(self, request, view):- # Per team, not per credential. The inherited key prefers the personal API key hash, so one- # member holding several keys would get a fresh budget with each of them — and the skill- # being published belongs to the team either way.- team_id = self.safely_get_team_id_from_view(view)- if team_id is None:- return super().get_cache_key(request, view)- return self.cache_format % {"scope": self.scope, "ident": f"team-{team_id}"}---class CommunityPublishBurstThrottle(_CommunityPublishThrottle):- scope = "community_skill_publish_burst"- rate = "6/hour"---class CommunityPublishSustainedThrottle(_CommunityPublishThrottle):- scope = "community_skill_publish_sustained"- rate = "20/day"---class _SkillUserThrottle(PersonalApiKeyOrUserRateThrottle):- """Per-credential throttling for skill endpoints, including OAuth and sessions.-- The general BurstRateThrottle/SustainedRateThrottle only count personal-API-key traffic, so an- OAuth or session caller would reach expensive skill operations unthrottled.- PersonalApiKeyOrUserRateThrottle counts every auth method, but its inherited key identifies- session and OAuth callers by project, so one user's burst would 429 every other user in the- project. Those callers get a per-user bucket instead; a personal API key keeps its own.- """-- def get_cache_key(self, request: Request, view: APIView) -> str:- if not request.user.is_authenticated or isinstance(- request.successful_authenticator, PersonalAPIKeyAuthentication- ):- return super().get_cache_key(request, view)- return self.cache_format % {"scope": self.scope, "ident": f"user:{request.user.pk}"}---class SkillBundleBurstThrottle(_SkillUserThrottle):- # A sandbox fetches the bundle once at session start, so 30/minute clears a burst of concurrent- # starts for one user while still catching a scripted loop hammering the zip build.- scope = "skills_bundle_burst"- rate = "30/minute"---class SkillBundleSustainedThrottle(_SkillUserThrottle):- # A few hundred session starts an hour per user is well beyond normal use and short of what- # sustained abuse of the 5 MB zip build could cost unthrottled.- scope = "skills_bundle_sustained"- rate = "300/hour"---class SkillSearchBurstThrottle(_SkillUserThrottle):- scope = "skills_search_burst"- rate = "60/minute"---class SkillSearchSustainedThrottle(_SkillUserThrottle):- scope = "skills_search_sustained"- rate = "600/hour"---class SkillListBurstThrottle(_SkillUserThrottle):- scope = "skills_list_burst"- rate = BurstRateThrottle.rate---class SkillListSustainedThrottle(_SkillUserThrottle):- scope = "skills_list_sustained"- rate = SustainedRateThrottle.rate---class ZipRenderer(BaseRenderer):- """Lets ``Accept: application/zip`` through content negotiation on the zip actions.-- DRF negotiates before the action runs, so with the JSON-only default a client that asks for the- zip it was promised gets 406. The zip itself is a raw HttpResponse and never reaches a renderer;- only the actions' error Responses do, and those stay JSON so the client can read them.- """-- media_type = "application/zip"- format = "zip"-- def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:- if renderer_context is not None:- renderer_context["response"]["Content-Type"] = "application/json"- return SafeJSONRenderer().render(data, "application/json", renderer_context)---def _spec_problem_messages(export: SkillExport) -> list[str]:- """The shared packaging rules as plain messages, for the endpoints that report them as strings."""- return [- # Most rules word the message for the `spec_problems` field, which carries the path in its- # own column. A flat string has nowhere else to put it, so two bad files would otherwise- # produce the same sentence twice and the author could not tell which file to rename.- f"file '{problem.file_path}': {problem.message}" if problem.file_path else problem.message- for problem in compute_spec_problems(export.name, export.description, [f.path for f in export.files])- ]---def _spec_problems_detail(lead: str, problems: list[str], next_step: str) -> str:- # Clients such as the app toast show only `detail`, so the specific problems must live there too.- sentences = ". ".join((problem[:1].upper() + problem[1:]).removesuffix(".") for problem in problems)- return f"{lead} {sentences}. {next_step}"---_ZIP_ACTIONS = ("bundle", "export")-# With two renderers on an action, drf-spectacular advertises DRF's ``?format=`` override as a query-# parameter. Clients select the zip with ``Accept``; keep the generated types free of it.-_FORMAT_QUERY_PARAM_EXCLUDED = OpenApiParameter(name="format", location=OpenApiParameter.QUERY, exclude=True)--class LLMSkillViewSet(TeamAndOrgViewSetMixin,AccessControlViewSetMixin,+ SkillVersionActionsMixin,+ SkillLifecycleActionsMixin,+ SkillFileActionsMixin,+ SkillTransferActionsMixin,+ SkillMarketplaceActionsMixin,+ SkillCommunityPublishMixin,mixins.CreateModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet,@@ -580,7 +102,7 @@ class LLMSkillViewSet(def get_renderers(self) -> list[BaseRenderer]:renderers = super().get_renderers()- if self.action in _ZIP_ACTIONS:+ if self.action in ZIP_ACTIONS:return [*renderers, ZipRenderer()]return renderers@@ -621,153 +143,13 @@ class LLMSkillViewSet(return ["llm_skill:write"] if request.method == "POST" else ["llm_skill:read"]return None- def _ensure_web_authenticated(self, request: Request) -> Response | None:- if not isinstance(- request.successful_authenticator,- SessionAuthentication | JwtAuthentication | PersonalAPIKeyAuthentication | OAuthAccessTokenAuthentication,- ):- return Response(- {"detail": "This endpoint is only available to web-authenticated users."},- status=status.HTTP_403_FORBIDDEN,- )- return None-- def _skill_not_found_response(self, skill_name: str, version: int | None = None) -> Response:- """A 404 that answers from the same rows `list` returns.-- An agent that lists a skill and then cannot read it concludes the store is inconsistent- and abandons the skill, so a miss has to say which of the two lookups it is: an unknown- name (near-miss names the caller can actually read) or a known name at an absent version- (the versions it does hold).- """- visible = self._visible_skills_queryset()- if version is not None:- available_versions = list(- visible.filter(name=skill_name).order_by("version").values_list("version", flat=True)- )- if available_versions:- return Response(- {- "detail": (- f"Skill with name '{skill_name}' has no version {version}. "- f"Available versions: {', '.join(str(v) for v in available_versions)}."- ),- "type": "skill_version_not_found",- "skill_name": skill_name,- "available_versions": available_versions,- },- status=status.HTTP_404_NOT_FOUND,- )-- suggestions = get_close_matches(- skill_name,- visible.filter(is_latest=True).values_list("name", flat=True)[:MAX_SKILL_NAME_MATCH_CANDIDATES],- n=MAX_SKILL_NAME_SUGGESTIONS,- cutoff=SKILL_NAME_SUGGESTION_CUTOFF,- )- detail = f"Skill with name '{skill_name}' not found."- if suggestions:- detail += " Did you mean " + ", ".join(f"'{name}'" for name in suggestions) + "?"- return Response(- {- "detail": detail,- "type": "skill_not_found",- "skill_name": skill_name,- "suggestions": suggestions,- },- status=status.HTTP_404_NOT_FOUND,- )-- def _load_skill_with_object_access(- self,- request: Request,- skill_name: str,- version: int | None = None,- version_id: str | None = None,- ) -> LLMSkill | None:- # has_permission passes anyone with a grant on any one skill, so the loaded row is checked here.- skill = get_skill_by_name_from_db(self.team, skill_name, version, version_id)- if skill is not None:- self.check_object_permissions(request, skill)- skill = self._apply_trial_skill(request, skill)- return skill-- def _guard_object_access(self, request: Request, skill_name: str) -> Response | None:- if self._load_skill_with_object_access(request, skill_name) is None:- return self._skill_not_found_response(skill_name)- return None-- @cached_property- def _trial_skill(self) -> "ScoutTrialSkill | None":- authenticator = self.request.successful_authenticator- if not isinstance(authenticator, OAuthAccessTokenAuthentication):- return None- token = authenticator.access_token- if "scout_experiment_internal:read" not in (token.scope or "").split():- return None- if token.sandbox_task_id is None:- raise PermissionDenied()- trial_skill = get_scout_trial_skill_override(- team_id=self.team.id, task_id=token.sandbox_task_id, token_id=token.pk- )- if trial_skill is None:- raise PermissionDenied()- return trial_skill-- def _apply_trial_skill(self, request: Request, skill: LLMSkill) -> LLMSkill:- trial_skill = self._trial_skill- if trial_skill is None or trial_skill.name != skill.name:- return skill- pinned = get_skill_by_name_from_db(self.team, skill.name, trial_skill.version)- if pinned is None:- raise NotFound()- self.check_object_permissions(request, pinned)- pinned.body = trial_skill.body- pinned.stamp_digest()- return pinned-- def _handle_skill_write_error(self, err: Exception, skill_name: str) -> Response | None:- """Render the error responses shared by create_file / delete_file / rename_file.+ def _is_scout_sandbox_caller(self) -> bool:+ """Whether the request is authenticated with a Signals scout sandbox token.- Returns None if the error is not one of the shared ones — callers re-raise.+ The scout harness's sandbox token is the only issuer of `signal_scout_internal:*`+ scopes, so their presence identifies a scout run. Session auth and ordinary API+ keys never carry them."""- if isinstance(err, LLMSkillNotFoundError):- return self._skill_not_found_response(skill_name)- if isinstance(err, LLMSkillVersionConflictError):- return Response(- {- "detail": "The skill changed since you opened it. Reload the latest version and try again.",- "current_version": err.current_version,- },- status=status.HTTP_409_CONFLICT,- )- if isinstance(err, LLMSkillVersionLimitError):- return Response(- {- "detail": (- f"Skill has reached the maximum of {err.max_version} versions. "- "Archive and recreate the skill to continue publishing."- ),- },- status=status.HTTP_400_BAD_REQUEST,- )- if isinstance(err, LLMSkillFileLimitError):- return Response(- {"detail": f"Skill has reached the maximum of {err.max_count} files."},- status=status.HTTP_400_BAD_REQUEST,- )- if isinstance(err, LLMSkillDescriptionTooLongError):- return Response(- {- "detail": (- f"Shorten the skill description to {err.max_length} characters before creating a new version."- )- },- status=status.HTTP_400_BAD_REQUEST,- )- return None-- def _is_scout_sandbox_caller(self) -> bool:return is_scout_sandbox_request(self.request)def get_serializer_context(self) -> dict[str, Any]:@@ -776,195 +158,6 @@ class LLMSkillViewSet(context["scout_sandbox_caller"] = Truereturn context- def _serialize_skill(- self, skill: LLMSkill, *, body_offset: int | None = None, body_length: int | None = None- ) -> dict[str, Any]:- context = self.get_serializer_context()- if body_offset is not None or body_length is not None:- context = {**context, "body_offset": body_offset, "body_length": body_length}- return cast(dict[str, Any], LLMSkillSerializer(skill, context=context).data)-- def _serialize_version_summaries(self, skills: list[LLMSkill]) -> list[dict[str, Any]]:- return cast(list[dict[str, Any]], LLMSkillVersionSummarySerializer(skills, many=True).data)-- def _get_requested_version_params(self, request: Request) -> dict[str, Any]:- serializer = LLMSkillFetchQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return serializer.validated_data-- def _get_body_fetch_params(self, request: Request) -> dict[str, Any]:- serializer = LLMSkillBodyFetchQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return serializer.validated_data-- def _get_resolve_query_params(self, request: Request) -> dict[str, Any]:- serializer = LLMSkillResolveQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return serializer.validated_data-- def _get_list_params(self, request: Request) -> dict[str, Any]:- serializer = LLMSkillListQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return serializer.validated_data-- def _visible_skills_queryset(self) -> QuerySet[LLMSkill]:- """Every active skill row this caller may read. `list` and every by-name read share it, so- a name the list returned can never be denied by a read as if it did not exist."""- return self.user_access_control.filter_queryset_by_access_level(- get_active_skill_queryset(self.team), resource="llm_skill"- )-- def _get_list_queryset(self, request: Request) -> QuerySet[LLMSkill]:- params = self._get_list_params(request)-- queryset = self._visible_skills_queryset().filter(is_latest=True)-- search = params.get("search", "").strip()- if search:- queryset = queryset.filter(Q(name__icontains=search) | Q(description__icontains=search))-- created_by_id = params.get("created_by_id")- if created_by_id:- queryset = queryset.filter(created_by_id=created_by_id)-- # Owners are keyed on the logical skill name, not on a version row, so the filter matches by- # name across every version the queryset could surface.- owner_id = params.get("owner_id")- if owner_id:- queryset = queryset.filter(name__in=skill_names_owned_by(self.team, owner_id))-- # Presence of the param — even as an empty string — is a filter: `?category=` returns only- # uncategorized skills, `?category=scout` only scouts. Omitting it returns every category.- if "category" in request.query_params:- queryset = queryset.filter(category=params.get("category") or "")-- order_by = request.query_params.get("order_by", "-created_at")- queryset = queryset.order_by(order_by if order_by in ALLOWED_LIST_ORDERINGS else "-created_at", "-id")- return queryset-- def _get_search_query(self, request: Request) -> str:- serializer = LLMSkillSearchQuerySerializer(data=request.query_params)- serializer.is_valid(raise_exception=True)- return cast(str, serializer.validated_data["query"])-- def _get_search_queryset(self, query: str) -> QuerySet[LLMSkill]:- skill_files = LLMSkillFile.objects.filter(skill_id=OuterRef("pk"))- tokens = _skill_search_tokens(query)- matching_skill_files = skill_files.filter(- _skill_search_field_query("path", query, tokens)- | (_is_markdown_file_query() & _skill_search_field_query("content", query, tokens))- )- file_path_score = Coalesce(- Subquery(- skill_files.annotate(score=_skill_search_field_score("path", query, tokens, 120))- .order_by("-score")- .values("score")[:1],- output_field=IntegerField(),- ),- Value(0),- )- file_content_score = Coalesce(- Subquery(- skill_files.filter(_is_markdown_file_query())- .annotate(score=_skill_search_field_score("content", query, tokens, 40))- .order_by("-score")- .values("score")[:1],- output_field=IntegerField(),- ),- Value(0),- )-- queryset = LLMSkill.objects.filter(- team=self.team,- deleted=False,- is_latest=True,- category="",- )- queryset = self.user_access_control.filter_queryset_by_access_level(queryset, resource="llm_skill")- queryset = queryset.filter(- _skill_search_field_query("name", query, tokens)- | _skill_search_field_query("description", query, tokens)- | _skill_search_field_query("body", query, tokens)- | Q(Exists(matching_skill_files))- )-- exact_name_score = Case(- When(name__iexact=query, then=Value(SKILL_SEARCH_EXACT_NAME_BONUS)),- default=Value(0),- output_field=IntegerField(),- )- score = (- exact_name_score- + _skill_search_field_score("name", query, tokens, 1_000)- + _skill_search_field_score("description", query, tokens, 300)- + _skill_search_field_score("body", query, tokens, 80)- + file_path_score- + file_content_score- )- return queryset.annotate(search_score=score).order_by("-search_score", "name", "id")[:SKILL_SEARCH_RESULT_LIMIT]-- def _get_search_matches(self, skill: LLMSkill, query: str) -> list[dict[str, Any]]:- matches: list[dict[str, Any]] = []- tokens = _skill_search_tokens(query)-- if _skill_search_match_term(skill.name, query, tokens) is not None:- matches.append({"matched_field": "name", "excerpt": skill.name})- description_match = _skill_search_match_term(skill.description, query, tokens)- if description_match is not None:- match_index = skill.description.lower().find(description_match.lower())- excerpt_start = max(0, match_index - SKILL_SEARCH_EXCERPT_LENGTH // 2)- matches.append(- {- "matched_field": "description",- "excerpt": skill.description[excerpt_start : excerpt_start + SKILL_SEARCH_EXCERPT_LENGTH],- }- )- body_match_term = _skill_search_match_term(skill.body, query, tokens)- body_match = (- _content_search_match(skill.body, body_match_term, matched_field="body", path="SKILL.md")- if body_match_term is not None- else None- )- if body_match is not None:- matches.append(body_match)-- if len(matches) < SKILL_SEARCH_MATCH_LIMIT:- remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)- matching_paths = (- skill.files.filter(_skill_search_field_query("path", query, tokens))- .annotate(search_match_score=_skill_search_field_score("path", query, tokens, 120))- .order_by("-search_match_score", "path")- .values_list("path", flat=True)[:remaining_match_count]- )- for path in matching_paths:- matches.append({"matched_field": "file_path", "path": path, "excerpt": path})-- if len(matches) < SKILL_SEARCH_MATCH_LIMIT:- remaining_match_count = SKILL_SEARCH_MATCH_LIMIT - len(matches)- file_content_query = Q(content__icontains=query)- for variants in tokens:- file_content_query |= _skill_search_variant_query("content", variants)- content_files = (- skill.files.filter(_is_markdown_file_query(), file_content_query)- .annotate(search_match_score=_skill_search_field_score("content", query, tokens, 40))- .order_by("-search_match_score", "path")- .values_list("path", "content")- )[:remaining_match_count]- for path, content in content_files:- match_term = _skill_search_match_term(content, query, tokens)- if match_term is None:- continue- match = _content_search_match(- content,- match_term,- matched_field="file_content",- path=path,- )- if match is not None:- matches.append(match)-- return matches[:SKILL_SEARCH_MATCH_LIMIT]-@extend_schema(parameters=[LLMSkillSearchQuerySerializer],responses={@@ -985,22 +178,10 @@ class LLMSkillViewSet(@llma_track_latency("llma_skills_search")@monitor(feature=None, endpoint="llma_skills_search", method="GET")def search(self, request: Request, *args: Any, **kwargs: Any) -> Response:- query = self._get_search_query(request)+ query = cast(str, self._validated_query(LLMSkillSearchQuerySerializer, request)["query"])try:- with execute_with_timeout(SKILL_SEARCH_TIMEOUT_MS):- results: list[dict[str, Any]] = []- for skill in self._get_search_queryset(query):- results.append(- {- "name": skill.name,- "description": skill.description,- "score": cast(_ScoredSkill, skill).search_score,- "matches": self._get_search_matches(skill, query),- }- )- except OperationalError as err:- if not isinstance(err.__cause__, psycopg.errors.QueryCanceled):- raise+ results = search_skills(self.team, self.user_access_control, query)+ except SkillSearchTimeout:return Response({"detail": "Skill search timed out. Use a more specific query and try again."},status=status.HTTP_503_SERVICE_UNAVAILABLE,@@ -1018,1196 +199,16 @@ class LLMSkillViewSet(def perform_create(self, serializer: BaseSerializer[Any]) -> None:instance = cast(LLMSkill, serializer.save())- props = _skill_analytics_props(instance)- logger.info(- "llma_skill_created",- team_id=self.team.id,- user_id=cast(User, self.request.user).id,- **props,- )- report_user_action(- cast(User, self.request.user),- "llma skill created",- props,+ props = skill_analytics_props(instance)+ record_skill_event(+ log_event="llma_skill_created",+ action="llma skill created",+ user=cast(User, self.request.user),team=self.team,request=self.request,+ props=props,)- @extend_schema(- parameters=[LLMSkillBodyFetchQuerySerializer],- responses={200: LLMSkillSerializer},- )- @action(methods=["GET"], detail=False, url_path=r"name/(?P<skill_name>[^/]+)")- @llma_track_latency("llma_skills_get_by_name")- @monitor(feature=None, endpoint="llma_skills_get_by_name", method="GET")- def get_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:- version_params = self._get_body_fetch_params(request)- version = cast(int | None, version_params.get("version"))- skill = self._load_skill_with_object_access(request, skill_name, version)-- if skill is None and _is_uuid(skill_name):- redirect = self._redirect_to_name(request, skill_name)- if redirect is not None:- return redirect-- if skill is None:- return self._skill_not_found_response(skill_name, version)-- # Cap the first page when the caller doesn't page explicitly, so body_next_offset is a- # valid continuation offset even when the full body would be truncated in transit.- body_length = cast(int | None, version_params.get("body_length"))- if body_length is None:- body_length = DEFAULT_BODY_PAGE_LENGTH-- return Response(- self._serialize_skill(- skill,- body_offset=cast(int | None, version_params.get("body_offset")),- body_length=body_length,- )- )-- def _redirect_to_name(self, request: Request, skill_name: str) -> Response | None:- skill_by_id = get_active_skill_queryset(self.team).filter(id=skill_name).first()- if skill_by_id is None:- return None- self.check_object_permissions(request, skill_by_id)- # Use a relative path (no build_absolute_uri) to avoid embedding the- # Host header in the Location value — prevents host-header open-redirect.- redirect_url = request.get_full_path().replace(skill_name, skill_by_id.name, 1)- response = Response(status=status.HTTP_302_FOUND)- response["Location"] = redirect_url- return response-- @extend_schema(request=LLMSkillPublishSerializer, responses={200: LLMSkillSerializer})- @get_by_name.mapping.patch- @llma_track_latency("llma_skills_publish_by_name")- @monitor(feature=None, endpoint="llma_skills_publish_by_name", method="PATCH")- def update_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- payload = LLMSkillPublishSerializer(data=request.data)- payload.is_valid(raise_exception=True)-- # Resolve owners before publishing so a bad UUID 400s without minting a version. `owner_uuids`- # is None when omitted (owners left untouched), [] when the caller clears them.- owner_uuids = payload.validated_data.get("owners")- owner_users = None- if owner_uuids is not None:- try:- owner_users = resolve_owner_users(self.team, [str(u) for u in owner_uuids])- except LLMSkillOwnerNotFoundError as err:- raise serializers.ValidationError(- {"owners": f"User '{err.user_uuid}' is not a member of this project."},- code="invalid_owner",- )-- # An owner-only PATCH must not publish a version: owners live on the logical skill, not a- # version row, so minting an identical version would rewrite version-history authorship, bump- # marketplace/update timestamps, and burn toward MAX_SKILL_VERSION for a no-op body. Same- # optimistic-concurrency contract as a publish when `base_version` is supplied: a stale value- # still 409s. It may be omitted (the generated PATCH schema marks it optional), which skips- # the version check — ownership isn't version-keyed, so the replace is still exact.- if owner_uuids is not None and all(payload.validated_data.get(p) is None for p in PUBLISH_CONTENT_FIELDS):- base_version = payload.validated_data.get("base_version")- # Lock the latest row for the check + replace (mirrors publish_skill_version): requests- # run autocommit, so without the lock an owner update racing a publish from the same- # base_version could pass a stale check and 200 where the contract advertises 409.- with transaction.atomic():- current_latest = (- LLMSkill.objects.select_for_update()- .filter(team=self.team, name=skill_name, deleted=False, is_latest=True)- .order_by("-version", "-created_at", "-id")- .first()- )- if current_latest is None:- return self._skill_not_found_response(skill_name)- if base_version is not None and base_version != current_latest.version:- return Response(- {- "detail": "The skill changed since you opened it. Reload the latest version and try again.",- "current_version": current_latest.version,- },- status=status.HTTP_409_CONFLICT,- )- set_skill_owners(self.team, skill_name, cast(list, owner_users))- refreshed = get_skill_by_name_from_db(self.team, skill_name=skill_name)- return Response(self._serialize_skill(cast(LLMSkill, refreshed)))-- try:- # One transaction for the version publish *and* the owner replacement: if setting owners- # fails, the published version rolls back with it — otherwise the new body/files would be- # live while ownership stayed stale, and a retry with the original base_version would 409.- with transaction.atomic():- published_skill = publish_skill_version(- self.team,- user=cast(User, request.user),- skill_name=skill_name,- body=payload.validated_data.get("body"),- edits=payload.validated_data.get("edits"),- description=payload.validated_data.get("description"),- license=payload.validated_data.get("license"),- compatibility=payload.validated_data.get("compatibility"),- allowed_tools=payload.validated_data.get("allowed_tools"),- metadata=payload.validated_data.get("metadata"),- files=payload.validated_data.get("files"),- file_edits=payload.validated_data.get("file_edits"),- base_version=payload.validated_data["base_version"],- version_description=payload.validated_data.get("version_description"),- )- # Owners are keyed on the logical skill, so this runs only when the caller passed- # `owners` — a plain body edit never touches ownership.- if owner_uuids is not None:- set_skill_owners(self.team, skill_name, cast(list, owner_users))- except IntegrityError as err:- if "unique_skill_file_path" in str(err):- raise serializers.ValidationError({"files": "Duplicate file paths are not allowed."}, code="unique")- raise- except LLMSkillNotFoundError:- return self._skill_not_found_response(skill_name)- except LLMSkillVersionConflictError as err:- return Response(- {- "detail": "The skill changed since you opened it. Reload the latest version and try again.",- "current_version": err.current_version,- },- status=status.HTTP_409_CONFLICT,- )- except LLMSkillVersionLimitError as err:- return Response(- {- "detail": (- f"Skill has reached the maximum of {err.max_version} versions. "- "Archive and recreate the skill to continue publishing."- ),- },- status=status.HTTP_400_BAD_REQUEST,- )- except LLMSkillDescriptionTooLongError as err:- return Response(- {- "detail": (- f"Shorten the skill description to {err.max_length} characters before creating a new version."- )- },- status=status.HTTP_400_BAD_REQUEST,- )- except LLMSkillEditError as err:- error_body: dict[str, Any] = {"detail": err.message}- if err.edit_index is not None:- error_body["edit_index"] = err.edit_index- if err.file_path is not None:- error_body["file_path"] = err.file_path- return Response(error_body, status=status.HTTP_400_BAD_REQUEST)-- edits_value = payload.validated_data.get("edits")- file_edits_value = payload.validated_data.get("file_edits")- files_value = payload.validated_data.get("files")- props = {- **_skill_analytics_props(published_skill),- "base_version": payload.validated_data["base_version"],- "body_changed": payload.validated_data.get("body") is not None or edits_value is not None,- "files_replaced": files_value is not None,- "files_replaced_count": len(files_value) if files_value is not None else 0,- "edits_used": edits_value is not None,- "edits_count": len(edits_value) if edits_value is not None else 0,- "file_edits_used": file_edits_value is not None,- "file_edits_count": len(file_edits_value) if file_edits_value is not None else 0,- "description_changed": payload.validated_data.get("description") is not None,- "license_changed": payload.validated_data.get("license") is not None,- "compatibility_changed": payload.validated_data.get("compatibility") is not None,- "allowed_tools_changed": payload.validated_data.get("allowed_tools") is not None,- "metadata_changed": payload.validated_data.get("metadata") is not None,- "owners_changed": owner_uuids is not None,- "version_description_set": payload.validated_data.get("version_description") is not None,- }- logger.info(- "llma_skill_version_published",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill version published",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(published_skill))-- @extend_schema(parameters=[LLMSkillResolveQuerySerializer], responses={200: LLMSkillResolveResponseSerializer})- @action(- methods=["GET"],- detail=False,- url_path=r"resolve/name/(?P<skill_name>[^/]+)",- required_scopes=["llm_skill:read"],- )- @llma_track_latency("llma_skills_resolve_by_name")- @monitor(feature=None, endpoint="llma_skills_resolve_by_name", method="GET")- def resolve_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- query_params = self._get_resolve_query_params(request)- version = cast(int | None, query_params.get("version"))- version_id = query_params.get("version_id")- skill = self._load_skill_with_object_access(- request,- skill_name,- version,- str(version_id) if version_id else None,- )- if skill is None:- return self._skill_not_found_response(skill_name, version)-- limit = cast(int, query_params["limit"])- offset = cast(int | None, query_params.get("offset"))- before_version = cast(int | None, query_params.get("before_version"))- versions, has_more = resolve_versions_page(- self.team,- skill_name=skill_name,- limit=limit,- offset=offset,- before_version=before_version,- )- return Response(- {- "skill": self._serialize_skill(skill),- "versions": self._serialize_version_summaries(versions),- "has_more": has_more,- }- )-- @extend_schema(- parameters=[LLMSkillFetchQuerySerializer],- responses={200: LLMSkillMarkdownSerializer},- )- # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients- @action(- methods=["GET"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/skill-md",- required_scopes=["llm_skill:read"],- )- @llma_track_latency("llma_skills_skill_md")- @monitor(feature=None, endpoint="llma_skills_skill_md", method="GET")- def skill_md(self, request: Request, skill_name: str = "", **kwargs) -> Response:- """The rendered SKILL.md plus its frontmatter as JSON, for a host that serves the file.-- Both halves come from one renderer, so a digest a client takes over ``content`` still- describes the fields it reads from ``frontmatter``.- """- version_params = self._get_requested_version_params(request)- version = cast(int | None, version_params.get("version"))- skill = self._load_skill_with_object_access(request, skill_name, version)- if skill is None:- return self._skill_not_found_response(skill_name, version)-- # SKILL.md never carries the bundled files, so don't load them just to render it.- export = skill.to_export()- payload = LLMSkillMarkdownSerializer(- instance={- "name": skill.name,- "version": skill.version,- "content": render_skill_md(export),- "frontmatter": frontmatter_document(export),- }- )- return Response(payload.data)-- @extend_schema(- parameters=[LLMSkillFetchQuerySerializer, _FORMAT_QUERY_PARAM_EXCLUDED],- responses={(200, "application/zip"): OpenApiTypes.BINARY},- )- @action(methods=["GET"], detail=False, url_path=r"name/(?P<skill_name>[^/]+)/export")- @llma_track_latency("llma_skills_export")- @monitor(feature=None, endpoint="llma_skills_export", method="GET")- def export(self, request: Request, skill_name: str = "", **kwargs) -> Response | HttpResponse:- version_params = self._get_requested_version_params(request)- version = cast(int | None, version_params.get("version"))- skill = self._load_skill_with_object_access(request, skill_name, version)- if skill is None:- return self._skill_not_found_response(skill_name, version)-- export = load_skill_export(skill)- problems = _spec_problem_messages(export)- if problems:- return Response(- {- "detail": _spec_problems_detail(- "Couldn't download this skill because it doesn't meet the Agent Skills spec.",- problems,- "Edit the skill to fix this, then try again.",- ),- "problems": problems,- },- status=status.HTTP_400_BAD_REQUEST,- )-- zip_bytes = build_skill_zip(export)- response = HttpResponse(zip_bytes, content_type="application/zip")- response["Content-Disposition"] = f'attachment; filename="{skill.name}.zip"'- return response-- @extend_schema(- parameters=[LLMSkillBundleQuerySerializer, _FORMAT_QUERY_PARAM_EXCLUDED],- responses={(200, "application/zip"): OpenApiTypes.BINARY},- )- @action(methods=["GET"], detail=False, url_path="bundle", required_scopes=["llm_skill:read"])- @llma_track_latency("llma_skills_bundle")- @monitor(feature=None, endpoint="llma_skills_bundle", method="GET")- def bundle(self, request: Request, **kwargs) -> Response | HttpResponse:- """One zip of the requesting user's store skills, for unpacking into a skills directory."""- query = LLMSkillBundleQuerySerializer(data=request.query_params)- query.is_valid(raise_exception=True)- authenticator = request.successful_authenticator- if (- query.validated_data["content"] == "full"- and isinstance(authenticator, OAuthAccessTokenAuthentication)- and "scout_experiment_internal:read" in (authenticator.access_token.scope or "").split()- ):- # Full bundles load rows independently and cannot apply a run's pinned candidate.- raise PermissionDenied(- "Scout trials must fetch individual skills or use a stub bundle instead of a full bundle."- )- user = cast(User, request.user)- flag_value = posthog_feature_flag_value(- SANDBOX_SKILLS_FEATURE_FLAG,- sandbox_skills_flag_distinct_id(user),- organization_id=self.organization.id,- team_id=self.team.id,- )- # None means the flag service did not answer. A sandbox treats 404 as "not enabled", so- # do not hand it that on an outage; 503 lets the caller tell the two apart.- if flag_value is None:- return Response(- {"detail": "Feature flag evaluation is unavailable."}, status=status.HTTP_503_SERVICE_UNAVAILABLE- )- # A plain 404 Response, not NotFound: @monitor counts raised exceptions as endpoint errors,- # and every sandbox in a non-flagged project hits this path once per run.- if not flag_value:- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)-- # Same object-level filter the list endpoint applies, so the bundle never carries a skill the- # list would hide from this user.- readable_skills = self.user_access_control.filter_queryset_by_access_level(- LLMSkill.objects.filter(team=self.team), resource="llm_skill"- )- bundle = build_skill_bundle(- self.team,- user,- readable_skills,- content=query.validated_data["content"],- limit=query.validated_data["limit"],- )- response = HttpResponse(bundle.zip_bytes, content_type="application/zip")- response["Content-Disposition"] = 'attachment; filename="skills-bundle.zip"'- # Counts only: names are unbounded and would blow past proxy header limits for heavy users.- response["X-Skills-Included"] = str(len(bundle.included))- response["X-Skills-Dropped"] = str(bundle.dropped_count)- response["X-Skills-Skipped"] = str(bundle.skipped_count)- return response-- @extend_schema(request=LLMSkillImportSerializer, responses={201: LLMSkillSerializer})- @action(- methods=["POST"],- detail=False,- url_path="import",- required_scopes=["llm_skill:write"],- parser_classes=[MultiPartParser, FormParser],- )- @llma_track_latency("llma_skills_import")- @monitor(feature=None, endpoint="llma_skills_import", method="POST")- def import_skill(self, request: Request, **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- upload = request.FILES.get("file")- if upload is None:- return Response(- {"detail": "Attach the skill .zip as multipart form field 'file'."},- status=status.HTTP_400_BAD_REQUEST,- )- # Bound the read by bytes (read one past the cap) — upload.size is not always reliable, so- # don't trust it as the only guard against buffering an oversized body into memory.- raw = upload.read(MAX_IMPORT_ZIP_BYTES + 1)- if len(raw) > MAX_IMPORT_ZIP_BYTES:- return Response(- {"detail": f"Zip must be {MAX_IMPORT_ZIP_BYTES} bytes or fewer."},- status=status.HTTP_400_BAD_REQUEST,- )-- try:- skill_export = parse_skill_zip(raw)- except SkillImportError as err:- return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)-- problems = self._import_problems(skill_export)- if problems:- return Response(- {- "detail": _spec_problems_detail(- "Couldn't import this zip because it doesn't meet the Agent Skills spec.",- problems,- "Fix the skill files, then try again.",- ),- "problems": problems,- },- status=status.HTTP_400_BAD_REQUEST,- )-- try:- skill = create_skill(- self.team,- user=cast(User, request.user),- name=skill_export.name,- description=skill_export.description,- body=skill_export.body,- license=skill_export.license,- compatibility=skill_export.compatibility,- allowed_tools=skill_export.allowed_tools,- metadata=skill_export.metadata,- files=[- {"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill_export.files- ],- )- except LLMSkillDuplicateNameConflictError:- return Response(- {"attr": "name", "detail": f"A skill named '{skill_export.name}' already exists."},- status=status.HTTP_400_BAD_REQUEST,- )- except LLMSkillFilePathConflictError:- return Response({"detail": "Duplicate bundled file paths in the zip."}, status=status.HTTP_400_BAD_REQUEST)- except LLMSkillFileLimitError as err:- return Response(- {"detail": f"Skill exceeds the maximum of {err.max_count} bundled files."},- status=status.HTTP_400_BAD_REQUEST,- )-- props = {**_skill_analytics_props(skill), "imported": True}- logger.info("llma_skill_imported", team_id=self.team.id, user_id=cast(User, request.user).id, **props)- report_user_action(cast(User, request.user), "llma skill imported", props, team=self.team, request=request)- return Response(self._serialize_skill(skill), status=status.HTTP_201_CREATED)-- def _import_problems(self, skill_export) -> list[str]:- # The import path calls create_skill directly, so it must re-apply the same size/shape limits- # the create/edit serializers enforce — otherwise a spec-valid zip could persist content- # (oversized body/files, whitespace-bearing tools) the rest of the system assumes is bounded.- # _spec_problem_messages already covers the description, the name shape and the file paths.- problems: list[str] = _spec_problem_messages(skill_export)- # The reserved-name and bundled-name rules are all this adds on top of the shape rules- # above, so calling it for a malformed name would report that defect twice.- if skill_name_is_well_formed(skill_export.name):- try:- validate_new_skill_name_value(skill_export.name)- except serializers.ValidationError as err:- problems.append(f"name: {self._first_error(err)}")- try:- validate_skill_body_size(skill_export.body)- except serializers.ValidationError as err:- problems.append(f"body: {self._first_error(err)}")- for tool in skill_export.allowed_tools:- try:- validate_allowed_tool(tool)- except serializers.ValidationError as err:- problems.append(f"allowed-tools '{tool}': {self._first_error(err)}")- if len(skill_export.license) > 255:- problems.append("license must be 255 characters or fewer")- if len(skill_export.compatibility) > 500:- problems.append("compatibility must be 500 characters or fewer")-- for skill_file in skill_export.files:- # create_skill inserts the files with bulk_create, which runs no model validation, so a- # path the column cannot hold reaches Postgres as a DataError and fails the request.- if len(skill_file.path) > 500:- problems.append(f"file '{skill_file.path}': path must be 500 characters or fewer")- if len(skill_file.content.encode("utf-8")) > MAX_SKILL_FILE_BYTES:- problems.append(f"file '{skill_file.path}': content must be {MAX_SKILL_FILE_BYTES} bytes or fewer")- return problems-- @staticmethod- def _first_error(err: serializers.ValidationError) -> str:- detail = err.detail- if isinstance(detail, list) and detail:- return str(detail[0])- return str(detail)-- def _marketplace_command_payload(self, request: Request, key, token: str | None, status_str: str) -> dict[str, Any]:- """Shape the marketplace-command response from a credential (or absence of one)."""- team_id = self.team.id-- def claude(tok: str | None) -> str:- return build_install_command(team_id, tok, plugin_name=PLUGIN_NAME, marketplace_name=MARKETPLACE_NAME)-- def codex(tok: str | None) -> str:- return build_codex_install_command(team_id, tok, plugin_name=PLUGIN_NAME, marketplace_name=MARKETPLACE_NAME)-- return {- "status": status_str,- "connected": key is not None,- "plugin_name": PLUGIN_NAME,- "marketplace_name": MARKETPLACE_NAME,- "label": marketplace_credential_label(team_id),- "repo_url": marketplace_repo_url(team_id),- "command": claude(token) if token else None,- "command_template": claude(None),- "codex_command": codex(token) if token else None,- "codex_command_template": codex(None),- "token": token,- "mask_value": key.mask_value if key is not None else None,- "created_at": key.created_at if key is not None else None,- "last_rolled_at": key.last_rolled_at if key is not None else None,- }-- @extend_schema(responses={200: LLMSkillMarketplaceCommandSerializer})- # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients- @action(methods=["GET"], detail=False, url_path="marketplace/install-command")- @llma_track_latency("llma_skills_marketplace_command")- @monitor(feature=None, endpoint="llma_skills_marketplace_command", method="GET")- def marketplace_command(self, request: Request, **kwargs) -> Response:- """Report whether the user already has a marketplace credential, without minting one.-- The token is unrecoverable, so an existing credential returns its mask only — the UI shows- "already connected, existing setups keep working" and offers an explicit rotate.- """- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- key = get_marketplace_credential(self.team, cast(User, request.user))- payload = self._marketplace_command_payload(request, key, None, "exists" if key is not None else "absent")- return Response(LLMSkillMarketplaceCommandSerializer(payload).data)-- @extend_schema(request=LLMSkillMarketplaceIssueSerializer, responses={200: LLMSkillMarketplaceCommandSerializer})- @marketplace_command.mapping.post- @llma_track_latency("llma_skills_marketplace_issue")- @monitor(feature=None, endpoint="llma_skills_marketplace_issue", method="POST")- def issue_marketplace_command(self, request: Request, **kwargs) -> Response:- """Mint the user's read-only marketplace credential (or rotate it) and return the install command.-- Per-user: rotating only ever invalidates this user's own credential, never a teammate's.- """- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- payload = LLMSkillMarketplaceIssueSerializer(data=request.data)- payload.is_valid(raise_exception=True)-- issued = issue_marketplace_credential(- self.team, cast(User, request.user), rotate=payload.validated_data["rotate"]- )-- if issued.status in ("created", "rotated"):- props = {"status": issued.status, "plugin_name": PLUGIN_NAME}- logger.info(- "llma_skill_marketplace_credential_issued",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill marketplace credential issued",- props,- team=self.team,- request=request,- )-- result = self._marketplace_command_payload(request, issued.key, issued.token, issued.status)- return Response(LLMSkillMarketplaceCommandSerializer(result).data)-- @extend_schema(- request=None,- responses={- 204: None,- 403: OpenApiResponse(- description="Another product owns what this skill runs and refuses this caller's archive."- ),- },- )- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/archive",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_archive")- @monitor(feature=None, endpoint="llma_skills_archive", method="POST")- def archive(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- try:- skill_versions = archive_skill(- self.team,- skill_name,- acting_user=cast(User, request.user),- authenticator=request.successful_authenticator,- )- except SkillArchiveRefused as err:- # A sibling product owns what this skill runs and says this caller may not remove it.- return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)- except LLMSkillNotFoundError:- return self._skill_not_found_response(skill_name)-- props = {- "skill_name": skill_name,- "skill_versions": skill_versions,- "skill_version_count": len(skill_versions),- "skill_latest_version": max(skill_versions) if skill_versions else None,- }- logger.info(- "llma_skill_archived",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill archived",- props,- team=self.team,- request=request,- )- return Response(status=status.HTTP_204_NO_CONTENT)-- @extend_schema(request=LLMSkillDuplicateSerializer, responses={201: LLMSkillSerializer})- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/duplicate",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_duplicate")- @monitor(feature=None, endpoint="llma_skills_duplicate", method="POST")- def duplicate(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- payload = LLMSkillDuplicateSerializer(data=request.data)- payload.is_valid(raise_exception=True)- new_name = payload.validated_data["new_name"]-- try:- new_skill = duplicate_skill(- self.team,- user=cast(User, request.user),- source_name=skill_name,- new_name=new_name,- )- except LLMSkillNotFoundError:- return self._skill_not_found_response(skill_name)- except LLMSkillDuplicateNameConflictError:- return Response(- {"attr": "new_name", "detail": "A skill with this name already exists."},- status=status.HTTP_400_BAD_REQUEST,- )- except LLMSkillDescriptionTooLongError as err:- return Response(- {- "detail": (- f"Shorten the source skill description to {err.max_length} characters before duplicating it."- )- },- status=status.HTTP_400_BAD_REQUEST,- )-- props = {- **_skill_analytics_props(new_skill),- "source_skill_name": skill_name,- }- logger.info(- "llma_skill_duplicated",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill duplicated",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(new_skill), status=status.HTTP_201_CREATED)-- @extend_schema(- request=LLMSkillRenameSerializer,- responses={- 200: LLMSkillSerializer,- 403: OpenApiResponse(- description="Another product owns what this skill runs and refuses this caller's rename."- ),- },- )- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/rename",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_rename")- @monitor(feature=None, endpoint="llma_skills_rename", method="POST")- def rename(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- payload = LLMSkillRenameSerializer(data=request.data)- payload.is_valid(raise_exception=True)- new_name = payload.validated_data["new_name"]-- try:- renamed_skill = rename_skill(- self.team,- skill_name=skill_name,- new_name=new_name,- acting_user=cast(User, request.user),- authenticator=request.successful_authenticator,- )- except SkillRenameRefused as err:- return Response({"detail": str(err)}, status=status.HTTP_403_FORBIDDEN)- except SkillRenameConflict as err:- raise serializers.ValidationError({"new_name": str(err)}, code="unique")- except LLMSkillNotFoundError:- return self._skill_not_found_response(skill_name)- except LLMSkillDuplicateNameConflictError:- raise serializers.ValidationError(- {"new_name": "A skill with this name already exists."},- code="unique",- )- except LLMSkillRenameNotAllowedError as err:- raise serializers.ValidationError(- {- "new_name": (- f"Names starting with '{err.prefix}' keep product settings under the skill name, "- "so a skill can't be renamed into or out of them. Duplicate the skill instead."- )- },- code="reserved_prefix",- )-- props = {- **_skill_analytics_props(renamed_skill),- "previous_skill_name": skill_name,- }- logger.info(- "llma_skill_renamed",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill renamed",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(renamed_skill))-- @extend_schema(- request=LLMSkillPublishToCommunitySerializer,- responses={201: CommunitySkillPublishResultSerializer, 409: LLMSkillPublishConflictSerializer},- )- # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/publish-community",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_publish_community")- @monitor(feature=None, endpoint="llma_skills_publish_community", method="POST")- def publish_to_community(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- skill = self._load_skill_with_object_access(request, skill_name)- if skill is None:- return self._skill_not_found_response(skill_name)-- payload = LLMSkillPublishToCommunitySerializer(data=request.data)- payload.is_valid(raise_exception=True)-- # Category rides along with id and version because registering a skill as a scout stamps- # `category` without raising the version: on version alone, a skill reviewed as an ordinary- # one could publish as a scout, carrying a schedule its publisher never consented to.- expected_category = payload.validated_data.get("expected_category")- if (- skill.id != payload.validated_data["expected_skill_id"]- or skill.version != payload.validated_data["expected_version"]- or (expected_category is not None and skill.category != expected_category)- ):- return Response(- {- "detail": "This skill changed after you reviewed it. Reopen the dialog and review the latest version."- },- status=status.HTTP_409_CONFLICT,- )-- files = [{"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill.files.all()]- supplied_tags = payload.validated_data.get("tags")- # An explicit empty list means "publish with no tags", so fall back to the skill's own tags- # only when the caller omitted the field. Those are unvalidated metadata, unlike the ones the- # serializer checked, so they go through publishable_tags first.- if supplied_tags is None:- supplied_tags = publishable_tags((skill.metadata or {}).get("tags"))- # The LLMSkill name is the kebab slug; default the community display name to a title-cased form.- display_name = payload.validated_data.get("display_name") or skill.name.replace("-", " ").title()-- # Derived, not caller-supplied: a scout published as a plain skill is exactly the entry the- # catalog can't tell apart, and it lands in another project inert.- kind = (- CommunitySkillKind.SCOUT.value if skill.category == SCOUT_SKILL_CATEGORY else CommunitySkillKind.SKILL.value- )-- try:- result = publish_skill_to_community(- slug=skill.name,- # Scopes the publish branch to this team, so one team cannot rewrite another team's- # open pull request for the same slug.- publisher_id=str(self.team.uuid),- name=display_name,- description=skill.description,- body=skill.body,- files=files or None,- tags=supplied_tags,- allowed_tools=skill.allowed_tools or [],- license=skill.license or "",- compatibility=skill.compatibility or "",- author_handle=payload.validated_data.get("author_handle", ""),- metadata=skill.metadata,- kind=kind,- scout_config=payload.validated_data.get("scout_config"),- )- except CommunitySkillPublishNotConfiguredError:- # The fail-safe is otherwise silent, so an instance that meant to have publishing on- # looks like one that never configured it until somebody reports the toast.- logger.warning(- "llma_skill_publish_to_community_not_configured",- team_id=self.team.id,- user_id=cast(User, request.user).id,- skill_name=skill.name,- )- return Response(- {"detail": "Publishing to the community is not available on this instance."},- status=status.HTTP_503_SERVICE_UNAVAILABLE,- )- except CommunitySkillPublishValidationError as err:- # Nothing reached GitHub, and republishing the same skill fails the same way — the- # publisher has to edit it. That is a 400, not the 502 an unreachable GitHub gets.- return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)- except CommunitySkillPublishError as err:- # The client sees the reason once; without this the server keeps no record of a publish- # that failed against GitHub.- logger.warning(- "llma_skill_publish_to_community_failed",- team_id=self.team.id,- user_id=cast(User, request.user).id,- skill_name=skill.name,- error=str(err),- )- return Response({"detail": str(err)}, status=status.HTTP_502_BAD_GATEWAY)-- props = {**_skill_analytics_props(skill), "community_pr_number": result["pr_number"]}- logger.info(- "llma_skill_published_to_community",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill published to community",- props,- team=self.team,- request=request,- )- return Response(result, status=status.HTTP_201_CREATED)-- @extend_schema(- parameters=[LLMSkillFetchQuerySerializer],- responses={200: LLMSkillFileSerializer},- )- # NOTE: `required_scopes` is intentionally not set on @action here. delete_file is registered- # below via @get_file.mapping.delete and shares this URL pattern's initkwargs — setting- # required_scopes here would short-circuit ScopeBasePermission._get_required_scopes for DELETE- # too, granting llm_skill:read access to a destructive operation. Scopes are resolved per-method- # in dangerously_get_required_scopes instead.- @action(- methods=["GET"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/files/(?P<file_path>.+)",- )- @llma_track_latency("llma_skills_get_file")- @monitor(feature=None, endpoint="llma_skills_get_file", method="GET")- def get_file(self, request: Request, skill_name: str = "", file_path: str = "", **kwargs) -> Response:- version_params = self._get_requested_version_params(request)- version = cast(int | None, version_params.get("version"))- skill = self._load_skill_with_object_access(request, skill_name, version)- if skill is None:- return self._skill_not_found_response(skill_name, version)-- file_path = file_path.rstrip("/")- normalized = file_path.replace("\\", "/")- if ".." in normalized.split("/") or normalized.startswith("/"):- return Response(- {"detail": "Invalid file path."},- status=status.HTTP_400_BAD_REQUEST,- )- skill_file = LLMSkillFile.objects.filter(skill=skill, path=file_path).first()- if skill_file is None:- return Response(- {"detail": f"File '{file_path}' not found in skill '{skill_name}'."},- status=status.HTTP_404_NOT_FOUND,- )-- return Response(LLMSkillFileSerializer(skill_file).data)-- @extend_schema(request=LLMSkillFileCreateSerializer, responses={201: LLMSkillSerializer})- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/files",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_create_file")- @monitor(feature=None, endpoint="llma_skills_create_file", method="POST")- def create_file(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- payload = LLMSkillFileCreateSerializer(data=request.data)- payload.is_valid(raise_exception=True)-- try:- published_skill = create_skill_file(- self.team,- user=cast(User, request.user),- skill_name=skill_name,- path=payload.validated_data["path"],- content=payload.validated_data["content"],- content_type=payload.validated_data.get("content_type", "text/plain"),- base_version=payload.validated_data.get("base_version"),- )- except (- LLMSkillNotFoundError,- LLMSkillVersionConflictError,- LLMSkillVersionLimitError,- LLMSkillFileLimitError,- LLMSkillDescriptionTooLongError,- ) as err:- response = self._handle_skill_write_error(err, skill_name)- if response is None:- raise- return response- except LLMSkillFilePathConflictError as err:- return Response(- {"detail": f"File '{err.path}' already exists in skill '{skill_name}'."},- status=status.HTTP_409_CONFLICT,- )-- path_value = payload.validated_data["path"]- content_value = payload.validated_data["content"]- props = {- **_skill_analytics_props(published_skill),- "path": path_value,- "content_type": payload.validated_data.get("content_type", "text/plain"),- "file_content_length": len(content_value),- "file_extension": _file_extension(path_value),- }- logger.info(- "llma_skill_file_created",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill file created",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(published_skill), status=status.HTTP_201_CREATED)-- @extend_schema(parameters=[LLMSkillFileDeleteQuerySerializer], responses={200: LLMSkillSerializer})- @get_file.mapping.delete- @llma_track_latency("llma_skills_delete_file")- @monitor(feature=None, endpoint="llma_skills_delete_file", method="DELETE")- def delete_file(self, request: Request, skill_name: str = "", file_path: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- file_path = file_path.rstrip("/")- normalized = file_path.replace("\\", "/")- if ".." in normalized.split("/") or normalized.startswith("/"):- return Response({"detail": "Invalid file path."}, status=status.HTTP_400_BAD_REQUEST)-- query = LLMSkillFileDeleteQuerySerializer(data=request.query_params)- query.is_valid(raise_exception=True)-- try:- published_skill = delete_skill_file(- self.team,- user=cast(User, request.user),- skill_name=skill_name,- path=file_path,- base_version=query.validated_data.get("base_version"),- )- except (- LLMSkillNotFoundError,- LLMSkillVersionConflictError,- LLMSkillVersionLimitError,- LLMSkillFileLimitError,- LLMSkillDescriptionTooLongError,- ) as err:- response = self._handle_skill_write_error(err, skill_name)- if response is None:- raise- return response- except LLMSkillFileNotFoundError as err:- return Response(- {"detail": f"File '{err.path}' not found in skill '{skill_name}'."},- status=status.HTTP_404_NOT_FOUND,- )-- props = {- **_skill_analytics_props(published_skill),- "path": file_path,- "file_extension": _file_extension(file_path),- }- logger.info(- "llma_skill_file_deleted",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill file deleted",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(published_skill))-- @extend_schema(request=LLMSkillFileRenameSerializer, responses={200: LLMSkillSerializer})- # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients- @action(- methods=["POST"],- detail=False,- url_path=r"name/(?P<skill_name>[^/]+)/files-rename",- required_scopes=["llm_skill:write"],- )- @llma_track_latency("llma_skills_rename_file")- @monitor(feature=None, endpoint="llma_skills_rename_file", method="POST")- def rename_file(self, request: Request, skill_name: str = "", **kwargs) -> Response:- auth_error = self._ensure_web_authenticated(request)- if auth_error is not None:- return auth_error-- access_error = self._guard_object_access(request, skill_name)- if access_error is not None:- return access_error-- payload = LLMSkillFileRenameSerializer(data=request.data)- payload.is_valid(raise_exception=True)-- try:- published_skill = rename_skill_file(- self.team,- user=cast(User, request.user),- skill_name=skill_name,- old_path=payload.validated_data["old_path"],- new_path=payload.validated_data["new_path"],- base_version=payload.validated_data.get("base_version"),- )- except (- LLMSkillNotFoundError,- LLMSkillVersionConflictError,- LLMSkillVersionLimitError,- LLMSkillFileLimitError,- LLMSkillDescriptionTooLongError,- ) as err:- response = self._handle_skill_write_error(err, skill_name)- if response is None:- raise- return response- except LLMSkillFileNotFoundError as err:- return Response(- {"detail": f"File '{err.path}' not found in skill '{skill_name}'."},- status=status.HTTP_404_NOT_FOUND,- )- except LLMSkillFilePathConflictError as err:- return Response(- {"detail": f"File '{err.path}' already exists in skill '{skill_name}'."},- status=status.HTTP_409_CONFLICT,- )-- old_path_value = payload.validated_data["old_path"]- new_path_value = payload.validated_data["new_path"]- old_extension = _file_extension(old_path_value)- new_extension = _file_extension(new_path_value)- props = {- **_skill_analytics_props(published_skill),- "old_path": old_path_value,- "new_path": new_path_value,- "old_file_extension": old_extension,- "new_file_extension": new_extension,- "extension_changed": old_extension != new_extension,- }- logger.info(- "llma_skill_file_renamed",- team_id=self.team.id,- user_id=cast(User, request.user).id,- **props,- )- report_user_action(- cast(User, request.user),- "llma skill file renamed",- props,- team=self.team,- request=request,- )- return Response(self._serialize_skill(published_skill))-@extend_schema(parameters=[LLMSkillListQuerySerializer],responses={@@ -2232,7 +233,15 @@ class LLMSkillViewSet(return responsedef _list_response(self, request: Request) -> Response:- queryset = self.filter_queryset(self._get_list_queryset(request))+ params = self._validated_query(LLMSkillListQuerySerializer, request)+ queryset = self.filter_queryset(+ list_queryset(+ team=self.team,+ user_access_control=self.user_access_control,+ params=params,+ query_params=request.query_params,+ )+ )page = self.paginate_queryset(queryset)if page is not None:page = [self._apply_trial_skill(request, skill) for skill in page]diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.pyindex 4c2eb2a8ea8c..12a80420dfda 100644--- a/products/skills/backend/api/test/test_marketplace_endpoints.py+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py@@ -544,7 +544,7 @@ class TestSkillBundle(APIBaseTest):assert self._skill_dirs(response) == set()@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)- @patch("products.skills.backend.api.skills.SkillBundleBurstThrottle.rate", new="1/minute")+ @patch("products.skills.backend.api.skill_throttles.SkillBundleBurstThrottle.rate", new="1/minute")def test_oauth_and_session_callers_are_throttled(self, *_args):# The general Burst/Sustained throttles only count personal-API-key traffic, so an OAuth# (or session) caller would otherwise hit this expensive zip endpoint unthrottled. Thediff --git a/products/skills/backend/api/test/test_skill_import.py b/products/skills/backend/api/test/test_skill_import.pynew file mode 100644index 000000000000..06782896016a--- /dev/null+++ b/products/skills/backend/api/test/test_skill_import.py@@ -0,0 +1,59 @@+from parameterized import parameterized++from products.skills.backend.api.skill_import import import_problems+from products.skills.backend.api.skill_serializers import MAX_SKILL_FILE_BYTES+from products.skills.backend.marketplace.packaging import SkillExport, SkillFileExport, build_skill_zip, parse_skill_zip+++def _round_tripped(**overrides) -> SkillExport:+ fields = {"name": "a-skill", "description": "A skill.", "body": "# a-skill\n", "version": 1, **overrides}+ return parse_skill_zip(build_skill_zip(SkillExport(**fields)))+++class TestImportProblems:+ @parameterized.expand(+ [+ (+ "description over the spec limit",+ {"description": "d" * 1025},+ "The description is 1025 characters. Shorten it to 1024 characters or fewer",+ ),+ ("license over the cap", {"license": "L" * 256}, "license must be 255 characters or fewer"),+ (+ "compatibility over the cap",+ {"compatibility": "C" * 501},+ "compatibility must be 500 characters or fewer",+ ),+ ("body over the byte cap", {"body": "# a-skill\n" + "x" * 1_000_001}, "body: "),+ (+ "bundled file over the byte cap",+ {"files": [SkillFileExport(path="data.txt", content="x" * (MAX_SKILL_FILE_BYTES + 1))]},+ f"file 'data.txt': content must be {MAX_SKILL_FILE_BYTES} bytes or fewer",+ ),+ (+ "bundled files colliding case-insensitively",+ {+ "files": [+ SkillFileExport(path="Notes.md", content="a"),+ SkillFileExport(path="notes.md", content="b"),+ ]+ },+ "file 'notes.md': Rename this file. It differs from 'Notes.md' only in letter case, so the two become one file on a case-insensitive filesystem.",+ ),+ ]+ )+ def test_reports_each_limit_the_import_path_enforces(self, _label, overrides, expected) -> None:+ problems = import_problems(_round_tripped(**overrides))++ assert len(problems) == 1, problems+ assert expected in problems[0]++ def test_reports_nothing_for_a_zip_within_every_limit(self) -> None:+ export = _round_tripped(+ license="MIT",+ compatibility="claude-code",+ allowed_tools=["Bash", "Write"],+ files=[SkillFileExport(path="scripts/run.sh", content="#!/bin/bash\necho hi\n")],+ )++ assert import_problems(export) == []diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 924cb07b86c9..ade12dcd1aec 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -30,6 +30,7 @@ from ...api.community_publish_services import (CommunitySkillPublishNotConfiguredError,CommunitySkillPublishValidationError,)+from ...api.skill_search import SKILL_SEARCH_RESULT_LIMITfrom ...api.skill_serializers import (DEFAULT_BODY_PAGE_LENGTH,LLMSkillCreateSerializer,@@ -48,11 +49,11 @@ from ...api.skill_services import (resolve_skill_owners,set_skill_owners,)-from ...api.skills import SKILL_SEARCH_RESULT_LIMITfrom ...marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH, parse_skill_mdfrom ...models.skills import SCOUT_SKILL_CATEGORY, LLMSkill, LLMSkillFileCOMMUNITY_FLAG = "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled"+SKILL_ANALYTICS_REPORT = "products.skills.backend.api.skill_analytics.report_user_action"class TestLLMSkillAPI(APIBaseTest):@@ -880,7 +881,7 @@ class TestLLMSkillAPI(APIBaseTest):with (patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False),- patch(f"products.skills.backend.api.skills.SkillSearch{window}Throttle.rate", new=f"1/{period}"),+ patch(f"products.skills.backend.api.skill_throttles.SkillSearch{window}Throttle.rate", new=f"1/{period}"),patch("rest_framework.throttling.SimpleRateThrottle.timer", return_value=1000) as timer,):url = self._url("search?query=throttle")@@ -2088,7 +2089,7 @@ class TestLLMSkillAPI(APIBaseTest):# --- Publish to community ---@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_succeeds(self, mock_publish, _mock_flag):mock_publish.return_value = {"pr_url": "https://github.com/PostHog/community-skills/pull/7",@@ -2141,7 +2142,7 @@ class TestLLMSkillAPI(APIBaseTest):])@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_tags(self, _label: str, payload: dict, metadata_tags: list, expected: list, mock_publish, _mock_flag):@@ -2164,7 +2165,7 @@ class TestLLMSkillAPI(APIBaseTest):])@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_scout_rejects_an_invalid_config(self, _label: str, scout_config: dict, mock_publish, _mock_flag):skill = self.create_skill(name="signals-scout-feed", category="scout")@@ -2178,7 +2179,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_unknown_skill_returns_404(self, mock_publish, _mock_flag):response = self.client.post(self._url("name/does-not-exist/publish-community"), data={}, format="json")@@ -2186,7 +2187,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_rejects_a_version_that_the_publisher_did_not_review(self, mock_publish, _mock_flag):skill = self.create_skill(name="make-pr")@@ -2203,7 +2204,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_rejects_a_skill_registered_as_a_scout_after_review(self, mock_publish, _mock_flag):# Registering a skill as a scout stamps `category` without raising the version, so version# alone would let a skill reviewed as an ordinary one publish as a scout on a schedule.@@ -2224,7 +2225,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_accepts_the_category_the_publisher_reviewed(self, mock_publish, _mock_flag):mock_publish.return_value = {"pr_url": "https://github.com/PostHog/community-skills/pull/1", "pr_number": 1}skill = self.create_skill(name="make-pr")@@ -2243,7 +2244,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_called_once()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_rejects_a_recreated_skill_with_the_same_version(self, mock_publish, _mock_flag):reviewed_skill = self.create_skill(name="make-pr")archive_skill(self.team, "make-pr", acting_user=None)@@ -2267,7 +2268,7 @@ class TestLLMSkillAPI(APIBaseTest):])@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_rejects_display_name(self, _label: str, display_name: str, mock_publish, _mock_flag):skill = self.create_skill(name="make-pr")@@ -2281,7 +2282,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=False)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_is_gated_on_the_community_flag(self, mock_publish, _mock_flag):skill = self.create_skill(name="make-pr")@@ -2295,7 +2296,7 @@ class TestLLMSkillAPI(APIBaseTest):mock_publish.assert_not_called()@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_not_configured_returns_503(self, mock_publish, _mock_flag):mock_publish.side_effect = CommunitySkillPublishNotConfiguredError("nope")skill = self.create_skill(name="make-pr")@@ -2309,7 +2310,7 @@ class TestLLMSkillAPI(APIBaseTest):assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_invalid_skill_returns_400(self, mock_publish, _mock_flag):# Nothing reached GitHub and republishing the same skill fails the same way, so a 502 would# tell the publisher to retry an upstream request that was never the problem.@@ -2326,7 +2327,7 @@ class TestLLMSkillAPI(APIBaseTest):assert response.json()["detail"] == "that slug is reserved"@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_publish_to_community_github_error_returns_502(self, mock_publish, _mock_flag):mock_publish.side_effect = CommunitySkillPublishError("github exploded")skill = self.create_skill(name="make-pr")@@ -2343,6 +2344,99 @@ class TestLLMSkillAPI(APIBaseTest):# llm_skill is its own access-control resource (see ACCESS_CONTROL_RESOURCES in# products/access_control/backend/facade/user_access_control.py) - same as TestSkillMarketplaceRBAC in# test_marketplace_endpoints.py covers for the git clone endpoint, this covers the JSON skill API.+class TestSkillWriteAnalytics(APIBaseTest):+ # Every skill write reports one product event, and the properties on it power the internal+ # skills adoption dashboards — a renamed event or a dropped property breaks them silently.+ def _url(self, path: str = "") -> str:+ return f"/api/environments/{self.team.id}/llm_skills/{path}"++ def setUp(self) -> None:+ super().setUp()+ self.skill = LLMSkill.objects.create(+ team=self.team,+ name="tracked-skill",+ description="A tracked skill.",+ body="# V1",+ version=1,+ is_latest=True,+ created_by=self.user,+ )+ LLMSkillFile.objects.create(skill=self.skill, path="old.md", content="hi")+ set_skill_owners(self.team, "tracked-skill", [self.user])++ @parameterized.expand(+ [+ (+ "create",+ "post",+ "",+ {"name": "new-skill", "description": "A new skill.", "body": "# New"},+ "llma skill created",+ ),+ (+ "publish",+ "patch",+ "name/tracked-skill",+ {"body": "# V2", "base_version": 1},+ "llma skill version published",+ ),+ ("archive", "post", "name/tracked-skill/archive", None, "llma skill archived"),+ (+ "duplicate",+ "post",+ "name/tracked-skill/duplicate",+ {"new_name": "copied-skill"},+ "llma skill duplicated",+ ),+ ("rename", "post", "name/tracked-skill/rename", {"new_name": "renamed-skill"}, "llma skill renamed"),+ (+ "create file",+ "post",+ "name/tracked-skill/files",+ {"path": "notes.md", "content": "hi"},+ "llma skill file created",+ ),+ (+ "rename file",+ "post",+ "name/tracked-skill/files-rename",+ {"old_path": "old.md", "new_path": "new.md"},+ "llma skill file renamed",+ ),+ ]+ )+ @patch(SKILL_ANALYTICS_REPORT)+ def test_each_write_reports_its_own_event(self, _label, method, path, data, expected_event, mock_report) -> None:+ response = getattr(self.client, method)(self._url(path), data=data or {}, format="json")++ assert response.status_code in (status.HTTP_200_OK, status.HTTP_201_CREATED, status.HTTP_204_NO_CONTENT), (+ response.content+ )+ assert mock_report.call_count == 1+ reported_user, reported_event, reported_props = mock_report.call_args.args+ assert reported_user == self.user+ assert reported_event == expected_event+ assert reported_props["skill_name"]++ @patch(SKILL_ANALYTICS_REPORT)+ def test_publish_reports_which_parts_of_the_skill_the_caller_changed(self, mock_report) -> None:+ response = self.client.patch(+ self._url("name/tracked-skill"),+ data={"body": "# V2", "description": "Now described.", "base_version": 1},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ props = mock_report.call_args.args[2]+ assert props["base_version"] == 1+ assert props["skill_version"] == 2+ assert props["body_changed"] is True+ assert props["description_changed"] is True+ assert props["files_replaced"] is False+ assert props["owners_changed"] is False+ assert props["edits_used"] is False++class TestSkillAccessControlRBAC(APIBaseTest):def setUp(self):super().setUp()@@ -2584,7 +2678,7 @@ class TestSkillAccessControlRBAC(APIBaseTest):assert response.status_code == expected_status@patch(COMMUNITY_FLAG, return_value=True)- @patch("products.skills.backend.api.skills.publish_skill_to_community")+ @patch("products.skills.backend.api.skill_view_community.publish_skill_to_community")def test_an_owner_with_editor_access_can_publish(self, mock_publish, _mock_flag):mock_publish.return_value = {"pr_url": "https://example.com/pull/1", "pr_number": 1, "branch": "b"}self._grant_llm_skill_access("editor")@@ -2838,7 +2932,7 @@ class TestScoutTrialSkillAPI(APIBaseTest):self.token.scope = "llm_skill:read signal_scout_internal:write"self.token.save(update_fields=["scope"])url = f"/api/projects/{self.team.id}/llm_skills/bundle/"- with patch("products.skills.backend.api.skills.posthog_feature_flag_value", return_value=True):+ with patch("products.skills.backend.api.skill_view_transfer.posthog_feature_flag_value", return_value=True):full = self.client.get(url, {"content": "full"})stub = self.client.get(url)assert full.status_code == (status.HTTP_403_FORBIDDEN if is_trial else status.HTTP_200_OK)