:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): templated community skills server (6/7) (#65015)
Andrew Maguire43e81b165780
diff --git a/products/skills/backend/api/community_skill_serializers.py b/products/skills/backend/api/community_skill_serializers.pyindex 47f432adee71..ab19067c7547 100644--- a/products/skills/backend/api/community_skill_serializers.py+++ b/products/skills/backend/api/community_skill_serializers.py@@ -4,6 +4,7 @@ from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillTrustTier+from .skill_template_services import parse_template_variablesALLOWED_LIST_ORDERINGS = frozenset({@@ -21,6 +22,23 @@ ALLOWED_LIST_ORDERINGS = frozenset()+class CommunitySkillTemplateVariableSerializer(serializers.Serializer):+ """One declared variable of a templated skill — the schema a client renders a form from."""++ name = serializers.CharField(help_text="Variable identifier, substituted for `{{ name }}` in the skill body.")+ prompt = serializers.CharField(+ allow_blank=True,+ help_text="Human-readable question shown when collecting a value for this variable.",+ )+ is_required = serializers.BooleanField(+ help_text="Whether a value must be supplied at install time (otherwise it falls back to the default).",+ )+ default = serializers.CharField(+ allow_blank=True,+ help_text="Value used when none is supplied. Empty when the variable has no default.",+ )++class CommunitySkillFileSerializer(serializers.ModelSerializer):class Meta:model = CommunitySkillFile@@ -58,6 +76,12 @@ class CommunitySkillSerializer(serializers.ModelSerializer):files = serializers.SerializerMethodField(help_text="Bundled files manifest — path and content_type only. File contents are copied in on install.",)+ template_variables = serializers.SerializerMethodField(+ help_text=(+ "Declared template variables, parsed from metadata. Non-empty marks this skill as a template: "+ "collect a value for each and pass them as `variables` when installing."+ ),+ )vote_count = serializers.SerializerMethodField(help_text="Total number of upvotes this skill has received.",)@@ -82,6 +106,7 @@ class CommunitySkillSerializer(serializers.ModelSerializer):"author_handle","github_url","files",+ "template_variables","install_count","vote_count","has_voted",@@ -109,6 +134,13 @@ class CommunitySkillSerializer(serializers.ModelSerializer):# second query and defeat the viewset's manifest-only prefetch.return [{"path": f.path, "content_type": f.content_type} for f in instance.files.all()]+ @extend_schema_field(CommunitySkillTemplateVariableSerializer(many=True))+ def get_template_variables(self, instance: CommunitySkill) -> list[dict[str, Any]]:+ return [+ {"name": v.name, "prompt": v.prompt, "is_required": v.required, "default": v.default}+ for v in parse_template_variables(instance.metadata)+ ]+def get_vote_count(self, instance: CommunitySkill) -> int:# Provided by the viewset's annotated queryset; fall back to a count for unannotated instances.annotated = getattr(instance, "vote_count", None)@@ -157,6 +189,16 @@ class CommunitySkillInstallSerializer(serializers.Serializer):allow_blank=True,help_text="Name for the installed skill in your team. Defaults to the community skill's slug.",)+ variables = serializers.DictField(+ # trim_whitespace=False so a value's exact text (multiline snippets, leading/trailing+ # whitespace meant for the rendered output) survives into the installed skill.+ child=serializers.CharField(allow_blank=True, trim_whitespace=False),+ required=False,+ help_text=(+ "Values for a template skill's declared variables, as a {name: value} map. Required only when "+ "installing a template (see the skill's `template_variables`); ignored for non-template skills."+ ),+ )class CommunitySkillVoteResponseSerializer(serializers.Serializer):diff --git a/products/skills/backend/api/community_skill_services.py b/products/skills/backend/api/community_skill_services.pyindex a508f3cae6c7..ce04e3ce270e 100644--- a/products/skills/backend/api/community_skill_services.py+++ b/products/skills/backend/api/community_skill_services.py@@ -1,3 +1,5 @@+from typing import Any+from django.db import IntegrityError, transactionfrom django.db.models import F@@ -9,6 +11,7 @@ from ..models.community_skills import CommunitySkill, CommunitySkillVotefrom ..models.skills import LLMSkillfrom .skill_serializers import validate_allowed_tool, validate_skill_file_path, validate_skill_name_valuefrom .skill_services import MAX_SKILL_FILE_BYTES, create_skill+from .skill_template_services import parse_template_variables, render_template_skill# Namespaces where PostHog auto-registers and runs a skill under privileged scopes on an enrolled# team: Signals scouts on the scout coordinator, ReviewHog's review skills on a team's first PR@@ -82,12 +85,17 @@ def install_community_skill(user: User,slug: str,new_name: str | None = None,+ variables: dict[str, str] | None = None,) -> LLMSkill:"""Copy a community skill into a team as a regular LLMSkill and bump its install counter.+ When the community skill is a template (its metadata declares `variables`), the user-supplied+ `variables` are bound into the body and bundled files before the LLMSkill is created.+Raises CommunitySkillNotFoundError if the slug is unknown, LLMSkillDuplicateNameConflictError- if the target name already exists in the team, and CommunitySkillInvalidPayloadError if the- catalog entry can't be safely installed.+ if the target name already exists in the team, CommunitySkillInvalidPayloadError if the catalog+ entry can't be safely installed, and MissingTemplateVariableError /+ UnknownTemplatePlaceholderError on template render failures."""community_skill = get_community_skill_by_slug(slug)if community_skill is None:@@ -126,23 +134,42 @@ def install_community_skill(if not (locked.description or "").strip():raise CommunitySkillInvalidPayloadError("This community skill has no description and can't be installed.")files = _validate_installable_files(locked)+ body = locked.body++ # Stamp provenance so an installed skill can be traced back to its community source, but+ # first drop any internal ReviewHog ownership keys the catalog entry might carry.+ metadata: dict[str, Any] = {+ **{k: v for k, v in (locked.metadata or {}).items() if k not in _INTERNAL_METADATA_KEYS},+ "community_skill_slug": locked.slug,+ "community_skill_id": str(locked.id),+ }++ template_variables = parse_template_variables(locked.metadata)+ if template_variables:+ rendered = render_template_skill(+ variables=template_variables,+ body=locked.body,+ files=files,+ supplied=variables,+ )+ body = rendered.body+ files = rendered.files+ # The instantiated skill is a concrete skill, not a template — drop the variable schema and+ # record what it was rendered from so a re-render stays deterministic.+ metadata.pop("variables", None)+ metadata["instantiated_from"] = f"{locked.slug}@{locked.source_sha}"+ metadata["variable_bindings"] = rendered.bindingsinstalled = create_skill(team,user=user,name=target_name,description=locked.description,- body=locked.body,+ body=body,license=locked.license,compatibility=locked.compatibility,allowed_tools=locked.allowed_tools,- # Stamp provenance so an installed skill can be traced back to its community source, but- # first drop any internal ReviewHog ownership keys the catalog entry might carry.- metadata={- **{k: v for k, v in (locked.metadata or {}).items() if k not in _INTERNAL_METADATA_KEYS},- "community_skill_slug": locked.slug,- "community_skill_id": str(locked.id),- },+ metadata=metadata,files=files or None,)diff --git a/products/skills/backend/api/community_skills.py b/products/skills/backend/api/community_skills.pyindex 61b74a9092cb..c6e905012741 100644--- a/products/skills/backend/api/community_skills.py+++ b/products/skills/backend/api/community_skills.py@@ -7,7 +7,7 @@ import posthoganalyticsfrom drf_spectacular.utils import extend_schemafrom rest_framework import mixins, status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import PermissionDenied+from rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -34,6 +34,13 @@ from .community_skill_services import ()from .skill_serializers import LLMSkillSerializerfrom .skill_services import LLMSkillDuplicateNameConflictError, LLMSkillFileLimitError, LLMSkillFilePathConflictError+from .skill_template_services import (+ MissingTemplateVariableError,+ TemplateRenderTooLargeError,+ TemplateVariableTooLargeError,+ UnknownSuppliedVariableError,+ UnknownTemplatePlaceholderError,+)logger = structlog.get_logger(__name__)@@ -186,12 +193,36 @@ class CommunitySkillViewSet(user=cast(User, request.user),slug=slug,new_name=payload.validated_data.get("new_name"),+ variables=payload.validated_data.get("variables"),)except CommunitySkillNotFoundError:return Response({"detail": f"Community skill '{slug}' not found."},status=status.HTTP_404_NOT_FOUND,)+ except (+ MissingTemplateVariableError,+ TemplateRenderTooLargeError,+ TemplateVariableTooLargeError,+ UnknownSuppliedVariableError,+ ) as err:+ # All four are fixable by the caller (supply the value / shorter values / fix the key),+ # so they're 400s against the field that carried them.+ raise ValidationError({"variables": str(err)}) from err+ except UnknownTemplatePlaceholderError as err:+ # The template body references a variable it never declared — a content-repo bug the+ # caller can't fix, so surface it as a server-side fault, not a bad request. Returning a+ # hand-built 500 skips DRF's exception handler, so log it here or a broken catalog entry+ # fails every install with no server-side signal.+ logger.exception(+ "Community skill template references an undeclared placeholder",+ slug=slug,+ placeholder=err.placeholder,+ )+ return Response(+ {"detail": str(err)},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )except LLMSkillDuplicateNameConflictError:# Only blame the new_name field when the caller actually supplied it — otherwise the# conflicting name is the skill's own slug, so a generic message is accurate.@@ -222,6 +253,7 @@ class CommunitySkillViewSet({"community_skill_slug": slug,"installed_skill_name": installed.name,+ "installed_as_template": "instantiated_from" in (installed.metadata or {}),},team=self.team,request=request,diff --git a/products/skills/backend/api/skill_template_services.py b/products/skills/backend/api/skill_template_services.pynew file mode 100644index 000000000000..42a0a8203bad--- /dev/null+++ b/products/skills/backend/api/skill_template_services.py@@ -0,0 +1,242 @@+"""Server-side rendering for templated skills.++A skill is a *template* when its `metadata.variables` declares one or more variables. The body and+bundled files carry `{{ variable }}` placeholders that get bound to user-supplied values when the+skill is instantiated (installed) into a team. Rendering is deliberately plain string substitution —+never a template engine — so a community-published template can't execute logic against tenant data.+"""++import re+from collections.abc import Iterator+from dataclasses import dataclass+from typing import Any++from .skill_services import MAX_SKILL_BODY_BYTES, MAX_SKILL_FILE_BYTES++# `{{ name }}` with optional surrounding whitespace. Names are Python-identifier-like.+_PLACEHOLDER_RE = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")++# A single supplied value, and all resolved bindings together. Bindings are persisted verbatim on+# the installed skill's metadata, so these bound that row independently of what the values render+# into — an unused variable never reaches the render-size checks below.+MAX_TEMPLATE_VARIABLE_BYTES = 10_000+MAX_TEMPLATE_BINDINGS_BYTES = 100_000++# Every rendered file and the body together. The per-file limit alone bounds nothing in aggregate:+# a template of 200 small files that each repeat a placeholder renders to 200 MB while every+# individual file stays under its own 1 MB cap.+MAX_RENDERED_SKILL_BYTES = 5_000_000+++def _iter_placeholder_tokens(text: str) -> Iterator[str]:+ r"""Yield every `{{ ... }}` token, shortest-match, in one forward pass.++ Deliberately not a regex: `\{\{.*?\}\}` rescans the rest of the input for every unmatched `{{`,+ so a template carrying kilobytes of unclosed delimiters costs quadratic time and ties up an+ installer's worker. Both indices here only move forward, so a hostile template costs one pass.+ An unclosed trailing `{{` yields nothing and stays literal, matching the regex it replaces.+ """+ pos = 0+ while True:+ start = text.find("{{", pos)+ if start == -1:+ return+ end = text.find("}}", start + 2)+ if end == -1:+ return+ yield text[start : end + 2]+ pos = end + 2+++@dataclass(frozen=True)+class TemplateVariable:+ name: str+ prompt: str+ required: bool+ default: str+++class TemplateRenderError(Exception):+ """Base class for failures while rendering a templated skill."""+++class MissingTemplateVariableError(TemplateRenderError):+ """A required variable had no supplied value and no default."""++ def __init__(self, variable: TemplateVariable) -> None:+ self.variable = variable+ super().__init__(f"Missing required template variable '{variable.name}': {variable.prompt}")+++class UnknownTemplatePlaceholderError(TemplateRenderError):+ """The body or a file referenced a `{{ placeholder }}` with no declared variable."""++ def __init__(self, placeholder: str) -> None:+ self.placeholder = placeholder+ super().__init__(f"Template references undeclared variable '{placeholder}'.")+++class TemplateRenderTooLargeError(TemplateRenderError):+ """Rendering expanded the body or a file past the skill size limit."""++ def __init__(self, what: str, limit: int) -> None:+ super().__init__(f"Rendered {what} exceeds the {limit} byte size limit.")+++class TemplateVariableTooLargeError(TemplateRenderError):+ """A supplied value, or all of them together, exceeded the template variable size limit."""++ def __init__(self, what: str, limit: int) -> None:+ super().__init__(f"Template variable {what} exceeds the {limit} byte size limit.")+++class UnknownSuppliedVariableError(TemplateRenderError):+ """The caller supplied values for variables the template doesn't declare (likely a typo)."""++ def __init__(self, names: list[str]) -> None:+ self.names = names+ super().__init__(f"Unknown template variable(s) supplied: {', '.join(names)}.")+++def parse_template_variables(metadata: dict[str, Any] | None) -> list[TemplateVariable]:+ """Read the `variables` schema out of a skill's frontmatter metadata.++ Tolerant of malformed entries from synced/external content: a non-dict metadata or anything+ without a usable string `name` is skipped rather than raising, so a bad row never breaks+ discovery or install.+ """+ if not isinstance(metadata, dict):+ return []+ raw = metadata.get("variables")+ if not isinstance(raw, list):+ return []++ variables: list[TemplateVariable] = []+ seen: set[str] = set()+ for item in raw:+ if not isinstance(item, dict):+ continue+ name = item.get("name")+ if not isinstance(name, str) or not name or name in seen:+ continue+ seen.add(name)+ default = item.get("default", "")+ variables.append(+ TemplateVariable(+ name=name,+ prompt=str(item.get("prompt", "")),+ # Default to required unless a default is supplied or `required` is explicitly false.+ required=bool(item.get("required", "default" not in item)),+ default=str(default) if default is not None else "",+ )+ )+ return variables+++def is_template(metadata: dict[str, Any] | None) -> bool:+ return len(parse_template_variables(metadata)) > 0+++def resolve_bindings(variables: list[TemplateVariable], supplied: dict[str, str] | None) -> dict[str, str]:+ """Build the final {name: value} map, applying defaults and enforcing required variables.++ An explicitly supplied value (including "") is used verbatim — only an absent key falls back to+ the default. Supplying a value for an undeclared variable is an error (likely a typo), and a+ value (or a whole binding set) past the size caps is rejected before anything is persisted.+ """+ supplied = supplied or {}+ unknown = sorted(set(supplied) - {v.name for v in variables})+ if unknown:+ raise UnknownSuppliedVariableError(unknown)++ bindings: dict[str, str] = {}+ for variable in variables:+ if variable.name in supplied:+ value = supplied[variable.name]+ if value == "" and variable.required:+ raise MissingTemplateVariableError(variable)+ elif variable.default:+ value = variable.default+ elif variable.required:+ raise MissingTemplateVariableError(variable)+ else:+ value = ""+ bindings[variable.name] = value++ total = 0+ for name, value in bindings.items():+ size = len(value.encode("utf-8"))+ if size > MAX_TEMPLATE_VARIABLE_BYTES:+ raise TemplateVariableTooLargeError(f"'{name}'", MAX_TEMPLATE_VARIABLE_BYTES)+ total += size+ if total > MAX_TEMPLATE_BINDINGS_BYTES:+ raise TemplateVariableTooLargeError("values in total", MAX_TEMPLATE_BINDINGS_BYTES)+ return bindings+++def _validate_and_project(text: str, bindings: dict[str, str], binding_sizes: dict[str, int]) -> int:+ """Check every placeholder is declared and return the exact rendered byte size, allocating nothing.++ Validation runs against the source `text` only — a supplied value may legitimately contain+ literal `{{ }}` and must not be re-interpreted as a placeholder. Sizing the output without+ building it is what lets the caller reject an amplifying template before it allocates: every+ token here is a strict placeholder, so summing the substitution deltas is exact.+ """+ projected = len(text.encode("utf-8"))+ for token in _iter_placeholder_tokens(text):+ strict = _PLACEHOLDER_RE.fullmatch(token)+ if strict is None:+ # A `{{ ... }}` whose name the strict pattern can't match (e.g. a hyphen) — fail loudly+ # rather than install a skill with a dangling placeholder.+ raise UnknownTemplatePlaceholderError(token.strip())+ name = strict.group(1)+ if name not in bindings:+ raise UnknownTemplatePlaceholderError(name)+ projected += binding_sizes[name] - len(token.encode("utf-8"))+ return projected+++def _substitute(text: str, bindings: dict[str, str]) -> str:+ return _PLACEHOLDER_RE.sub(lambda m: bindings[m.group(1)], text)+++@dataclass(frozen=True)+class RenderedTemplate:+ body: str+ files: list[dict[str, str]]+ bindings: dict[str, str]+++def render_template_skill(+ *,+ variables: list[TemplateVariable],+ body: str,+ files: list[dict[str, str]],+ supplied: dict[str, str] | None,+) -> RenderedTemplate:+ """Resolve user-supplied values against the declared variables and render body + files.++ `variables` is the already-parsed schema (see `parse_template_variables`) so the caller can+ parse once and reuse the result. Raises MissingTemplateVariableError when a required value is+ absent, UnknownTemplatePlaceholderError when a placeholder has no matching declared variable,+ TemplateVariableTooLargeError when a supplied value is oversized, and TemplateRenderTooLargeError+ when a user-supplied value expands output past the size limit.+ """+ bindings = resolve_bindings(variables, supplied)+ binding_sizes = {name: len(value.encode("utf-8")) for name, value in bindings.items()}++ # Size the whole skill before substituting any of it, so an amplifying template is rejected+ # rather than allocated: peak memory here is the aggregate cap, not the sum of the per-file ones.+ total = _validate_and_project(body, bindings, binding_sizes)+ if total > MAX_SKILL_BODY_BYTES:+ raise TemplateRenderTooLargeError("skill body", MAX_SKILL_BODY_BYTES)+ for file in files:+ size = _validate_and_project(file["content"], bindings, binding_sizes)+ if size > MAX_SKILL_FILE_BYTES:+ raise TemplateRenderTooLargeError(f"file '{file['path']}'", MAX_SKILL_FILE_BYTES)+ total += size+ if total > MAX_RENDERED_SKILL_BYTES:+ raise TemplateRenderTooLargeError("skill", MAX_RENDERED_SKILL_BYTES)++ rendered_files = [{**file, "content": _substitute(file["content"], bindings)} for file in files]+ return RenderedTemplate(body=_substitute(body, bindings), files=rendered_files, bindings=bindings)diff --git a/products/skills/backend/api/test/test_community_skills.py b/products/skills/backend/api/test/test_community_skills.pyindex 28f0cfaeafb6..ff3be9acdc02 100644--- a/products/skills/backend/api/test/test_community_skills.py+++ b/products/skills/backend/api/test/test_community_skills.py@@ -1,3 +1,5 @@+import time+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -11,6 +13,19 @@ from posthog.models.user import Userfrom ...models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillVotefrom ...models.skills import LLMSkill+from ..skill_template_services import (+ MAX_RENDERED_SKILL_BYTES,+ MAX_TEMPLATE_BINDINGS_BYTES,+ MAX_TEMPLATE_VARIABLE_BYTES,+ MissingTemplateVariableError,+ TemplateRenderTooLargeError,+ TemplateVariableTooLargeError,+ UnknownSuppliedVariableError,+ UnknownTemplatePlaceholderError,+ is_template,+ parse_template_variables,+ render_template_skill,+)try:from ee.models.rbac.access_control import AccessControl@@ -38,6 +53,23 @@ def _create_community_skill()+def _create_template_skill(*, slug: str = "feed-scout") -> CommunitySkill:+ return CommunitySkill.objects.create(+ slug=slug,+ name="Feed scout",+ description="Watch a feed for problems.",+ body="# Scout\nWatch table {{ feed_table }} on {{ default_branch }}.",+ trust_tier="official",+ source_sha="sha123",+ metadata={+ "variables": [+ {"name": "feed_table", "prompt": "Warehouse table", "required": True},+ {"name": "default_branch", "prompt": "Branch", "default": "main"},+ ]+ },+ )++@patch("products.skills.backend.api.community_skills.posthoganalytics.feature_enabled",return_value=True,@@ -180,6 +212,86 @@ class TestCommunitySkillAPI(APIBaseTest):response = self.client.post(self._url("does-not-exist/install/"), {})self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ def test_retrieve_surfaces_template_variables(self, _mock_flag) -> None:+ _create_template_skill(slug="feed-scout")+ response = self.client.get(self._url("feed-scout/"))+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ variables = response.json()["template_variables"]+ self.assertEqual([v["name"] for v in variables], ["feed_table", "default_branch"])+ self.assertEqual(+ variables[0], {"name": "feed_table", "prompt": "Warehouse table", "is_required": True, "default": ""}+ )+ self.assertFalse(variables[1]["is_required"]) # has a default++ def test_install_template_renders_variables(self, _mock_flag) -> None:+ skill = _create_template_skill(slug="feed-scout")+ CommunitySkillFile.objects.create(+ skill=skill, path="references/notes.md", content="Query {{ feed_table }} carefully."+ )++ response = self.client.post(+ self._url("feed-scout/install/"),+ {"variables": {"feed_table": "slack_abc", "default_branch": "develop"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)++ installed = LLMSkill.objects.get(team=self.team, name="feed-scout")+ self.assertEqual(installed.body, "# Scout\nWatch table slack_abc on develop.")+ self.assertEqual(installed.files.get(path="references/notes.md").content, "Query slack_abc carefully.")+ # The instantiated skill is concrete, not a template.+ self.assertNotIn("variables", installed.metadata)+ self.assertEqual(installed.metadata["instantiated_from"], "feed-scout@sha123")+ self.assertEqual(+ installed.metadata["variable_bindings"], {"feed_table": "slack_abc", "default_branch": "develop"}+ )++ def test_install_template_uses_default_when_omitted(self, _mock_flag) -> None:+ _create_template_skill(slug="feed-scout")+ response = self.client.post(+ self._url("feed-scout/install/"),+ {"variables": {"feed_table": "slack_abc"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)+ installed = LLMSkill.objects.get(team=self.team, name="feed-scout")+ self.assertEqual(installed.body, "# Scout\nWatch table slack_abc on main.")++ def test_install_template_missing_required_returns_400(self, _mock_flag) -> None:+ _create_template_skill(slug="feed-scout")+ response = self.client.post(self._url("feed-scout/install/"), {}, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "variables")+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="feed-scout").exists())++ def test_install_template_oversized_variable_returns_400(self, _mock_flag) -> None:+ _create_template_skill(slug="feed-scout")+ response = self.client.post(+ self._url("feed-scout/install/"),+ {"variables": {"feed_table": "x" * (MAX_TEMPLATE_VARIABLE_BYTES + 1)}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="feed-scout").exists())++ def test_install_template_undeclared_placeholder_is_logged(self, _mock_flag) -> None:+ skill = _create_template_skill(slug="feed-scout")+ skill.body = "Watch {{ feed_table }} and {{ undeclared }}."+ skill.save(update_fields=["body"])++ with patch("products.skills.backend.api.community_skills.logger.exception") as mock_exception:+ response = self.client.post(+ self._url("feed-scout/install/"),+ {"variables": {"feed_table": "slack_abc"}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)+ # The hand-built 500 bypasses DRF's exception handler, so this log line is the only signal+ # that a catalog entry is broken.+ mock_exception.assert_called_once()+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="feed-scout").exists())+def test_vote_toggles_on_and_off(self, _mock_flag) -> None:_create_community_skill(slug="web-analytics-triage")@@ -244,3 +356,167 @@ class TestCommunitySkillFeatureFlagGate(APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/community_skills/")self.assertEqual(response.status_code, expected_status, response.content)+++class TestSkillTemplateRendering(APIBaseTest):+ @parameterized.expand(+ [+ ("no metadata", None, False),+ ("empty", {}, False),+ ("non-list variables", {"variables": "nope"}, False),+ ("empty list", {"variables": []}, False),+ ("declared", {"variables": [{"name": "repo"}]}, True),+ ]+ )+ def test_is_template(self, _name, metadata, expected) -> None:+ self.assertEqual(is_template(metadata), expected)++ def test_parse_skips_malformed_and_dedupes(self) -> None:+ variables = parse_template_variables(+ {+ "variables": [+ {"name": "repo"},+ {"no_name": 1},+ "bad",+ {"name": "repo"},+ {"name": "branch", "default": "main"},+ ]+ }+ )+ self.assertEqual([v.name for v in variables], ["repo", "branch"])+ # Bare declaration defaults to required; a default makes it optional.+ self.assertTrue(variables[0].required)+ self.assertFalse(variables[1].required)++ def test_render_substitutes_and_records_bindings(self) -> None:+ rendered = render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "repo", "required": True}]}),+ body="watch {{ repo }}",+ files=[{"path": "a.md", "content": "ref {{ repo }}", "content_type": "text/plain"}],+ supplied={"repo": "posthog/posthog"},+ )+ self.assertEqual(rendered.body, "watch posthog/posthog")+ self.assertEqual(rendered.files[0]["content"], "ref posthog/posthog")+ self.assertEqual(rendered.bindings, {"repo": "posthog/posthog"})++ def test_render_missing_required_raises(self) -> None:+ with self.assertRaises(MissingTemplateVariableError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "repo", "required": True}]}),+ body="watch {{ repo }}",+ files=[],+ supplied={},+ )++ def test_render_unknown_placeholder_raises(self) -> None:+ with self.assertRaises(UnknownTemplatePlaceholderError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "repo", "required": True}]}),+ body="watch {{ repo }} and {{ undeclared }}",+ files=[],+ supplied={"repo": "x"},+ )++ def test_render_rejects_unrenderable_variable_name(self) -> None:+ # A declared name the placeholder regex can't match (hyphen) must fail, not install dangling.+ with self.assertRaises(UnknownTemplatePlaceholderError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "repo-name", "required": True}]}),+ body="watch {{ repo-name }}",+ files=[],+ supplied={"repo-name": "x"},+ )++ def test_render_explicit_blank_overrides_default(self) -> None:+ rendered = render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "suffix", "default": "!"}]}),+ body="hi{{ suffix }}",+ files=[],+ supplied={"suffix": ""},+ )+ self.assertEqual(rendered.body, "hi")++ def test_render_explicit_blank_required_raises(self) -> None:+ with self.assertRaises(MissingTemplateVariableError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "repo", "required": True}]}),+ body="{{ repo }}",+ files=[],+ supplied={"repo": ""},+ )++ def test_render_unknown_supplied_key_raises(self) -> None:+ with self.assertRaises(UnknownSuppliedVariableError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "feed_table", "required": True}]}),+ body="{{ feed_table }}",+ files=[],+ supplied={"feed_table": "x", "feedtable": "typo"},+ )++ def test_render_allows_braces_inside_supplied_value(self) -> None:+ # Validation is on the source template, so a value containing literal {{ }} is not re-parsed.+ rendered = render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "snippet", "required": True}]}),+ body="config: {{ snippet }}",+ files=[],+ supplied={"snippet": "{{ not_a_var }}"},+ )+ self.assertEqual(rendered.body, "config: {{ not_a_var }}")++ def test_render_oversized_output_raises(self) -> None:+ # A value well inside the per-variable cap still amplifies past the body limit when the+ # template repeats its placeholder, so the size check can't assume a small input.+ with self.assertRaises(TemplateRenderTooLargeError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "v", "required": True}]}),+ body="{{ v }}" * 200,+ files=[],+ supplied={"v": "x" * 9_000},+ )++ @parameterized.expand(+ [+ ("one oversized value", 1, MAX_TEMPLATE_VARIABLE_BYTES + 1),+ (+ "values oversized in total",+ MAX_TEMPLATE_BINDINGS_BYTES // MAX_TEMPLATE_VARIABLE_BYTES + 1,+ MAX_TEMPLATE_VARIABLE_BYTES,+ ),+ ]+ )+ def test_render_rejects_oversized_bindings(self, _name, count, size) -> None:+ names = [f"v{i}" for i in range(count)]+ with self.assertRaises(TemplateVariableTooLargeError):+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": n, "required": True} for n in names]}),+ # Unrendered on purpose: bindings are persisted to the installed skill's metadata+ # whether or not they appear in the body, so render-size checks don't bound them.+ body="no placeholders here",+ files=[],+ supplied=dict.fromkeys(names, "x" * size),+ )++ def test_render_rejects_oversized_total_across_files(self) -> None:+ # Each file renders to ~700 KB, under the 1 MB per-file cap, but 200 of them are 140 MB.+ # A per-file limit bounds nothing in aggregate, so the whole-skill cap has to exist.+ with self.assertRaises(TemplateRenderTooLargeError) as ctx:+ render_template_skill(+ variables=parse_template_variables({"variables": [{"name": "v", "required": True}]}),+ body="small",+ files=[+ {"path": f"references/{i}.md", "content": "{{ v }}" * 100, "content_type": "text/plain"}+ for i in range(200)+ ],+ supplied={"v": "x" * 7_000},+ )+ self.assertIn(str(MAX_RENDERED_SKILL_BYTES), str(ctx.exception))++ def test_render_scans_unmatched_delimiters_in_one_pass(self) -> None:+ # Unclosed `{{` stay literal. A `{{.*?}}` regex rescans the rest of the input for each of+ # them, so this body took tens of seconds to validate before the scan became single-pass.+ body = "{{" * 32_000+ started = time.monotonic()+ rendered = render_template_skill(variables=[], body=body, files=[], supplied=None)+ self.assertEqual(rendered.body, body)+ self.assertLess(time.monotonic() - started, 5)diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex eb19c3f6fc24..3bb9b58f96c5 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -20,6 +20,20 @@ export const TrustTierEnumApi = {Community: 'community',} as const+/**+ * One declared variable of a templated skill — the schema a client renders a form from.+ */+export interface CommunitySkillTemplateVariableApi {+ /** Variable identifier, substituted for `{{ name }}` in the skill body. */+ name: string+ /** Human-readable question shown when collecting a value for this variable. */+ prompt: string+ /** Whether a value must be supplied at install time (otherwise it falls back to the default). */+ is_required: boolean+ /** Value used when none is supplied. Empty when the variable has no default. */+ default: string+}+/*** Arbitrary key-value metadata carried from the skill's frontmatter.*/@@ -56,6 +70,8 @@ export interface CommunitySkillListApi {readonly author_handle: string/** Link to the skill's source directory on GitHub. */readonly github_url: string+ /** Declared template variables, parsed from metadata. Non-empty marks this skill as a template: collect a value for each and pass them as `variables` when installing. */+ readonly template_variables: readonly CommunitySkillTemplateVariableApi[]/** Number of times this skill has been installed into a team. */readonly install_count: number/** Total number of upvotes this skill has received. */@@ -124,6 +140,8 @@ export interface CommunitySkillApi {readonly github_url: string/** Bundled files manifest — path and content_type only. File contents are copied in on install. */readonly files: readonly CommunitySkillFileManifestApi[]+ /** Declared template variables, parsed from metadata. Non-empty marks this skill as a template: collect a value for each and pass them as `variables` when installing. */+ readonly template_variables: readonly CommunitySkillTemplateVariableApi[]/** Number of times this skill has been installed into a team. */readonly install_count: number/** Total number of upvotes this skill has received. */@@ -139,12 +157,19 @@ export interface CommunitySkillApi {readonly updated_at: string}+/**+ * Values for a template skill's declared variables, as a {name: value} map. Required only when installing a template (see the skill's `template_variables`); ignored for non-template skills.+ */+export type CommunitySkillInstallApiVariables = { [key: string]: string }+export interface CommunitySkillInstallApi {/*** Name for the installed skill in your team. Defaults to the community skill's slug.* @maxLength 64*/new_name?: string+ /** Values for a template skill's declared variables, as a {name: value} map. Required only when installing a template (see the skill's `template_variables`); ignored for non-template skills. */+ variables?: CommunitySkillInstallApiVariables}/**diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.tsindex 4e43aff5b237..a9efd19e8de6 100644--- a/products/skills/frontend/generated/api.zod.ts+++ b/products/skills/frontend/generated/api.zod.ts@@ -17,6 +17,12 @@ export const CommunitySkillsInstallCreateBody = /* @__PURE__ */ zod.object({.max(communitySkillsInstallCreateBodyNewNameMax).optional().describe("Name for the installed skill in your team. Defaults to the community skill's slug."),+ variables: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ "Values for a template skill's declared variables, as a {name: value} map. Required only when installing a template (see the skill's `template_variables`); ignored for non-template skills."+ ),})export const llmSkillsCreateBodyNameMax = 64diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 912686f27d62..26647a20d32d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17792,6 +17792,20 @@ export namespace Schemas {content_type?: string;}+ /**+ * One declared variable of a templated skill — the schema a client renders a form from.+ */+ export interface CommunitySkillTemplateVariable {+ /** Variable identifier, substituted for `{{ name }}` in the skill body. */+ name: string;+ /** Human-readable question shown when collecting a value for this variable. */+ prompt: string;+ /** Whether a value must be supplied at install time (otherwise it falls back to the default). */+ is_required: boolean;+ /** Value used when none is supplied. Empty when the variable has no default. */+ default: string;+ }+export interface CommunitySkill {readonly id: string;/** Stable identifier matching the skill's directory in the community-skills repo. */@@ -17824,6 +17838,8 @@ export namespace Schemas {readonly github_url: string;/** Bundled files manifest — path and content_type only. File contents are copied in on install. */readonly files: readonly CommunitySkillFileManifest[];+ /** Declared template variables, parsed from metadata. Non-empty marks this skill as a template: collect a value for each and pass them as `variables` when installing. */+ readonly template_variables: readonly CommunitySkillTemplateVariable[];/** Number of times this skill has been installed into a team. */readonly install_count: number;/** Total number of upvotes this skill has received. */@@ -17839,12 +17855,19 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * Values for a template skill's declared variables, as a {name: value} map. Required only when installing a template (see the skill's `template_variables`); ignored for non-template skills.+ */+ export type CommunitySkillInstallVariables = {[key: string]: string};+export interface CommunitySkillInstall {/*** Name for the installed skill in your team. Defaults to the community skill's slug.* @maxLength 64*/new_name?: string;+ /** Values for a template skill's declared variables, as a {name: value} map. Required only when installing a template (see the skill's `template_variables`); ignored for non-template skills. */+ variables?: CommunitySkillInstallVariables;}/**@@ -17883,6 +17906,8 @@ export namespace Schemas {readonly author_handle: string;/** Link to the skill's source directory on GitHub. */readonly github_url: string;+ /** Declared template variables, parsed from metadata. Non-empty marks this skill as a template: collect a value for each and pass them as `variables` when installing. */+ readonly template_variables: readonly CommunitySkillTemplateVariable[];/** Number of times this skill has been installed into a team. */readonly install_count: number;/** Total number of upvotes this skill has received. */