:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(skills): add a bundle endpoint for a user's store skills (#89584)
Andrew Maguired9634b0a650d
diff --git a/docs/internal/skills/skill-bundle-api.md b/docs/internal/skills/skill-bundle-api.mdnew file mode 100644index 000000000000..dfee89d121e7--- /dev/null+++ b/docs/internal/skills/skill-bundle-api.md@@ -0,0 +1,68 @@+# Skill bundle API++The skill bundle is one zip of the skills a user created or owns in the team skills store.+A consumer unpacks it into a skills directory (`~/.claude/skills`, `~/.agents/skills`) so a harness discovers the skills natively.+The first consumer is the agent server in a task sandbox, which fetches the bundle at session start.++Viewset: `products/skills/backend/api/skills.py` (`LLMSkillViewSet.bundle`).+Walk and caps: `products/skills/backend/marketplace/adapters.py` (`build_skill_bundle`).+Stub rendering and zip assembly: `products/skills/backend/marketplace/packaging.py`.++## Endpoint++```text+GET /api/projects/{team_id}/llm_skills/bundle/?content=stub|full&limit=N+```++| Param | Default | Behavior |+| --------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| `content` | `stub` | `stub` writes one `SKILL.md` per skill with its name, description and instructions to fetch the skill over MCP. `full` writes the whole skill. |+| `limit` | `20` | Maximum skills in the zip, newest first, at most `100`. Every skill in the zip costs the agent prompt context on each turn, so keep it small. |++The response is `application/zip` with `Content-Disposition: attachment; filename="skills-bundle.zip"`.+Each skill sits under `<name>/`.+Send `Accept: application/zip` or leave `Accept` unset; both pass content negotiation.+Error responses are JSON either way.++## Authentication and gating++- Session, personal API key and OAuth callers all work. The action requires `llm_skill:read`, which the sandbox OAuth token already carries.+- Gated by the `skills-store-in-sandbox` feature flag, evaluated for the requesting user with the organization and project groups.+ Flag off returns `404`, so a consumer can treat it as "not enabled".+ Flag service unavailable returns `503`, so a consumer can tell an outage from a disabled flag.+- Throttled per user (`30/minute`, `300/hour`), so one caller cannot exhaust the budget for the rest of the project.++## Which skills are in the zip++A skill is a candidate when the user created version 1 of it or is listed as an owner, it is the latest version, it is not archived, and its category is not `scout` (the scout harness loads its own skill).+The candidate set is filtered by the same object-level access control as the list endpoint, so a skill the list would hide from the user stays out of the bundle.++Candidates are walked newest first.+Each one is either included, skipped or dropped:++- **Skipped**: the skill fails the Agent Skills spec check (missing or over-long description), or it carries a legacy name or file path the harness could not unpack safely (a malformed name, a path that is not canonical, a case-insensitive collision, a file where another entry needs a directory). Skipped skills do not count toward the limit or the byte cap.+- **Dropped**: the skill would cross the `limit` or, for `content=full`, the 5 MB uncompressed byte cap. The walk stops at the first such skill; everything after it is dropped unread. The byte cap counts content plus zip entry names and framing.++## Response headers++| Header | Meaning |+| ------------------- | ----------------------------------------------------- |+| `X-Skills-Included` | Skills in the zip. |+| `X-Skills-Dropped` | Skills past the limit or the byte cap. |+| `X-Skills-Skipped` | Skills left out because they would not unpack safely. |++Headers carry counts only.+Names are logged server-side (`skills_bundle_skipped`, `skills_bundle_dropped_over_cap`).++## What a stub contains++A stub `SKILL.md` has the skill's `name`, `description` and `metadata.version`, plus `metadata.source: posthog-skills-store` so a consumer can tell store stubs from skills installed by other means.+Its body tells the agent to:++1. Call `skill-get` for the skill and note the returned `version`.+2. Page through the body with `body_offset` until `body_next_offset` is null, passing the same `version` each time.+3. Follow the complete body as the skill's instructions.+4. Fetch any referenced bundled file with `skill-file-get` at that `version` and write it into the skill directory before use.++Pinning the version keeps a publish that lands mid-fetch from mixing two versions of the skill.+Skill content only crosses the MCP server when a skill is invoked; the bundle itself carries discovery metadata only.diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex af99a21dca22..e55037789b98 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -9,6 +9,7 @@ from posthog.api.shared import UserBasicSerializerfrom products.ai_observability.backend.markdown_outline import get_markdown_outline+from ..marketplace.packaging import DEFAULT_BUNDLE_SKILLS, MAX_BUNDLE_SKILLSfrom ..models.skills import LLMSkill, LLMSkillFile, category_for_skill_namefrom .community_publish_services import (DISPLAY_NAME_PATTERN,@@ -18,6 +19,7 @@ from .community_publish_services import (OPTIONAL_GITHUB_HANDLE_PATTERN,)from .skill_services import (+ MAX_SKILL_NAME_LENGTH,RESERVED_SKILL_NAMES,SKILL_NAME_PATTERN,LLMSkillOwnerNotFoundError,@@ -59,12 +61,12 @@ def validate_skill_name_value(value: str) -> str:f"'{value}' is a reserved name and cannot be used.",code="reserved_name",)- if len(value) > 64:+ if len(value) > MAX_SKILL_NAME_LENGTH:raise serializers.ValidationError(- "Skill name must be 64 characters or fewer.",+ f"Skill name must be {MAX_SKILL_NAME_LENGTH} characters or fewer.",code="max_length",)- if not SKILL_NAME_PATTERN.match(value):+ if not SKILL_NAME_PATTERN.fullmatch(value):raise serializers.ValidationError("Only lowercase letters, numbers, and hyphens are allowed. ""Must not start or end with a hyphen or contain consecutive hyphens.",@@ -123,6 +125,28 @@ class LLMSkillFetchQuerySerializer(serializers.Serializer):)+class LLMSkillBundleQuerySerializer(serializers.Serializer):+ limit = serializers.IntegerField(+ min_value=1,+ max_value=MAX_BUNDLE_SKILLS,+ default=DEFAULT_BUNDLE_SKILLS,+ help_text=(+ f"Maximum number of skills in the zip, newest first; default {DEFAULT_BUNDLE_SKILLS}, at most "+ f"{MAX_BUNDLE_SKILLS}. Every skill in the zip costs the agent prompt context on each turn, so pick "+ "what the harness can usefully carry. Skills past the limit are reported in X-Skills-Dropped."+ ),+ )+ content = serializers.ChoiceField(+ choices=["stub", "full"],+ default="stub",+ help_text=(+ "What each skill directory in the zip contains. 'stub' (default) writes a SKILL.md with the name, "+ "description and instructions to fetch the skill over the PostHog MCP when it is invoked. 'full' writes "+ "the rendered SKILL.md, every bundled file and the Codex sidecar."+ ),+ )++class LLMSkillBodyFetchQuerySerializer(LLMSkillFetchQuerySerializer):"""Fetch-by-name query params plus optional body paging — only the body-returning endpoint uses these."""diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex c1b18057e641..add4dfa1db20 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -27,11 +27,22 @@ MAX_SKILL_FILE_COUNT = 200# importing the serializers that import it.RESERVED_SKILL_NAMES = {"new", "scouts", "review-hog", "community"}SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")+MAX_SKILL_NAME_LENGTH = 64# Bundled-file paths that would collide with generated artifacts in the exported skill# tree / plugin marketplace (the rendered SKILL.md). Compared case-insensitively.RESERVED_SKILL_FILE_PATHS = {"skill.md"}+def skill_name_is_well_formed(value: str) -> bool:+ """The shape half of the skill-name contract, without the reserved-name rule.++ ``fullmatch`` rather than ``match``: ``$`` matches before a trailing newline, so ``match`` would+ accept ``"safe\n"``. Archive writers use this to skip legacy rows that predate the validator,+ where a name is a directory and a reserved route name is harmless.+ """+ return len(value) <= MAX_SKILL_NAME_LENGTH and SKILL_NAME_PATTERN.fullmatch(value) is not None and "--" not in value++def normalize_skill_file_path(value: str) -> str:"""Return the canonical relative path for a bundled file, raising ValueError if it has none.diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 7d33fec92726..5aede5264f8f 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -8,12 +8,13 @@ from django.http import HttpResponseimport structlogfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.parsers import FormParser, MultiPartParserfrom rest_framework.permissions import BasePermission+from rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer@@ -29,13 +30,14 @@ from posthog.auth import ()from posthog.event_usage import report_user_actionfrom posthog.models import User-from posthog.permissions import AccessControlPermission, get_authenticator_scopes+from posthog.permissions import AccessControlPermission, get_authenticator_scopes, posthog_feature_flag_valuefrom posthog.rate_limit import BurstRateThrottle, PersonalApiKeyOrUserRateThrottle, SustainedRateThrottle+from posthog.renderers import SafeJSONRendererfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.ai_observability.backend.api.metrics import llma_track_latency-from ..marketplace.adapters import MARKETPLACE_NAME, PLUGIN_NAME, load_skill_export+from ..marketplace.adapters import MARKETPLACE_NAME, PLUGIN_NAME, build_skill_bundle, load_skill_exportfrom ..marketplace.credentials import (build_codex_install_command,build_install_command,@@ -60,6 +62,7 @@ from .skill_serializers import (PUBLISH_CONTENT_FIELDS,CommunitySkillPublishResultSerializer,LLMSkillBodyFetchQuerySerializer,+ LLMSkillBundleQuerySerializer,LLMSkillCreateSerializer,LLMSkillDuplicateSerializer,LLMSkillFetchQuerySerializer,@@ -118,6 +121,9 @@ logger = structlog.get_logger(__name__)MAX_IMPORT_ZIP_BYTES = 10_000_000+SANDBOX_SKILLS_FEATURE_FLAG = "skills-store-in-sandbox"++def _file_extension(path: str) -> str:return path.rsplit(".", 1)[1].lower() if "." in path else ""@@ -260,6 +266,62 @@ class CommunityPublishSustainedThrottle(_CommunityPublishThrottle):rate = "20/day"+class _SkillBundleThrottle(PersonalApiKeyOrUserRateThrottle):+ """Throttle for the skill bundle, which a sandbox fetches over OAuth.++ The general BurstRateThrottle/SustainedRateThrottle only count personal-API-key traffic, so an+ OAuth or session caller would reach the zip build (candidate queries, a file query per skill,+ DEFLATE of up to MAX_BUNDLE_BYTES) unthrottled. PersonalApiKeyOrUserRateThrottle counts+ every auth method, but its inherited key idents session and OAuth callers by project, so one+ user's burst would 429 every other sandbox 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(_SkillBundleThrottle):+ # 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(_SkillBundleThrottle):+ # 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 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 LLMSkillViewSet(TeamAndOrgViewSetMixin,AccessControlViewSetMixin,@@ -279,9 +341,17 @@ class LLMSkillViewSet(def safely_get_queryset(self, queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:return get_active_skill_queryset(self.team)+ def get_renderers(self) -> list[BaseRenderer]:+ renderers = super().get_renderers()+ if self.action in _ZIP_ACTIONS:+ return [*renderers, ZipRenderer()]+ return renderers+def get_throttles(self):if self.action == "publish_to_community":return [CommunityPublishBurstThrottle(), CommunityPublishSustainedThrottle()]+ if self.action == "bundle":+ return [SkillBundleBurstThrottle(), SkillBundleSustainedThrottle()]if self.action in ["update_by_name", "get_by_name", "resolve_by_name"]:return [BurstRateThrottle(), SustainedRateThrottle()]return super().get_throttles()@@ -699,7 +769,7 @@ class LLMSkillViewSet()@extend_schema(- parameters=[LLMSkillFetchQuerySerializer],+ 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")@@ -725,6 +795,55 @@ class LLMSkillViewSet(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)+ user = cast(User, request.user)+ flag_value = posthog_feature_flag_value(+ SANDBOX_SKILLS_FEATURE_FLAG,+ user.distinct_id or str(user.uuid),+ 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"],diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.pyindex 8f902661097a..450fdf9efc6e 100644--- a/products/skills/backend/api/test/test_marketplace_endpoints.py+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py@@ -3,6 +3,7 @@ import jsonimport base64import zipfilefrom datetime import timedelta+from typing import Anyimport pytestfrom posthog.test.base import APIBaseTest@@ -10,8 +11,12 @@ from unittest.mock import patchfrom django.core.cache import cachefrom django.core.files.uploadedfile import SimpleUploadedFile+from django.db import connection+from django.http import HttpResponse+from django.test.utils import CaptureQueriesContextfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import serializers, statusfrom posthog.constants import AvailableFeature@@ -23,7 +28,7 @@ from posthog.models.utils import hash_key_valuefrom products.access_control.backend.models.access_control import AccessControlfrom ...api.skill_serializers import validate_skill_file_path-from ...api.skill_services import archive_skill+from ...api.skill_services import archive_skill, set_skill_ownersfrom ...marketplace import adaptersfrom ...marketplace.adapters import build_team_marketplace_treefrom ...marketplace.credentials import issue_marketplace_credential@@ -89,6 +94,15 @@ class TestSkillZipExport(APIBaseTest):def test_export_missing_skill_404(self):assert self.client.get(self._url("nope")).status_code == status.HTTP_404_NOT_FOUND+ def test_export_honors_a_zip_accept_header(self):+ self._create_skill()++ response = self.client.get(self._url("make-fractals"), HTTP_ACCEPT="application/zip")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response["Content-Type"] == "application/zip"+ assert zipfile.is_zipfile(io.BytesIO(response.content))+def test_export_then_reimport_round_trip(self):skill = LLMSkill.objects.create(team=self.team,@@ -155,6 +169,348 @@ class TestSkillZipExport(APIBaseTest):assert response.json()["problems"]+SANDBOX_FLAG = "posthog.permissions.posthoganalytics.feature_enabled"+++class TestSkillBundle(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", None)++ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/llm_skills/bundle"++ def _create_skill(self, name: str, *, created_by: User | None = None, **overrides: Any) -> LLMSkill:+ fields = {+ "team": self.team,+ "name": name,+ "description": f"{name} description.",+ "body": f"# {name}\n",+ "version": 1,+ "is_latest": True,+ "created_by": created_by or self.user,+ **overrides,+ }+ return LLMSkill.objects.create(**fields)++ def _fetch(+ self,+ *,+ flag: bool | None = True,+ authorization: str | None = None,+ content: str | None = None,+ limit: int | str | None = None,+ accept: str | None = None,+ ) -> HttpResponse:+ query: dict[str, str] = {}+ if content:+ query["content"] = content+ if limit is not None:+ query["limit"] = str(limit)+ headers = {name: value for name, value in {"Authorization": authorization, "Accept": accept}.items() if value}+ with patch(SANDBOX_FLAG, return_value=flag):+ return self.client.get(self._url(), query, headers=headers)++ @staticmethod+ def _skill_dirs(response: HttpResponse) -> set[str]:+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ return {name.split("/", 1)[0] for name in archive.namelist()}++ def test_flag_off_is_404(self):+ self._create_skill("mine")+ assert self._fetch(flag=False).status_code == status.HTTP_404_NOT_FOUND++ def test_flag_service_unavailable_is_503_not_404(self):+ self._create_skill("mine")+ assert self._fetch(flag=None).status_code == status.HTTP_503_SERVICE_UNAVAILABLE++ def test_personal_api_key_with_read_scope_gets_the_bundle(self):+ self._create_skill("mine")+ self.client.logout()+ _mint_pak(self.user, scopes=["llm_skill:read"])++ response = self._fetch(authorization=f"Bearer {_PAK_TOKEN}")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert self._skill_dirs(response) == {"mine"}++ def test_bundle_contains_only_skills_the_user_created_or_owns(self):+ self._create_skill("mine")+ LLMSkillFile.objects.create(skill=self._create_skill("with-file"), path="scripts/run.py", content="print(1)\n")+ self._create_skill("owned", created_by=self.other_user)+ set_skill_owners(self.team, "owned", [self.user])+ self._create_skill("someone-elses", created_by=self.other_user)+ self._create_skill("signals-scout-x", category="scout")+ self._create_skill("archived", deleted=True)+ self._create_skill("old-version", is_latest=False)+ # The latest row carries the last editor; the creator of version 1 still gets the skill.+ self._create_skill("edited-by-other", is_latest=False)+ self._create_skill("edited-by-other", version=2, created_by=self.other_user)+ self._create_skill("created-by-other-edited-by-me", created_by=self.other_user, is_latest=False)+ self._create_skill("created-by-other-edited-by-me", version=2)++ response = self._fetch(content="full")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response["Content-Type"] == "application/zip"+ assert response["X-Skills-Included"] == "4"+ assert response["X-Skills-Dropped"] == "0"+ assert response["X-Skills-Skipped"] == "0"+ assert self._skill_dirs(response) == {"mine", "with-file", "owned", "edited-by-other"}+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ assert "with-file/scripts/run.py" in archive.namelist()+ assert "with-file/agents/openai.yaml" in archive.namelist()+ assert "name: mine" in archive.read("mine/SKILL.md").decode()++ @parameterized.expand(["stub", "full"])+ def test_over_cap_keeps_newest_and_drops_the_rest(self, content: str):+ base = timezone.now()+ for index, name in enumerate(["oldest", "middle", "newest"]):+ skill = self._create_skill(name)+ LLMSkill.objects.filter(pk=skill.pk).update(updated_at=base + timedelta(minutes=index))++ response = self._fetch(content=content, limit=2)++ assert response.status_code == status.HTTP_200_OK+ assert self._skill_dirs(response) == {"newest", "middle"}+ assert response["X-Skills-Dropped"] == "1"++ def test_byte_cap_stops_at_the_first_skill_that_does_not_fit(self):+ base = timezone.now()+ for index, (name, body) in enumerate([("older-small", "x"), ("huge", "x" * 10_000), ("newest-small", "x")]):+ skill = self._create_skill(name, body=body)+ LLMSkill.objects.filter(pk=skill.pk).update(updated_at=base + timedelta(minutes=index))++ with patch.object(adapters, "MAX_BUNDLE_BYTES", 5_000):+ response = self._fetch(content="full")++ assert self._skill_dirs(response) == {"newest-small"}+ assert response["X-Skills-Dropped"] == "2"++ @parameterized.expand(["stub", "full"])+ def test_spec_invalid_skill_is_skipped_not_fatal(self, content: str):+ self._create_skill("fine")+ self._create_skill("too-long", description="x" * 1025)++ response = self._fetch(content=content)++ assert response.status_code == status.HTTP_200_OK+ assert self._skill_dirs(response) == {"fine"}+ assert response["X-Skills-Skipped"] == "1"+ assert response["X-Skills-Dropped"] == "0"++ @parameterized.expand(+ [+ ("traversal", ["../escape.md"]),+ ("not_canonical", ["refs\\guide.md"]),+ ("case_collision", ["Refs/guide.md", "refs/Guide.md"]),+ ("sidecar_case_variant", ["Agents/OpenAI.yaml"]),+ ("file_where_a_directory_is_needed", ["assets", "assets/logo.png"]),+ ("file_where_the_sidecar_directory_is_needed", ["agents"]),+ ]+ )+ def test_skill_with_an_unsafe_legacy_path_is_skipped(self, _label: str, paths: list[str]):+ self._create_skill("fine")+ unsafe = self._create_skill("unsafe")+ # Bypasses the serializer validation so the rows look like ones that predate it.+ for path in paths:+ LLMSkillFile.objects.create(skill=unsafe, path=path, content="x")+ self._create_skill("Bad/Name")++ response = self._fetch(content="full")++ assert response.status_code == status.HTTP_200_OK+ assert self._skill_dirs(response) == {"fine"}+ assert response["X-Skills-Skipped"] == "2"+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ assert not any(".." in name or name.startswith("/") for name in archive.namelist())++ @parameterized.expand(+ [+ ("stub", "safe\n"),+ ("stub", "bad--name"),+ ("full", "safe\n"),+ ("full", "bad--name"),+ ]+ )+ def test_skill_with_a_malformed_legacy_name_is_skipped(self, content: str, name: str):+ self._create_skill("fine")+ # Bypasses the serializer validation so the row looks like one that predates it.+ self._create_skill(name)++ response = self._fetch(content=content)++ assert response.status_code == status.HTTP_200_OK+ assert self._skill_dirs(response) == {"fine"}+ assert response["X-Skills-Skipped"] == "1"++ def test_zip_accept_header_gets_the_zip_and_errors_stay_json(self):+ self._create_skill("mine")++ response = self._fetch(accept="application/zip")+ assert response.status_code == status.HTTP_200_OK, response.content+ assert response["Content-Type"] == "application/zip"+ assert self._skill_dirs(response) == {"mine"}++ not_enabled = self._fetch(flag=False, accept="application/zip")+ assert not_enabled.status_code == status.HTTP_404_NOT_FOUND+ assert not_enabled["Content-Type"] == "application/json"+ assert json.loads(not_enabled.content)["detail"] == "Not found."++ def test_skipped_skills_page_at_a_fixed_size_not_the_limit(self):+ def queries_with_skipped_rows(count: int) -> int:+ while LLMSkill.objects.filter(team=self.team, name__startswith="too-long-").count() < count:+ index = LLMSkill.objects.filter(team=self.team, name__startswith="too-long-").count()+ self._create_skill(f"too-long-{index}", description="x" * 1025)+ with CaptureQueriesContext(connection) as context:+ response = self._fetch(limit=1)+ assert response.status_code == status.HTTP_200_OK+ assert response["X-Skills-Skipped"] == str(count)+ return len(context.captured_queries)++ self._create_skill("fine")+ # The first request of a test warms per-process caches; compare only warm requests.+ self._fetch(limit=1)++ # Skipped rows do not count toward the limit, so a limit-sized page would add a query per row.+ # Compare past the log-sample size too: the header must report the true skip count, not the+ # bounded sample the walk retains.+ assert queries_with_skipped_rows(1) == queries_with_skipped_rows(adapters._SKIPPED_LOG_SAMPLE_SIZE + 5)++ def test_skill_archived_while_the_bundle_is_built_is_left_out_not_fatal(self):+ self._create_skill("stays")+ vanishing = self._create_skill("vanishing")+ real_batches = adapters._candidate_batches++ def archive_after_reading(rows: Any) -> Any:+ for row in real_batches(rows):+ if row["name"] == "vanishing":+ LLMSkill.objects.filter(pk=vanishing.pk).update(deleted=True)+ yield row++ with patch.object(adapters, "_candidate_batches", side_effect=archive_after_reading):+ response = self._fetch(content="full")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert self._skill_dirs(response) == {"stays"}+ assert response["X-Skills-Dropped"] == "0"++ def test_a_bundled_sidecar_file_overrides_the_generated_one(self):+ skill = self._create_skill("mine")+ LLMSkillFile.objects.create(skill=skill, path="agents/openai.yaml", content="interface: custom\n")++ response = self._fetch(content="full")++ assert self._skill_dirs(response) == {"mine"}+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ assert archive.read("mine/agents/openai.yaml").decode() == "interface: custom\n"++ def test_an_invalid_skill_ahead_of_the_byte_cap_is_skipped_not_capping(self):+ base = timezone.now()+ for index, (name, body, description) in enumerate(+ [("older-valid", "x", "fine"), ("newest-invalid-and-huge", "x" * 10_000, "d" * 1025)]+ ):+ skill = self._create_skill(name, body=body, description=description)+ LLMSkill.objects.filter(pk=skill.pk).update(updated_at=base + timedelta(minutes=index))++ with patch.object(adapters, "MAX_BUNDLE_BYTES", 5_000):+ response = self._fetch(content="full")++ assert self._skill_dirs(response) == {"older-valid"}+ assert response["X-Skills-Skipped"] == "1"+ assert response["X-Skills-Dropped"] == "0"++ def test_skill_the_user_is_blocked_from_reading_is_left_out(self):+ cache.clear()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ member = User.objects.create_and_join(self.organization, "[email protected]", None)+ AccessControl.objects.create(+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="member"+ )+ # Resource default "none": the member reaches a skill only through an explicit object grant.+ AccessControl.objects.create(team=self.team, resource="llm_skill", resource_id=None, access_level="none")+ allowed = self._create_skill("allowed")+ self._create_skill("blocked")+ set_skill_owners(self.team, "allowed", [member])+ set_skill_owners(self.team, "blocked", [member])+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=str(allowed.id),+ access_level="viewer",+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),+ )+ self.client.force_login(member)++ response = self._fetch()++ assert response.status_code == status.HTTP_200_OK, response.content+ assert self._skill_dirs(response) == {"allowed"}++ def test_default_bundle_is_stubs_that_point_at_the_mcp(self):+ skill = self._create_skill("mine", description="Forecast quota usage.", body="# The real instructions\n")+ LLMSkillFile.objects.create(skill=skill, path="scripts/run.py", content="print(1)\n")+ self._create_skill("Bad/Name")++ response = self._fetch()++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response["X-Skills-Included"] == "1"+ assert response["X-Skills-Skipped"] == "1"+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ assert archive.namelist() == ["mine/SKILL.md"]+ stub = archive.read("mine/SKILL.md").decode()+ assert "name: mine" in stub+ assert "description: Forecast quota usage." in stub+ assert "source: posthog-skills-store" in stub+ assert 'call skill-get {"skill_name": "mine"}' in stub+ assert "body_next_offset" in stub+ assert '"version": <version>' in stub+ assert "The real instructions" not in stub++ @parameterized.expand(+ [+ ("unknown_content", {"content": "partial"}),+ ("limit_over_ceiling", {"limit": 101}),+ ("limit_zero", {"limit": 0}),+ ]+ )+ def test_bad_query_params_are_400(self, _label: str, query: dict[str, Any]):+ self._create_skill("mine")++ assert self._fetch(**query).status_code == status.HTTP_400_BAD_REQUEST++ def test_no_skills_is_an_empty_zip(self):+ response = self._fetch()++ assert response.status_code == status.HTTP_200_OK+ assert response["X-Skills-Included"] == "0"+ 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")+ 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. The+ # patched rate trips the second call; the test client uses session auth, the same+ # "authenticated, no personal API key" class the sandbox's OAuth token falls into.+ self._create_skill("mine")++ first = self._fetch()+ assert first.status_code == status.HTTP_200_OK, first.content++ second = self._fetch()+ assert second.status_code == status.HTTP_429_TOO_MANY_REQUESTS++ # The bucket is per user, so one caller's burst does not 429 the rest of the project.+ self.client.force_login(self.other_user)+ assert self._fetch().status_code == status.HTTP_200_OK++class TestSkillMarketplaceGit(APIBaseTest):def setUp(self):super().setUp()diff --git a/products/skills/backend/api/test/test_marketplace_packaging.py b/products/skills/backend/api/test/test_marketplace_packaging.pyindex 7b4028f67746..11145bf5386b 100644--- a/products/skills/backend/api/test/test_marketplace_packaging.py+++ b/products/skills/backend/api/test/test_marketplace_packaging.py@@ -103,6 +103,14 @@ class TestSkillTreeAndZip:assert "make-fractals/SKILL.md" in namesassert "make-fractals/scripts/mandelbrot.py" in names+ def test_file_tree_bytes_counts_the_archive_name_prefix(self):+ # Bundle entries are archived under <name>/ and a zip stores each entry name twice, so the+ # cap must charge the prefix; omitting it undercounts long-named skills against MAX_BUNDLE_BYTES.+ tree = build_skill_tree(_skill())+ prefix = "make-fractals/"+ expected = pkg.file_tree_bytes(tree) + 2 * len(prefix.encode("utf-8")) * len(tree)+ assert pkg.file_tree_bytes(tree, prefix=prefix) == expected+class TestMarketplaceTree:def _tree(self, skills=None):diff --git a/products/skills/backend/marketplace/README.md b/products/skills/backend/marketplace/README.mdindex 1d6f37f8c80c..7e73b7118f1b 100644--- a/products/skills/backend/marketplace/README.md+++ b/products/skills/backend/marketplace/README.md@@ -24,6 +24,22 @@ unit-testable against the real `git` binary without booting the app- **Zip export** — `GET /api/projects/:team/llm_skills/name/:name/export` → `application/zip`,one spec-compliant skill directory nested under `:name/` (web-authenticated, `llm_skill:read`).+- **Skill bundle** — `GET /api/projects/:team/llm_skills/bundle?content=stub|full&limit=N` →+ `application/zip`, every skill the requesting user created or owns (latest, not archived, not+ `scout`, and readable under the same object-level access filter as the list endpoint), each nested+ under `<name>/` so the zip unpacks straight into `~/.claude/skills` / `~/.agents/skills`.+ `content=stub` (default) writes one `SKILL.md` per skill with only its name, description and+ instructions to fetch the real skill with `skill-get` / `skill-file-get` when it is invoked, so a+ sandbox gets discovery for a few KB and skill content only moves over MCP when a skill is used.+ `content=full` writes the rendered `SKILL.md`, bundled files and Codex sidecar. Newest first,+ `limit` skills (default 20, at most 100; every skill in the zip costs the agent prompt context on+ each turn) and 5 MB uncompressed for `full`; the walk stops at the first skill that would cross a+ cap, and sizes are checked from column byte counts before any content loads.+ `X-Skills-Included`, `X-Skills-Dropped` (over the cap) and `X-Skills-Skipped` (failed the spec+ check, or a legacy name or file path that is not safe to unpack) carry counts; names are logged.+ Behind the `skills-store-in-sandbox` flag (off → 404, flag service unavailable → 503).+ `llm_skill:read`, which the sandbox OAuth token already carries. Throttled per user, so one caller+ cannot 429 the rest of the project. Consumer-facing contract: `docs/internal/skills/skill-bundle-api.md`.- **Zip import** — `POST /api/projects/:team/llm_skills/import` (multipart `file` field, a specskill `.zip`) → creates the skill (web-authenticated, `llm_skill:write`). The inverse ofexport: `parse_skill_zip` reads `SKILL.md` frontmatter + bundled files. Round-trips with export.diff --git a/products/skills/backend/marketplace/adapters.py b/products/skills/backend/marketplace/adapters.pyindex a2f0a206f4fe..bfcf904b02ec 100644--- a/products/skills/backend/marketplace/adapters.py+++ b/products/skills/backend/marketplace/adapters.py@@ -4,20 +4,40 @@ Everything that touches the database for export/marketplace lives here, so theserialization and git synthesis stay unit-testable without booting the app."""-from typing import Any+from collections.abc import Iterator+from typing import Any, Literal, TypeVarfrom django.core.cache import cache-from django.db.models import Max+from django.db.models import F, Func, IntegerField, Max, Q, QuerySet, TextField+from django.db.models.functions import Castimport structlogfrom rest_framework import serializers-from posthog.models import Team+from posthog.dataclasses import frozen+from posthog.models import Team, Userfrom ..api.skill_serializers import validate_skill_file_path+from ..api.skill_services import normalize_skill_file_path, skill_name_is_well_formed, skill_names_owned_byfrom ..models.skills import LLMSkill, LLMSkillFilefrom .git_smart_http import FileTree, SynthesizedRepo, synthesize_repo-from .packaging import SkillExport, SkillFileExport, build_marketplace_tree, compute_plugin_version+from .packaging import (+ CODEX_METADATA_PATH,+ DEFAULT_BUNDLE_SKILLS,+ MAX_BUNDLE_SKILLS,+ SPEC_DESCRIPTION_MAX_LENGTH,+ SkillExport,+ SkillFileExport,+ SkillStub,+ archive_entry_bytes,+ build_marketplace_tree,+ build_skill_stub_tree,+ build_skill_tree,+ build_skills_bundle_zip,+ compute_plugin_version,+ file_tree_bytes,+ validate_for_export,+)logger = structlog.get_logger(__name__)@@ -44,6 +64,15 @@ _MAX_MARKETPLACE_TREE_BYTES = 64_000_000# Don't pickle a very large synthesized repo into the shared cache — serve it uncached instead._MAX_CACHEABLE_PACKFILE_BYTES = 16_000_000+# A full bundle carries skill content, so it is bounded by what a coding agent can usefully load,+# not by what the team owns. The count limit lives with the other bundle policy in packaging.+MAX_BUNDLE_BYTES = 5_000_000++# A heavy user can skip very many skills, so the walk keeps only a fixed-size sample of their names+# plus a running count — never a list proportional to the skip total. The warning logs that sample+# and count; the response header carries the count only.+_SKIPPED_LOG_SAMPLE_SIZE = 20+def skill_to_export(skill: LLMSkill, files: list[LLMSkillFile]) -> SkillExport:return SkillExport(@@ -184,3 +213,248 @@ def _team_plugin_version(team: Team) -> str:# within the same second still produce distinct versions and clients don't miss an update.latest = LLMSkill.objects.filter(team=team).aggregate(latest=Max("updated_at"))["latest"]return compute_plugin_version(int(latest.timestamp() * 1000)) if latest is not None else "1.0.0"+++@frozen+class SkillBundle:+ zip_bytes: bytes+ included: list[str]+ dropped_count: int+ skipped_count: int+++BundleContent = Literal["stub", "full"]+++@frozen+class _BundleWalk:+ trees: dict[str, FileTree]+ dropped_count: int+ skipped_count: int+ skipped_sample: list[str]+++def _octet_length(expression: F | Cast) -> Func:+ return Func(expression, function="OCTET_LENGTH", output_field=IntegerField())+++_Row = TypeVar("_Row")+++def _candidate_batches(rows: "QuerySet[LLMSkill, _Row]") -> Iterator[_Row]:+ """Yield candidate rows in fixed-size slices so a user with thousands of skills never has them+ all in memory at once; the caller stops iterating once the bundle is capped.++ The slice size is the ceiling, not the caller's limit: skipped skills do not count toward the+ limit, so paging by a small limit would cost one query per skipped row.+ """+ offset = 0+ while True:+ batch = list(rows[offset : offset + MAX_BUNDLE_SKILLS])+ if not batch:+ return+ yield from batch+ offset += len(batch)+++def _bundle_candidates(team: Team, user: User, readable_skills: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:+ # Creation seeds an owner row, but skills that predate owners only carry ``created_by``. The+ # version 1 row keeps the original creator; later versions are stamped with whoever edited them.+ created_names = LLMSkill.objects.filter(team=team, deleted=False, version=1, created_by=user).values("name")+ return (+ readable_skills.filter(team=team, deleted=False, is_latest=True)+ .exclude(category="scout")+ .filter(Q(name__in=created_names) | Q(name__in=skill_names_owned_by(team, user.id)))+ .order_by("-updated_at", "name")+ )+++def build_skill_bundle(+ team: Team,+ user: User,+ readable_skills: QuerySet[LLMSkill],+ content: BundleContent = "stub",+ limit: int = DEFAULT_BUNDLE_SKILLS,+) -> SkillBundle:+ """One zip of the skills a user created or owns, for unpacking into a skills directory.++ ``content="stub"`` writes one ``SKILL.md`` per skill with only its name and description and a+ body that tells the agent to fetch the real skill over MCP when it is invoked. That keeps the+ per-run payload to discovery metadata; skill content only moves when a skill is used.+ ``content="full"`` writes the whole skill: rendered ``SKILL.md``, bundled files and the Codex+ sidecar.++ ``readable_skills`` is the caller's access-filtered view of the team's skills. The walk only+ selects from it, so a skill the list endpoint would hide from the user stays out of the bundle.++ Newest first, at most ``limit`` skills; the caller chooses the limit, up to ``MAX_BUNDLE_SKILLS``.+ Skills that fail the spec check or carry a name or path the harness could not unpack safely are+ ``skipped``; they do not count toward the caps and are checked before them. The walk stops at+ the first skill that would cross the count or byte cap; everything after it is counted as+ dropped and never read. Scouts are excluded because the scout harness loads its own skill.+ """+ candidates = _bundle_candidates(team, user, readable_skills)+ limit = min(limit, MAX_BUNDLE_SKILLS)+ walk = _walk_stubs(candidates, limit) if content == "stub" else _walk_full(candidates, limit)++ if walk.skipped_count:+ logger.warning(+ "skills_bundle_skipped",+ team_id=team.id,+ user_id=user.id,+ skipped_count=walk.skipped_count,+ skills_sample=walk.skipped_sample,+ )+ if walk.dropped_count:+ logger.warning(+ "skills_bundle_dropped_over_cap", team_id=team.id, user_id=user.id, dropped_count=walk.dropped_count+ )++ return SkillBundle(+ zip_bytes=build_skills_bundle_zip(walk.trees),+ included=list(walk.trees),+ dropped_count=walk.dropped_count,+ skipped_count=walk.skipped_count,+ )+++def _dropped_count(candidates: QuerySet[LLMSkill], trees: dict[str, FileTree], skipped_count: int) -> int:+ # Every candidate the walk did not include or skip was dropped at the cap. One count query+ # instead of holding the tail of names in memory for a user with thousands of skills.+ return candidates.count() - len(trees) - skipped_count+++def _record_skip(count: int, sample: list[str], name: str) -> int:+ """Bump the skip count and keep only a fixed-size sample of names, so the retained list never+ grows with the number of skipped skills. Returns the new count."""+ if len(sample) < _SKIPPED_LOG_SAMPLE_SIZE:+ sample.append(name)+ return count + 1+++def _walk_stubs(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:+ trees: dict[str, FileTree] = {}+ skipped_count = 0+ skipped_sample: list[str] = []+ for row in _candidate_batches(candidates.values("name", "description", "version")):+ if len(trees) >= limit:+ return _BundleWalk(+ trees=trees,+ dropped_count=_dropped_count(candidates, trees, skipped_count),+ skipped_count=skipped_count,+ skipped_sample=skipped_sample,+ )+ name = row["name"]+ if not _name_and_description_are_valid(name, row["description"]):+ skipped_count = _record_skip(skipped_count, skipped_sample, name)+ continue+ trees[name] = build_skill_stub_tree(+ SkillStub(name=name, description=row["description"], version=row["version"])+ )+ return _BundleWalk(trees=trees, dropped_count=0, skipped_count=skipped_count, skipped_sample=skipped_sample)+++def _name_and_description_are_valid(name: str, description: str) -> bool:+ return (+ skill_name_is_well_formed(name)+ and bool(description.strip())+ and len(description) <= SPEC_DESCRIPTION_MAX_LENGTH+ )+++_GENERATED_ENTRIES = ("SKILL.md", CODEX_METADATA_PATH)+++def _bundle_paths_are_safe(paths: list[str]) -> bool:+ """True when a skill's archive entries unpack cleanly into a home directory on any filesystem.++ Every stored path must already be canonical (a legacy ``refs\\guide.md`` would be archived+ verbatim and land as one flat file, or collide with ``refs/guide.md``), no two entries may+ collide case-insensitively, and no entry may name a directory another entry needs+ (``assets`` next to ``assets/logo.png``), counting the generated SKILL.md and Codex sidecar.+ """+ seen = {entry.lower() for entry in _GENERATED_ENTRIES}+ for path in paths:+ try:+ canonical = normalize_skill_file_path(path)+ except ValueError:+ return False+ if canonical != path:+ return False+ lowered = path.lower()+ # Only the exact sidecar path replaces the generated one (see build_skill_tree); a case+ # variant like `Agents/OpenAI.yaml` keys a second tree entry and would collide instead.+ if lowered in seen and path != CODEX_METADATA_PATH:+ return False+ seen.add(lowered)+ for lowered in seen:+ parts = lowered.split("/")+ if any("/".join(parts[:depth]) in seen for depth in range(1, len(parts))):+ return False+ return True+++def _walk_full(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:+ # Names, descriptions and column byte counts only. A skill's row and files load one skill at a+ # time, and only once it has passed every check, so a user with many or very large skills does+ # not cost the worker more than the bundle cap. File sizes come from the per-skill path query+ # below rather than a join here, so the database never aggregates past the current slice.+ sized = candidates.values("id", "name", "description").annotate(+ body_bytes=_octet_length(F("body")),+ # metadata and allowed_tools render into SKILL.md and have no per-field size limit.+ meta_bytes=_octet_length(Cast(F("metadata"), TextField()))+ + _octet_length(Cast(F("allowed_tools"), TextField())),+ )++ trees: dict[str, FileTree] = {}+ skipped_count = 0+ skipped_sample: list[str] = []+ total_bytes = 0+ capped = False+ for candidate in _candidate_batches(sized):+ name = candidate["name"]+ if len(trees) >= limit:+ capped = True+ break+ # Skips are decided before the cap so an invalid skill never caps the bundle. Validity is+ # cheap: the name and description are in the row, and the paths are a small query.+ if not _name_and_description_are_valid(name, candidate["description"]):+ skipped_count = _record_skip(skipped_count, skipped_sample, name)+ continue+ sized_files = list(+ LLMSkillFile.objects.filter(skill_id=candidate["id"])+ .annotate(content_bytes=_octet_length(F("content")))+ .values_list("path", "content_bytes")+ )+ if not _bundle_paths_are_safe([path for path, _ in sized_files]):+ skipped_count = _record_skip(skipped_count, skipped_sample, name)+ continue+ # The stored bytes are a floor for the rendered tree, so a skill that fails here would fail+ # the exact check below too. Checking first keeps its content out of memory entirely.+ # Charge the archived member name (build_skills_bundle_zip nests every entry under+ # <name>/), not just the relative path, so long names count against the cap.+ file_bytes = sum(archive_entry_bytes(f"{name}/{path}", content_bytes) for path, content_bytes in sized_files)+ if total_bytes + candidate["body_bytes"] + candidate["meta_bytes"] + file_bytes > MAX_BUNDLE_BYTES:+ capped = True+ break+ skill = candidates.filter(id=candidate["id"]).first()+ if skill is None:+ # Archived or superseded since the slice was read. The closing count query will not see+ # it either, so it is neither included, skipped nor dropped.+ continue+ files = list(LLMSkillFile.objects.filter(skill=skill).order_by("path"))+ export = skill_to_export(skill, files)+ if validate_for_export(export):+ skipped_count = _record_skip(skipped_count, skipped_sample, name)+ continue+ tree = build_skill_tree(export)+ tree_bytes = file_tree_bytes(tree, prefix=f"{name}/")+ if total_bytes + tree_bytes > MAX_BUNDLE_BYTES:+ capped = True+ break+ total_bytes += tree_bytes+ trees[name] = tree+ dropped_count = _dropped_count(candidates, trees, skipped_count) if capped else 0+ return _BundleWalk(+ trees=trees, dropped_count=dropped_count, skipped_count=skipped_count, skipped_sample=skipped_sample+ )diff --git a/products/skills/backend/marketplace/packaging.py b/products/skills/backend/marketplace/packaging.pyindex 521e85dd8d27..90ba18d647e8 100644--- a/products/skills/backend/marketplace/packaging.py+++ b/products/skills/backend/marketplace/packaging.py@@ -27,6 +27,13 @@ from .git_smart_http import FileTree# but stored at 4096 today — export validates rather than silently truncating.SPEC_DESCRIPTION_MAX_LENGTH = 1024+# A skill bundle is unpacked into a harness's skill directory, and every skill in it costs prompt+# context on each turn (the harness lists name and description of every discovered skill), so the+# count is bounded by what an agent can usefully carry, not by what the user owns. The client picks+# the count up to the ceiling.+DEFAULT_BUNDLE_SKILLS = 20+MAX_BUNDLE_SKILLS = 100+# Zip-bomb defense for import: bound member count and per-member *decompressed* read so a small# zip can't inflate into GBs of memory. These are coarse hard stops — the precise per-field/per-file# size caps are enforced downstream by the import validator. Member count is kept comfortably above@@ -94,6 +101,45 @@ def render_skill_md(skill: SkillExport) -> str:return render_frontmatter(skill) + "\n" + skill.body+@dataclass(frozen=True)+class SkillStub:+ """The discovery half of a skill: enough for a harness to list and invoke it by name."""++ name: str+ description: str+ version: int+++# The stub must read as a pointer, not as the skill. An agent that treats it as the skill's body+# improvises instead of fetching the real instructions, so the first line says what the file is+# and the steps say exactly which MCP calls to make.+_STUB_BODY = """\+This skill lives in the PostHog skills store. This file is a pointer for discovery, not the skill itself.++Before you act on it:++1. Run `call skill-get {{"skill_name": "{name}"}}` with the PostHog MCP `exec` tool. Note the `version` in the response and pass it to every later call for this skill, so a publish in the meantime cannot mix two versions.+2. If the response has a non-null `body_next_offset`, call `skill-get` again with `"version"` set to that version and `"body_offset"` set to `body_next_offset`, and append the returned `body`. Repeat until `body_next_offset` is null.+3. Follow the complete `body` as the instructions for this skill.+4. If the body references bundled files, fetch each one with `call skill-file-get {{"skill_name": "{name}", "file_path": "<path>", "version": <version>}}` and write it into this directory before you use it.+"""+++def render_skill_stub_md(stub: SkillStub) -> str:+ document: dict[str, object] = {+ "name": stub.name,+ "description": stub.description,+ "metadata": {"version": str(stub.version), "source": "posthog-skills-store"},+ }+ frontmatter = yaml.safe_dump(document, sort_keys=False, allow_unicode=True, default_flow_style=False)+ return f"---\n{frontmatter}---\n\n" + _STUB_BODY.format(name=stub.name)+++def build_skill_stub_tree(stub: SkillStub) -> FileTree:+ """A one-file skill directory whose SKILL.md tells the agent to fetch the real skill over MCP."""+ return {"SKILL.md": render_skill_stub_md(stub)}++def validate_for_export(skill: SkillExport) -> list[str]:"""Return spec-compliance problems that should block or warn on export. Empty == clean."""problems: list[str] = []@@ -156,6 +202,40 @@ def build_skill_zip(skill: SkillExport) -> bytes:return buffer.getvalue()+def build_skills_bundle_zip(trees: dict[str, FileTree]) -> bytes:+ """Many rendered skill trees in one zip, each nested under ``<name>/`` like ``build_skill_zip``.++ Unpacking the result into a skills directory (``~/.claude/skills``, ``~/.agents/skills``)+ yields one spec-compliant directory per skill, so a harness discovers them natively.+ """+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ for name, tree in trees.items():+ for rel_path, content in tree.items():+ archive.writestr(f"{name}/{rel_path}", content)+ return buffer.getvalue()+++# A zip stores each entry's name twice (local file header and central directory entry) plus a+# fixed header per entry (30 and 46 bytes). Counting it keeps a bundle of many empty files with+# long paths inside the byte cap.+_ZIP_ENTRY_OVERHEAD_BYTES = 76+++def archive_entry_bytes(path: str, content_bytes: int) -> int:+ return content_bytes + 2 * len(path.encode("utf-8")) + _ZIP_ENTRY_OVERHEAD_BYTES+++def file_tree_bytes(tree: FileTree, prefix: str = "") -> int:+ """Uncompressed bytes the tree costs in a zip: content plus per-entry framing.++ ``prefix`` is prepended to each entry name to mirror how the tree is archived —+ ``build_skills_bundle_zip`` nests every entry under ``<name>/`` — so the cap counts the real+ archive-member name, not just the tree-relative path.+ """+ return sum(archive_entry_bytes(prefix + path, len(content.encode("utf-8"))) for path, content in tree.items())++def parse_skill_md(content: str) -> dict:"""Parse a SKILL.md string into spec fields (inverse of ``render_skill_md``).diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex 93a9d3a0bc52..4c849b23b2ea 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -794,6 +794,31 @@ export type LlmSkillsListParams = {search?: string}+export type LlmSkillsBundleRetrieveParams = {+ /**+ * What each skill directory in the zip contains. 'stub' (default) writes a SKILL.md with the name, description and instructions to fetch the skill over the PostHog MCP when it is invoked. 'full' writes the rendered SKILL.md, every bundled file and the Codex sidecar.+ *+ * * `stub` - stub+ * * `full` - full+ * @minLength 1+ */+ content?: LlmSkillsBundleRetrieveContent+ /**+ * Maximum number of skills in the zip, newest first; default 20, at most 100. Every skill in the zip costs the agent prompt context on each turn, so pick what the harness can usefully carry. Skills past the limit are reported in X-Skills-Dropped.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+}++export type LlmSkillsBundleRetrieveContent =+ (typeof LlmSkillsBundleRetrieveContent)[keyof typeof LlmSkillsBundleRetrieveContent]++export const LlmSkillsBundleRetrieveContent = {+ Stub: 'stub',+ Full: 'full',+} as const+export type LlmSkillsNameRetrieveParams = {/*** Maximum number of characters of the body to return starting at body_offset. Omit to return the whole body from the offset onwards. When the slice stops before the end, body_next_offset is the offset to request next.diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.tsindex 6354c8ab3f33..fe424d0dc1d3 100644--- a/products/skills/frontend/generated/api.ts+++ b/products/skills/frontend/generated/api.ts@@ -25,6 +25,7 @@ import type {LLMSkillMarketplaceIssueApi,LLMSkillPublishToCommunityApi,LLMSkillResolveResponseApi,+ LlmSkillsBundleRetrieveParams,LlmSkillsListParams,LlmSkillsNameExportRetrieveParams,LlmSkillsNameFilesDestroyParams,@@ -172,6 +173,36 @@ export const llmSkillsCreate = async (})}+export const getLlmSkillsBundleRetrieveUrl = (projectId: string, params?: LlmSkillsBundleRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/llm_skills/bundle/?${stringifiedParams}`+ : `/api/projects/${projectId}/llm_skills/bundle/`+}++/**+ * One zip of the requesting user's store skills, for unpacking into a skills directory.+ */+export const llmSkillsBundleRetrieve = async (+ projectId: string,+ params?: LlmSkillsBundleRetrieveParams,+ options?: RequestInit+): Promise<Blob> => {+ return apiMutator<Blob>(getLlmSkillsBundleRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getLlmSkillsImportCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/llm_skills/import/`}diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yamlindex 5adc6a02c72d..2c4fcc602e11 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -21,6 +21,9 @@ tools:community-skills-vote-create:operation: community_skills_vote_createenabled: false+ llm-skills-bundle-retrieve:+ operation: llm_skills_bundle_retrieve+ enabled: falsellm-skills-import-create:operation: llm_skills_import_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 605d20c07cf2..9fb3cd51a285 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -94440,6 +94440,31 @@ export namespace Schemas {search?: string;};+ export type LlmSkillsBundleRetrieveParams = {+ /**+ * What each skill directory in the zip contains. 'stub' (default) writes a SKILL.md with the name, description and instructions to fetch the skill over the PostHog MCP when it is invoked. 'full' writes the rendered SKILL.md, every bundled file and the Codex sidecar.+ *+ * * `stub` - stub+ * * `full` - full+ * @minLength 1+ */+ content?: LlmSkillsBundleRetrieveContent;+ /**+ * Maximum number of skills in the zip, newest first; default 20, at most 100. Every skill in the zip costs the agent prompt context on each turn, so pick what the harness can usefully carry. Skills past the limit are reported in X-Skills-Dropped.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ };++ export type LlmSkillsBundleRetrieveContent = typeof LlmSkillsBundleRetrieveContent[keyof typeof LlmSkillsBundleRetrieveContent];+++ export const LlmSkillsBundleRetrieveContent = {+ Stub: 'stub',+ Full: 'full',+ } as const;+export type LlmSkillsNameRetrieveParams = {/*** Maximum number of characters of the body to return starting at body_offset. Omit to return the whole body from the offset onwards. When the slice stops before the end, body_next_offset is the offset to request next.