: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
fix(skills): preserve template variables when publishing (#90870)
Puspo Adityac644806acd0e
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.mdindex febd16adecb3..f0e8f79252bc 100644--- a/docs/internal/skills/community-skills-api.md+++ b/docs/internal/skills/community-skills-api.md@@ -101,6 +101,11 @@ Rendering and the GitHub calls are in `community_publish_services.py`.against the publisher's PostHog account, so the PR body presents it as a handle the publisher gave.- Bundled files are text only. `CommunitySkillFile.content` is a `TextField` and the renderer takes`str`, so a skill referencing an image or other binary asset cannot round-trip through the catalog.+- Template skills publish their normalized `metadata.variables` schema (and no other store metadata).+ Publishing checks that the template installs with only its defaults: every `{{ variable }}` in+ `SKILL.md` or a bundled file is declared, and the defaults and rendered output fit the install+ size caps. A failed check stops publishing with `400` before any GitHub write. A skill with no+ variables is not a template, so its `{{ }}` text publishes verbatim, as install keeps it.### Settingsdiff --git a/products/skills/backend/api/community_publish_services.py b/products/skills/backend/api/community_publish_services.pyindex ee5b93fd131a..e41163752a8c 100644--- a/products/skills/backend/api/community_publish_services.py+++ b/products/skills/backend/api/community_publish_services.py@@ -35,6 +35,7 @@ from .skill_services import (check_allowed_tool_name,normalize_skill_file_path,)+from .skill_template_services import TemplateRenderError, parse_template_variables, validate_templatelogger = structlog.get_logger(__name__)@@ -177,6 +178,7 @@ def render_skill_md(license: str = "",compatibility: str = "",author_handle: str = "",+ metadata: dict[str, Any] | None = None,) -> str:"""Render an LLMSkill's fields into community-skills `SKILL.md` content (frontmatter + body).@@ -227,6 +229,20 @@ def render_skill_md(frontmatter["compatibility"] = compatibility.strip()if allowed_tools:frontmatter["allowed_tools"] = list(allowed_tools)+ template_variables = parse_template_variables(metadata)+ if template_variables:+ # `required` is always written, so an omitted `default` reads back the same as an empty one.+ frontmatter["metadata"] = {+ "variables": [+ {+ "name": variable.name,+ "prompt": variable.prompt,+ "required": variable.required,+ **({"default": variable.default} if variable.default else {}),+ }+ for variable in template_variables+ ]+ }# sort_keys=False keeps the human-friendly field order above; default_flow_style=False emits# block-style YAML (lists as `- item`) that the repo's yaml.safe_load round-trips.@@ -249,6 +265,7 @@ def render_community_skill_files(license: str = "",compatibility: str = "",author_handle: str = "",+ metadata: dict[str, Any] | None = None,) -> list[RenderedFile]:"""Render the full set of files to commit for a skill: SKILL.md plus any bundled files.@@ -257,6 +274,14 @@ def render_community_skill_files("""_validate_slug(slug)_validate_entry_caps(body=body, files=files or [])+ # Only a template reads `{{ }}` as placeholders. A plain skill keeps that text verbatim, the way+ # install does, so a skill quoting GitHub Actions or Go template syntax still publishes.+ template_variables = parse_template_variables(metadata)+ if template_variables:+ try:+ validate_template(variables=template_variables, body=body, files=files or [])+ except TemplateRenderError as err:+ raise CommunitySkillPublishValidationError(str(err)) from errskill_root = f"{SKILLS_DIR}/{slug}"rendered: list[RenderedFile] = [@@ -271,6 +296,7 @@ def render_community_skill_files(license=license,compatibility=compatibility,author_handle=author_handle,+ metadata=metadata,),)]@@ -551,6 +577,7 @@ def publish_skill_to_community(license: str = "",compatibility: str = "",author_handle: str = "",+ metadata: dict[str, Any] | None = None,) -> dict[str, Any]:"""Open a PR in PostHog/community-skills adding (or updating) this skill. Returns the PR url/number.@@ -582,6 +609,7 @@ def publish_skill_to_community(license=license,compatibility=compatibility,author_handle=author_handle,+ metadata=metadata,)publisher = get_community_skills_publisher()diff --git a/products/skills/backend/api/skill_template_services.py b/products/skills/backend/api/skill_template_services.pyindex 42a0a8203bad..72e8ee2c22b2 100644--- a/products/skills/backend/api/skill_template_services.py+++ b/products/skills/backend/api/skill_template_services.py@@ -163,6 +163,11 @@ def resolve_bindings(variables: list[TemplateVariable], supplied: dict[str, str]value = ""bindings[variable.name] = value+ _check_binding_sizes(bindings)+ return bindings+++def _check_binding_sizes(bindings: dict[str, str]) -> None:total = 0for name, value in bindings.items():size = len(value.encode("utf-8"))@@ -171,7 +176,6 @@ def resolve_bindings(variables: list[TemplateVariable], supplied: dict[str, str]total += sizeif total > MAX_TEMPLATE_BINDINGS_BYTES:raise TemplateVariableTooLargeError("values in total", MAX_TEMPLATE_BINDINGS_BYTES)- return bindingsdef _validate_and_project(text: str, bindings: dict[str, str], binding_sizes: dict[str, int]) -> int:@@ -196,6 +200,37 @@ def _validate_and_project(text: str, bindings: dict[str, str], binding_sizes: direturn projected+def _check_rendered_size(body: str, files: list[dict[str, str]], bindings: dict[str, str]) -> None:+ """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.+ """+ binding_sizes = {name: len(value.encode("utf-8")) for name, value in bindings.items()}+ 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)+++def validate_template(*, variables: list[TemplateVariable], body: str, files: list[dict[str, str]]) -> None:+ """Check a template installs with only its defaults: every placeholder is declared, every default+ fits the value caps, and the rendered output fits the size limits.++ For callers that check a template without rendering it, such as publishing. A required variable+ with no default binds to the empty string here, so it cannot inflate the output; an installer's+ own values are checked again at install. Raises the same TemplateRenderError subclasses as+ `render_template_skill`.+ """+ bindings = {variable.name: variable.default for variable in variables}+ _check_binding_sizes(bindings)+ _check_rendered_size(body, files, bindings)++def _substitute(text: str, bindings: dict[str, str]) -> str:return _PLACEHOLDER_RE.sub(lambda m: bindings[m.group(1)], text)@@ -223,20 +258,7 @@ def render_template_skill(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)+ _check_rendered_size(body, files, bindings)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/skills.py b/products/skills/backend/api/skills.pyindex ae737b9652c7..68b9a778d812 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1214,6 +1214,7 @@ class LLMSkillViewSet(license=skill.license or "",compatibility=skill.compatibility or "",author_handle=payload.validated_data.get("author_handle", ""),+ metadata=skill.metadata,)except CommunitySkillPublishNotConfiguredError:# The fail-safe is otherwise silent, so an instance that meant to have publishing ondiff --git a/products/skills/backend/api/test/test_community_publish_services.py b/products/skills/backend/api/test/test_community_publish_services.pyindex 185367a0c678..db2650f3e0d5 100644--- a/products/skills/backend/api/test/test_community_publish_services.py+++ b/products/skills/backend/api/test/test_community_publish_services.py@@ -25,6 +25,7 @@ from products.skills.backend.api.community_publish_services import (render_skill_md,)from products.skills.backend.api.skill_services import MAX_SKILL_BODY_BYTES, MAX_SKILL_FILE_BYTES, MAX_SKILL_FILE_COUNT+from products.skills.backend.api.skill_template_services import MAX_TEMPLATE_VARIABLE_BYTES, parse_template_variablesfrom products.skills.backend.marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH# Mirror of the community-skills repo's frontmatter parser (scripts/build_registry.py) so these@@ -72,6 +73,32 @@ class TestRenderSkillMd:assert frontmatter["compatibility"] == "Requires gh"assert frontmatter["author_handle"] == "andymaguire"+ def test_renders_normalized_template_variables(self) -> None:+ metadata = {+ "owner": "internal-only",+ "variables": [+ {"name": "service", "prompt": "Service name", "required": True},+ {"name": "environment", "prompt": "Target environment", "default": "staging"},+ ],+ }+ content = render_skill_md(+ name="Deploy service",+ description="Deploy a service to an environment.",+ body="Deploy {{ service }} to {{ environment }}.",+ metadata=metadata,+ )++ frontmatter, _ = _parse(content)++ assert frontmatter["metadata"] == {+ "variables": [+ {"name": "service", "prompt": "Service name", "required": True},+ {"name": "environment", "prompt": "Target environment", "required": False, "default": "staging"},+ ]+ }+ # Install reads the schema back out of this frontmatter, so it must parse to the same variables.+ assert parse_template_variables(frontmatter["metadata"]) == parse_template_variables(metadata)+def test_preserves_leading_whitespace_in_the_body(self) -> None:# strip() would turn an opening indented code block into an ordinary paragraph, so the# published skill would instruct differently from the skill it was published from.@@ -152,6 +179,77 @@ class TestRenderCommunitySkillFiles:"skills/make-pr/scripts/run.sh",}+ @parameterized.expand(+ [+ (+ "undeclared placeholder in the body",+ "Deploy {{ missing }}.",+ "hints",+ {},+ "undeclared variable 'missing'",+ ),+ (+ "undeclared placeholder in a bundled file",+ "body",+ "Use {{ missing }}.",+ {},+ "undeclared variable 'missing'",+ ),+ (+ "default over the value cap",+ "{{ repository }}",+ "hints",+ {"default": "x" * (MAX_TEMPLATE_VARIABLE_BYTES + 1)},+ "exceeds the",+ ),+ (+ "default that renders the body past its cap",+ "{{ repository }}" * (MAX_SKILL_BODY_BYTES // 20),+ "hints",+ {"default": "0123456789" * 3},+ "skill body exceeds the",+ ),+ ]+ )+ def test_rejects_a_template_that_could_not_install(+ self, _label: str, body: str, file_content: str, variable: dict[str, Any], message: str+ ) -> None:+ # Sync does not validate templates, so a broken one otherwise merges and fails every install.+ with pytest.raises(CommunitySkillPublishValidationError, match=message):+ render_community_skill_files(+ slug="make-pr",+ name="Make PR",+ description="Open a PR.",+ body=body,+ files=[{"path": "references/playbook.md", "content": file_content, "content_type": "text/markdown"}],+ metadata={"variables": [{"name": "repository", "prompt": "Repository", **variable}]},+ )++ @parameterized.expand(+ [+ ("no metadata", None),+ ("variables is not a list", {"variables": "repository"}),+ ("variables has no valid declarations", {"variables": [{"prompt": "Repository"}]}),+ ]+ )+ def test_a_plain_skill_keeps_double_braces_verbatim(self, _label: str, metadata: dict[str, Any] | None) -> None:+ # Install leaves a plain skill's text alone, so publish must too: GitHub Actions, Liquid and Go+ # template syntax cannot be declared as variables and must not block publishing.+ rendered = render_community_skill_files(+ slug="make-pr",+ name="Make PR",+ description="Open a PR.",+ body="Run on ${{ github.ref }}.",+ files=[{"path": "references/playbook.md", "content": "{{ .Title }}", "content_type": "text/markdown"}],+ metadata=metadata,+ )++ frontmatter, body = _parse(rendered[0].content)++ assert "metadata" not in frontmatter+ assert body == "Run on ${{ github.ref }}."+ assert rendered[1].content == "{{ .Title }}"+def test_rejects_bad_slug(self) -> None:# "new" and the category-tab slugs are rejected by ingest, so publishing one merges a pull# request whose skill never appears in the catalog. A trailing newline needs `fullmatch`.diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex f71af664c9ff..92505f16e996 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -1355,7 +1355,10 @@ class TestLLMSkillAPI(APIBaseTest):description="Open a PR.",body="# Make PR",allowed_tools=["query"],- metadata={"tags": ["github"]},+ metadata={+ "tags": ["github"],+ "variables": [{"name": "repository", "prompt": "Repository to update"}],+ },)LLMSkillFile.objects.create(skill=skill, path="references/playbook.md", content="hints", content_type="text/markdown"@@ -1374,6 +1377,7 @@ class TestLLMSkillAPI(APIBaseTest):assert kwargs["name"] == "Make Pr" # default display name = title-cased slugassert kwargs["description"] == "Open a PR."assert kwargs["tags"] == ["github"] # falls back to metadata tags+ assert kwargs["metadata"] == skill.metadataassert kwargs["allowed_tools"] == ["query"]assert kwargs["author_handle"] == "andymaguire"assert kwargs["files"] == [diff --git a/products/skills/frontend/skillSceneComponents.tsx b/products/skills/frontend/skillSceneComponents.tsxindex efa9d34eaa89..b3a6aad106fa 100644--- a/products/skills/frontend/skillSceneComponents.tsx+++ b/products/skills/frontend/skillSceneComponents.tsx@@ -47,7 +47,7 @@ export function openPublishToCommunityDialog({LemonDialog.openForm({title: 'Publish to community',description:- "Publishing commits the skill's instructions and every bundled file to a public GitHub repo, then opens a pull request for a maintainer to review. The contents are public from the moment you submit, so don't include credentials or internal details.",+ "Publishing commits the skill's instructions, every bundled file, and any template variables (their prompts and defaults) to a public GitHub repo, then opens a pull request for a maintainer to review. The contents are public from the moment you submit, so don't include credentials or internal details.",initialValues: {display_name: skillName.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),tags: '',