Skip to content

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

feat(skills): Claude Code & Codex plugin marketplace + zip export (#64385)

Danilo Campos9d789e876011
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f9369bb0c1dd..aea55f562cdc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4433,9 +4433,9 @@ snapshots:
scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--medium--light:
hash: v1.k794b7964.2840e9974f0c9dc78a532d205c853b03d0b657126d5d2086c74b32aec6baccb5.1jWYJEN5ZRDNFh8iMkQNTAOAHv3UqYcn9VcczlkNzEk
scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--dark:
- hash: v1.k794b7964.f00d31d0d8e7b95b7ad07fb7f8383a7d6ea6044fb1cc25791407e4e60f0b9901.pE41arFxTiOq8cwkPx0r2kl8OLHOF30KOGocaKwA-fU
+ hash: v1.k794b7964.52c92de8ea06b0a69d14608b9db08b781ae20b116c94efff1b0ba1ca07f7cb4f.JfWC_7Alg-qMjsl4Rw-n8zMCKZ95nwlEOni7lAbbnPg
scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--light:
- hash: v1.k794b7964.31997786f70c2eb737f5050aba82d4e49faac804f231ae7d6b3c9e0648adfb84.pcnXDmeN6SI2-Vc7-DSwVW625tTYmzFo1Hu23SV7gX4
+ hash: v1.k794b7964.ef580d47a394f197ebb785c2cac8156ae7e76b62d3220ea7f7b6f2a0609803e6.8rGPQkHXBXwGCatN1swSo0VYg_ZFgpa2fksd77fzWjM
scenes-app-ai-observability-trace--full--dark:
hash: v1.k794b7964.c96ac17075c438842f6c9cba3108ad203ac5c6f5b2623e9eb6cee27850f4121a.cLPI-cVw9u_9N1Zrt8FTQs9NzQ7VCNiXUHUdMVbN9qM
scenes-app-ai-observability-trace--full--light:
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 2642948249ba..51f5fb2b5cea 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -141,9 +141,17 @@ def exception_handler(exc: Exception, context: ExceptionContext) -> Optional[Res
response = _exceptions_hog_handler(exc, context)
if response is not None and response.status_code == status.HTTP_401_UNAUTHORIZED:
- # Pin to SITE_URL rather than request.build_absolute_uri(): with permissive
- # ALLOWED_HOSTS, the Host header can otherwise steer the discovery hint to an
- # attacker-controlled origin.
- metadata_url = absolute_uri("/.well-known/oauth-protected-resource")
- response["WWW-Authenticate"] = f'Bearer resource_metadata="{metadata_url}"'
+ # A view may pin its own challenge (e.g. the skills marketplace git endpoints, which
+ # git clients can only satisfy with Basic — they cannot complete a Bearer/OAuth flow).
+ view_challenge = getattr(context.get("view"), "www_authenticate_challenge", None)
+ if view_challenge:
+ # Strip CR/LF defensively — this is a view-supplied value, so never let it inject
+ # additional response headers even if a future view derives it from request data.
+ response["WWW-Authenticate"] = view_challenge.replace("\r", "").replace("\n", "")
+ else:
+ # Pin to SITE_URL rather than request.build_absolute_uri(): with permissive
+ # ALLOWED_HOSTS, the Host header can otherwise steer the discovery hint to an
+ # attacker-controlled origin.
+ metadata_url = absolute_uri("/.well-known/oauth-protected-resource")
+ response["WWW-Authenticate"] = f'Bearer resource_metadata="{metadata_url}"'
return response
diff --git a/products/skills/backend/api/marketplace_views.py b/products/skills/backend/api/marketplace_views.py
new file mode 100644
index 000000000000..238ab3b35b65
--- /dev/null
+++ b/products/skills/backend/api/marketplace_views.py
@@ -0,0 +1,121 @@
+"""Read-only Claude Code plugin-marketplace endpoints for a team's skills.
+
+Serves the team's latest skills as a synthesized git repo over Git Smart HTTP so
+``/plugin marketplace add <url>`` (which is ``git clone`` underneath) can install them.
+Authenticated with a Project Secret API Key carried over HTTP Basic (the only auth
+``git clone`` speaks) — never the user's personal key. Team-private: the PSAK's scope
+and team binding (enforced by ``APIScopePermission``) gate access to one team's skills.
+
+These are git-protocol endpoints, not part of the typed JSON/MCP API surface, so they
+are excluded from the OpenAPI schema.
+"""
+
+from typing import Any
+
+from django.db.models import QuerySet
+from django.http import HttpResponse
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.parsers import BaseParser
+from rest_framework.permissions import BasePermission, IsAuthenticated
+from rest_framework.renderers import BaseRenderer
+from rest_framework.request import Request
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.permissions import AccessControlPermission, APIScopePermission, TeamMemberAccessPermission
+
+from ..marketplace import git_smart_http as git
+from ..marketplace.adapters import synthesize_team_marketplace_repo
+from ..marketplace.auth import MarketplaceGitBasicAuthentication
+from ..models.skills import LLMSkill
+
+# git-upload-pack negotiation bodies are tiny (a handful of pkt-lines); cap the read so a
+# client can't make us buffer an arbitrarily large body the handler only substring-checks.
+_MAX_GIT_REQUEST_BYTES = 1_000_000
+
+
+class GitProtocolParser(BaseParser):
+ """Passthrough parser so DRF accepts git's request bodies (read back via ``request.data``).
+
+ Returns a latin-1 ``str`` (lossless over any byte) rather than ``bytes`` so that fallback
+ authenticators in the stack — which probe ``"...key" in request.data`` — don't raise a
+ TypeError on a raw-bytes body; with a str the membership test cleanly returns False.
+ """
+
+ media_type = "*/*"
+
+ def parse(self, stream, media_type=None, parser_context=None) -> str: # type: ignore[override] # passthrough returns a str, not the base Mapping/DataAndFiles
+ return stream.read(_MAX_GIT_REQUEST_BYTES).decode("latin-1")
+
+
+class GitProtocolRenderer(BaseRenderer):
+ """Accept any media type so git's specific Accept header passes content negotiation
+ (the views return raw HttpResponses, so this never actually renders)."""
+
+ media_type = "*/*"
+ format = "git"
+
+ def render(self, data, accepted_media_type=None, renderer_context=None):
+ return data
+
+
+class LLMSkillMarketplaceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "llm_skill"
+ # git clients can't complete a Bearer/OAuth flow — make the 401 advertise Basic so the
+ # credential helper (or token-in-URL) supplies the Personal API Key.
+ www_authenticate_challenge = 'Basic realm="PostHog Skills Marketplace"'
+ # Git fetch is a read even though upload-pack is a POST — force read scope for both actions.
+ required_scopes = ["llm_skill:read"]
+ authentication_classes = [MarketplaceGitBasicAuthentication]
+ parser_classes = [GitProtocolParser]
+ renderer_classes = [GitProtocolRenderer]
+ queryset = LLMSkill.objects.none()
+
+ def safely_get_queryset(self, queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:
+ return LLMSkill.objects.none()
+
+ def dangerously_get_permissions(self) -> list[BasePermission]:
+ # The credential is a real (scoped, read-only) Personal API Key, so the standard checks
+ # apply to its owner and are re-evaluated on every request — the clone stops working the
+ # moment the user loses access, with no manual revocation:
+ # - APIScopePermission: enforces the llm_skill:read scope + the key's team scoping
+ # - AccessControlPermission: gates the read by the same llm_skill RBAC as the JSON skill
+ # APIs (so losing skill access revokes the clone, not just leaving the team)
+ # - TeamMemberAccessPermission: requires current project membership
+ # (`user_access_control`, which AccessControlPermission needs, comes from TeamAndOrgViewSetMixin
+ # — the heavier AccessControlViewSetMixin only adds the access-control management action, which
+ # this git endpoint doesn't want.)
+ return [IsAuthenticated(), APIScopePermission(), AccessControlPermission(), TeamMemberAccessPermission()]
+
+ def _synthesize(self) -> git.SynthesizedRepo:
+ # Cached on the content version, so info/refs polling and the two-request clone reuse
+ # one synthesis instead of rebuilding the whole repo each time.
+ return synthesize_team_marketplace_repo(self.team)
+
+ @extend_schema(exclude=True)
+ @action(methods=["GET"], detail=False, url_path="info/refs")
+ def marketplace_info_refs(self, request: Request, **kwargs: Any) -> HttpResponse:
+ if request.query_params.get("service") != "git-upload-pack":
+ return HttpResponse("Unsupported service", status=403)
+ repo = self._synthesize()
+ return HttpResponse(
+ git.build_info_refs(repo.head_sha),
+ content_type=git.INFO_REFS_CONTENT_TYPE,
+ headers={"Cache-Control": "no-cache"},
+ )
+
+ @extend_schema(exclude=True)
+ @action(methods=["POST"], detail=False, url_path="git-upload-pack")
+ def marketplace_upload_pack(self, request: Request, **kwargs: Any) -> HttpResponse:
+ # GitProtocolParser consumed the stream into request.data (a latin-1 str), so request.body
+ # is no longer readable — recover the raw bytes from the parsed value.
+ parsed: Any = request.data
+ body = parsed.encode("latin-1") if isinstance(parsed, str) else bytes(parsed or b"")
+ repo = self._synthesize()
+ return HttpResponse(
+ git.build_upload_pack(body, repo),
+ content_type=git.UPLOAD_PACK_CONTENT_TYPE,
+ headers={"Cache-Control": "no-cache"},
+ )
diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.py
index 808435ff204e..b65df4868092 100644
--- a/products/skills/backend/api/skill_serializers.py
+++ b/products/skills/backend/api/skill_serializers.py
@@ -13,6 +13,9 @@ from products.ai_observability.backend.markdown_outline import get_markdown_outl
from ..models.skills import LLMSkill, LLMSkillFile
RESERVED_SKILL_NAMES = {"new"}
+# 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"}
DEFAULT_VERSION_PAGE_SIZE = 50
MAX_SKILL_BODY_BYTES = 1_000_000
MAX_SKILL_FILE_BYTES = 1_000_000
@@ -46,13 +49,26 @@ def validate_skill_name_value(value: str) -> str:
def validate_skill_file_path(value: str) -> str:
+ # Paths become git tree entries (and zip/marketplace paths), so anything that would
+ # produce an empty or ambiguous entry name must be rejected — otherwise a single bad
+ # path synthesizes a corrupt git tree and breaks the whole team's marketplace clone.
normalized = value.replace("\\", "/")
- parts = normalized.split("/")
- if any(part == ".." for part in parts):
- raise serializers.ValidationError("File paths must not contain '..' traversal segments.")
+ if not normalized or normalized != normalized.strip():
+ raise serializers.ValidationError("File path must be a non-empty, trimmed relative path.")
if normalized.startswith("/"):
raise serializers.ValidationError("File paths must be relative, not absolute.")
- return value
+ if normalized.endswith("/"):
+ raise serializers.ValidationError("File paths must not end with a slash.")
+ if any(part in ("", ".", "..") for part in normalized.split("/")):
+ raise serializers.ValidationError("File paths must not contain empty, '.', or '..' segments.")
+ if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in normalized):
+ raise serializers.ValidationError("File paths must not contain control characters.")
+ if normalized.lower() in RESERVED_SKILL_FILE_PATHS:
+ raise serializers.ValidationError(f"'{value}' is a reserved file path and cannot be used.")
+ # Persist the normalized (forward-slash) form, not the original: backslashes mean "separator"
+ # here, so storing them verbatim would make `references\guide.md` a single flat tree entry
+ # rather than a file under `references/`, and would let the two spellings dodge dedup.
+ return normalized
def _validate_files(files: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -77,6 +93,14 @@ def validate_skill_body_size(body: str) -> str:
return body
+def validate_allowed_tool(value: str) -> None:
+ # The Agent Skills spec serializes allowed-tools as a single space-separated string, so a tool
+ # name containing whitespace would silently fracture into multiple tools on export/round-trip.
+ # Returns None (raise-only) so it fits a DRF `validators=[...]` list.
+ if any(ch.isspace() for ch in value):
+ raise serializers.ValidationError("Tool names cannot contain whitespace.")
+
+
class LLMSkillFetchQuerySerializer(serializers.Serializer):
version = serializers.IntegerField(
min_value=1,
@@ -233,9 +257,9 @@ class LLMSkillPublishSerializer(serializers.Serializer):
help_text="Environment requirements.",
)
allowed_tools = serializers.ListField(
- child=serializers.CharField(),
+ child=serializers.CharField(validators=[validate_allowed_tool]),
required=False,
- help_text="List of pre-approved tools the skill may use.",
+ help_text="List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
)
metadata = serializers.DictField(
required=False,
@@ -297,10 +321,10 @@ class LLMSkillSerializer(serializers.ModelSerializer):
version_count = serializers.SerializerMethodField()
first_version_created_at = serializers.SerializerMethodField()
allowed_tools = serializers.ListField(
- child=serializers.CharField(),
+ child=serializers.CharField(validators=[validate_allowed_tool]),
required=False,
default=list,
- help_text="List of pre-approved tools the skill may use.",
+ help_text="List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
)
metadata = serializers.DictField(
required=False,
@@ -479,6 +503,12 @@ class LLMSkillVersionSummarySerializer(serializers.ModelSerializer):
read_only_fields = fields
+class LLMSkillImportSerializer(serializers.Serializer):
+ file = serializers.FileField(
+ help_text="A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts/, references/, assets/).",
+ )
+
+
class LLMSkillDuplicateSerializer(serializers.Serializer):
new_name = serializers.CharField(
max_length=64,
@@ -545,3 +575,66 @@ class LLMSkillFileDeleteQuerySerializer(serializers.Serializer):
"when another write has landed in the meantime."
),
)
+
+
+class LLMSkillMarketplaceIssueSerializer(serializers.Serializer):
+ rotate = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Roll the existing marketplace credential to issue a fresh token, replacing the old one "
+ "(this invalidates any setup using the previous token). Ignored when no credential exists yet — "
+ "the first call always mints one. Only affects this user's own credential."
+ ),
+ )
+
+
+class LLMSkillMarketplaceCommandSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=["absent", "exists", "created", "rotated"],
+ help_text=(
+ "absent: no credential yet. exists: one already exists (no token returned). "
+ "created: a new credential was just minted. rotated: the existing credential was rolled."
+ ),
+ )
+ connected = serializers.BooleanField(
+ help_text="Whether this user already has a marketplace credential for the team's skill store."
+ )
+ plugin_name = serializers.CharField(help_text="The plugin name the command installs (Claude Code and Codex).")
+ marketplace_name = serializers.CharField(help_text="The marketplace name, used by the Codex install command.")
+ label = serializers.CharField( # type: ignore[assignment] # field name shadows Field.label (str); intentional
+ help_text="Label of this user's marketplace credential (a scoped Personal API Key)."
+ )
+ repo_url = serializers.CharField(help_text="The marketplace git repository URL, with no credential embedded.")
+ command = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Claude Code: ready-to-paste `/plugin marketplace add` command with the live token embedded. "
+ "Returned only when a token was just issued (status created/rotated); null otherwise."
+ ),
+ )
+ command_template = serializers.CharField(
+ help_text="Claude Code install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present."
+ )
+ codex_command = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "OpenAI Codex: two-line `codex plugin marketplace add` + `codex plugin add` command with the live "
+ "token embedded. Returned only when a token was just issued (status created/rotated); null otherwise."
+ ),
+ )
+ codex_command_template = serializers.CharField(
+ help_text="Codex install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present."
+ )
+ token = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The raw read-only `phx_` credential. Returned once, only when minted or rotated; "
+ "it cannot be retrieved again afterwards."
+ ),
+ )
+ mask_value = serializers.CharField(
+ allow_null=True, help_text="Masked preview of the existing credential (e.g. phx_...abcd)."
+ )
+ created_at = serializers.DateTimeField(allow_null=True, help_text="When the credential was created.")
+ last_rolled_at = serializers.DateTimeField(allow_null=True, help_text="When the credential was last rotated.")
diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.py
index 621b900b700b..2f4d59b3ec12 100644
--- a/products/skills/backend/api/skill_services.py
+++ b/products/skills/backend/api/skill_services.py
@@ -3,6 +3,7 @@ from typing import Any
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
+from django.utils import timezone
from posthog.models import Team, User
@@ -567,8 +568,12 @@ def archive_skill(team: Team, skill_name: str) -> list[int]:
)
if not skill_versions:
raise LLMSkillNotFoundError()
+ # Bump updated_at (the .update() bypasses auto_now) so the marketplace plugin version,
+ # derived from max(updated_at) across all team rows, advances on archive too — otherwise
+ # archiving the most-recently-updated skill would regress the version.
LLMSkill.objects.filter(team=team, name=skill_name, deleted=False).update(
deleted=True,
is_latest=False,
+ updated_at=timezone.now(),
)
return skill_versions
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.py
index 49f6598fe11f..360c319344e3 100644
--- a/products/skills/backend/api/skills.py
+++ b/products/skills/backend/api/skills.py
@@ -3,12 +3,15 @@ from uuid import UUID
from django.db import IntegrityError
from django.db.models import Q, QuerySet
+from django.http import HttpResponse
import structlog
import posthoganalytics
+from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.decorators import action
+from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -30,8 +33,19 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from products.ai_observability.backend.api.metrics import llma_track_latency
+from ..marketplace.adapters import MARKETPLACE_NAME, PLUGIN_NAME, load_skill_export
+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 SkillImportError, build_skill_zip, parse_skill_zip, validate_for_export
from ..models.skills import LLMSkill, LLMSkillFile
from .skill_serializers import (
+ MAX_SKILL_FILE_BYTES,
LLMSkillCreateSerializer,
LLMSkillDuplicateSerializer,
LLMSkillFetchQuerySerializer,
@@ -39,13 +53,20 @@ from .skill_serializers import (
LLMSkillFileDeleteQuerySerializer,
LLMSkillFileRenameSerializer,
LLMSkillFileSerializer,
+ LLMSkillImportSerializer,
LLMSkillListQuerySerializer,
LLMSkillListSerializer,
+ LLMSkillMarketplaceCommandSerializer,
+ LLMSkillMarketplaceIssueSerializer,
LLMSkillPublishSerializer,
LLMSkillResolveQuerySerializer,
LLMSkillResolveResponseSerializer,
LLMSkillSerializer,
LLMSkillVersionSummarySerializer,
+ validate_allowed_tool,
+ validate_skill_body_size,
+ validate_skill_file_path,
+ validate_skill_name_value,
)
from .skill_services import (
LLMSkillDuplicateNameConflictError,
@@ -57,6 +78,7 @@ from .skill_services import (
LLMSkillVersionConflictError,
LLMSkillVersionLimitError,
archive_skill,
+ create_skill,
create_skill_file,
delete_skill_file,
duplicate_skill,
@@ -72,6 +94,10 @@ logger = structlog.get_logger(__name__)
LLM_SKILL_FEATURE_FLAG = "llm-analytics-skills"
+# Generous ceiling for an uploaded skill zip — per-skill content (body, 50 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 _file_extension(path: str) -> str:
return path.rsplit(".", 1)[1].lower() if "." in path else ""
@@ -186,6 +212,10 @@ class LLMSkillViewSet(
return ["llm_skill:write"]
if request.method in ("GET", "HEAD"):
return ["llm_skill:read"]
+ # marketplace_command (GET, read state) and issue_marketplace_command (POST, mint/rotate the
+ # credential) share a URL via @marketplace_command.mapping.post. Resolve per-method.
+ if view.action in ["marketplace_command", "issue_marketplace_command"]:
+ return ["llm_skill:write"] if request.method == "POST" else ["llm_skill:read"]
return None
def _ensure_web_authenticated(self, request: Request) -> Response | None:
@@ -471,6 +501,237 @@ class LLMSkillViewSet(
}
)
+ @extend_schema(
+ parameters=[LLMSkillFetchQuerySerializer],
+ 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 = get_skill_by_name_from_db(self.team, skill_name, version)
+ if skill is None:
+ return self._skill_not_found_response(skill_name)
+
+ export = load_skill_export(skill)
+ problems = validate_for_export(export)
+ if problems:
+ return Response(
+ {"detail": "Skill is not export-ready under the Agent Skills spec.", "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(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": "Zip is not a valid, spec-compliant skill.", "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.
+ # validate_for_export already covers the description (non-empty, ≤ spec limit).
+ problems: list[str] = list(validate_for_export(skill_export))
+ try:
+ validate_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")
+
+ seen_lower: set[str] = set()
+ for skill_file in skill_export.files:
+ try:
+ validate_skill_file_path(skill_file.path)
+ except serializers.ValidationError as err:
+ problems.append(f"file '{skill_file.path}': {self._first_error(err)}")
+ 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")
+ lowered = skill_file.path.lower()
+ if lowered in seen_lower:
+ problems.append(f"file '{skill_file.path}': collides with another file (case-insensitive)")
+ seen_lower.add(lowered)
+ 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})
+ @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})
@action(
methods=["POST"],
diff --git a/products/skills/backend/api/test/test_marketplace_endpoints.py b/products/skills/backend/api/test/test_marketplace_endpoints.py
new file mode 100644
index 000000000000..cf4984f2b69f
--- /dev/null
+++ b/products/skills/backend/api/test/test_marketplace_endpoints.py
@@ -0,0 +1,593 @@
+import io
+import json
+import base64
+import zipfile
+from datetime import timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.utils import timezone
+
+from rest_framework import serializers, status
+
+from posthog.constants import AvailableFeature
+from posthog.models import PersonalAPIKey, User
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team import Team
+from posthog.models.utils import hash_key_value
+
+from ee.models.rbac.access_control import AccessControl
+
+from ...api.skill_serializers import validate_skill_file_path
+from ...api.skill_services import archive_skill
+from ...marketplace import adapters
+from ...marketplace.adapters import build_team_marketplace_tree
+from ...marketplace.credentials import issue_marketplace_credential
+from ...marketplace.packaging import SkillExport, build_skill_zip
+from ...models.skills import LLMSkill, LLMSkillFile
+
+_PAK_TOKEN = "phx_marketplacetoken123"
+
+
+def _basic_header(token: str) -> str:
+ raw = base64.b64encode(f"x-access-token:{token}".encode()).decode()
+ return f"Basic {raw}"
+
+
+def _mint_pak(
+ user: User, *, scopes: list[str], scoped_teams: list[int] | None = None, token: str = _PAK_TOKEN
+) -> PersonalAPIKey:
+ return PersonalAPIKey.objects.create(
+ user=user,
+ label="marketplace-test",
+ secure_value=hash_key_value(token),
+ mask_value="phx...key",
+ scopes=scopes,
+ scoped_teams=scoped_teams,
+ )
+
+
+@patch("products.skills.backend.api.skills.posthoganalytics.feature_enabled", return_value=True)
+class TestSkillZipExport(APIBaseTest):
+ def _url(self, name: str) -> str:
+ return f"/api/environments/{self.team.id}/llm_skills/name/{name}/export"
+
+ def _create_skill(self) -> LLMSkill:
+ skill = LLMSkill.objects.create(
+ team=self.team,
+ name="make-fractals",
+ description="Render fractals.",
+ body="# make-fractals\n\nDo the thing.",
+ version=2,
+ is_latest=True,
+ allowed_tools=["Bash", "Write"],
+ created_by=self.user,
+ )
+ LLMSkillFile.objects.create(
+ skill=skill, path="scripts/run.py", content="print(1)\n", content_type="text/x-python"
+ )
+ return skill
+
+ def test_export_returns_spec_zip(self, _mock_flag):
+ self._create_skill()
+ response = self.client.get(self._url("make-fractals"))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response["Content-Type"] == "application/zip"
+ assert "make-fractals.zip" in response["Content-Disposition"]
+
+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
+ names = set(archive.namelist())
+ skill_md = archive.read("make-fractals/SKILL.md").decode()
+ assert "make-fractals/SKILL.md" in names
+ assert "make-fractals/scripts/run.py" in names
+ assert "allowed-tools: Bash Write" in skill_md
+
+ def test_export_missing_skill_404(self, _mock_flag):
+ assert self.client.get(self._url("nope")).status_code == status.HTTP_404_NOT_FOUND
+
+ def test_export_then_reimport_round_trip(self, _mock_flag):
+ skill = LLMSkill.objects.create(
+ team=self.team,
+ name="round-trip",
+ description="Round trip me.",
+ body="# round-trip\n\nbody here.\n",
+ version=1,
+ is_latest=True,
+ allowed_tools=["Bash", "Write"],
+ created_by=self.user,
+ )
+ LLMSkillFile.objects.create(
+ skill=skill, path="scripts/x.py", content="print(1)\n", content_type="text/x-python"
+ )
+
+ export = self.client.get(self._url("round-trip"))
+ assert export.status_code == status.HTTP_200_OK
+ zip_bytes = export.content
+
+ # Free the name so the re-import recreates it cleanly.
+ archive_skill(self.team, "round-trip")
+
+ upload = SimpleUploadedFile("round-trip.zip", zip_bytes, content_type="application/zip")
+ imported = self.client.post(
+ f"/api/environments/{self.team.id}/llm_skills/import", {"file": upload}, format="multipart"
+ )
+ assert imported.status_code == status.HTTP_201_CREATED, imported.content
+ data = imported.json()
+ assert data["name"] == "round-trip"
+ assert data["description"] == "Round trip me."
+ assert data["body"] == "# round-trip\n\nbody here.\n"
+ assert data["allowed_tools"] == ["Bash", "Write"]
+ assert any(f["path"] == "scripts/x.py" for f in data["files"])
+
+ def test_import_missing_file_is_400(self, _mock_flag):
+ response = self.client.post(f"/api/environments/{self.team.id}/llm_skills/import", {}, format="multipart")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_import_duplicate_name_is_400(self, _mock_flag):
+ LLMSkill.objects.create(
+ team=self.team, name="dupe", description="d", body="b", version=1, is_latest=True, created_by=self.user
+ )
+ export = SkillExport(name="dupe", description="A dupe.", body="# dupe\n", version=1)
+ upload = SimpleUploadedFile("dupe.zip", build_skill_zip(export), content_type="application/zip")
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_skills/import", {"file": upload}, format="multipart"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_export_rejects_spec_invalid_description(self, _mock_flag):
+ # Stored limit is 4096 but the spec caps description at 1024 — export must refuse rather
+ # than emit a spec-invalid SKILL.md.
+ LLMSkill.objects.create(
+ team=self.team,
+ name="too-long",
+ description="x" * 1025,
+ body="# too-long\n",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ response = self.client.get(self._url("too-long"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["problems"]
+
+
+class TestSkillMarketplaceGit(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ # Git clients carry no session — clear the base-class force_login so the only
+ # credential is the Basic header (or none), matching how `git clone` authenticates.
+ self.client.logout()
+ # The synthesized repo is cached on team_id + content version; clear so cross-test
+ # state (LocMemCache isn't rolled back with the DB) can't leak between cases.
+ cache.clear()
+
+ def _info_refs_url(self) -> str:
+ return f"/api/projects/{self.team.id}/llm_skills/marketplace.git/info/refs"
+
+ def _upload_pack_url(self) -> str:
+ return f"/api/projects/{self.team.id}/llm_skills/marketplace.git/git-upload-pack"
+
+ def _create_skill(self) -> LLMSkill:
+ return LLMSkill.objects.create(
+ team=self.team,
+ name="make-fractals",
+ description="Render fractals.",
+ body="# make-fractals\n",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+
+ def test_info_refs_requires_credentials(self):
+ # No credential → 401 with a Basic challenge (git can't complete a Bearer/OAuth flow, so the
+ # view pins WWW-Authenticate to Basic via the global 401 handler).
+ response = self.client.get(self._info_refs_url(), {"service": "git-upload-pack"})
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert response.get("WWW-Authenticate", "").startswith("Basic")
+
+ def test_info_refs_with_pak_advertises_refs(self):
+ self._create_skill()
+ _mint_pak(self.user, scopes=["llm_skill:read"], scoped_teams=[self.team.id])
+ response = self.client.get(
+ self._info_refs_url(),
+ {"service": "git-upload-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response["Content-Type"] == "application/x-git-upload-pack-advertisement"
+ assert b"# service=git-upload-pack" in response.content
+ assert b"refs/heads/main" in response.content
+
+ def test_info_refs_rejects_unknown_service(self):
+ _mint_pak(self.user, scopes=["llm_skill:read"], scoped_teams=[self.team.id])
+ response = self.client.get(
+ self._info_refs_url(),
+ {"service": "git-receive-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_pak_without_scope_is_denied(self):
+ _mint_pak(self.user, scopes=["dashboard:read"], scoped_teams=[self.team.id]) # lacks llm_skill access
+ response = self.client.get(
+ self._info_refs_url(),
+ {"service": "git-upload-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ def test_pak_scoped_to_other_team_is_denied(self):
+ # A key scoped to a different team can't clone this team's marketplace (team scoping).
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ _mint_pak(self.user, scopes=["llm_skill:read"], scoped_teams=[other_team.id])
+ response = self.client.get(
+ self._info_refs_url(),
+ {"service": "git-upload-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ def test_non_member_credential_is_denied(self):
+ # The point of using a user-tied Personal API Key: when the owner is not (or no longer) a
+ # member of the team, their credential stops working — no manual revocation needed.
+ outsider = User.objects.create_user("[email protected]", "pw", first_name="Out")
+ _mint_pak(outsider, scopes=["llm_skill:read"], scoped_teams=[self.team.id])
+ response = self.client.get(
+ self._info_refs_url(),
+ {"service": "git-upload-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ def test_upload_pack_with_pak_returns_packfile_result(self):
+ self._create_skill()
+ _mint_pak(self.user, scopes=["llm_skill:read"], scoped_teams=[self.team.id])
+ response = self.client.post(
+ self._upload_pack_url(),
+ # A valid pkt-line "done" command (0009 = length 9, payload "done\n") after a flush-pkt.
+ data=b"00000009done\n",
+ content_type="application/x-git-upload-pack-request",
+ # git sends this Accept; the passthrough renderer must satisfy content negotiation (no 406).
+ HTTP_ACCEPT="application/x-git-upload-pack-result",
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response["Content-Type"] == "application/x-git-upload-pack-result"
+ assert len(response.content) > 0
+
+
+class TestSkillFilePathValidation:
+ @pytest.mark.parametrize(
+ "bad_path",
+ ["", "scripts/", "a//b.md", "..", "../x.md", "/abs.md", "SKILL.md", "skill.md", "a\x00b.md"],
+ )
+ def test_rejects_unsafe_paths(self, bad_path):
+ with pytest.raises(serializers.ValidationError):
+ validate_skill_file_path(bad_path)
+
+ @pytest.mark.parametrize("good_path", ["scripts/run.py", "references/guide.md", "a/b/c.md", "scripts/skill.md"])
+ def test_accepts_safe_paths(self, good_path):
+ assert validate_skill_file_path(good_path) == good_path
+
+ def test_backslashes_are_normalized_to_slashes(self):
+ # Stored as forward-slash so it nests as a real file in the git tree (and so the two
+ # spellings can't dodge dedup), not a flat entry literally named "references\\guide.md".
+ assert validate_skill_file_path("references\\guide.md") == "references/guide.md"
+
+
+class TestMarketplaceResilience(APIBaseTest):
+ def test_skill_with_uncloneable_paths_is_skipped_not_fatal(self):
+ # A skill with two files colliding only by case would synthesize a tree that aborts
+ # `git clone` on a case-insensitive filesystem — it must be skipped, not break the whole
+ # team's marketplace.
+ good = LLMSkill.objects.create(
+ team=self.team, name="good", description="d", body="b", version=1, is_latest=True, created_by=self.user
+ )
+ LLMSkillFile.objects.create(skill=good, path="scripts/run.py", content="x", content_type="text/x-python")
+ bad = LLMSkill.objects.create(
+ team=self.team, name="bad", description="d", body="b", version=1, is_latest=True, created_by=self.user
+ )
+ LLMSkillFile.objects.create(skill=bad, path="a.md", content="x", content_type="text/markdown")
+ LLMSkillFile.objects.create(skill=bad, path="A.md", content="y", content_type="text/markdown")
+
+ tree = build_team_marketplace_tree(self.team)
+ assert "plugins/posthog-skill-store/skills/good/SKILL.md" in tree
+ assert "plugins/posthog-skill-store/skills/bad/SKILL.md" not in tree
+
+
+class TestMarketplaceVersion(APIBaseTest):
+ def _plugin_version_epoch(self) -> int:
+ tree = build_team_marketplace_tree(self.team)
+ version = json.loads(tree[".claude-plugin/marketplace.json"])["plugins"][0]["version"]
+ return int(version.rsplit(".", 1)[1])
+
+ def test_plugin_version_query_is_cached_across_requests(self):
+ # The Max(updated_at) query should run once per window, not on every synthesis — a clone is
+ # two requests (info/refs + upload-pack) plus repeated auto-update polls.
+ LLMSkill.objects.create(
+ team=self.team, name="s", description="d", body="x", version=1, is_latest=True, created_by=self.user
+ )
+ cache.clear()
+ with patch.object(adapters, "_team_plugin_version", wraps=adapters._team_plugin_version) as spy:
+ adapters.synthesize_team_marketplace_repo(self.team)
+ adapters.synthesize_team_marketplace_repo(self.team)
+ assert spy.call_count == 1
+
+ def test_archiving_newest_skill_does_not_regress_version(self):
+ now = timezone.now().replace(microsecond=0)
+ older = LLMSkill.objects.create(
+ team=self.team,
+ name="skill-old",
+ description="old",
+ body="x",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ newest = LLMSkill.objects.create(
+ team=self.team,
+ name="skill-new",
+ description="new",
+ body="x",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ # Make the to-be-archived skill clearly the most-recently-updated.
+ LLMSkill.objects.filter(pk=older.pk).update(updated_at=now - timedelta(hours=2))
+ LLMSkill.objects.filter(pk=newest.pk).update(updated_at=now)
+
+ before = self._plugin_version_epoch()
+ archive_skill(self.team, "skill-new")
+ after = self._plugin_version_epoch()
+
+ # Without the archive bumping updated_at, the version would drop back to the older
+ # skill's timestamp; with the fix it advances (archive is itself a change).
+ assert after >= before
+
+
+@patch("products.skills.backend.api.skills.posthoganalytics.feature_enabled", return_value=True)
+class TestMarketplaceInstallCommand(APIBaseTest):
+ def _url(self) -> str:
+ return f"/api/environments/{self.team.id}/llm_skills/marketplace/install-command"
+
+ def _label(self) -> str:
+ return f"Skill store · team {self.team.id}"
+
+ def _credential(self) -> PersonalAPIKey | None:
+ return PersonalAPIKey.objects.filter(user=self.user, label=self._label()).first()
+
+ def test_get_reports_absent_when_no_credential(self, _mock_flag):
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["status"] == "absent"
+ assert body["connected"] is False
+ assert body["token"] is None
+ assert body["command"] is None
+ assert body["plugin_name"] == "posthog-skill-store"
+ assert "YOUR_PHX_TOKEN" in body["command_template"]
+ assert self._credential() is None
+
+ def test_get_does_not_mint(self, _mock_flag):
+ self.client.get(self._url())
+ assert PersonalAPIKey.objects.filter(user=self.user).count() == 0
+
+ def test_post_mints_read_only_team_scoped_credential(self, _mock_flag):
+ response = self.client.post(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["status"] == "created"
+ assert body["connected"] is True
+ assert body["token"].startswith("phx_")
+ assert body["token"] in body["command"]
+ assert "x-access-token:" in body["command"]
+ assert f"/api/projects/{self.team.id}/llm_skills/marketplace.git" in body["command"]
+ # Claude Code command is two lines: marketplace add, then plugin install.
+ assert "/plugin marketplace add" in body["command"]
+ assert f"/plugin install posthog-skill-store@{body['marketplace_name']}" in body["command"]
+
+ # Codex command carries the same token and the two-step add/install sequence.
+ assert body["token"] in body["codex_command"]
+ assert "codex plugin marketplace add" in body["codex_command"]
+ assert f"codex plugin add posthog-skill-store@{body['marketplace_name']}" in body["codex_command"]
+
+ key = self._credential()
+ assert key is not None
+ assert key.scopes == ["llm_skill:read"]
+ assert key.scoped_teams == [self.team.id] # locked to this team
+ assert key.label == self._label()
+ assert PersonalAPIKey.objects.filter(user=self.user).count() == 1
+
+ def test_post_again_without_rotate_reuses_and_returns_no_token(self, _mock_flag):
+ self.client.post(self._url())
+ original = self._credential()
+ assert original is not None
+
+ response = self.client.post(self._url())
+ body = response.json()
+ assert body["status"] == "exists"
+ assert body["token"] is None
+ assert body["command"] is None
+ assert body["mask_value"] == original.mask_value
+
+ # No new key, and the stored secret is untouched — existing setups keep working.
+ assert PersonalAPIKey.objects.filter(user=self.user).count() == 1
+ original.refresh_from_db()
+ reloaded = self._credential()
+ assert reloaded is not None
+ assert reloaded.secure_value == original.secure_value
+
+ def test_post_with_rotate_rolls_same_key_and_issues_fresh_token(self, _mock_flag):
+ self.client.post(self._url())
+ original = self._credential()
+ assert original is not None
+ old_secure = original.secure_value
+
+ response = self.client.post(self._url(), {"rotate": True}, format="json")
+ body = response.json()
+ assert body["status"] == "rotated"
+ assert body["token"].startswith("phx_")
+
+ # Same record (no sprawl), new secret, rotation timestamp set, and crucially the returned
+ # token matches the stored hash (the rotate is atomic — no lost update).
+ assert PersonalAPIKey.objects.filter(user=self.user).count() == 1
+ rolled = self._credential()
+ assert rolled is not None
+ assert rolled.id == original.id
+ assert rolled.secure_value != old_secure
+ assert rolled.last_rolled_at is not None
+ assert hash_key_value(body["token"]) == rolled.secure_value
+
+ def test_reuse_re_narrows_a_drifted_key_without_minting_a_token(self, _mock_flag):
+ # A same-label key that somehow carries broader scopes must be pulled back to read-only,
+ # single-team before it's handed back — the UI/endpoint describe it as exactly that.
+ issue_marketplace_credential(self.team, self.user, rotate=False)
+ drifted = self._credential()
+ assert drifted is not None
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ drifted.scopes = ["llm_skill:read", "llm_skill:write"]
+ drifted.scoped_teams = [self.team.id, other_team.id]
+ drifted.scoped_organizations = [str(self.organization.id)]
+ drifted.save()
+
+ result = issue_marketplace_credential(self.team, self.user, rotate=False)
+
+ assert result.status == "exists"
+ assert result.token is None # narrowing needs no new token
+ result.key.refresh_from_db()
+ assert result.key.scopes == ["llm_skill:read"]
+ assert result.key.scoped_teams == [self.team.id]
+ assert result.key.scoped_organizations == []
+
+ def test_rotate_re_narrows_scopes_alongside_the_fresh_token(self, _mock_flag):
+ issue_marketplace_credential(self.team, self.user, rotate=False)
+ drifted = self._credential()
+ assert drifted is not None
+ drifted.scopes = ["llm_skill:read", "llm_skill:write"]
+ drifted.save(update_fields=["scopes"])
+
+ result = issue_marketplace_credential(self.team, self.user, rotate=True)
+
+ assert result.status == "rotated"
+ assert result.token is not None
+ result.key.refresh_from_db()
+ # A freshly minted token must never inherit the broader scopes.
+ assert result.key.scopes == ["llm_skill:read"]
+ assert result.key.scoped_teams == [self.team.id]
+
+ def test_one_user_connecting_does_not_roll_another_users_credential(self, _mock_flag):
+ # Per-user keying: a teammate connecting must not touch mine.
+ mine = issue_marketplace_credential(self.team, self.user, rotate=False)
+ my_secure = mine.key.secure_value
+
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "pw")
+ theirs = issue_marketplace_credential(self.team, teammate, rotate=False)
+
+ assert theirs.status == "created"
+ assert theirs.key.id != mine.key.id
+ assert PersonalAPIKey.objects.filter(user=self.user).count() == 1
+ assert PersonalAPIKey.objects.filter(user=teammate).count() == 1
+ mine.key.refresh_from_db()
+ assert mine.key.secure_value == my_secure # untouched
+
+
+@patch("products.skills.backend.api.skills.posthoganalytics.feature_enabled", return_value=True)
+class TestImportAndCreateValidation(APIBaseTest):
+ def _import_url(self) -> str:
+ return f"/api/environments/{self.team.id}/llm_skills/import"
+
+ def test_import_rejects_oversized_body(self, _mock_flag):
+ # A spec-valid zip (short description) must still be rejected when its SKILL.md body exceeds
+ # the same byte cap the create/edit paths enforce — the import path used to skip that check.
+ export = SkillExport(name="big-skill", description="Big skill.", body="x" * 1_000_001, version=1)
+ upload = SimpleUploadedFile("big.zip", build_skill_zip(export), content_type="application/zip")
+ response = self.client.post(self._import_url(), {"file": upload}, format="multipart")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "body" in str(response.json()).lower()
+
+ def test_create_rejects_whitespace_allowed_tool(self, _mock_flag):
+ # A tool name with a space would fracture the spec's space-delimited allowed-tools string.
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_skills/",
+ {"name": "ws-tool-skill", "description": "d", "body": "b", "allowed_tools": ["Bash Write"]},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_oversize_skills_skipped_from_marketplace_tree(self, _mock_flag):
+ LLMSkill.objects.create(
+ team=self.team, name="aaa", description="d", body="x" * 100, version=1, is_latest=True, created_by=self.user
+ )
+ LLMSkill.objects.create(
+ team=self.team, name="zzz", description="d", body="y" * 100, version=1, is_latest=True, created_by=self.user
+ )
+ with patch.object(adapters, "_MAX_MARKETPLACE_TREE_BYTES", 150):
+ tree = build_team_marketplace_tree(self.team)
+ # First skill fits the (patched) ceiling; the second crosses it and is skipped rather than OOM.
+ assert "plugins/posthog-skill-store/skills/aaa/SKILL.md" in tree
+ assert "plugins/posthog-skill-store/skills/zzz/SKILL.md" not in tree
+
+
+class TestSkillMarketplaceRBAC(APIBaseTest):
+ """The marketplace read must be gated by the same llm_skill RBAC as the JSON skill APIs — a
+ project member who loses skill access can no longer clone, even with a previously minted key."""
+
+ def setUp(self):
+ super().setUp()
+ self.client.logout() # git carries no session; auth is the Basic-bridged PAK only
+ 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()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="member"
+ )
+ # Skills inherit their access-control resource from llm_analytics (RESOURCE_INHERITANCE_MAP).
+ # Make access grant-based: the resource default is "none", so a member only gets in with an
+ # explicit grant — restricting the default is how skill access is actually gated.
+ AccessControl.objects.create(team=self.team, resource="llm_analytics", resource_id=None, access_level="none")
+ LLMSkill.objects.create(
+ team=self.team,
+ name="make-fractals",
+ description="d",
+ body="# x\n",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ self.member = User.objects.create_and_join(self.organization, "[email protected]", "pw")
+ _mint_pak(self.member, scopes=["llm_skill:read"], scoped_teams=[self.team.id])
+
+ def _membership(self) -> OrganizationMembership:
+ return OrganizationMembership.objects.get(user=self.member, organization=self.organization)
+
+ def _clone_status(self) -> int:
+ return self.client.get(
+ f"/api/projects/{self.team.id}/llm_skills/marketplace.git/info/refs",
+ {"service": "git-upload-pack"},
+ HTTP_AUTHORIZATION=_basic_header(_PAK_TOKEN),
+ ).status_code
+
+ def test_member_without_skill_access_is_denied(self):
+ # Valid key, current project member — but no llm_skill grant → the clone is denied. This is
+ # the gap the JSON skill APIs close via AccessControlPermission, now closed here too.
+ assert self._clone_status() in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ def test_member_with_skill_access_can_clone(self):
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_analytics",
+ resource_id=None,
+ access_level="viewer",
+ organization_member=self._membership(),
+ )
+ assert self._clone_status() == status.HTTP_200_OK
diff --git a/products/skills/backend/api/test/test_marketplace_git.py b/products/skills/backend/api/test/test_marketplace_git.py
new file mode 100644
index 000000000000..c31d72fdc0c2
--- /dev/null
+++ b/products/skills/backend/api/test/test_marketplace_git.py
@@ -0,0 +1,155 @@
+import os
+import json
+import shutil
+import tempfile
+import threading
+import subprocess
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+from products.skills.backend.marketplace import git_smart_http as git
+from products.skills.backend.marketplace.packaging import (
+ SkillExport,
+ SkillFileExport,
+ build_marketplace_tree,
+ compute_plugin_version,
+)
+
+# End-to-end proof that the synthesized repo is clonable by a real git client (and therefore
+# by Claude Code's `/plugin marketplace add`). DB-free; skipped where the git binary is absent.
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git binary not available")
+
+
+def _marketplace_tree(epoch: int) -> dict[str, str]:
+ skill = SkillExport(
+ name="make-fractals",
+ description="Render fractal images. Use when asked to visualize fractals.",
+ body="# make-fractals\n\nDo the thing.\n",
+ version=2,
+ allowed_tools=["Bash", "Write"],
+ files=[SkillFileExport(path="scripts/mandelbrot.py", content="print('hi')\n", content_type="text/x-python")],
+ )
+ return build_marketplace_tree(
+ plugin_name="posthog-skill-store",
+ plugin_description="Team skills",
+ plugin_version=compute_plugin_version(epoch),
+ owner_name="PostHog",
+ marketplace_name="posthog-skill-store-marketplace",
+ skills=[skill],
+ )
+
+
+class _GitServer:
+ def __init__(self):
+ self._epoch = 1700000000
+
+ def repo():
+ return git.synthesize_repo(_marketplace_tree(self._epoch), author="PostHog", message="marketplace")
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ if self.path.split("?")[0].endswith("/info/refs"):
+ body = git.build_info_refs(repo().head_sha)
+ self._send(git.INFO_REFS_CONTENT_TYPE, body)
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+ def do_POST(self):
+ if self.path.endswith("/git-upload-pack"):
+ length = int(self.headers.get("Content-Length", 0))
+ body = git.build_upload_pack(self.rfile.read(length), repo())
+ self._send(git.UPLOAD_PACK_CONTENT_TYPE, body)
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+ def _send(self, content_type: str, body: bytes):
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Cache-Control", "no-cache")
+ self.end_headers()
+ self.wfile.write(body)
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
+ self._thread.start()
+
+ @property
+ def url(self) -> str:
+ return f"http://127.0.0.1:{self._server.server_address[1]}/marketplace.git"
+
+ def set_epoch(self, epoch: int):
+ self._epoch = epoch
+
+ def stop(self):
+ self._server.shutdown()
+
+
+def _clone(url: str, dest: str, *extra: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ ["git", "clone", "--quiet", *extra, url, dest],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
+ )
+
+
+def _plugin_version(checkout: str) -> str:
+ with open(os.path.join(checkout, ".claude-plugin", "marketplace.json")) as handle:
+ return json.load(handle)["plugins"][0]["version"]
+
+
+def git_server():
+ server = _GitServer()
+ try:
+ yield server
+ finally:
+ server.stop()
+
+
+def test_full_clone_yields_spec_marketplace_tree(git_server):
+ with tempfile.TemporaryDirectory() as tmp:
+ dest = os.path.join(tmp, "checkout")
+ result = _clone(git_server.url, dest)
+ assert result.returncode == 0, result.stderr
+
+ skill_md = os.path.join(dest, "plugins", "posthog-skill-store", "skills", "make-fractals", "SKILL.md")
+ script = os.path.join(
+ dest, "plugins", "posthog-skill-store", "skills", "make-fractals", "scripts", "mandelbrot.py"
+ )
+ assert os.path.exists(skill_md)
+ assert os.path.exists(script)
+ assert "allowed-tools: Bash Write" in open(skill_md).read()
+
+ fsck = subprocess.run(["git", "-C", dest, "fsck", "--full"], capture_output=True, text=True)
+ assert fsck.returncode == 0, fsck.stderr
+
+
+def test_shallow_clone_succeeds(git_server):
+ with tempfile.TemporaryDirectory() as tmp:
+ dest = os.path.join(tmp, "checkout")
+ result = _clone(git_server.url, dest, "--depth", "1")
+ assert result.returncode == 0, result.stderr
+
+
+def test_content_change_bumps_plugin_version(git_server):
+ with tempfile.TemporaryDirectory() as tmp:
+ first = os.path.join(tmp, "first")
+ assert _clone(git_server.url, first).returncode == 0
+ before = _plugin_version(first)
+
+ git_server.set_epoch(1700009999)
+ second = os.path.join(tmp, "second")
+ assert _clone(git_server.url, second).returncode == 0
+ after = _plugin_version(second)
+
+ assert before != after
+ assert after > before
diff --git a/products/skills/backend/api/test/test_marketplace_packaging.py b/products/skills/backend/api/test/test_marketplace_packaging.py
new file mode 100644
index 000000000000..7b4028f67746
--- /dev/null
+++ b/products/skills/backend/api/test/test_marketplace_packaging.py
@@ -0,0 +1,241 @@
+import io
+import json
+import zipfile
+
+import pytest
+
+import yaml
+
+from products.skills.backend.marketplace import packaging as pkg
+from products.skills.backend.marketplace.git_smart_http import GitSynthesisError, synthesize_repo
+from products.skills.backend.marketplace.packaging import (
+ CODEX_METADATA_PATH,
+ SkillExport,
+ SkillFileExport,
+ SkillImportError,
+ build_marketplace_tree,
+ build_skill_tree,
+ build_skill_zip,
+ compute_plugin_version,
+ parse_skill_zip,
+ render_frontmatter,
+ render_skill_md,
+ validate_for_export,
+)
+
+# These tests are intentionally DB-free — the packaging core takes plain dataclasses.
+
+
+def _skill(**overrides) -> SkillExport:
+ base: dict = {
+ "name": "make-fractals",
+ "description": "Render fractal images. Use when asked to visualize fractals.",
+ "body": "# make-fractals\n\nDo the thing.\n",
+ "version": 3,
+ "license": "MIT",
+ "compatibility": "",
+ "allowed_tools": ["Bash", "Write"],
+ "metadata": {"author": "posthog"},
+ "files": [SkillFileExport(path="scripts/mandelbrot.py", content="print('hi')\n", content_type="text/x-python")],
+ }
+ base.update(overrides)
+ return SkillExport(**base)
+
+
+class TestFrontmatter:
+ def test_frontmatter_is_valid_yaml_with_required_fields(self):
+ block = render_frontmatter(_skill())
+ assert block.startswith("---\n") and block.rstrip().endswith("---")
+ parsed = yaml.safe_load(block.strip().strip("-"))
+ assert parsed["name"] == "make-fractals"
+ assert parsed["description"].startswith("Render fractal images")
+
+ def test_allowed_tools_serialized_as_spec_space_string(self):
+ parsed = yaml.safe_load(render_frontmatter(_skill()).strip().strip("-"))
+ assert parsed["allowed-tools"] == "Bash Write"
+ assert "allowed_tools" not in parsed
+
+ def test_version_lives_under_metadata_not_top_level(self):
+ parsed = yaml.safe_load(render_frontmatter(_skill(version=7)).strip().strip("-"))
+ assert "version" not in parsed
+ assert parsed["metadata"]["version"] == "7"
+ assert parsed["metadata"]["author"] == "posthog"
+
+ def test_stored_metadata_version_cannot_clobber_platform_version(self):
+ parsed = yaml.safe_load(render_frontmatter(_skill(version=7, metadata={"version": "hax"})).strip().strip("-"))
+ assert parsed["metadata"]["version"] == "7"
+
+ def test_blank_optional_fields_are_omitted(self):
+ parsed = yaml.safe_load(
+ render_frontmatter(_skill(license="", compatibility="", allowed_tools=[])).strip().strip("-")
+ )
+ assert "license" not in parsed
+ assert "compatibility" not in parsed
+ assert "allowed-tools" not in parsed
+
+ def test_render_skill_md_appends_body_after_frontmatter(self):
+ out = render_skill_md(_skill())
+ assert "---\n" in out
+ assert out.rstrip().endswith("Do the thing.")
+
+
+class TestExportValidation:
+ def test_description_over_spec_limit_is_flagged(self):
+ problems = validate_for_export(_skill(description="x" * 1025))
+ assert any("1024" in p for p in problems)
+
+ def test_empty_description_is_flagged(self):
+ assert any("non-empty" in p for p in validate_for_export(_skill(description=" ")))
+
+ def test_clean_skill_has_no_problems(self):
+ assert validate_for_export(_skill()) == []
+
+
+class TestSkillTreeAndZip:
+ def test_skill_tree_contains_skill_md_and_bundled_files(self):
+ tree = build_skill_tree(_skill())
+ assert "SKILL.md" in tree
+ assert tree["scripts/mandelbrot.py"] == "print('hi')\n"
+
+ def test_zip_nests_under_directory_named_after_skill(self):
+ with zipfile.ZipFile(io.BytesIO(build_skill_zip(_skill()))) as archive:
+ names = set(archive.namelist())
+ assert "make-fractals/SKILL.md" in names
+ assert "make-fractals/scripts/mandelbrot.py" in names
+
+
+class TestMarketplaceTree:
+ def _tree(self, skills=None):
+ return build_marketplace_tree(
+ plugin_name="posthog-skill-store",
+ plugin_description="Team skills",
+ plugin_version="1.0.42",
+ owner_name="PostHog",
+ marketplace_name="posthog-skill-store-marketplace",
+ skills=skills if skills is not None else [_skill()],
+ )
+
+ def test_marketplace_json_lists_the_plugin_with_version(self):
+ manifest = json.loads(self._tree()[".claude-plugin/marketplace.json"])
+ assert manifest["name"] == "posthog-skill-store-marketplace"
+ assert manifest["owner"]["name"] == "PostHog"
+ plugin = manifest["plugins"][0]
+ assert plugin["name"] == "posthog-skill-store"
+ assert plugin["source"] == "./plugins/posthog-skill-store"
+ assert plugin["version"] == "1.0.42"
+
+ def test_plugin_json_present_and_versioned(self):
+ plugin = json.loads(self._tree()["plugins/posthog-skill-store/.claude-plugin/plugin.json"])
+ assert plugin["name"] == "posthog-skill-store"
+ assert plugin["version"] == "1.0.42"
+
+ def test_skill_files_nested_under_plugin_skill_dir(self):
+ tree = self._tree()
+ assert "plugins/posthog-skill-store/skills/make-fractals/SKILL.md" in tree
+ assert "plugins/posthog-skill-store/skills/make-fractals/scripts/mandelbrot.py" in tree
+
+ def test_empty_team_still_produces_a_valid_marketplace(self):
+ manifest = json.loads(self._tree(skills=[])[".claude-plugin/marketplace.json"])
+ assert manifest["plugins"][0]["name"] == "posthog-skill-store"
+
+
+class TestPluginVersion:
+ def test_version_is_monotonic_with_change_time(self):
+ assert compute_plugin_version(1700000000) < compute_plugin_version(1700009999)
+
+ def test_same_change_time_yields_same_version(self):
+ assert compute_plugin_version(1700000000) == compute_plugin_version(1700000000)
+
+
+class TestCodexMetadata:
+ def test_skill_tree_includes_codex_sidecar(self):
+ parsed = yaml.safe_load(build_skill_tree(_skill())[CODEX_METADATA_PATH])
+ assert parsed["interface"]["display_name"] == "Make fractals"
+ assert parsed["interface"]["short_description"].startswith("Render fractal")
+
+ def test_import_ignores_codex_sidecar(self):
+ # The generated Codex sidecar must not round-trip back in as a stored bundled file.
+ parsed = parse_skill_zip(build_skill_zip(_skill()))
+ assert all(f.path != CODEX_METADATA_PATH for f in parsed.files)
+
+
+class TestZipImport:
+ def test_round_trips_through_build_and_parse(self):
+ skill = _skill()
+ parsed = parse_skill_zip(build_skill_zip(skill))
+ assert parsed.name == skill.name
+ assert parsed.description == skill.description
+ assert parsed.body == skill.body
+ assert parsed.license == skill.license
+ assert parsed.allowed_tools == skill.allowed_tools
+ assert {(f.path, f.content) for f in parsed.files} == {(f.path, f.content) for f in skill.files}
+
+ def test_platform_version_dropped_user_metadata_kept(self):
+ parsed = parse_skill_zip(build_skill_zip(_skill(version=9, metadata={"author": "posthog"})))
+ assert "version" not in parsed.metadata
+ assert parsed.metadata.get("author") == "posthog"
+
+ def test_zip_without_skill_md_raises(self):
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("nope/readme.txt", "x")
+ with pytest.raises(SkillImportError):
+ parse_skill_zip(buffer.getvalue())
+
+ def test_non_zip_raises(self):
+ with pytest.raises(SkillImportError):
+ parse_skill_zip(b"not a zip")
+
+
+class TestGitTreeSafety:
+ def _synth(self, files: dict[str, str]):
+ return synthesize_repo(files, author="PostHog", message="m")
+
+ def test_valid_nested_tree_synthesizes(self):
+ assert self._synth({"SKILL.md": "a", "scripts/x.sh": "b"}).head_sha
+
+ @pytest.mark.parametrize(
+ "files",
+ [
+ {"a/": "x"}, # trailing slash → empty filename
+ {"a//b.md": "x"}, # empty path segment
+ {"scripts": "a", "scripts/x.sh": "b"}, # path used as both a file and a directory
+ {"a.md": "x", "A.md": "y"}, # case-only collision (breaks clone on case-insensitive FS)
+ ],
+ )
+ def test_corrupt_tree_is_rejected(self, files):
+ # A bad path must raise rather than emit a corrupt tree that breaks the whole team's clone.
+ with pytest.raises(GitSynthesisError):
+ self._synth(files)
+
+
+class TestZipBombDefense:
+ def _zip(self, members: dict[str, str]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, content in members.items():
+ archive.writestr(name, content)
+ return buffer.getvalue()
+
+ def test_too_many_members_rejected(self):
+ members = {"s/SKILL.md": "---\nname: s\ndescription: d\n---\nb"}
+ members.update({f"s/scripts/f{i}.txt": "x" for i in range(pkg._MAX_ZIP_MEMBERS + 1)})
+ with pytest.raises(SkillImportError):
+ parse_skill_zip(self._zip(members))
+
+ def test_oversize_member_rejected_without_full_inflation(self):
+ data = self._zip(
+ {
+ "s/SKILL.md": "---\nname: s\ndescription: d\n---\nb",
+ "s/big.txt": "x" * (pkg._MAX_ZIP_MEMBER_BYTES + 10),
+ }
+ )
+ with pytest.raises(SkillImportError):
+ parse_skill_zip(data)
+
+
+class TestSynthesizedPackfile:
+ def test_repo_carries_a_packfile(self):
+ repo = synthesize_repo({"SKILL.md": "a", "scripts/x.sh": "b"}, author="PostHog", message="m")
+ assert repo.packfile.startswith(b"PACK")
+ assert len(repo.packfile) > 12 # header + at least one object + trailer
diff --git a/products/skills/backend/marketplace/README.md b/products/skills/backend/marketplace/README.md
new file mode 100644
index 000000000000..1d6f37f8c80c
--- /dev/null
+++ b/products/skills/backend/marketplace/README.md
@@ -0,0 +1,110 @@
+# Skills: zip export + Claude Code plugin marketplace
+
+Spec-compliant ([agentskills.io](https://agentskills.io/specification)) packaging for stored
+skills, plus a live, team-private Claude Code plugin marketplace served straight from the
+database — no git repo, no static files, no build step. Modeled on Mnemion's approach
+(synthesize a virtual git repo on every request).
+
+## Layout
+
+| Module | Django? | Responsibility |
+| ----------------------------- | ------- | -------------------------------------------------------------------------- |
+| `packaging.py` | no | `SKILL.md` frontmatter serialization, zip + marketplace file-tree assembly |
+| `git_smart_http.py` | no | read-only Git Smart HTTP v2: file tree → packfile / ref advertisement |
+| `adapters.py` | yes | the only ORM layer: `LLMSkill` rows → the plain export dataclasses |
+| `credentials.py` | yes | mint / reuse / rotate the per-(user,team) read-only marketplace key |
+| `auth.py` | yes | HTTP Basic → Personal API Key bridge for `git clone` |
+| `../api/marketplace_views.py` | yes | the two git endpoints (`info/refs`, `git-upload-pack`) |
+
+The two stdlib-only modules are deliberately Django-free so the packfile synthesis is
+unit-testable against the real `git` binary without booting the app
+(`api/test/test_marketplace_git.py`, `api/test/test_marketplace_packaging.py`).
+
+## Endpoints
+
+- **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`).
+- **Zip import** — `POST /api/projects/:team/llm_skills/import` (multipart `file` field, a spec
+ skill `.zip`) → creates the skill (web-authenticated, `llm_skill:write`). The inverse of
+ export: `parse_skill_zip` reads `SKILL.md` frontmatter + bundled files. Round-trips with export.
+- **Install command** — `GET` (read connection state, no mint) + `POST` (mint/rotate the
+ credential, returns the ready-to-paste command) `…/llm_skills/marketplace/install-command`.
+ Web-authenticated; GET needs `llm_skill:read`, POST needs `llm_skill:write`. Powers the
+ "Connect to Claude Code" UI and the `skill-store-install-command` MCP tool. See
+ [Auth](#auth-a-dedicated-read-only-personal-api-key-revoked-with-the-user) for the
+ per-user credential model.
+- **Marketplace** — `…/llm_skills/marketplace.git/info/refs` + `…/git-upload-pack`. The repo
+ root is `…/llm_skills/marketplace.git`; `git` appends the rest. One plugin per team
+ (`posthog-skill-store`).
+
+## Spec mapping (storage → SKILL.md)
+
+- `allowed_tools` (stored list) → `allowed-tools` (spec's hyphenated, space-separated string)
+- platform `version` → `metadata.version` (the spec defines no top-level version field)
+- `description` is validated against the spec's 1024 limit on export (`validate_for_export`)
+
+## Cross-agent portability
+
+The `SKILL.md` artifact is the open standard ([agentskills.io](https://agentskills.io/specification)),
+read by Claude Code, OpenAI Codex, Gemini CLI, Copilot/VS Code, Cursor, Windsurf, and more — so the
+zip export drops straight into any of them. Each skill tree also includes an `agents/openai.yaml`
+sidecar (`render_codex_openai_yaml`) carrying Codex UI metadata; every other agent ignores it. On
+import (`parse_skill_zip`) that sidecar is skipped since export regenerates it.
+
+## Auth: a dedicated, read-only Personal API Key (revoked with the user)
+
+`git clone` (and therefore `/plugin marketplace add` / `codex plugin marketplace add`) speaks
+only HTTP Basic via git credential helpers — never Bearer, never OAuth. So the marketplace uses
+a **Personal API Key** (`phx_…`) carried as the Basic password. `auth.py` bridges Basic → PAK by
+pulling the token from the Basic credential and reusing the standard Personal API Key flow;
+`APIScopePermission` then enforces the `llm_skill:read` scope and the key's team scoping, and
+`TeamMemberAccessPermission` re-checks the user's current membership.
+
+**Why a Personal API Key, not a Project Secret API Key.** The credential must die with the
+user's access — no manual revocation, no offboarding checklist. A user-tied credential gets that
+for free: PostHog re-evaluates membership on every request, so the clone stops working the moment
+the user leaves the team or loses access. A PSAK is deliberately user-_less_ (built to outlive
+the people who make it), which is exactly the wrong property here. It's still _dedicated and
+read-only_ — one minted-for-this-purpose key per `(user, team)`, scoped to only `llm_skill:read`
+and that one team (`scoped_teams`), not the user's everyday key.
+
+**One credential per (user, team)** (`credentials.py`), labeled `Skill store · team <team-id>`
+under the user's account. The raw token is unrecoverable after creation, so "reuse" means
+return-if-present / roll-if-asked. `install-command`'s `GET` reports whether you're already
+connected without minting (the token can't be shown again), and `POST` only rolls when
+`rotate=true` (the rotate takes the row with `select_for_update` so concurrent rolls can't lose
+an update). The minted token lives in the user's OS keychain / git credential store.
+
+## Versioning / auto-update
+
+Claude Code re-pulls when the `version` in `marketplace.json` / `plugin.json` changes. We
+derive it from team content (`compute_plugin_version` keyed on the latest skill change time, in
+milliseconds) so any publish/archive bumps it forward monotonically with zero manual semver.
+The synthesized repo is cached on `team_id` + that version, so repeated clones and auto-update
+polls reuse one synthesis and the cache invalidates automatically on any change.
+
+> **Open question (the spike answers it):** whether Claude Code re-pulls on any version
+> _difference_ or only strictly-greater, and whether background auto-update reliably re-auths
+> via the credential helper. The monotonic-timestamp scheme is safe for either.
+
+## Job one — testing auto-updates (run once a dev env is reachable by a real Claude Code)
+
+1. Expose the dev stack at a URL Claude Code can reach (devbox public URL or a `cloudflared`
+ tunnel in front of `./bin/start` — `localhost` won't do).
+2. Get the ready-to-paste command (mints the per-user read-only credential and embeds it):
+ the **Connect to Claude Code** button in the skills UI, `POST
+/api/environments/:team/llm_skills/marketplace/install-command`, or the
+ `skill-store-install-command` MCP tool. The `phx_…` token is shown once.
+3. Create a skill (UI, API, or the `skill-create` MCP tool) so the marketplace is non-empty.
+4. In Claude Code, paste the command (it is the full
+ `/plugin marketplace add https://x-access-token:phx_…@<host>/api/projects/:team/llm_skills/marketplace.git`),
+ then install the `posthog-skill-store` plugin and confirm a skill loads (`/posthog-skill-store:<name>`).
+5. Publish a change to that skill → the plugin version advances. Trigger / wait for Claude
+ Code's marketplace update and confirm the new `SKILL.md` content is pulled.
+6. Record what actually triggers the re-pull (version diff vs. strictly-greater; manual update
+ vs. background) and whether the credential helper re-auths unattended — that resolves the
+ open question above and tells us whether the version scheme needs adjusting.
+
+Rung 1 (protocol correctness — clone, shallow clone, version bump, `git fsck`) is already
+proven offline against the real `git` binary in `test_marketplace_git.py`; rung 2 (the steps
+above) is the only part that needs a live client.
diff --git a/products/skills/backend/marketplace/__init__.py b/products/skills/backend/marketplace/__init__.py
new file mode 100644
index 000000000000..2e5fac763539
--- /dev/null
+++ b/products/skills/backend/marketplace/__init__.py
@@ -0,0 +1,7 @@
+"""Agent Skills spec packaging and Claude Code plugin-marketplace serving for skills.
+
+- ``packaging`` — Django-free SKILL.md serialization + zip / marketplace file-tree assembly
+- ``git_smart_http`` — Django-free read-only Git Smart HTTP synthesis of the marketplace repo
+- ``adapters`` — the only ORM-aware layer: turns ``LLMSkill`` rows into the plain export dataclasses
+- ``auth`` — Basic-auth -> Project Secret API Key bridge so ``git clone`` can authenticate
+"""
diff --git a/products/skills/backend/marketplace/adapters.py b/products/skills/backend/marketplace/adapters.py
new file mode 100644
index 000000000000..a2f0a206f4fe
--- /dev/null
+++ b/products/skills/backend/marketplace/adapters.py
@@ -0,0 +1,186 @@
+"""ORM-aware bridge between ``LLMSkill`` rows and the Django-free packaging core.
+
+Everything that touches the database for export/marketplace lives here, so the
+serialization and git synthesis stay unit-testable without booting the app.
+"""
+
+from typing import Any
+
+from django.core.cache import cache
+from django.db.models import Max
+
+import structlog
+from rest_framework import serializers
+
+from posthog.models import Team
+
+from ..api.skill_serializers import validate_skill_file_path
+from ..models.skills import LLMSkill, LLMSkillFile
+from .git_smart_http import FileTree, SynthesizedRepo, synthesize_repo
+from .packaging import SkillExport, SkillFileExport, build_marketplace_tree, compute_plugin_version
+
+logger = structlog.get_logger(__name__)
+
+# One plugin per team (the agreed grouping). Stable, predictable names so skills are
+# invocable as ``/posthog-skill-store:<name>`` once installed.
+PLUGIN_NAME = "posthog-skill-store"
+MARKETPLACE_NAME = "posthog-skill-store-marketplace"
+
+_MARKETPLACE_AUTHOR = "PostHog"
+_MARKETPLACE_COMMIT_MESSAGE = "PostHog skills marketplace"
+# The cache key already embeds the content-derived plugin version, so a hit is only ever
+# the current content. The TTL just bounds memory for superseded versions.
+_MARKETPLACE_REPO_CACHE_TTL_SECONDS = 300
+# The plugin version is Max(updated_at) over a team's skill rows — cheap, but it runs on every
+# info/refs, every upload-pack, and every auto-update poll. Briefly cache it so a clone + a burst of
+# polls collapse to one query per window instead of one per request. Auto-update detection lags by
+# at most this TTL (content is never stale — only the version label that triggers a re-pull).
+_MARKETPLACE_VERSION_CACHE_TTL_SECONDS = 15
+
+# Bound the in-memory/cached footprint of a team's marketplace so an outlier team with very many
+# (or very large) skills can't OOM the web worker on clone. Past this cumulative content size we
+# skip the remaining skills (logged) rather than synthesize an unbounded tree.
+_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
+
+
+def skill_to_export(skill: LLMSkill, files: list[LLMSkillFile]) -> SkillExport:
+ return SkillExport(
+ name=skill.name,
+ description=skill.description,
+ body=skill.body,
+ version=skill.version,
+ license=skill.license or "",
+ compatibility=skill.compatibility or "",
+ allowed_tools=list(skill.allowed_tools or []),
+ metadata=dict(skill.metadata or {}),
+ files=[SkillFileExport(path=f.path, content=f.content, content_type=f.content_type) for f in files],
+ )
+
+
+def load_skill_export(skill: LLMSkill) -> SkillExport:
+ files = list(LLMSkillFile.objects.filter(skill=skill).order_by("path"))
+ return skill_to_export(skill, files)
+
+
+def synthesize_team_marketplace_repo(team: Team) -> SynthesizedRepo:
+ """Return the synthesized git repo for a team's marketplace, cached on the content version.
+
+ A normal ``git clone`` hits ``info/refs`` then ``git-upload-pack``, and auto-update polls
+ repeatedly — synthesizing the whole repo (loading every skill + file, hashing every blob)
+ each time would be wasteful. The cache key embeds ``_team_plugin_version`` (which changes
+ exactly when content changes), so a hit is always current and any change invalidates it.
+ """
+ version = _team_plugin_version_cached(team)
+ cache_key = f"skills_marketplace_repo:{team.id}:{version}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+
+ tree = build_team_marketplace_tree(team, version=version)
+ repo = synthesize_repo(tree, author=_MARKETPLACE_AUTHOR, message=_MARKETPLACE_COMMIT_MESSAGE)
+ if len(repo.packfile) <= _MAX_CACHEABLE_PACKFILE_BYTES:
+ cache.set(cache_key, repo, timeout=_MARKETPLACE_REPO_CACHE_TTL_SECONDS)
+ return repo
+
+
+def build_team_marketplace_tree(team: Team, version: str | None = None) -> FileTree:
+ """Synthesize the full plugin-marketplace file tree for a team's latest skills."""
+ if version is None:
+ version = _team_plugin_version(team)
+
+ # Lean query: the marketplace only needs the latest live skills, not the version-history
+ # annotations / created_by join that get_latest_skills_queryset adds.
+ skills = list(LLMSkill.objects.filter(team=team, deleted=False, is_latest=True).order_by("name"))
+
+ files_by_skill = _files_by_skill_id(skills)
+
+ # Drop any skill whose bundled-file paths would synthesize a corrupt/uncloneable git tree
+ # (e.g. legacy rows that predate the stricter path validation, or case-only collisions). One
+ # bad skill is skipped rather than 500-ing the whole team's marketplace clone. We also cap the
+ # cumulative content size: past the ceiling, remaining skills are skipped so a pathological team
+ # can't OOM the clone.
+ exports: list[SkillExport] = []
+ skipped_unsafe: list[str] = []
+ skipped_oversize: list[str] = []
+ total_bytes = 0
+ for skill in skills:
+ files = files_by_skill.get(skill.id, [])
+ if not _skill_files_are_tree_safe(files):
+ skipped_unsafe.append(skill.name)
+ continue
+ skill_bytes = len((skill.body or "").encode("utf-8")) + sum(
+ len((f.content or "").encode("utf-8")) for f in files
+ )
+ # Always include at least one skill (per-skill content is already bounded); skip the rest
+ # once we'd cross the team ceiling.
+ if exports and total_bytes + skill_bytes > _MAX_MARKETPLACE_TREE_BYTES:
+ skipped_oversize.append(skill.name)
+ continue
+ total_bytes += skill_bytes
+ exports.append(skill_to_export(skill, files))
+ if skipped_unsafe:
+ logger.warning("skills_marketplace_skipped_unsafe_skills", team_id=team.id, skills=skipped_unsafe)
+ if skipped_oversize:
+ logger.warning(
+ "skills_marketplace_skipped_oversize",
+ team_id=team.id,
+ skipped_count=len(skipped_oversize),
+ included_bytes=total_bytes,
+ )
+
+ return build_marketplace_tree(
+ plugin_name=PLUGIN_NAME,
+ plugin_description=f"Shared agent skills for {team.name}",
+ plugin_version=version,
+ owner_name=team.organization.name,
+ marketplace_name=MARKETPLACE_NAME,
+ skills=exports,
+ )
+
+
+def _skill_files_are_tree_safe(files: list[LLMSkillFile]) -> bool:
+ """True if every file path is valid and no two collide case-insensitively — i.e. the set
+ synthesizes a tree real git can clone on any filesystem."""
+ seen_lower: set[str] = set()
+ for skill_file in files:
+ try:
+ validate_skill_file_path(skill_file.path)
+ except serializers.ValidationError:
+ return False
+ lowered = skill_file.path.lower()
+ if lowered in seen_lower:
+ return False
+ seen_lower.add(lowered)
+ return True
+
+
+def _files_by_skill_id(skills: list[LLMSkill]) -> dict[Any, list[LLMSkillFile]]:
+ grouped: dict[Any, list[LLMSkillFile]] = {} # keyed by skill UUID (matches skill.id lookups)
+ if not skills:
+ return grouped
+ for skill_file in LLMSkillFile.objects.filter(skill__in=skills).order_by("path"):
+ grouped.setdefault(skill_file.skill_id, []).append(skill_file)
+ return grouped
+
+
+def _team_plugin_version_cached(team: Team) -> str:
+ """``_team_plugin_version`` behind a short TTL so the Max() query runs ~once per window per team
+ instead of on every clone / upload-pack / auto-update poll."""
+ cache_key = f"skills_marketplace_version:{team.id}"
+ version = cache.get(cache_key)
+ if version is None:
+ version = _team_plugin_version(team)
+ cache.set(cache_key, version, timeout=_MARKETPLACE_VERSION_CACHE_TTL_SECONDS)
+ return version
+
+
+def _team_plugin_version(team: Team) -> str:
+ # Max over ALL of the team's skill rows, including archived ones. Publishes add a row with a
+ # fresh updated_at and archive_skill bumps updated_at on the rows it soft-deletes, so this is
+ # monotonic and reflects archives. Deriving it from only live skills would regress the version
+ # when the most-recently-updated skill is archived. Milliseconds (not seconds) so two edits
+ # 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"
diff --git a/products/skills/backend/marketplace/auth.py b/products/skills/backend/marketplace/auth.py
new file mode 100644
index 000000000000..6f669512bb67
--- /dev/null
+++ b/products/skills/backend/marketplace/auth.py
@@ -0,0 +1,65 @@
+"""HTTP Basic -> Personal API Key bridge for the git marketplace endpoints.
+
+``git clone`` (and therefore Claude Code's ``/plugin marketplace add`` / Codex's ``codex plugin
+marketplace add``) only speaks HTTP Basic auth via git credential helpers — it never sends a
+Bearer header. Personal API Key auth normally reads a Bearer header / body / query param, so this
+authenticator pulls the ``phx_`` token out of the Basic credential and otherwise reuses the whole
+standard Personal API Key flow.
+
+Because it's a real Personal API Key, the credential is tied to the user: the standard permission
+stack on the viewset (``APIScopePermission`` + ``TeamMemberAccessPermission``) re-checks the user's
+``llm_skill:read`` scope, team scoping, and current membership on every request — so the credential
+stops working automatically when the user is offboarded or loses team access. No manual revocation.
+
+The token may arrive in either Basic field — git credential helpers vary in whether they put it in
+the username or password — so both are tried.
+"""
+
+import base64
+import binascii
+from typing import Optional, Union
+
+from django.http import HttpRequest
+
+from rest_framework.request import Request
+
+from posthog.auth import PersonalAPIKeyAuthentication
+
+
+class MarketplaceGitBasicAuthentication(PersonalAPIKeyAuthentication):
+ # Subclasses PersonalAPIKeyAuthentication so APIScopePermission treats it as PAK auth (reads
+ # the key's scopes + team scoping) — we only swap the transport from Bearer to Basic by
+ # overriding where the token is read from. Everything else (hash lookup, user__is_active check,
+ # last_used bookkeeping, returning the real user) is inherited unchanged.
+ keyword = "Basic"
+
+ @classmethod
+ def find_key_with_source(cls, request, request_data=None, extra_data=None) -> Optional[tuple[str, str]]:
+ token = cls._extract_basic_token(request)
+ if token is None:
+ return None
+ return token, cls.SOURCE_HEADER
+
+ @staticmethod
+ def _extract_basic_token(request: Union[HttpRequest, Request]) -> Optional[str]:
+ header = request.META.get("HTTP_AUTHORIZATION", "")
+ if isinstance(header, bytes):
+ header = header.decode("latin1")
+ if not header.lower().startswith("basic "):
+ return None
+ try:
+ decoded = base64.b64decode(header[len("basic ") :].strip()).decode("utf-8")
+ except (binascii.Error, UnicodeDecodeError, ValueError):
+ return None
+ username, _, password = decoded.partition(":")
+ # Prefer the password field (the credential-helper convention), fall back to username.
+ token = password or username
+ # Only treat phx_-shaped values as a candidate, so arbitrary Basic creds aren't hashed/looked up.
+ if token and token.startswith("phx_"):
+ return token
+ return None
+
+ @classmethod
+ def authenticate_header(cls, request) -> str:
+ # A Basic challenge makes git retry through its credential helper instead of failing hard.
+ return 'Basic realm="PostHog Skills Marketplace"'
diff --git a/products/skills/backend/marketplace/credentials.py b/products/skills/backend/marketplace/credentials.py
new file mode 100644
index 000000000000..26154eb80125
--- /dev/null
+++ b/products/skills/backend/marketplace/credentials.py
@@ -0,0 +1,143 @@
+"""Per-user marketplace credential: mint / reuse / rotate a dedicated, scoped Personal API Key.
+
+The Claude Code / Codex plugin marketplace is authenticated with the credential carried as the
+git Basic password (see ``auth.py``). We use a **Personal API Key** — a dedicated, read-only one
+scoped to ``llm_skill:read`` and locked to a single team — rather than a Project Secret API Key.
+
+Why a Personal API Key: it's tied to the user, so its access is re-evaluated against current
+membership on every request. The moment the user is offboarded (or loses team access), the
+standard permission stack on the marketplace viewset denies the clone — the credential is
+"revoked" automatically, no manual cleanup. A Project Secret API Key is deliberately user-less
+(built to outlive the people who made it), which is exactly the wrong property here.
+
+It's still *dedicated and read-only* (not the user's everyday key): one minted-for-this-purpose
+key per (user, team), scoped to only ``llm_skill:read`` and that one team. The raw token is
+unrecoverable after creation, so "reuse" means return-if-present / roll-if-asked.
+"""
+
+from dataclasses import dataclass
+from urllib.parse import quote
+
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.models import PersonalAPIKey, Team, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value, mask_key_value
+from posthog.utils import absolute_uri
+
+# Read-only: a leaked credential can only read this one team's skills, nothing else.
+MARKETPLACE_CREDENTIAL_SCOPES = ["llm_skill:read"]
+
+# One key per (user, team). The Personal API Key is owned by the user, so the label only needs to
+# disambiguate teams; it's shown in the user's API-keys settings. Fits the 40-char label cap.
+_LABEL_PREFIX = "Skill store · team "
+
+
+@dataclass(frozen=True)
+class IssuedMarketplaceCredential:
+ key: PersonalAPIKey
+ # The raw ``phx_`` token, available only when we just minted or rotated. None when the
+ # existing key was returned untouched (its token is unrecoverable).
+ token: str | None
+ status: str # "created" | "rotated" | "exists"
+
+
+def marketplace_credential_label(team_id: int) -> str:
+ return f"{_LABEL_PREFIX}{team_id}"
+
+
+def get_marketplace_credential(team: Team, user: User) -> PersonalAPIKey | None:
+ return PersonalAPIKey.objects.filter(user=user, label=marketplace_credential_label(team.id)).first()
+
+
+def issue_marketplace_credential(team: Team, user: User, *, rotate: bool) -> IssuedMarketplaceCredential:
+ """Reuse the user's marketplace key when present; create if absent, roll only if ``rotate``.
+
+ The row is taken with ``select_for_update`` so concurrent rotations of the same key serialize
+ — without it, two ``rotate=True`` requests would each store a different token and the loser's
+ returned token would silently never match the stored hash.
+ """
+ label = marketplace_credential_label(team.id)
+ with transaction.atomic():
+ existing = PersonalAPIKey.objects.select_for_update().filter(user=user, label=label).first()
+ if existing is not None and not rotate:
+ # Re-narrow before handing it back: a same-label key that drifted to broader scopes
+ # would otherwise be returned while the endpoint/UI describe it as read-only and
+ # team-scoped. Narrowing needs no new token, so this stays "exists".
+ narrowed_fields = _narrow_to_marketplace_scope(existing, team)
+ if narrowed_fields:
+ existing.save(update_fields=narrowed_fields)
+ return IssuedMarketplaceCredential(key=existing, token=None, status="exists")
+
+ raw_token = generate_random_token_personal()
+ if existing is None:
+ key = PersonalAPIKey.objects.create(
+ user=user,
+ label=label,
+ secure_value=hash_key_value(raw_token),
+ mask_value=mask_key_value(raw_token),
+ scopes=list(MARKETPLACE_CREDENTIAL_SCOPES),
+ scoped_teams=[team.id],
+ scoped_organizations=[],
+ )
+ return IssuedMarketplaceCredential(key=key, token=raw_token, status="created")
+
+ existing.secure_value = hash_key_value(raw_token)
+ existing.mask_value = mask_key_value(raw_token)
+ existing.last_used_at = None
+ existing.last_rolled_at = timezone.now()
+ # Rotation re-mints the token, so re-assert the narrow scoping in the same write — a freshly
+ # minted token must never inherit scopes broader than what we advertise as read-only.
+ update_fields = ["secure_value", "mask_value", "last_used_at", "last_rolled_at"]
+ update_fields += _narrow_to_marketplace_scope(existing, team)
+ existing.save(update_fields=update_fields)
+ return IssuedMarketplaceCredential(key=existing, token=raw_token, status="rotated")
+
+
+def _narrow_to_marketplace_scope(key: PersonalAPIKey, team: Team) -> list[str]:
+ """Force ``key`` onto the canonical read-only, single-team scoping. Returns the field names
+ that actually changed (so callers can pass them to ``save(update_fields=...)``)."""
+ canonical: dict[str, list[str] | list[int]] = {
+ "scopes": list(MARKETPLACE_CREDENTIAL_SCOPES),
+ "scoped_teams": [team.id],
+ "scoped_organizations": [],
+ }
+ changed: list[str] = []
+ for field, value in canonical.items():
+ if getattr(key, field) != value:
+ setattr(key, field, value)
+ changed.append(field)
+ return changed
+
+
+# Placeholder shown in the command template before a token is minted (and never sent to a server).
+_TOKEN_PLACEHOLDER = "YOUR_PHX_TOKEN"
+
+
+def marketplace_repo_url(team_id: int) -> str:
+ """The marketplace git repo URL with no credential embedded — safe to display.
+
+ Pinned to ``SITE_URL`` via ``absolute_uri`` (not ``request.get_host()``): the host must not be
+ steerable by a request Host header, since the install command below embeds a live token.
+ """
+ return absolute_uri(f"/api/projects/{team_id}/llm_skills/marketplace.git")
+
+
+def _credentialed_git_url(team_id: int, token: str | None) -> str:
+ credential = quote(token, safe="") if token else _TOKEN_PLACEHOLDER
+ scheme, sep, rest = marketplace_repo_url(team_id).partition("://")
+ return f"{scheme}{sep}x-access-token:{credential}@{rest}"
+
+
+def build_install_command(team_id: int, token: str | None, *, plugin_name: str, marketplace_name: str) -> str:
+ """Claude Code: add the marketplace, then install the plugin (two slash commands)."""
+ add = f"/plugin marketplace add {_credentialed_git_url(team_id, token)}"
+ install = f"/plugin install {plugin_name}@{marketplace_name}"
+ return f"{add}\n{install}"
+
+
+def build_codex_install_command(team_id: int, token: str | None, *, plugin_name: str, marketplace_name: str) -> str:
+ """OpenAI Codex: add the same git marketplace, then install the plugin (two lines)."""
+ add = f'codex plugin marketplace add "{_credentialed_git_url(team_id, token)}"'
+ install = f"codex plugin add {plugin_name}@{marketplace_name}"
+ return f"{add}\n{install}"
diff --git a/products/skills/backend/marketplace/git_smart_http.py b/products/skills/backend/marketplace/git_smart_http.py
new file mode 100644
index 000000000000..23e75edd0f1a
--- /dev/null
+++ b/products/skills/backend/marketplace/git_smart_http.py
@@ -0,0 +1,258 @@
+"""Minimal read-only Git Smart HTTP v2 server for serving a synthesized marketplace repo.
+
+Synthesizes a virtual git repository from a file tree (``path -> content``) and
+implements just enough of the Git Smart HTTP protocol for ``git clone`` (and therefore
+Claude Code's ``/plugin marketplace add``). There is no repo on disk, no push support,
+and no delta compression.
+
+This module is deliberately framework-agnostic and stdlib-only — it imports no Django.
+That keeps the packfile synthesis unit-testable against the real ``git`` binary without
+booting the app, and lets the DRF view (and a throwaway stdlib server) share one code path.
+
+Ported from the reference implementation in daniloc/mnemion (``src/git.ts``).
+"""
+
+import zlib
+import hashlib
+from dataclasses import dataclass
+
+OBJ_COMMIT = 1
+OBJ_TREE = 2
+OBJ_BLOB = 3
+
+
+class GitSynthesisError(Exception):
+ """Raised when a file tree would produce a corrupt git object (empty or duplicate
+ tree-entry name, or a path used as both a file and a directory)."""
+
+
+# Fixed author/committer timestamp so identical content always hashes to the same
+# commit SHA — that determinism is what lets Claude Code decide "nothing changed".
+_FIXED_TIMESTAMP = "1700000000 +0000"
+
+FileTree = dict[str, str]
+
+
+@dataclass(frozen=True)
+class GitObject:
+ type: int
+ data: bytes
+ sha: str
+
+
+@dataclass(frozen=True)
+class SynthesizedRepo:
+ objects: list[GitObject]
+ head_sha: str
+ # The finished (zlib-compressed) packfile, computed once at synthesis. Carried on the repo so
+ # the team+version cache memoizes it — otherwise every clone / auto-update poll would recompress
+ # the whole corpus (the dominant CPU cost), which the cache otherwise wouldn't avoid.
+ packfile: bytes
+
+
+def _git_hash(obj_type: str, data: bytes) -> str:
+ header = f"{obj_type} {len(data)}\0".encode()
+ # SHA1 is the git object-ID hash mandated by the wire protocol, not a security primitive.
+ return hashlib.sha1(header + data, usedforsecurity=False).hexdigest() # nosemgrep
+
+
+def _create_blob(content: str) -> GitObject:
+ data = content.encode()
+ return GitObject(type=OBJ_BLOB, data=data, sha=_git_hash("blob", data))
+
+
+@dataclass(frozen=True)
+class _TreeEntry:
+ mode: str
+ name: str
+ sha: str
+
+
+def _create_tree(entries: list[_TreeEntry]) -> GitObject:
+ # Git sorts tree entries by name, treating directories as if they had a trailing slash.
+ def sort_key(entry: _TreeEntry) -> str:
+ return entry.name + "/" if entry.mode.startswith("40") else entry.name
+
+ parts = bytearray()
+ for entry in sorted(entries, key=sort_key):
+ parts += f"{entry.mode} {entry.name}\0".encode()
+ parts += bytes.fromhex(entry.sha)
+ data = bytes(parts)
+ return GitObject(type=OBJ_TREE, data=data, sha=_git_hash("tree", data))
+
+
+def _create_commit(tree_sha: str, message: str, author: str) -> GitObject:
+ email = f"{author.lower()}@localhost"
+ text = (
+ f"tree {tree_sha}\n"
+ f"author {author} <{email}> {_FIXED_TIMESTAMP}\n"
+ f"committer {author} <{email}> {_FIXED_TIMESTAMP}\n"
+ f"\n{message}\n"
+ )
+ data = text.encode()
+ return GitObject(type=OBJ_COMMIT, data=data, sha=_git_hash("commit", data))
+
+
+@dataclass
+class _DirNode:
+ files: dict[str, str] # filename -> blob sha
+ dirs: dict[str, "_DirNode"]
+
+
+def _reject_bad_tree_entry(name: str, seen: set[str]) -> None:
+ if not name:
+ raise GitSynthesisError("empty tree-entry name (a file path is empty or ends in '/')")
+ # Case-insensitive: two entries differing only by case pass git fsck but abort `git clone`
+ # on a case-insensitive filesystem (macOS/Windows) — break the whole team's clone.
+ key = name.lower()
+ if key in seen:
+ raise GitSynthesisError(
+ f"tree-entry name collides (case-insensitively) or is used as both file and dir: {name!r}"
+ )
+ seen.add(key)
+
+
+def synthesize_repo(files: FileTree, *, author: str, message: str) -> SynthesizedRepo:
+ """Turn a ``path -> content`` map into the git objects of a single-commit repo."""
+ objects: list[GitObject] = []
+ blob_shas: dict[str, str] = {}
+
+ for path, content in files.items():
+ blob = _create_blob(content)
+ objects.append(blob)
+ blob_shas[path] = blob.sha
+
+ root = _DirNode(files={}, dirs={})
+ for path in files:
+ parts = path.split("/")
+ filename = parts.pop()
+ node = root
+ for directory in parts:
+ node = node.dirs.setdefault(directory, _DirNode(files={}, dirs={}))
+ node.files[filename] = blob_shas[path]
+
+ def build_tree(node: _DirNode) -> str:
+ # Reject anything that would emit an invalid tree (empty name) or a tree with two
+ # entries of the same name (a path used as both a file and a directory) — real git
+ # refuses to unpack such a pack, which would break the clone for the whole team.
+ seen: set[str] = set()
+ entries: list[_TreeEntry] = []
+ for name, sha in node.files.items():
+ _reject_bad_tree_entry(name, seen)
+ entries.append(_TreeEntry(mode="100644", name=name, sha=sha))
+ for name, child in node.dirs.items():
+ _reject_bad_tree_entry(name, seen)
+ entries.append(_TreeEntry(mode="40000", name=name, sha=build_tree(child)))
+ tree = _create_tree(entries)
+ objects.append(tree)
+ return tree.sha
+
+ root_sha = build_tree(root)
+ commit = _create_commit(root_sha, message=message, author=author)
+ objects.append(commit)
+ return SynthesizedRepo(objects=objects, head_sha=commit.sha, packfile=build_packfile(objects))
+
+
+def _encode_obj_header(obj_type: int, size: int) -> bytes:
+ out = bytearray()
+ b = (obj_type << 4) | (size & 0x0F)
+ size >>= 4
+ if size > 0:
+ b |= 0x80
+ out.append(b)
+ while size > 0:
+ b = size & 0x7F
+ size >>= 7
+ if size > 0:
+ b |= 0x80
+ out.append(b)
+ return bytes(out)
+
+
+def build_packfile(objects: list[GitObject]) -> bytes:
+ body = bytearray()
+ body += b"PACK"
+ body += (2).to_bytes(4, "big")
+ body += len(objects).to_bytes(4, "big")
+ for obj in objects:
+ body += _encode_obj_header(obj.type, len(obj.data))
+ body += zlib.compress(obj.data)
+ # Packfile trailer is a SHA1 checksum over the pack contents, fixed by the git pack format.
+ body += hashlib.sha1(bytes(body), usedforsecurity=False).digest() # nosemgrep
+ return bytes(body)
+
+
+def _pkt_line(data: str) -> bytes:
+ payload = data.encode()
+ return f"{len(payload) + 4:04x}".encode() + payload
+
+
+_FLUSH_PKT = b"0000"
+
+
+def _side_band_chunks(band: int, data: bytes) -> bytes:
+ # side-band-64k frames cap the payload at 65520 minus 4 (length) and 1 (band byte).
+ max_chunk = 65515
+ out = bytearray()
+ for offset in range(0, len(data), max_chunk):
+ slice_ = data[offset : offset + max_chunk]
+ length = len(slice_) + 5
+ out += f"{length:04x}".encode()
+ out.append(band)
+ out += slice_
+ return bytes(out)
+
+
+INFO_REFS_CONTENT_TYPE = "application/x-git-upload-pack-advertisement"
+UPLOAD_PACK_CONTENT_TYPE = "application/x-git-upload-pack-result"
+
+
+def build_info_refs(head_sha: str) -> bytes:
+ """Body for ``GET /info/refs?service=git-upload-pack`` (the ref advertisement)."""
+ caps = "side-band-64k shallow symref=HEAD:refs/heads/main"
+ out = bytearray()
+ out += _pkt_line("# service=git-upload-pack\n")
+ out += _FLUSH_PKT
+ out += _pkt_line(f"{head_sha} HEAD\0{caps}\n")
+ out += _pkt_line(f"{head_sha} refs/heads/main\n")
+ out += _FLUSH_PKT
+ return bytes(out)
+
+
+def _parse_pkt_lines(body: bytes) -> list[bytes]:
+ """Split a Git pkt-line stream into its payloads (flush-pkts skipped). Stops at the
+ first malformed length rather than scanning raw bytes — so command detection matches
+ actual pkt-line commands, not substrings that merely appear in a ref name."""
+ lines: list[bytes] = []
+ offset = 0
+ total = len(body)
+ while offset + 4 <= total:
+ try:
+ length = int(body[offset : offset + 4], 16)
+ except ValueError:
+ break
+ if length == 0: # flush-pkt
+ offset += 4
+ continue
+ if length < 4 or offset + length > total:
+ break
+ lines.append(body[offset + 4 : offset + length])
+ offset += length
+ return lines
+
+
+def build_upload_pack(request_body: bytes, repo: SynthesizedRepo) -> bytes:
+ """Body for ``POST /git-upload-pack`` (negotiation result + packfile)."""
+ commands = _parse_pkt_lines(request_body)
+ is_shallow = any(line.startswith(b"deepen") for line in commands)
+ is_done = any(line.rstrip(b"\n") == b"done" for line in commands)
+
+ out = bytearray()
+ if is_shallow:
+ out += _pkt_line(f"shallow {repo.head_sha}\n")
+ out += _FLUSH_PKT
+ if is_done:
+ out += _pkt_line("NAK\n")
+ out += _side_band_chunks(1, repo.packfile) # precomputed at synthesis (cached), not recompressed here
+ out += _FLUSH_PKT
+ return bytes(out)
diff --git a/products/skills/backend/marketplace/packaging.py b/products/skills/backend/marketplace/packaging.py
new file mode 100644
index 000000000000..2f33fdc78d4a
--- /dev/null
+++ b/products/skills/backend/marketplace/packaging.py
@@ -0,0 +1,325 @@
+"""Spec-compliant SKILL.md serialization and marketplace/zip file-tree assembly.
+
+The single source of truth for turning a skill into Agent Skills spec artifacts
+(https://agentskills.io/specification). Three consumers share this core:
+
+- zip export (per-skill ``SKILL.md`` + bundled files)
+- the live plugin marketplace (synthesized git repo, served over Smart HTTP)
+- plain-HTTP marketplace file serving
+
+It is Django-free on purpose — it operates on the plain dataclasses below, so a thin
+model adapter (see ``adapters.py``) is the only place that touches the ORM. That keeps
+the spec serialization and tree assembly unit-testable without booting the app.
+"""
+
+import io
+import re
+import json
+import zipfile
+import mimetypes
+from dataclasses import dataclass, field
+
+import yaml
+
+from .git_smart_http import FileTree
+
+# Spec caps (https://agentskills.io/specification). Description is 1024 in the spec
+# but stored at 4096 today — export validates rather than silently truncating.
+SPEC_DESCRIPTION_MAX_LENGTH = 1024
+
+# 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. Kept comfortably above legit limits
+# (a SKILL.md body / bundled file is capped at ~1 MB each, ≤50 files).
+_MAX_ZIP_MEMBERS = 200
+_MAX_ZIP_MEMBER_BYTES = 2_000_000
+_MAX_ZIP_TOTAL_UNCOMPRESSED_BYTES = 80_000_000
+
+# Matches a leading YAML frontmatter block: ``---`` line, body until a closing ``---`` line.
+_FRONTMATTER_RE = re.compile(r"\A---[^\n]*\n(.*?)\n---[^\n]*\n?(.*)\Z", re.DOTALL)
+
+
+class SkillImportError(Exception):
+ """Raised when an uploaded zip / SKILL.md can't be parsed into a skill."""
+
+
+@dataclass(frozen=True)
+class SkillFileExport:
+ path: str
+ content: str
+ content_type: str = "text/plain"
+
+
+@dataclass(frozen=True)
+class SkillExport:
+ name: str
+ description: str
+ body: str
+ version: int
+ license: str = ""
+ compatibility: str = ""
+ allowed_tools: list[str] = field(default_factory=list)
+ metadata: dict[str, str] = field(default_factory=dict)
+ files: list[SkillFileExport] = field(default_factory=list)
+
+
+def render_frontmatter(skill: SkillExport) -> str:
+ """Serialize a skill's spec fields as a YAML frontmatter block (with delimiters).
+
+ Maps storage shape -> spec shape: ``allowed_tools`` (list) becomes the spec's
+ hyphenated, space-separated ``allowed-tools`` string, and the platform ``version``
+ is parked under ``metadata`` since the spec defines no top-level version field.
+ """
+ document: dict[str, object] = {"name": skill.name, "description": skill.description}
+ if skill.license:
+ document["license"] = skill.license
+ if skill.compatibility:
+ document["compatibility"] = skill.compatibility
+
+ # Spec metadata is a string->string map. Stored metadata first, then the platform version
+ # last so it always wins — a user-stored metadata["version"] must not clobber the real one.
+ metadata: dict[str, str] = {str(k): str(v) for k, v in skill.metadata.items()}
+ metadata["version"] = str(skill.version)
+ document["metadata"] = metadata
+
+ if skill.allowed_tools:
+ document["allowed-tools"] = " ".join(skill.allowed_tools)
+
+ body = yaml.safe_dump(document, sort_keys=False, allow_unicode=True, default_flow_style=False)
+ return f"---\n{body}---\n"
+
+
+def render_skill_md(skill: SkillExport) -> str:
+ return render_frontmatter(skill) + "\n" + skill.body
+
+
+def validate_for_export(skill: SkillExport) -> list[str]:
+ """Return spec-compliance problems that should block or warn on export. Empty == clean."""
+ problems: list[str] = []
+ if len(skill.description) > SPEC_DESCRIPTION_MAX_LENGTH:
+ problems.append(
+ f"description is {len(skill.description)} characters; the spec maximum is {SPEC_DESCRIPTION_MAX_LENGTH}"
+ )
+ if not skill.description.strip():
+ problems.append("description is required and must be non-empty")
+ return problems
+
+
+# OpenAI Codex reads this optional sidecar for UI metadata + tool deps; every other agent
+# ignores it. Generated into the tree so the same artifact is first-class in Codex too.
+CODEX_METADATA_PATH = "agents/openai.yaml"
+
+
+def _humanize_skill_name(name: str) -> str:
+ spaced = name.replace("-", " ").strip()
+ return spaced[:1].upper() + spaced[1:] if spaced else name
+
+
+def render_codex_openai_yaml(skill: SkillExport) -> str:
+ """Codex's ``agents/openai.yaml`` — UI metadata derived from the skill's spec fields."""
+ document = {
+ "interface": {
+ "display_name": _humanize_skill_name(skill.name),
+ "short_description": skill.description,
+ }
+ }
+ return yaml.safe_dump(document, sort_keys=False, allow_unicode=True, default_flow_style=False)
+
+
+def build_skill_tree(skill: SkillExport) -> FileTree:
+ """Files for one skill relative to its own root: ``SKILL.md`` + Codex sidecar + bundled files.
+
+ The bundled file ``path`` already encodes its ``scripts/`` / ``references/`` /
+ ``assets/`` subdirectory, so it maps straight through.
+ """
+ tree: FileTree = {
+ "SKILL.md": render_skill_md(skill),
+ # Generated first so a user-bundled file at the same path overrides it below.
+ CODEX_METADATA_PATH: render_codex_openai_yaml(skill),
+ }
+ for skill_file in skill.files:
+ tree[skill_file.path] = skill_file.content
+ return tree
+
+
+def build_skill_zip(skill: SkillExport) -> bytes:
+ """A spec-compliant skill directory zipped under a top-level folder named after the skill.
+
+ The ``<name>/`` top directory satisfies the spec's "name must match the parent
+ directory" rule for the unpacked result.
+ """
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for rel_path, content in build_skill_tree(skill).items():
+ archive.writestr(f"{skill.name}/{rel_path}", content)
+ return buffer.getvalue()
+
+
+def parse_skill_md(content: str) -> dict:
+ """Parse a SKILL.md string into spec fields (inverse of ``render_skill_md``).
+
+ Returns the frontmatter fields mapped to storage shape (``allowed-tools`` space-string ->
+ list, the platform-owned ``metadata.version`` dropped) plus the markdown ``body``.
+ """
+ match = _FRONTMATTER_RE.match(content)
+ if not match:
+ raise SkillImportError("SKILL.md is missing its YAML frontmatter block.")
+ try:
+ frontmatter = yaml.safe_load(match.group(1))
+ except yaml.YAMLError as err:
+ raise SkillImportError(f"SKILL.md frontmatter is not valid YAML: {err}")
+ if not isinstance(frontmatter, dict):
+ raise SkillImportError("SKILL.md frontmatter must be a key/value mapping.")
+
+ name = frontmatter.get("name")
+ if not name or not isinstance(name, str):
+ raise SkillImportError("SKILL.md frontmatter is missing a 'name'.")
+
+ body = match.group(2)
+ if body.startswith("\n"): # render_skill_md joins frontmatter and body with a single newline
+ body = body[1:]
+
+ raw_metadata = frontmatter.get("metadata")
+ metadata = (
+ {str(k): str(v) for k, v in raw_metadata.items() if str(k) != "version"}
+ if isinstance(raw_metadata, dict)
+ else {}
+ )
+ allowed = frontmatter.get("allowed-tools", "")
+ allowed_tools = allowed.split() if isinstance(allowed, str) else [str(x) for x in (allowed or [])]
+
+ return {
+ "name": name,
+ "description": str(frontmatter.get("description") or ""),
+ "license": str(frontmatter.get("license") or ""),
+ "compatibility": str(frontmatter.get("compatibility") or ""),
+ "metadata": metadata,
+ "allowed_tools": allowed_tools,
+ "body": body,
+ }
+
+
+def parse_skill_zip(data: bytes) -> SkillExport:
+ """Parse a spec-compliant skill zip (the inverse of ``build_skill_zip``) into a SkillExport.
+
+ Finds the single ``SKILL.md`` (at the zip root or one directory deep), parses its frontmatter,
+ and collects sibling files under the same directory as bundled files (content type guessed
+ from the path). Text (UTF-8) content only — bundled files are stored as text.
+ """
+ try:
+ archive = zipfile.ZipFile(io.BytesIO(data))
+ except zipfile.BadZipFile:
+ raise SkillImportError("The uploaded file is not a valid zip archive.")
+
+ with archive:
+ infos = archive.infolist()
+ # Reject zip-bombs up front using the archive's declared sizes (no decompression yet):
+ # too many members, or a total uncompressed size that would blow up memory.
+ if len(infos) > _MAX_ZIP_MEMBERS:
+ raise SkillImportError(f"The zip contains too many files (max {_MAX_ZIP_MEMBERS}).")
+ if sum(info.file_size for info in infos) > _MAX_ZIP_TOTAL_UNCOMPRESSED_BYTES:
+ raise SkillImportError("The zip's uncompressed contents are too large.")
+
+ members = [n for n in archive.namelist() if not n.endswith("/")]
+ skill_md_members = [n for n in members if n.rsplit("/", 1)[-1] == "SKILL.md"]
+ if not skill_md_members:
+ raise SkillImportError("The zip does not contain a SKILL.md file.")
+ if len(skill_md_members) > 1:
+ raise SkillImportError("The zip contains multiple SKILL.md files; expected exactly one.")
+
+ skill_md_name = skill_md_members[0]
+ prefix = skill_md_name[: -len("SKILL.md")] # "" (root) or "<dir>/"
+
+ fields = parse_skill_md(_read_zip_text(archive, skill_md_name, "SKILL.md"))
+
+ files: list[SkillFileExport] = []
+ for member in members:
+ if member == skill_md_name or not member.startswith(prefix):
+ continue
+ # Normalize backslashes to "/" so a zip member like `references\guide.md` becomes a
+ # nested file, not a flat entry, matching how the write path stores bundled paths.
+ rel_path = member[len(prefix) :].replace("\\", "/")
+ if rel_path == CODEX_METADATA_PATH:
+ continue # generated Codex sidecar — regenerated on export, not a stored file
+ content = _read_zip_text(archive, member, rel_path)
+ content_type = mimetypes.guess_type(rel_path)[0] or "text/plain"
+ files.append(SkillFileExport(path=rel_path, content=content, content_type=content_type))
+
+ return SkillExport(version=1, files=files, **fields)
+
+
+def _read_zip_text(archive: zipfile.ZipFile, member: str, label: str) -> str:
+ # Bounded decompression: read one byte past the cap so an over-large (or size-spoofed,
+ # decompress-bomb) member is rejected without materializing its full inflated content.
+ with archive.open(member) as handle:
+ raw = handle.read(_MAX_ZIP_MEMBER_BYTES + 1)
+ if len(raw) > _MAX_ZIP_MEMBER_BYTES:
+ raise SkillImportError(f"'{label}' is too large.")
+ try:
+ return raw.decode("utf-8")
+ except UnicodeDecodeError:
+ raise SkillImportError(f"'{label}' must be UTF-8 text; binary files are not supported.")
+
+
+def compute_plugin_version(latest_change_epoch_millis: int) -> str:
+ """Content-derived, monotonic plugin version so auto-update fires on any change.
+
+ Keyed off the most recent change time (in epoch milliseconds) across all of a team's skill
+ rows (see ``adapters._team_plugin_version``): publishes and file edits add/refresh a row's
+ ``updated_at``, and archive bumps it too, so this advances on every change and never
+ regresses. Millisecond resolution keeps two edits within the same second distinct. Whether
+ Claude Code re-pulls on any version *difference* vs. strictly-greater is the open question
+ the auto-update spike answers — this scheme is safe for either.
+ """
+ return f"1.0.{latest_change_epoch_millis}"
+
+
+def build_marketplace_tree(
+ *,
+ plugin_name: str,
+ plugin_description: str,
+ plugin_version: str,
+ owner_name: str,
+ marketplace_name: str,
+ skills: list[SkillExport],
+) -> FileTree:
+ """Assemble the full Claude Code plugin-marketplace file tree for one plugin.
+
+ Layout (skills are auto-discovered from the ``skills/`` directory; we don't emit an
+ explicit skills array, matching the known-working reference implementation)::
+
+ .claude-plugin/marketplace.json
+ plugins/<plugin>/.claude-plugin/plugin.json
+ plugins/<plugin>/skills/<name>/SKILL.md
+ plugins/<plugin>/skills/<name>/<bundled file path>
+ """
+ tree: FileTree = {}
+
+ tree[".claude-plugin/marketplace.json"] = json.dumps(
+ {
+ "name": marketplace_name,
+ "owner": {"name": owner_name},
+ "plugins": [
+ {
+ "name": plugin_name,
+ "source": f"./plugins/{plugin_name}",
+ "description": plugin_description,
+ "version": plugin_version,
+ }
+ ],
+ },
+ indent=2,
+ )
+
+ prefix = f"plugins/{plugin_name}"
+ tree[f"{prefix}/.claude-plugin/plugin.json"] = json.dumps(
+ {"name": plugin_name, "version": plugin_version, "description": plugin_description},
+ indent=2,
+ )
+
+ for skill in skills:
+ skill_prefix = f"{prefix}/skills/{skill.name}"
+ for rel_path, content in build_skill_tree(skill).items():
+ tree[f"{skill_prefix}/{rel_path}"] = content
+
+ return tree
diff --git a/products/skills/backend/routes.py b/products/skills/backend/routes.py
index 51f692b74413..b3e6b3cb37b2 100644
--- a/products/skills/backend/routes.py
+++ b/products/skills/backend/routes.py
@@ -1,7 +1,17 @@
from posthog.api.routing import RouterRegistry
+from products.skills.backend.api.marketplace_views import LLMSkillMarketplaceViewSet
from products.skills.backend.api.skills import LLMSkillViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.register_legacy_dual_route(r"llm_skills", LLMSkillViewSet, "project_llm_skills", ["team_id"])
+ # Git Smart HTTP marketplace. The prefix is the clone repo root: a client appends
+ # /info/refs and /git-upload-pack, which map to the viewset's two actions. New endpoint,
+ # so projects-only (no legacy environments alias).
+ routers.projects.register(
+ r"llm_skills/marketplace.git",
+ LLMSkillMarketplaceViewSet,
+ "project_llm_skills_marketplace",
+ ["team_id"],
+ )
diff --git a/products/skills/frontend/LLMSkillScene.tsx b/products/skills/frontend/LLMSkillScene.tsx
index fce59e0163f2..a03467a24a10 100644
--- a/products/skills/frontend/LLMSkillScene.tsx
+++ b/products/skills/frontend/LLMSkillScene.tsx
@@ -1,9 +1,18 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { combineUrl, router } from 'kea-router'
-import { lazy, Suspense, useEffect, useRef, useState } from 'react'
-
-import { IconChevronRight, IconColumns, IconDocument, IconPencil, IconPlus, IconTrash, IconX } from '@posthog/icons'
+import { Fragment, lazy, Suspense, useEffect, useRef, useState } from 'react'
+
+import {
+ IconChevronRight,
+ IconColumns,
+ IconDocument,
+ IconDownload,
+ IconPencil,
+ IconPlus,
+ IconTrash,
+ IconX,
+} from '@posthog/icons'
import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
@@ -62,10 +71,12 @@ export function LLMSkillScene(): JSX.Element {
versions,
canLoadMoreVersions,
fileContentsLoading,
+ downloadingZip,
} = useValues(llmSkillLogic)
const { searchParams } = useValues(router)
- const { submitSkillForm, deleteSkill, setMode, setSkillFormValues, loadMoreVersions } = useActions(llmSkillLogic)
+ const { submitSkillForm, deleteSkill, setMode, setSkillFormValues, loadMoreVersions, downloadSkill } =
+ useActions(llmSkillLogic)
if (isSkillMissing) {
return <NotFound object="skill" />
@@ -131,6 +142,20 @@ export function LLMSkillScene(): JSX.Element {
</AccessControlAction>
)}
+ {isSkill(skill) && (
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ onClick={downloadSkill}
+ loading={downloadingZip}
+ size="small"
+ tooltip="Download this skill as a spec-compliant .zip (SKILL.md + bundled files)"
+ data-attr="llma-skill-download-zip-button"
+ >
+ Download .zip
+ </LemonButton>
+ )}
+
<AccessControlAction
resourceType={AccessControlResourceType.LlmAnalytics}
minAccessLevel={AccessControlLevel.Editor}
@@ -267,6 +292,23 @@ function SkillViewDetails(): JSX.Element {
return <></>
}
+ // The spec frontmatter, rendered as a compact monospace key/value block. The top-level spec
+ // fields are authoritative, so any stored metadata entry that reuses one of their names (or
+ // `version`, the platform-owned field shown last) is dropped — otherwise it would render a
+ // second, duplicate row for the same key.
+ const reservedFrontmatterKeys = new Set(['license', 'compatibility', 'allowed-tools', 'version'])
+ const frontmatterRows: [string, string][] = [
+ ...(skill.license ? ([['license', skill.license]] as [string, string][]) : []),
+ ...(skill.compatibility ? ([['compatibility', skill.compatibility]] as [string, string][]) : []),
+ ...(skill.allowed_tools?.length
+ ? ([['allowed-tools', skill.allowed_tools.join(' ')]] as [string, string][])
+ : []),
+ ...Object.entries(skill.metadata ?? {})
+ .filter(([key]) => !reservedFrontmatterKeys.has(key))
+ .map(([key, value]): [string, string] => [key, String(value)]),
+ ['version', String(skill.version)],
+ ]
+
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center gap-2">
@@ -297,35 +339,19 @@ function SkillViewDetails(): JSX.Element {
<p className="text-sm">{skill.description}</p>
</div>
- {(skill.license || skill.compatibility) && (
- <div className="grid gap-3 sm:grid-cols-2">
- {skill.license && (
- <div>
- <label className="text-xs font-semibold uppercase text-secondary">License</label>
- <p className="text-sm">{skill.license}</p>
- </div>
- )}
- {skill.compatibility && (
- <div>
- <label className="text-xs font-semibold uppercase text-secondary">Compatibility</label>
- <p className="text-sm">{skill.compatibility}</p>
- </div>
- )}
- </div>
- )}
-
- {skill.allowed_tools && skill.allowed_tools.length > 0 && (
- <div>
- <label className="text-xs font-semibold uppercase text-secondary">Allowed tools</label>
- <div className="mt-1 flex flex-wrap gap-1">
- {skill.allowed_tools.map((tool) => (
- <LemonTag key={tool} type="highlight" size="small">
- {tool}
- </LemonTag>
- ))}
- </div>
+ <div>
+ <label className="text-xs font-semibold uppercase text-secondary">Frontmatter</label>
+ <div className="mt-1 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-0.5 font-mono text-xs">
+ {frontmatterRows.map(([key, value], index) => (
+ // Composite key: a metadata entry could share a name with a reserved
+ // frontmatter field (license/compatibility/allowed-tools), so `key` alone isn't unique.
+ <Fragment key={`${index}-${key}`}>
+ <span className="text-muted">{key}</span>
+ <span className="text-secondary whitespace-pre-wrap break-words">{value}</span>
+ </Fragment>
+ ))}
</div>
- )}
+ </div>
<div>
<div className="flex items-center gap-2">
@@ -527,6 +553,34 @@ function getFileLanguage(path: string, contentType?: string): Language | null {
return null
}
+// Bundled markdown files can carry their own YAML frontmatter; mirror the backend regex so it
+// renders as a tidy block rather than a run-on paragraph the markdown renderer makes of it.
+const BUNDLED_FRONTMATTER_RE = /^---[^\n]*\n([\s\S]*?)\n---[^\n]*\n?([\s\S]*)$/
+
+function splitBundledFrontmatter(text: string): { frontmatter: string; body: string } {
+ const match = text.match(BUNDLED_FRONTMATTER_RE)
+ if (!match) {
+ return { frontmatter: '', body: text }
+ }
+ return { frontmatter: match[1].replace(/\s+$/, ''), body: match[2] }
+}
+
+function BundledMarkdown({ content }: { content: string }): JSX.Element {
+ const { frontmatter, body } = splitBundledFrontmatter(content)
+ return (
+ <>
+ {frontmatter && (
+ <pre className="mb-2 overflow-auto whitespace-pre-wrap rounded bg-fill-secondary px-2 py-1 font-mono text-xs text-muted">
+ {frontmatter}
+ </pre>
+ )}
+ <LemonMarkdownWithMermaid className="text-sm" generateHeadingIds>
+ {body}
+ </LemonMarkdownWithMermaid>
+ </>
+ )
+}
+
function SkillFileViewer({
skillName,
file,
@@ -596,9 +650,7 @@ function SkillFileViewer({
<LemonSkeleton active className="h-3 w-1/2" />
</div>
) : content === null ? null : isMarkdown ? (
- <LemonMarkdownWithMermaid className="text-sm" generateHeadingIds>
- {content}
- </LemonMarkdownWithMermaid>
+ <BundledMarkdown content={content} />
) : codeLanguage !== null ? (
<CodeSnippet language={codeLanguage} compact thing={file.path} maxLinesWithoutExpansion={20}>
{content}
diff --git a/products/skills/frontend/LLMSkillsScene.tsx b/products/skills/frontend/LLMSkillsScene.tsx
index 8c803327bd7e..6e1051190c83 100644
--- a/products/skills/frontend/LLMSkillsScene.tsx
+++ b/products/skills/frontend/LLMSkillsScene.tsx
@@ -1,17 +1,20 @@
import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { useMemo } from 'react'
+import { useMemo, useRef } from 'react'
-import { IconPlusSmall } from '@posthog/icons'
-import { LemonSwitch, Link } from '@posthog/lemon-ui'
+import { IconDownload, IconPlusSmall, IconUpload } from '@posthog/icons'
+import { LemonDivider, LemonModal, LemonSwitch, Link } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
import { MemberSelect } from 'lib/components/MemberSelect'
+import { dayjs } from 'lib/dayjs'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -40,7 +43,8 @@ export const scene: SceneExport = {
function buildSkillColumns(
skillUrl: (name: string) => string,
duplicateSkill: (name: string, newName: string) => void,
- deleteSkill: (name: string) => void
+ deleteSkill: (name: string) => void,
+ downloadSkillZip: (name: string) => void
): LemonTableColumns<LLMSkillListApi> {
return [
{
@@ -103,6 +107,15 @@ function buildSkillColumns(
View
</LemonButton>
+ <LemonButton
+ icon={<IconDownload />}
+ onClick={() => downloadSkillZip(skill.name)}
+ data-attr="llma-skill-dropdown-download"
+ fullWidth
+ >
+ Download .zip
+ </LemonButton>
+
<AccessControlAction
resourceType={AccessControlResourceType.LlmAnalytics}
minAccessLevel={AccessControlLevel.Editor}
@@ -255,19 +268,144 @@ function GroupedSkillsView({
)
}
+function MarketplaceCredentialSection(): JSX.Element {
+ const { marketplaceCommand, codexCommand, marketplaceState, marketplaceLoading, issuingCredential } =
+ useValues(llmSkillsLogic)
+ const { issueMarketplaceCommand } = useActions(llmSkillsLogic)
+
+ if (marketplaceLoading && !marketplaceState) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-secondary">
+ <Spinner /> Checking your skill store connection…
+ </div>
+ )
+ }
+
+ const justIssued = !!marketplaceState?.token
+ const alreadyConnected = !!marketplaceState?.connected && !justIssued
+
+ return (
+ <>
+ {justIssued ? (
+ <LemonBanner type="warning" className="text-sm">
+ This token is shown <b>once</b>. It is <b>read-only</b> and scoped to skills only (
+ <code>llm_skill:read</code>) — it can't touch anything else. It's tied to your account and
+ automatically stops working if you lose access to this project. Manage or revoke it anytime in{' '}
+ <Link to={urls.settings('user-api-keys')}>Settings → Personal API keys</Link>.
+ </LemonBanner>
+ ) : alreadyConnected ? (
+ <LemonBanner type="info" className="text-sm">
+ You already have a skill store credential
+ {marketplaceState?.mask_value ? (
+ <>
+ {' '}
+ (<code>{marketplaceState.mask_value}</code>)
+ </>
+ ) : null}
+ {marketplaceState?.created_at ? <> from {dayjs(marketplaceState.created_at).fromNow()}</> : null}.
+ Existing setups keep working — the token can't be shown again. Setting up a new machine? Generate an
+ install command below.
+ </LemonBanner>
+ ) : (
+ <p className="m-0 text-sm text-secondary">
+ We'll mint a dedicated <b>read-only</b> credential (scope <code>llm_skill:read</code> only — it can
+ read this project's skills and nothing else), just for you, and drop it straight into a
+ ready-to-paste command.
+ </p>
+ )}
+ {!justIssued && (
+ <div>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.LlmAnalytics}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="primary"
+ onClick={() => issueMarketplaceCommand(alreadyConnected)}
+ loading={issuingCredential}
+ data-attr="generate-marketplace-credential-button"
+ >
+ {alreadyConnected
+ ? 'Generate an install command (replaces your old token)'
+ : 'Generate read-only credential & command'}
+ </LemonButton>
+ </AccessControlAction>
+ </div>
+ )}
+ <div className="flex flex-col gap-1">
+ <p className="m-0 text-xs font-semibold text-secondary">Claude Code</p>
+ <CodeSnippet language={Language.Bash} thing="Claude Code command">
+ {marketplaceCommand}
+ </CodeSnippet>
+ <p className="m-0 text-xs text-secondary">
+ Run each line in Claude Code — skills then appear as <code>/posthog-skill-store:&lt;name&gt;</code>,
+ auto-updating as you publish.
+ </p>
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="m-0 text-xs font-semibold text-secondary">Codex</p>
+ <CodeSnippet language={Language.Bash} thing="Codex command">
+ {codexCommand}
+ </CodeSnippet>
+ <p className="m-0 text-xs text-secondary">
+ Run both lines in your terminal — the same marketplace, added to Codex and installed. Codex loads
+ the skills automatically.
+ </p>
+ </div>
+ </>
+ )
+}
+
+function ConnectToClaudeCodeModal(): JSX.Element {
+ const { connectModalOpen } = useValues(llmSkillsLogic)
+ const { setConnectModalOpen } = useActions(llmSkillsLogic)
+
+ return (
+ <LemonModal
+ isOpen={connectModalOpen}
+ onClose={() => setConnectModalOpen(false)}
+ title="Connect a coding agent"
+ description="Install your team's skills into Claude Code or Codex with automatic updates – or let any MCP-connected agent load them directly."
+ width={640}
+ >
+ <div className="flex flex-col gap-4">
+ <section className="flex flex-col gap-2">
+ <h4 className="m-0 font-semibold">Plugin marketplace (Claude Code &amp; Codex)</h4>
+ <MarketplaceCredentialSection />
+ </section>
+
+ <LemonDivider />
+
+ <section className="flex flex-col gap-2">
+ <h4 className="m-0 font-semibold">Any agent (PostHog MCP)</h4>
+ <p className="m-0 text-sm text-secondary">
+ If the PostHog MCP is connected, an agent can list and load these skills directly via its{' '}
+ <code>skill-*</code> tools — no marketplace needed. Just ask:
+ </p>
+ <CodeSnippet language={Language.Text} thing="agent prompt">
+ List my PostHog skills, then load the one that fits this task.
+ </CodeSnippet>
+ </section>
+ </div>
+ </LemonModal>
+ )
+}
+
export function LLMSkillsScene(): JSX.Element {
- const { setFilters, deleteSkill, duplicateSkill } = useActions(llmSkillsLogic)
- const { skills, skillsLoading, sorting, pagination, filters, skillCountLabel, groupedSkills } =
+ const { setFilters, deleteSkill, duplicateSkill, downloadSkillZip, importSkill, setConnectModalOpen } =
+ useActions(llmSkillsLogic)
+ const { skills, skillsLoading, sorting, pagination, filters, skillCountLabel, groupedSkills, importing } =
useValues(llmSkillsLogic)
const { searchParams } = useValues(router)
const skillUrl = (name: string): string => combineUrl(urls.skill(name), searchParams).url
+ const fileInputRef = useRef<HTMLInputElement | null>(null)
// Memoize columns so the array reference doesn't change every render — otherwise every
// nested LemonTable inside the grouped tree reconciles on each parent re-render.
const columns = useMemo(
- () => buildSkillColumns(skillUrl, duplicateSkill, deleteSkill),
+ () => buildSkillColumns(skillUrl, duplicateSkill, deleteSkill, downloadSkillZip),
// eslint-disable-next-line react-hooks/exhaustive-deps
- [searchParams, duplicateSkill, deleteSkill]
+ [searchParams, duplicateSkill, deleteSkill, downloadSkillZip]
)
const showGroupedView = filters.group_by_prefix && groupedSkills && !skillsLoading
@@ -276,24 +414,64 @@ export function LLMSkillsScene(): JSX.Element {
return (
<SceneContent>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".zip,application/zip"
+ className="hidden"
+ data-attr="import-skill-file-input"
+ onChange={(e) => {
+ const file = e.currentTarget.files?.[0]
+ if (file) {
+ importSkill(file)
+ }
+ // Reset so selecting the same file again re-triggers onChange.
+ e.currentTarget.value = ''
+ }}
+ />
+ <ConnectToClaudeCodeModal />
<SceneTitleSection
name="Skills"
- description="Manage versioned agent skills that any MCP-connected agent can discover and use."
+ description="Manage versioned agent skills that any agent can discover and use."
resourceType={{ type: 'llm_analytics' }}
actions={
- <AccessControlAction
- resourceType={AccessControlResourceType.LlmAnalytics}
- minAccessLevel={AccessControlLevel.Editor}
- >
+ <>
<LemonButton
- type="primary"
- to={skillUrl('new')}
- icon={<IconPlusSmall />}
- data-attr="new-skill-button"
+ type="secondary"
+ onClick={() => setConnectModalOpen(true)}
+ data-attr="connect-coding-agent-button"
>
- New skill
+ Load skills in your agent
</LemonButton>
- </AccessControlAction>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.LlmAnalytics}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="secondary"
+ icon={<IconUpload />}
+ onClick={() => fileInputRef.current?.click()}
+ loading={importing}
+ data-attr="import-skill-button"
+ tooltip="Import a skill from a spec-compliant .zip"
+ >
+ Import
+ </LemonButton>
+ </AccessControlAction>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.LlmAnalytics}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="primary"
+ to={skillUrl('new')}
+ icon={<IconPlusSmall />}
+ data-attr="new-skill-button"
+ >
+ New skill
+ </LemonButton>
+ </AccessControlAction>
+ </>
}
/>
diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.ts
index ef497d14bf5a..f67da74b5b4e 100644
--- a/products/skills/frontend/generated/api.schemas.ts
+++ b/products/skills/frontend/generated/api.schemas.ts
@@ -103,7 +103,7 @@ export interface LLMSkillListApi {
* @maxLength 500
*/
compatibility?: string
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
metadata?: LLMSkillListApiMetadata
@@ -176,7 +176,7 @@ export interface LLMSkillCreateApi {
* @maxLength 500
*/
compatibility?: string
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
metadata?: LLMSkillCreateApiMetadata
@@ -195,6 +195,11 @@ export interface LLMSkillCreateApi {
readonly first_version_created_at: string
}
+export interface LLMSkillImportApi {
+ /** A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts/, references/, assets/). */
+ file: string
+}
+
/**
* Arbitrary key-value metadata.
*/
@@ -231,7 +236,7 @@ export interface LLMSkillApi {
* @maxLength 500
*/
compatibility?: string
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
metadata?: LLMSkillApiMetadata
@@ -250,6 +255,81 @@ export interface LLMSkillApi {
readonly first_version_created_at: string
}
+/**
+ * * `absent` - absent
+ * * `exists` - exists
+ * * `created` - created
+ * * `rotated` - rotated
+ */
+export type LLMSkillMarketplaceCommandStatusEnumApi =
+ (typeof LLMSkillMarketplaceCommandStatusEnumApi)[keyof typeof LLMSkillMarketplaceCommandStatusEnumApi]
+
+export const LLMSkillMarketplaceCommandStatusEnumApi = {
+ Absent: 'absent',
+ Exists: 'exists',
+ Created: 'created',
+ Rotated: 'rotated',
+} as const
+
+export interface LLMSkillMarketplaceCommandApi {
+ /** absent: no credential yet. exists: one already exists (no token returned). created: a new credential was just minted. rotated: the existing credential was rolled.
+ *
+ * * `absent` - absent
+ * * `exists` - exists
+ * * `created` - created
+ * * `rotated` - rotated */
+ status: LLMSkillMarketplaceCommandStatusEnumApi
+ /** Whether this user already has a marketplace credential for the team's skill store. */
+ connected: boolean
+ /** The plugin name the command installs (Claude Code and Codex). */
+ plugin_name: string
+ /** The marketplace name, used by the Codex install command. */
+ marketplace_name: string
+ /** Label of this user's marketplace credential (a scoped Personal API Key). */
+ label: string
+ /** The marketplace git repository URL, with no credential embedded. */
+ repo_url: string
+ /**
+ * Claude Code: ready-to-paste `/plugin marketplace add` command with the live token embedded. Returned only when a token was just issued (status created/rotated); null otherwise.
+ * @nullable
+ */
+ command: string | null
+ /** Claude Code install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present. */
+ command_template: string
+ /**
+ * OpenAI Codex: two-line `codex plugin marketplace add` + `codex plugin add` command with the live token embedded. Returned only when a token was just issued (status created/rotated); null otherwise.
+ * @nullable
+ */
+ codex_command: string | null
+ /** Codex install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present. */
+ codex_command_template: string
+ /**
+ * The raw read-only `phx_` credential. Returned once, only when minted or rotated; it cannot be retrieved again afterwards.
+ * @nullable
+ */
+ token: string | null
+ /**
+ * Masked preview of the existing credential (e.g. phx_...abcd).
+ * @nullable
+ */
+ mask_value: string | null
+ /**
+ * When the credential was created.
+ * @nullable
+ */
+ created_at: string | null
+ /**
+ * When the credential was last rotated.
+ * @nullable
+ */
+ last_rolled_at: string | null
+}
+
+export interface LLMSkillMarketplaceIssueApi {
+ /** Roll the existing marketplace credential to issue a fresh token, replacing the old one (this invalidates any setup using the previous token). Ignored when no credential exists yet — the first call always mints one. Only affects this user's own credential. */
+ rotate?: boolean
+}
+
/**
* Arbitrary key-value metadata.
*/
@@ -292,7 +372,7 @@ export interface PatchedLLMSkillPublishApi {
* @maxLength 500
*/
compatibility?: string
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
metadata?: PatchedLLMSkillPublishApiMetadata
@@ -402,6 +482,14 @@ export type LlmSkillsNameRetrieveParams = {
version?: number
}
+export type LlmSkillsNameExportRetrieveParams = {
+ /**
+ * Specific skill version to fetch. If omitted, the latest version is returned.
+ * @minimum 1
+ */
+ version?: number
+}
+
export type LlmSkillsNameFilesRetrieveParams = {
/**
* Specific skill version to fetch. If omitted, the latest version is returned.
diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.ts
index a85a3e0b8331..358f3f08d752 100644
--- a/products/skills/frontend/generated/api.ts
+++ b/products/skills/frontend/generated/api.ts
@@ -15,8 +15,12 @@ import type {
LLMSkillFileApi,
LLMSkillFileCreateApi,
LLMSkillFileRenameApi,
+ LLMSkillImportApi,
+ LLMSkillMarketplaceCommandApi,
+ LLMSkillMarketplaceIssueApi,
LLMSkillResolveResponseApi,
LlmSkillsListParams,
+ LlmSkillsNameExportRetrieveParams,
LlmSkillsNameFilesDestroyParams,
LlmSkillsNameFilesRetrieveParams,
LlmSkillsNameRetrieveParams,
@@ -86,6 +90,67 @@ export const llmSkillsCreate = async (
})
}
+export const getLlmSkillsImportCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/llm_skills/import/`
+}
+
+export const llmSkillsImportCreate = async (
+ projectId: string,
+ lLMSkillImportApi: LLMSkillImportApi,
+ options?: RequestInit
+): Promise<LLMSkillApi> => {
+ const formData = new FormData()
+ formData.append(`file`, lLMSkillImportApi.file)
+
+ return apiMutator<LLMSkillApi>(getLlmSkillsImportCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ body: formData,
+ })
+}
+
+export const getLlmSkillsMarketplaceInstallCommandRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/llm_skills/marketplace/install-command/`
+}
+
+/**
+ * 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.
+ */
+export const llmSkillsMarketplaceInstallCommandRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<LLMSkillMarketplaceCommandApi> => {
+ return apiMutator<LLMSkillMarketplaceCommandApi>(getLlmSkillsMarketplaceInstallCommandRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getLlmSkillsMarketplaceInstallCommandCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/llm_skills/marketplace/install-command/`
+}
+
+/**
+ * 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.
+ */
+export const llmSkillsMarketplaceInstallCommandCreate = async (
+ projectId: string,
+ lLMSkillMarketplaceIssueApi?: LLMSkillMarketplaceIssueApi,
+ options?: RequestInit
+): Promise<LLMSkillMarketplaceCommandApi> => {
+ return apiMutator<LLMSkillMarketplaceCommandApi>(getLlmSkillsMarketplaceInstallCommandCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(lLMSkillMarketplaceIssueApi),
+ })
+}
+
export const getLlmSkillsNameRetrieveUrl = (
projectId: string,
skillName: string,
@@ -169,6 +234,38 @@ export const llmSkillsNameDuplicateCreate = async (
})
}
+export const getLlmSkillsNameExportRetrieveUrl = (
+ projectId: string,
+ skillName: string,
+ params?: LlmSkillsNameExportRetrieveParams
+) => {
+ 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/name/${skillName}/export/?${stringifiedParams}`
+ : `/api/projects/${projectId}/llm_skills/name/${skillName}/export/`
+}
+
+export const llmSkillsNameExportRetrieve = async (
+ projectId: string,
+ skillName: string,
+ params?: LlmSkillsNameExportRetrieveParams,
+ options?: RequestInit
+): Promise<Blob> => {
+ return apiMutator<Blob>(getLlmSkillsNameExportRetrieveUrl(projectId, skillName, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getLlmSkillsNameFilesCreateUrl = (projectId: string, skillName: string) => {
return `/api/projects/${projectId}/llm_skills/name/${skillName}/files/`
}
diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.ts
index b8fe2ef81717..996370fb4a68 100644
--- a/products/skills/frontend/generated/api.zod.ts
+++ b/products/skills/frontend/generated/api.zod.ts
@@ -43,7 +43,10 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod
.max(llmSkillsCreateBodyCompatibilityMax)
.optional()
.describe('Environment requirements (intended product, system packages, network access, etc.).'),
- allowed_tools: zod.array(zod.string()).optional().describe('List of pre-approved tools the skill may use.'),
+ allowed_tools: zod
+ .array(zod.string())
+ .optional()
+ .describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),
metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),
files: zod
.array(
@@ -67,6 +70,30 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod
})
.describe('Create serializer — accepts bundled files as write-only input on POST.')
+export const LlmSkillsImportCreateBody = /* @__PURE__ */ zod.object({
+ file: zod
+ .url()
+ .describe(
+ 'A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts\/, references\/, assets\/).'
+ ),
+})
+
+/**
+ * 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.
+ */
+export const llmSkillsMarketplaceInstallCommandCreateBodyRotateDefault = false
+
+export const LlmSkillsMarketplaceInstallCommandCreateBody = /* @__PURE__ */ zod.object({
+ rotate: zod
+ .boolean()
+ .default(llmSkillsMarketplaceInstallCommandCreateBodyRotateDefault)
+ .describe(
+ "Roll the existing marketplace credential to issue a fresh token, replacing the old one (this invalidates any setup using the previous token). Ignored when no credential exists yet — the first call always mints one. Only affects this user's own credential."
+ ),
+})
+
export const llmSkillsNamePartialUpdateBodyDescriptionMax = 4096
export const llmSkillsNamePartialUpdateBodyLicenseMax = 255
@@ -113,7 +140,10 @@ export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({
.max(llmSkillsNamePartialUpdateBodyCompatibilityMax)
.optional()
.describe('Environment requirements.'),
- allowed_tools: zod.array(zod.string()).optional().describe('List of pre-approved tools the skill may use.'),
+ allowed_tools: zod
+ .array(zod.string())
+ .optional()
+ .describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),
metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),
files: zod
.array(
diff --git a/products/skills/frontend/llmSkillLogic.ts b/products/skills/frontend/llmSkillLogic.ts
index 01e8bbd9b6e5..62b1449a7eb3 100644
--- a/products/skills/frontend/llmSkillLogic.ts
+++ b/products/skills/frontend/llmSkillLogic.ts
@@ -24,7 +24,7 @@ import type {
} from 'products/skills/frontend/generated/api.schemas'
import type { llmSkillLogicType } from './llmSkillLogicType'
-import { llmSkillsLogic, LLM_SKILLS_FORCE_RELOAD_PARAM } from './llmSkillsLogic'
+import { exportAndDownloadSkill, llmSkillsLogic, LLM_SKILLS_FORCE_RELOAD_PARAM } from './llmSkillsLogic'
import { SKILL_DESCRIPTION_MAX_LENGTH, validateSkillName } from './skillConstants'
export enum SkillMode {
@@ -135,6 +135,8 @@ export const llmSkillLogic = kea<llmSkillLogicType>([
setFileContentsLoading: (loading: boolean) => ({ loading }),
toggleOutlineExpanded: true,
setCompareVersion: (compareVersion: number | null) => ({ compareVersion }),
+ downloadSkill: true,
+ setDownloadingZip: (downloadingZip: boolean) => ({ downloadingZip }),
}),
reducers(({ props }) => ({
@@ -193,6 +195,12 @@ export const llmSkillLogic = kea<llmSkillLogicType>([
loadSkillSuccess: () => null,
},
],
+ downloadingZip: [
+ false,
+ {
+ setDownloadingZip: (_, { downloadingZip }) => downloadingZip,
+ },
+ ],
})),
loaders(({ props }) => ({
@@ -399,6 +407,23 @@ export const llmSkillLogic = kea<llmSkillLogicType>([
}),
listeners(({ actions, props, values }) => ({
+ downloadSkill: async () => {
+ if (props.skillName === 'new') {
+ return
+ }
+ actions.setDownloadingZip(true)
+ try {
+ await exportAndDownloadSkill(props.skillName)
+ } catch (e) {
+ console.error('Failed to export skill', e)
+ const detail =
+ e !== null && typeof e === 'object' && 'detail' in e ? (e as { detail?: string }).detail : undefined
+ lemonToast.error(detail || (e instanceof Error ? e.message : 'Failed to export skill'))
+ } finally {
+ actions.setDownloadingZip(false)
+ }
+ },
+
deleteSkill: async () => {
if (props.skillName !== 'new' && values.skill && isSkill(values.skill)) {
try {
diff --git a/products/skills/frontend/llmSkillsLogic.ts b/products/skills/frontend/llmSkillsLogic.ts
index 943e7d93b8bc..1e6fd77a9014 100644
--- a/products/skills/frontend/llmSkillsLogic.ts
+++ b/products/skills/frontend/llmSkillsLogic.ts
@@ -4,7 +4,8 @@ import { router, urlToAction } from 'kea-router'
import { objectsEqual } from 'lib/utils/objects'
-import { ApiConfig } from '~/lib/api'
+import api, { ApiConfig } from '~/lib/api'
+import { downloadBlob } from '~/lib/components/ExportButton/exporter'
import { Sorting } from '~/lib/lemon-ui/LemonTable'
import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { PaginationManual } from '~/lib/lemon-ui/PaginationControl'
@@ -13,14 +14,55 @@ import { sceneLogic } from '~/scenes/sceneLogic'
import { urls } from '~/scenes/urls'
import {
+ getLlmSkillsNameExportRetrieveUrl,
+ llmSkillsImportCreate,
llmSkillsList,
+ llmSkillsMarketplaceInstallCommandCreate,
+ llmSkillsMarketplaceInstallCommandRetrieve,
llmSkillsNameArchiveCreate,
llmSkillsNameDuplicateCreate,
} from 'products/skills/frontend/generated/api'
-import type { LLMSkillListApi, PaginatedLLMSkillListListApi } from 'products/skills/frontend/generated/api.schemas'
+import type {
+ LLMSkillListApi,
+ LLMSkillMarketplaceCommandApi,
+ PaginatedLLMSkillListListApi,
+} from 'products/skills/frontend/generated/api.schemas'
import type { llmSkillsLogicType } from './llmSkillsLogicType'
+/** Builds the `/plugin marketplace add` command. The token is embedded once minted; until then
+ * a placeholder is shown. */
+export function buildMarketplaceCommand(token: string | null): string {
+ const teamId = ApiConfig.getCurrentTeamId()
+ const origin = window.location.origin
+ const scheme = origin.startsWith('https') ? 'https' : 'http'
+ const host = origin.replace(/^https?:\/\//, '')
+ return `/plugin marketplace add ${scheme}://x-access-token:${token ?? 'YOUR_PHS_TOKEN'}@${host}/api/projects/${teamId}/llm_skills/marketplace.git`
+}
+
+function errorDetail(error: unknown): string | undefined {
+ return error !== null && typeof error === 'object' && 'detail' in error
+ ? (error as { detail?: string }).detail
+ : undefined
+}
+
+/** Download a skill as a spec-compliant zip. The generated export client JSON-parses the
+ * binary response, so fetch the raw blob via the generated URL builder instead. */
+export async function exportAndDownloadSkill(skillName: string): Promise<void> {
+ const url = getLlmSkillsNameExportRetrieveUrl(String(ApiConfig.getCurrentTeamId()), skillName, {})
+ const response = await api.getResponse(url)
+ if (!response.ok) {
+ let detail = 'Failed to export skill'
+ try {
+ detail = (await response.json())?.detail || detail
+ } catch {
+ // non-JSON error body; keep the default message
+ }
+ throw new Error(detail)
+ }
+ downloadBlob(await response.blob(), `${skillName}.zip`)
+}
+
export const SKILLS_PER_PAGE = 30
// Hard upper bound for "group by prefix" mode — grouping is a client-side aggregation,
// so we fetch the full list once instead of paging.
@@ -153,6 +195,16 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
loadSkills: (debounce: boolean = true) => ({ debounce }),
deleteSkill: (skillName: string) => ({ skillName }),
duplicateSkill: (skillName: string, newName: string) => ({ skillName, newName }),
+ importSkill: (file: File) => ({ file }),
+ setImporting: (importing: boolean) => ({ importing }),
+ downloadSkillZip: (skillName: string) => ({ skillName }),
+ setConnectModalOpen: (open: boolean) => ({ open }),
+ loadMarketplaceState: true,
+ // rotate=false mints when absent / returns the masked existing key; rotate=true rolls it.
+ issueMarketplaceCommand: (rotate: boolean = false) => ({ rotate }),
+ setMarketplaceState: (state: LLMSkillMarketplaceCommandApi | null) => ({ state }),
+ setMarketplaceLoading: (loading: boolean) => ({ loading }),
+ setIssuingCredential: (issuing: boolean) => ({ issuing }),
}),
reducers({
@@ -167,6 +219,39 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
}),
},
],
+ importing: [
+ false,
+ {
+ setImporting: (_, { importing }) => importing,
+ },
+ ],
+ connectModalOpen: [
+ false,
+ {
+ setConnectModalOpen: (_, { open }) => open,
+ },
+ ],
+ // The full server response (status, command, command_template, token, mask). The live phs_
+ // token only ever lives here and only on create/rotate; clear it when the modal closes.
+ marketplaceState: [
+ null as LLMSkillMarketplaceCommandApi | null,
+ {
+ setMarketplaceState: (_, { state }) => state,
+ setConnectModalOpen: (state, { open }) => (open ? state : null),
+ },
+ ],
+ marketplaceLoading: [
+ false,
+ {
+ setMarketplaceLoading: (_, { loading }) => loading,
+ },
+ ],
+ issuingCredential: [
+ false,
+ {
+ setIssuingCredential: (_, { issuing }) => issuing,
+ },
+ ],
}),
loaders(({ values }) => ({
@@ -219,6 +304,21 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
count: [(s) => [s.skills], (skills: PaginatedLLMSkillListListApi) => skills.count],
+ marketplaceCommand: [
+ (s) => [s.marketplaceState],
+ (marketplaceState: LLMSkillMarketplaceCommandApi | null): string =>
+ // Live command (token embedded) once issued, else the server placeholder template,
+ // else a locally-built placeholder before the state has loaded.
+ marketplaceState?.command ?? marketplaceState?.command_template ?? buildMarketplaceCommand(null),
+ ],
+
+ codexCommand: [
+ (s) => [s.marketplaceState],
+ (marketplaceState: LLMSkillMarketplaceCommandApi | null): string =>
+ // Same per-user credential; the Codex two-line command. Only shown once state loads.
+ marketplaceState?.codex_command ?? marketplaceState?.codex_command_template ?? '',
+ ],
+
sorting: [
(s) => [s.filters],
(filters: SkillFilters): Sorting | null => {
@@ -278,7 +378,7 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
],
}),
- listeners(({ asyncActions, values, selectors }) => ({
+ listeners(({ actions, asyncActions, values, selectors }) => ({
setFilters: async ({ debounce }, _, __, previousState) => {
const oldFilters = selectors.filters(previousState)
const { filters } = values
@@ -311,6 +411,72 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
lemonToast.error('Failed to duplicate skill')
}
},
+
+ importSkill: async ({ file }) => {
+ actions.setImporting(true)
+ try {
+ // Orval types the FileField as string; the generated client appends the File to FormData.
+ const skill = await llmSkillsImportCreate(String(ApiConfig.getCurrentTeamId()), {
+ file: file as unknown as string,
+ })
+ lemonToast.success(`Imported "${skill.name}".`)
+ actions.loadSkills(false)
+ router.actions.push(urls.skill(skill.name))
+ } catch (e) {
+ console.error('Failed to import skill', e)
+ lemonToast.error(errorDetail(e) || 'Failed to import skill — is it a valid skill zip?')
+ } finally {
+ actions.setImporting(false)
+ }
+ },
+
+ downloadSkillZip: async ({ skillName }) => {
+ try {
+ await exportAndDownloadSkill(skillName)
+ } catch (e) {
+ console.error('Failed to export skill', e)
+ lemonToast.error(errorDetail(e) || (e instanceof Error ? e.message : 'Failed to export skill'))
+ }
+ },
+
+ setConnectModalOpen: ({ open }) => {
+ // Reload the (token-less) connection state each time the modal opens so we never
+ // re-surface a previously minted token and always reflect the current credential.
+ if (open) {
+ actions.loadMarketplaceState()
+ }
+ },
+
+ loadMarketplaceState: async () => {
+ actions.setMarketplaceLoading(true)
+ try {
+ const state = await llmSkillsMarketplaceInstallCommandRetrieve(String(ApiConfig.getCurrentTeamId()))
+ actions.setMarketplaceState(state)
+ } catch (e) {
+ console.error('Failed to load marketplace connection state', e)
+ lemonToast.error(errorDetail(e) || 'Failed to check your skill store connection.')
+ } finally {
+ actions.setMarketplaceLoading(false)
+ }
+ },
+
+ issueMarketplaceCommand: async ({ rotate }) => {
+ actions.setIssuingCredential(true)
+ try {
+ // Per-user read-only credential: mints if absent, rolls (rotate=true) only this user's own key.
+ const state = await llmSkillsMarketplaceInstallCommandCreate(String(ApiConfig.getCurrentTeamId()), {
+ rotate,
+ })
+ actions.setMarketplaceState(state)
+ } catch (e) {
+ console.error('Failed to issue marketplace credential', e)
+ lemonToast.error(
+ errorDetail(e) || 'Failed to issue credential. Do you have permission to manage API keys?'
+ )
+ } finally {
+ actions.setIssuingCredential(false)
+ }
+ },
})),
trackedActionToUrl(({ values }) => {
diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yaml
index 279b21ad8562..0dcc95411496 100644
--- a/products/skills/mcp/tools.yaml
+++ b/products/skills/mcp/tools.yaml
@@ -9,6 +9,15 @@ feature: skills
url_prefix: /skills
ui_apps: {}
tools:
+ llm-skills-import-create:
+ operation: llm_skills_import_create
+ enabled: false
+ llm-skills-marketplace-install-command-retrieve:
+ operation: llm_skills_marketplace_install_command_retrieve
+ enabled: false
+ llm-skills-name-export-retrieve:
+ operation: llm_skills_name_export_retrieve
+ enabled: false
skill-archive:
operation: llm_skills_name_archive_create
enabled: true
@@ -153,6 +162,34 @@ tools:
skill-resolve:
operation: llm_skills_resolve_name_retrieve
enabled: false
+ skill-store-install-command:
+ operation: llm_skills_marketplace_install_command_create
+ enabled: true
+ scopes:
+ - llm_skill:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Get skill store install command
+ description: >
+ Get ready-to-paste commands that install this team's skill store into a coding agent as an auto-updating
+ plugin marketplace. Returns both a Claude Code command (the `command` field) and an OpenAI Codex command
+ (the `codex_command` field) for the same marketplace. On first use it mints a dedicated, read-only
+ credential (scoped to skills only, scope llm_skill:read) for the calling user and returns the full commands
+ with the token embedded. If the user is already connected it returns the existing connection masked, with no
+ token — pass rotate=true to issue a fresh token. The credential is per-user, so rotating only ever replaces
+ the caller's own token and never breaks a teammate's setup. Only call this when the user asks to connect or
+ install their skills into a coding agent. Give the user the command matching their agent (Claude Code or
+ Codex).
+ include_params:
+ - rotate
+ param_overrides:
+ rotate:
+ description: >
+ Set true only when the user explicitly wants a fresh token (e.g. setting up a new machine): it rolls
+ the caller's existing credential, invalidating their previous token. Leave false (default) to reuse
+ the existing credential — the first call always mints one regardless.
skill-update:
operation: llm_skills_name_partial_update
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a5f3a0b92d34..73a1581d7352 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6255,6 +6255,20 @@
"readOnlyHint": true
}
},
+ "skill-store-install-command": {
+ "description": "Get ready-to-paste commands that install this team's skill store into a coding agent as an auto-updating plugin marketplace. Returns both a Claude Code command (the `command` field) and an OpenAI Codex command (the `codex_command` field) for the same marketplace. On first use it mints a dedicated, read-only credential (scoped to skills only, scope llm_skill:read) for the calling user and returns the full commands with the token embedded. If the user is already connected it returns the existing connection masked, with no token — pass rotate=true to issue a fresh token. The credential is per-user, so rotating only ever replaces the caller's own token and never breaks a teammate's setup. Only call this when the user asks to connect or install their skills into a coding agent. Give the user the command matching their agent (Claude Code or Codex).",
+ "category": "Skills",
+ "feature": "skills",
+ "summary": "Get skill store install command",
+ "title": "Get skill store install command",
+ "required_scopes": ["llm_skill:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"skill-update": {
"description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.",
"category": "Skills",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4cc0e1b956d0..c533c0eee374 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6750,6 +6750,20 @@
"readOnlyHint": true
}
},
+ "skill-store-install-command": {
+ "description": "Get ready-to-paste commands that install this team's skill store into a coding agent as an auto-updating plugin marketplace. Returns both a Claude Code command (the `command` field) and an OpenAI Codex command (the `codex_command` field) for the same marketplace. On first use it mints a dedicated, read-only credential (scoped to skills only, scope llm_skill:read) for the calling user and returns the full commands with the token embedded. If the user is already connected it returns the existing connection masked, with no token — pass rotate=true to issue a fresh token. The credential is per-user, so rotating only ever replaces the caller's own token and never breaks a teammate's setup. Only call this when the user asks to connect or install their skills into a coding agent. Give the user the command matching their agent (Claude Code or Codex).",
+ "category": "Skills",
+ "feature": "skills",
+ "summary": "Get skill store install command",
+ "title": "Get skill store install command",
+ "required_scopes": ["llm_skill:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"skill-update": {
"description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.",
"category": "Skills",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3173ce4b302c..4e1179ea3b3a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25848,7 +25848,7 @@ export namespace Schemas {
* @maxLength 500
*/
compatibility?: string;
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[];
/** Arbitrary key-value metadata. */
metadata?: LLMSkillMetadata;
@@ -25914,7 +25914,7 @@ export namespace Schemas {
* @maxLength 500
*/
compatibility?: string;
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[];
/** Arbitrary key-value metadata. */
metadata?: LLMSkillCreateMetadata;
@@ -26004,6 +26004,11 @@ export namespace Schemas {
base_version?: number;
}
+ export interface LLMSkillImport {
+ /** A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts/, references/, assets/). */
+ file: string;
+ }
+
/**
* Arbitrary key-value metadata.
*/
@@ -26034,7 +26039,7 @@ export namespace Schemas {
* @maxLength 500
*/
compatibility?: string;
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[];
/** Arbitrary key-value metadata. */
metadata?: LLMSkillListMetadata;
@@ -26051,6 +26056,81 @@ export namespace Schemas {
readonly first_version_created_at: string;
}
+ /**
+ * * `absent` - absent
+ * * `exists` - exists
+ * * `created` - created
+ * * `rotated` - rotated
+ */
+ export type LLMSkillMarketplaceCommandStatusEnum = typeof LLMSkillMarketplaceCommandStatusEnum[keyof typeof LLMSkillMarketplaceCommandStatusEnum];
+
+
+ export const LLMSkillMarketplaceCommandStatusEnum = {
+ Absent: 'absent',
+ Exists: 'exists',
+ Created: 'created',
+ Rotated: 'rotated',
+ } as const;
+
+ export interface LLMSkillMarketplaceCommand {
+ /** absent: no credential yet. exists: one already exists (no token returned). created: a new credential was just minted. rotated: the existing credential was rolled.
+ *
+ * * `absent` - absent
+ * * `exists` - exists
+ * * `created` - created
+ * * `rotated` - rotated */
+ status: LLMSkillMarketplaceCommandStatusEnum;
+ /** Whether this user already has a marketplace credential for the team's skill store. */
+ connected: boolean;
+ /** The plugin name the command installs (Claude Code and Codex). */
+ plugin_name: string;
+ /** The marketplace name, used by the Codex install command. */
+ marketplace_name: string;
+ /** Label of this user's marketplace credential (a scoped Personal API Key). */
+ label: string;
+ /** The marketplace git repository URL, with no credential embedded. */
+ repo_url: string;
+ /**
+ * Claude Code: ready-to-paste `/plugin marketplace add` command with the live token embedded. Returned only when a token was just issued (status created/rotated); null otherwise.
+ * @nullable
+ */
+ command: string | null;
+ /** Claude Code install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present. */
+ command_template: string;
+ /**
+ * OpenAI Codex: two-line `codex plugin marketplace add` + `codex plugin add` command with the live token embedded. Returned only when a token was just issued (status created/rotated); null otherwise.
+ * @nullable
+ */
+ codex_command: string | null;
+ /** Codex install command with a YOUR_PHS_TOKEN placeholder instead of a live token; always present. */
+ codex_command_template: string;
+ /**
+ * The raw read-only `phx_` credential. Returned once, only when minted or rotated; it cannot be retrieved again afterwards.
+ * @nullable
+ */
+ token: string | null;
+ /**
+ * Masked preview of the existing credential (e.g. phx_...abcd).
+ * @nullable
+ */
+ mask_value: string | null;
+ /**
+ * When the credential was created.
+ * @nullable
+ */
+ created_at: string | null;
+ /**
+ * When the credential was last rotated.
+ * @nullable
+ */
+ last_rolled_at: string | null;
+ }
+
+ export interface LLMSkillMarketplaceIssue {
+ /** Roll the existing marketplace credential to issue a fresh token, replacing the old one (this invalidates any setup using the previous token). Ignored when no credential exists yet — the first call always mints one. Only affects this user's own credential. */
+ rotate?: boolean;
+ }
+
export interface LLMSkillVersionSummary {
readonly id: string;
readonly version: number;
@@ -35660,7 +35740,7 @@ export namespace Schemas {
* @maxLength 500
*/
compatibility?: string;
- /** List of pre-approved tools the skill may use. */
+ /** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[];
/** Arbitrary key-value metadata. */
metadata?: PatchedLLMSkillPublishMetadata;
@@ -52782,6 +52862,14 @@ export namespace Schemas {
version?: number;
};
+ export type EnvironmentsLlmSkillsNameExportRetrieveParams = {
+ /**
+ * Specific skill version to fetch. If omitted, the latest version is returned.
+ * @minimum 1
+ */
+ version?: number;
+ };
+
export type EnvironmentsLlmSkillsNameFilesRetrieveParams = {
/**
* Specific skill version to fetch. If omitted, the latest version is returned.
@@ -58999,6 +59087,14 @@ export namespace Schemas {
version?: number;
};
+ export type LlmSkillsNameExportRetrieveParams = {
+ /**
+ * Specific skill version to fetch. If omitted, the latest version is returned.
+ * @minimum 1
+ */
+ version?: number;
+ };
+
export type LlmSkillsNameFilesRetrieveParams = {
/**
* Specific skill version to fetch. If omitted, the latest version is returned.
diff --git a/services/mcp/src/generated/skills/api.ts b/services/mcp/src/generated/skills/api.ts
index 5cadeffb5a5f..8e4594a3b447 100644
--- a/services/mcp/src/generated/skills/api.ts
+++ b/services/mcp/src/generated/skills/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 10 enabled ops
+ * PostHog API - MCP 11 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -65,7 +65,10 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod
.max(llmSkillsCreateBodyCompatibilityMax)
.optional()
.describe('Environment requirements (intended product, system packages, network access, etc.).'),
- allowed_tools: zod.array(zod.string()).optional().describe('List of pre-approved tools the skill may use.'),
+ allowed_tools: zod
+ .array(zod.string())
+ .optional()
+ .describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),
metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),
files: zod
.array(
@@ -89,6 +92,30 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod
})
.describe('Create serializer — accepts bundled files as write-only input on POST.')
+/**
+ * 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.
+ */
+export const LlmSkillsMarketplaceInstallCommandCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const llmSkillsMarketplaceInstallCommandCreateBodyRotateDefault = false
+
+export const LlmSkillsMarketplaceInstallCommandCreateBody = /* @__PURE__ */ zod.object({
+ rotate: zod
+ .boolean()
+ .default(llmSkillsMarketplaceInstallCommandCreateBodyRotateDefault)
+ .describe(
+ "Roll the existing marketplace credential to issue a fresh token, replacing the old one (this invalidates any setup using the previous token). Ignored when no credential exists yet — the first call always mints one. Only affects this user's own credential."
+ ),
+})
+
export const llmSkillsNameRetrievePathSkillNameRegExp = new RegExp('^[^/]+$')
export const LlmSkillsNameRetrieveParams = /* @__PURE__ */ zod.object({
@@ -165,7 +192,10 @@ export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({
.max(llmSkillsNamePartialUpdateBodyCompatibilityMax)
.optional()
.describe('Environment requirements.'),
- allowed_tools: zod.array(zod.string()).optional().describe('List of pre-approved tools the skill may use.'),
+ allowed_tools: zod
+ .array(zod.string())
+ .optional()
+ .describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),
metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),
files: zod
.array(
diff --git a/services/mcp/src/tools/generated/skills.ts b/services/mcp/src/tools/generated/skills.ts
index d6fa91aebafd..158be182ba88 100644
--- a/services/mcp/src/tools/generated/skills.ts
+++ b/services/mcp/src/tools/generated/skills.ts
@@ -5,6 +5,7 @@ import type { Schemas } from '@/api/generated'
import {
LlmSkillsCreateBody,
LlmSkillsListQueryParams,
+ LlmSkillsMarketplaceInstallCommandCreateBody,
LlmSkillsNameArchiveCreateParams,
LlmSkillsNameDuplicateCreateBody,
LlmSkillsNameDuplicateCreateParams,
@@ -245,6 +246,33 @@ const skillList = (): ToolBase<typeof SkillListSchema, Schemas.PaginatedLLMSkill
},
})
+const SkillStoreInstallCommandSchema = LlmSkillsMarketplaceInstallCommandCreateBody.extend({
+ rotate: LlmSkillsMarketplaceInstallCommandCreateBody.shape['rotate'].describe(
+ "Set true only when the user explicitly wants a fresh token (e.g. setting up a new machine): it rolls the caller's existing credential, invalidating their previous token. Leave false (default) to reuse the existing credential — the first call always mints one regardless."
+ ),
+})
+
+const skillStoreInstallCommand = (): ToolBase<
+ typeof SkillStoreInstallCommandSchema,
+ Schemas.LLMSkillMarketplaceCommand
+> => ({
+ name: 'skill-store-install-command',
+ schema: SkillStoreInstallCommandSchema,
+ handler: async (context: Context, params: z.infer<typeof SkillStoreInstallCommandSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.rotate !== undefined) {
+ body['rotate'] = params.rotate
+ }
+ const result = await context.api.request<Schemas.LLMSkillMarketplaceCommand>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/marketplace/install-command/`,
+ body,
+ })
+ return result
+ },
+})
+
const SkillUpdateSchema = LlmSkillsNamePartialUpdateParams.omit({ project_id: true }).extend(
LlmSkillsNamePartialUpdateBody.shape
)
@@ -304,5 +332,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'skill-file-rename': skillFileRename,
'skill-get': skillGet,
'skill-list': skillList,
+ 'skill-store-install-command': skillStoreInstallCommand,
'skill-update': skillUpdate,
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json
index e9f8a5893c7a..3efc490b4c23 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json
@@ -3,7 +3,7 @@
"description": "Create serializer — accepts bundled files as write-only input on POST.",
"properties": {
"allowed_tools": {
- "description": "List of pre-approved tools the skill may use.",
+ "description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
"items": {
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json
index ccab96beb18b..170874d0e23f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"allowed_tools": {
- "description": "List of pre-approved tools the skill may use.",
+ "description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
"items": {
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json
index e9f8a5893c7a..3efc490b4c23 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json
@@ -3,7 +3,7 @@
"description": "Create serializer — accepts bundled files as write-only input on POST.",
"properties": {
"allowed_tools": {
- "description": "List of pre-approved tools the skill may use.",
+ "description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
"items": {
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-store-install-command.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-store-install-command.json
new file mode 100644
index 000000000000..e509619e77ad
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-store-install-command.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "rotate": {
+ "default": false,
+ "description": "Set true only when the user explicitly wants a fresh token (e.g. setting up a new machine): it rolls the caller's existing credential, invalidating their previous token. Leave false (default) to reuse the existing credential — the first call always mints one regardless.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json
index ccab96beb18b..170874d0e23f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"allowed_tools": {
- "description": "List of pre-approved tools the skill may use.",
+ "description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",
"items": {
"type": "string"
},