: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): expose shared skills to posthog ai (#58616)
Andrew Maguireb9f470867b16
diff --git a/ee/hogai/chat_agent/toolkit.py b/ee/hogai/chat_agent/toolkit.pyindex 6450c6836356..d17209560fc2 100644--- a/ee/hogai/chat_agent/toolkit.py+++ b/ee/hogai/chat_agent/toolkit.py@@ -6,6 +6,7 @@ from django.conf import settingsfrom langchain_core.runnables import RunnableConfig+from products.ai_observability.backend.tools.skills import GetLLMSkillFileTool, GetLLMSkillTool, ListLLMSkillsToolfrom products.tasks.backend.max_tools import (CreateTaskTool,GetTaskRunLogsTool,@@ -51,6 +52,9 @@ DEFAULT_TOOLS: list[type[MaxTool]] = [SwitchModeTool,CreateFormTool,CreateNotebookTool,+ ListLLMSkillsTool,+ GetLLMSkillTool,+ GetLLMSkillFileTool,]TASK_TOOLS: list[type[MaxTool]] = [diff --git a/ee/hogai/core/agent_modes/presets/ai_observability.py b/ee/hogai/core/agent_modes/presets/ai_observability.pyindex df55f5d4da00..f3458d1b7fa8 100644--- a/ee/hogai/core/agent_modes/presets/ai_observability.py+++ b/ee/hogai/core/agent_modes/presets/ai_observability.py@@ -70,7 +70,49 @@ The assistant used run_hog_eval_test because:3. The assistant can iterate on the fix by running the tool again""".strip()-AI_OBSERVABILITY_MODE_DESCRIPTION = "Specialized mode for AI observability. Search and analyze LLM traces for usage, costs, latency, and errors. Write and test Hog evaluation code against real events."+POSITIVE_EXAMPLE_DISCOVER_SKILL = """+User: Audit my error tracking issues for last week+Assistant: I'll check whether the team already has a shared skill that covers this audit, then follow it.+*Uses list_llm_skills with search: "error tracking"*+*Finds "audit-error-tracking" — uses get_llm_skill with skill_name: "audit-error-tracking" to load the body*+*Follows the workflow steps defined in the SKILL.md body*+""".strip()++POSITIVE_EXAMPLE_DISCOVER_SKILL_REASONING = """+The assistant used list_llm_skills + get_llm_skill because:+1. The user asked for a multi-step workflow (an "audit") — exactly the kind of recipe that's often saved as a skill+2. Following a team skill stays consistent with how the team has previously asked for the same task+3. Discovery is cheap: list_llm_skills returns just names + descriptions, so the assistant can scan and only load the relevant body+""".strip()++POSITIVE_EXAMPLE_SAVE_SKILL = """+User: Save this workflow as a shared skill called "audit-error-tracking"+Assistant: I'll save it as a shared skill so the whole team can reuse it.+*Uses create_llm_skill with name: "audit-error-tracking", a clear description, and the body summarizing the workflow we just walked through*+""".strip()++POSITIVE_EXAMPLE_SAVE_SKILL_REASONING = """+The assistant used create_llm_skill because:+1. The user explicitly asked to save the workflow as a shared skill+2. The skill body captures the multi-step recipe so future agents can follow it+3. A specific kebab-case name and a description with "when to use it" wording make it discoverable+""".strip()++POSITIVE_EXAMPLE_UPDATE_SKILL = """+User: The audit-error-tracking skill is missing the step where we group by impact+Assistant: I'll fetch the skill, then publish a targeted edit.+*Uses get_llm_skill with skill_name: "audit-error-tracking" to read the body and note the current version*+*Uses update_llm_skill with skill_name: "audit-error-tracking", base_version: <fetched version>, and edits that insert the new step*+""".strip()++POSITIVE_EXAMPLE_UPDATE_SKILL_REASONING = """+The assistant used get_llm_skill then update_llm_skill because:+1. Updates need the current version for optimistic concurrency — fetch first+2. The change is a small insertion, so `edits` is more precise (and less risky) than rewriting the whole body+3. Carrying every other field forward means the assistant didn't have to round-trip description, license, files, etc.+""".strip()++AI_OBSERVABILITY_MODE_DESCRIPTION = "Specialized mode for AI observability. Search and analyze LLM traces for usage, costs, latency, and errors. Write and test Hog evaluation code against real events. Create, update, and archive shared agent skills for the team."class AIObservabilityAgentToolkit(AgentToolkit):@@ -91,13 +133,36 @@ class AIObservabilityAgentToolkit(AgentToolkit):example=POSITIVE_EXAMPLE_FIX_EVAL_ERRORS,reasoning=POSITIVE_EXAMPLE_FIX_EVAL_ERRORS_REASONING,),+ TodoWriteExample(+ example=POSITIVE_EXAMPLE_DISCOVER_SKILL,+ reasoning=POSITIVE_EXAMPLE_DISCOVER_SKILL_REASONING,+ ),+ TodoWriteExample(+ example=POSITIVE_EXAMPLE_SAVE_SKILL,+ reasoning=POSITIVE_EXAMPLE_SAVE_SKILL_REASONING,+ ),+ TodoWriteExample(+ example=POSITIVE_EXAMPLE_UPDATE_SKILL,+ reasoning=POSITIVE_EXAMPLE_UPDATE_SKILL_REASONING,+ ),]@propertydef tools(self) -> list[type["MaxTool"]]:from products.ai_observability.backend.tools.run_hog_eval_test import RunHogEvalTestTool-- return [SearchLLMTracesTool, RunHogEvalTestTool]+ from products.ai_observability.backend.tools.skills import (+ ArchiveLLMSkillTool,+ CreateLLMSkillTool,+ UpdateLLMSkillTool,+ )++ return [+ SearchLLMTracesTool,+ RunHogEvalTestTool,+ CreateLLMSkillTool,+ UpdateLLMSkillTool,+ ArchiveLLMSkillTool,+ ]ai_observability_agent = AgentModeDefinition(diff --git a/ee/hogai/core/agent_modes/presets/test/test_ai_observability_preset.py b/ee/hogai/core/agent_modes/presets/test/test_ai_observability_preset.pyindex 2f8c11a30ae8..42511a867f34 100644--- a/ee/hogai/core/agent_modes/presets/test/test_ai_observability_preset.py+++ b/ee/hogai/core/agent_modes/presets/test/test_ai_observability_preset.py@@ -19,6 +19,10 @@ class TestAIObservabilityAgentToolkit(BaseTest):tool_class_names = [tool_class.__name__ for tool_class in tool_classes]self.assertIn("SearchLLMTracesTool", tool_class_names)+ self.assertIn("RunHogEvalTestTool", tool_class_names)+ self.assertIn("CreateLLMSkillTool", tool_class_names)+ self.assertIn("UpdateLLMSkillTool", tool_class_names)+ self.assertIn("ArchiveLLMSkillTool", tool_class_names)def test_toolkit_has_trajectory_examples(self):self.assertIsNotNone(AIObservabilityAgentToolkit.POSITIVE_TODO_EXAMPLES)diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 837a811a19cf..605d6bdd5650 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -3583,6 +3583,12 @@"call_mcp_server","search_llm_traces","run_hog_eval_test",+ "list_llm_skills",+ "get_llm_skill",+ "get_llm_skill_file",+ "create_llm_skill",+ "update_llm_skill",+ "archive_llm_skill","diagnose_proxy","web_analytics_doctor","marketing_diagnose_setup",diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex 02c97a8f17a6..42bbf474f4b1 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -499,6 +499,12 @@ export type AssistantTool =| 'call_mcp_server'| 'search_llm_traces'| 'run_hog_eval_test'+ | 'list_llm_skills'+ | 'get_llm_skill'+ | 'get_llm_skill_file'+ | 'create_llm_skill'+ | 'update_llm_skill'+ | 'archive_llm_skill'| 'diagnose_proxy'| 'web_analytics_doctor'| 'marketing_diagnose_setup'diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex ac0ed7d1e136..1a50f7b9e70d 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -135,8 +135,23 @@ export const DEFAULT_TOOL_KEYS: (keyof typeof TOOL_DEFINITIONS)[] = ['list_data','search','switch_mode',+ 'list_llm_skills',+ 'get_llm_skill',+ 'get_llm_skill_file',]+function skillStatusFormatter(+ toolCall: EnhancedToolCall,+ { completedLabel, pendingLabel, nameArgKey }: { completedLabel: string; pendingLabel: string; nameArgKey?: string }+): string {+ const rawName = nameArgKey ? toolCall.args?.[nameArgKey] : undefined+ const suffix = typeof rawName === 'string' && rawName ? ` "${rawName}"` : ''+ if (toolCall.status === 'completed') {+ return `${completedLabel}${suffix}`+ }+ return `${pendingLabel}${suffix}...`+}+export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {call_mcp_server: {name: 'Call an MCP server',@@ -1115,6 +1130,77 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {return 'Testing evaluation code...'},},+ list_llm_skills: {+ name: 'List shared skills',+ description: 'List shared skills stored for this team',+ icon: <IconBook />,+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Listed shared skills',+ pendingLabel: 'Listing shared skills',+ }),+ },+ get_llm_skill: {+ name: 'Load shared skill',+ description: 'Load shared skill body and file manifest',+ icon: <IconBook />,+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Loaded shared skill',+ pendingLabel: 'Loading shared skill',+ nameArgKey: 'skill_name',+ }),+ },+ get_llm_skill_file: {+ name: 'Load shared skill file',+ description: 'Load shared skill file bundled in a skill',+ icon: <IconBook />,+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Loaded skill file',+ pendingLabel: 'Loading skill file',+ nameArgKey: 'file_path',+ }),+ },+ create_llm_skill: {+ name: 'Create shared skill',+ description: 'Create shared skill to save a reusable workflow',+ product: Scene.AIObservability,+ icon: <IconBook />,+ modes: [AgentMode.AIObservability],+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Created shared skill',+ pendingLabel: 'Creating shared skill',+ nameArgKey: 'name',+ }),+ },+ update_llm_skill: {+ name: 'Update shared skill',+ description: 'Update shared skill by publishing a new version',+ product: Scene.AIObservability,+ icon: <IconBook />,+ modes: [AgentMode.AIObservability],+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Updated shared skill',+ pendingLabel: 'Updating shared skill',+ nameArgKey: 'skill_name',+ }),+ },+ archive_llm_skill: {+ name: 'Archive shared skill',+ description: 'Archive shared skill to hide it from suggestions',+ product: Scene.AIObservability,+ icon: <IconBook />,+ modes: [AgentMode.AIObservability],+ displayFormatter: (toolCall) =>+ skillStatusFormatter(toolCall, {+ completedLabel: 'Archived shared skill',+ pendingLabel: 'Archiving shared skill',+ nameArgKey: 'skill_name',+ }),+ },}export const MODE_DEFINITIONS: Record<diff --git a/posthog/schema.py b/posthog/schema.pyindex 1f1963454a89..9c02dccead09 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -735,6 +735,12 @@ class AssistantTool(StrEnum):CALL_MCP_SERVER = "call_mcp_server"SEARCH_LLM_TRACES = "search_llm_traces"RUN_HOG_EVAL_TEST = "run_hog_eval_test"+ LIST_LLM_SKILLS = "list_llm_skills"+ GET_LLM_SKILL = "get_llm_skill"+ GET_LLM_SKILL_FILE = "get_llm_skill_file"+ CREATE_LLM_SKILL = "create_llm_skill"+ UPDATE_LLM_SKILL = "update_llm_skill"+ ARCHIVE_LLM_SKILL = "archive_llm_skill"DIAGNOSE_PROXY = "diagnose_proxy"WEB_ANALYTICS_DOCTOR = "web_analytics_doctor"MARKETING_DIAGNOSE_SETUP = "marketing_diagnose_setup"diff --git a/products/ai_observability/backend/api/skill_services.py b/products/ai_observability/backend/api/skill_services.pyindex cf017767be1c..621b900b700b 100644--- a/products/ai_observability/backend/api/skill_services.py+++ b/products/ai_observability/backend/api/skill_services.py@@ -302,6 +302,82 @@ def _copy_files()+def create_skill(+ team: Team,+ *,+ user: User,+ name: str,+ description: str,+ body: str,+ license: str | None = None,+ compatibility: str | None = None,+ allowed_tools: list[str] | None = None,+ metadata: dict[str, Any] | None = None,+ files: list[dict[str, str]] | None = None,+) -> LLMSkill:+ if files and len(files) > MAX_SKILL_FILE_COUNT:+ raise LLMSkillFileLimitError(max_count=MAX_SKILL_FILE_COUNT)++ if files:+ seen_paths: set[str] = set()+ for item in files:+ path = item["path"]+ if path in seen_paths:+ raise LLMSkillFilePathConflictError(path=path)+ seen_paths.add(path)++ with transaction.atomic():+ # Lock any existing rows for this (team, name) so a concurrent create can't slip past.+ existing = list(+ LLMSkill.objects.select_for_update()+ .filter(team=team, name=name, deleted=False)+ .values_list("id", flat=True)+ )+ if existing:+ raise LLMSkillDuplicateNameConflictError()++ try:+ new_skill = LLMSkill.objects.create(+ team=team,+ name=name,+ description=description,+ body=body,+ license=license or "",+ compatibility=compatibility or "",+ allowed_tools=allowed_tools or [],+ metadata=metadata or {},+ version=1,+ is_latest=True,+ created_by=user,+ )+ except IntegrityError as err:+ err_str = str(err)+ if "unique_llm_skill_latest_per_team" in err_str or "unique_llm_skill_version_per_team" in err_str:+ raise LLMSkillDuplicateNameConflictError() from err+ raise++ if files:+ try:+ LLMSkillFile.objects.bulk_create(+ [+ LLMSkillFile(+ skill=new_skill,+ path=item["path"],+ content=item.get("content", ""),+ content_type=item.get("content_type", "text/plain"),+ )+ for item in files+ ]+ )+ except IntegrityError as err:+ if "unique_skill_file_path" in str(err):+ raise LLMSkillFilePathConflictError(path="") from err+ raise++ refreshed = get_active_skill_queryset(team).filter(pk=new_skill.pk).first()+ return refreshed if refreshed is not None else new_skill++def duplicate_skill(team: Team,*,diff --git a/products/ai_observability/backend/tools/skills.py b/products/ai_observability/backend/tools/skills.pynew file mode 100644index 000000000000..f187dfd55b8b--- /dev/null+++ b/products/ai_observability/backend/tools/skills.py@@ -0,0 +1,483 @@+import posixpath+from typing import Any++from pydantic import BaseModel, Field++from posthog.schema import AssistantTool++from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObject+from posthog.sync import database_sync_to_async++from products.ai_observability.backend.api.skill_services import (+ LLMSkillDuplicateNameConflictError,+ LLMSkillEditError,+ LLMSkillFileLimitError,+ LLMSkillFilePathConflictError,+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ archive_skill,+ create_skill,+ get_latest_skills_queryset,+ get_skill_by_name_from_db,+ publish_skill_version,+)+from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile++from ee.hogai.tool import MaxTool+from ee.hogai.tool_errors import MaxToolFatalError++MAX_LIST_RESULTS = 50+++LIST_SKILLS_DESCRIPTION = """List shared agent skills stored for this team.++Returns each skill's name and description. Use the descriptions to decide which skill to fetch — never load every body upfront.++# When to use this tool+- Before tackling a non-trivial task, check whether the team has a stored skill that already covers it (a workflow,+ runbook, or multi-step recipe).+- When the user mentions "skills", "team skills", "shared skills", or asks what skills are available.+- When the user asks you to follow a specific named workflow that may exist as a skill.++# What this tool returns+A list of `name` + `description` pairs, plus an indication of whether more results were truncated. This is the+discovery step in progressive disclosure — load the body with `get_llm_skill` once you have a candidate."""+++GET_SKILL_DESCRIPTION = """Fetch a stored agent skill by name. Returns the full SKILL.md body (markdown instructions), metadata, and a+manifest of bundled files (paths only — content is loaded on demand via `get_llm_skill_file`).++# When to use this tool+- After `list_llm_skills` surfaces a skill whose description matches the task.+- When the user names a skill explicitly ("use the make-fractals skill", "follow the onboarding-audit skill").+- When you need to manage a skill (edit / archive) — fetch first to get the current `version` so you can pass+ `base_version` for the next write.++# What this tool returns+The skill body (treat as system instructions for the current task), description, version, optional license /+compatibility / allowed_tools / metadata, and a file manifest (path + content_type only). Read the body, then pull+individual files with `get_llm_skill_file` only when the body references them."""+++GET_SKILL_FILE_DESCRIPTION = """Fetch a single bundled file from a stored skill by path.++# When to use this tool+- The skill body references a script, reference doc, or asset and you actually need its content.+- Do NOT preload every file in the manifest — only fetch what the body's decision tree points to.++# What this tool returns+The file `path`, `content`, and `content_type`."""+++CREATE_SKILL_DESCRIPTION = """Create a new agent skill (a reusable workflow stored for the whole team).++# When to use this tool+- The user asks to save, store, or remember a workflow, runbook, or multi-step procedure as a shared skill.+- A reusable recipe emerged from the conversation and the user wants it captured.++# Required input+- `name`: kebab-case, lowercase letters/numbers/hyphens, <=64 chars, no leading/trailing/consecutive hyphens.+- `description`: explains what it does AND when to use it (this is the only thing visible at discovery time).+- `body`: the SKILL.md instructions as markdown. Keep under ~500 lines — move long scripts and references into+ `files` so the body stays scannable.++# Optional input+- `license`, `compatibility`, `allowed_tools`, `metadata`: spec fields (see agentskills.io).+- `files`: bundled files (`path`, `content`, `content_type`). Use `scripts/` for executable code, `references/` for+ docs, `assets/` for templates."""+++UPDATE_SKILL_DESCRIPTION = """Publish a new version of an existing skill. Any field not provided is carried forward from the current latest.++# When to use this tool+- The user asks to update, edit, or improve an existing skill.+- You spotted an error or improvement opportunity in a skill body and the user approved the change.++# Required input+- `skill_name`: the kebab-case name of the skill.+- `base_version`: the version number returned by the most recent `get_llm_skill`. Required for optimistic+ concurrency — the request fails if someone else published a newer version in the meantime.++# Body changes (pick one)+- `body`: full replacement (good for substantial rewrites).+- `edits`: incremental find/replace (good for small tweaks). Each entry needs `old` (must match exactly once) and+ `new`. Mutually exclusive with `body`.++# Other writable fields+- `description`, `license`, `compatibility`, `allowed_tools`, `metadata`.+- `file_edits`: per-file find/replace patches. Each entry targets one existing file by `path` with its own `edits`+ list. Files not mentioned are carried forward unchanged. Cannot add, remove, or rename files."""+++ARCHIVE_SKILL_DESCRIPTION = """Archive every active version of a skill by name. This hides the skill from default lists and cannot be+undone. Use `get_llm_skill` first if you need to inspect the skill before archiving it."""+++class ListSkillsArgs(BaseModel):+ search: str | None = Field(+ default=None,+ description="Optional case-insensitive substring filter applied to name and description.",+ )+++class GetSkillArgs(BaseModel):+ skill_name: str = Field(description="The kebab-case name of the skill to fetch.")+ version: int | None = Field(+ default=None,+ description="Optional specific version to fetch. Defaults to the latest active version.",+ )+++class GetSkillFileArgs(BaseModel):+ skill_name: str = Field(description="The kebab-case name of the skill that owns the file.")+ file_path: str = Field(description="The path of the bundled file as it appears in the skill's file manifest.")+ version: int | None = Field(+ default=None,+ description="Optional specific skill version. Defaults to the latest active version.",+ )+++class CreateSkillArgs(BaseModel):+ name: str = Field(description="Kebab-case skill name. <=64 chars. Must be unique within the team.")+ description: str = Field(+ description="Short summary explaining what the skill does and when agents should pick it. <=4096 chars.",+ )+ body: str = Field(description="SKILL.md instructions as markdown. Treated as system instructions when invoked.")+ license: str | None = Field(default=None, description="Optional license string (e.g. 'MIT').")+ compatibility: str | None = Field(+ default=None,+ description="Optional compatibility notes (e.g. 'Requires Python 3.10+ with Pillow').",+ )+ allowed_tools: list[str] | None = Field(+ default=None,+ description="Optional list of tool names the skill is permitted to invoke.",+ )+ metadata: dict[str, Any] | None = Field(+ default=None,+ description="Optional free-form metadata dict (author, category, etc.).",+ )+ files: list[dict[str, str]] | None = Field(+ default=None,+ description=(+ "Optional bundled files. Each item: {path, content, content_type?}. "+ "Use scripts/, references/, or assets/ subdirs by convention."+ ),+ )+++class UpdateSkillArgs(BaseModel):+ skill_name: str = Field(description="The kebab-case name of the skill to update.")+ base_version: int = Field(+ description="The version observed at fetch time. Required for optimistic concurrency.",+ )+ body: str | None = Field(default=None, description="Full replacement body. Mutually exclusive with 'edits'.")+ edits: list[dict[str, str]] | None = Field(+ default=None,+ description=(+ "Incremental find/replace edits applied sequentially to the current body. "+ "Each entry: {old, new}. 'old' must match exactly once. Mutually exclusive with 'body'."+ ),+ )+ description: str | None = Field(default=None, description="Optional new description.")+ license: str | None = Field(default=None, description="Optional new license.")+ compatibility: str | None = Field(default=None, description="Optional new compatibility string.")+ allowed_tools: list[str] | None = Field(default=None, description="Optional replacement for allowed_tools.")+ metadata: dict[str, Any] | None = Field(default=None, description="Optional replacement for metadata.")+ file_edits: list[dict[str, Any]] | None = Field(+ default=None,+ description=(+ "Per-file find/replace edits. Each entry: {path, edits: [{old, new}, ...]}. "+ "Files not mentioned are carried forward unchanged. Cannot add, remove, or rename files."+ ),+ )+++class ArchiveSkillArgs(BaseModel):+ skill_name: str = Field(description="The kebab-case name of the skill to archive.")+++def _format_skill_summary(skill: LLMSkill) -> str:+ description = (skill.description or "").strip() or "(no description)"+ return f"- {skill.name} (v{skill.version}): {description}"+++def _format_skill_detail(skill: LLMSkill, files: list[LLMSkillFile]) -> str:+ lines = [+ f"# {skill.name} (v{skill.version})",+ "",+ f"Description: {skill.description}",+ ]+ if skill.license:+ lines.append(f"License: {skill.license}")+ if skill.compatibility:+ lines.append(f"Compatibility: {skill.compatibility}")+ if skill.allowed_tools:+ lines.append(f"Allowed tools: {', '.join(skill.allowed_tools)}")+ if skill.metadata:+ lines.append(f"Metadata: {skill.metadata}")++ lines.append("")+ if files:+ lines.append("Bundled files (use `get_llm_skill_file` to load content):")+ for skill_file in files:+ lines.append(f" - {skill_file.path} ({skill_file.content_type})")+ else:+ lines.append("Bundled files: (none)")+ lines.append("")+ lines.append("--- BODY ---")+ lines.append(skill.body or "")+ return "\n".join(lines)+++def _publish_error_message(err: Exception, skill_name: str) -> str:+ if isinstance(err, LLMSkillNotFoundError):+ return f"Skill '{skill_name}' was not found. Use `list_llm_skills` to discover available skills."+ if isinstance(err, LLMSkillVersionConflictError):+ return (+ f"Skill '{skill_name}' was modified by another writer (current version: {err.current_version}). "+ "Refetch with `get_llm_skill` and retry the update with the new base_version."+ )+ if isinstance(err, LLMSkillVersionLimitError):+ return (+ f"Skill '{skill_name}' has reached the maximum of {err.max_version} versions. "+ "Archive and recreate the skill to continue publishing."+ )+ if isinstance(err, LLMSkillFileLimitError):+ return f"Skill '{skill_name}' has reached the maximum of {err.max_count} bundled files."+ if isinstance(err, LLMSkillEditError):+ detail = err.message+ if err.edit_index is not None:+ detail = f"{detail} (edit index: {err.edit_index})"+ if err.file_path is not None:+ detail = f"{detail} (file: {err.file_path})"+ return detail+ return str(err)+++class ListLLMSkillsTool(MaxTool):+ name: str = AssistantTool.LIST_LLM_SKILLS.value+ description: str = LIST_SKILLS_DESCRIPTION+ args_schema: type[BaseModel] = ListSkillsArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "viewer")]++ async def _arun_impl(self, search: str | None = None) -> tuple[str, None]:+ skills = await database_sync_to_async(self._list_skills)(search)+ if not skills:+ empty_msg = "No shared skills are stored for this team yet."+ if search:+ empty_msg = f"No shared skills matched the search query '{search}'."+ return empty_msg, None++ truncated = len(skills) > MAX_LIST_RESULTS+ visible = skills[:MAX_LIST_RESULTS]+ lines = [f"Found {len(visible)} skill(s):", ""]+ lines.extend(_format_skill_summary(s) for s in visible)+ if truncated:+ lines.append("")+ lines.append(+ f"(Truncated to {MAX_LIST_RESULTS} results — pass a `search` term to narrow the list if needed.)"+ )+ return "\n".join(lines), None++ def _list_skills(self, search: str | None) -> list[LLMSkill]:+ queryset = get_latest_skills_queryset(self._team)+ if search:+ from django.db.models import Q++ queryset = queryset.filter(Q(name__icontains=search) | Q(description__icontains=search))+ # Fetch one extra row so we can distinguish "exactly at the cap" from "truncated".+ return list(queryset.order_by("name")[: MAX_LIST_RESULTS + 1])+++class GetLLMSkillTool(MaxTool):+ name: str = AssistantTool.GET_LLM_SKILL.value+ description: str = GET_SKILL_DESCRIPTION+ args_schema: type[BaseModel] = GetSkillArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "viewer")]++ async def _arun_impl(self, skill_name: str, version: int | None = None) -> tuple[str, None]:+ skill, files = await database_sync_to_async(self._fetch_skill_with_files)(skill_name, version)+ if skill is None:+ return (+ f"Skill '{skill_name}' was not found. Use `list_llm_skills` to discover available skills.",+ None,+ )+ return _format_skill_detail(skill, files), None++ def _fetch_skill_with_files(+ self, skill_name: str, version: int | None+ ) -> tuple[LLMSkill | None, list[LLMSkillFile]]:+ skill = get_skill_by_name_from_db(self._team, skill_name, version)+ if skill is None:+ return None, []+ files = list(LLMSkillFile.objects.filter(skill=skill).order_by("path"))+ return skill, files+++class GetLLMSkillFileTool(MaxTool):+ name: str = AssistantTool.GET_LLM_SKILL_FILE.value+ description: str = GET_SKILL_FILE_DESCRIPTION+ args_schema: type[BaseModel] = GetSkillFileArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "viewer")]++ async def _arun_impl(+ self,+ skill_name: str,+ file_path: str,+ version: int | None = None,+ ) -> tuple[str, None]:+ # Normalize so that `scripts/../foo.py` collapses to `foo.py` before we filter on the+ # exact stored path — the DB lookup itself only matches literal strings, so the guard+ # has to do the work of resolving `..` segments rather than just checking for them.+ cleaned = file_path.replace("\\", "/").rstrip("/")+ if not cleaned:+ return f"Invalid file path '{file_path}'.", None+ normalized = posixpath.normpath(cleaned)+ if posixpath.isabs(normalized) or normalized == ".." or normalized.startswith("../"):+ return f"Invalid file path '{file_path}'.", None++ skill_file = await database_sync_to_async(self._fetch_skill_file)(skill_name, normalized, version)+ if skill_file is None:+ return (+ f"File '{file_path}' was not found in skill '{skill_name}'. "+ "Fetch the skill again with `get_llm_skill` to refresh the file manifest.",+ None,+ )++ return (+ f"# {skill_name} / {skill_file.path}\nContent-Type: {skill_file.content_type}\n\n{skill_file.content}",+ None,+ )++ def _fetch_skill_file(self, skill_name: str, file_path: str, version: int | None) -> LLMSkillFile | None:+ skill = get_skill_by_name_from_db(self._team, skill_name, version)+ if skill is None:+ return None+ return LLMSkillFile.objects.filter(skill=skill, path=file_path).first()+++class CreateLLMSkillTool(MaxTool):+ name: str = AssistantTool.CREATE_LLM_SKILL.value+ description: str = CREATE_SKILL_DESCRIPTION+ args_schema: type[BaseModel] = CreateSkillArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "editor")]++ async def _arun_impl(+ self,+ name: str,+ description: str,+ body: str,+ license: str | None = None,+ compatibility: str | None = None,+ allowed_tools: list[str] | None = None,+ metadata: dict[str, Any] | None = None,+ files: list[dict[str, str]] | None = None,+ ) -> tuple[str, None]:+ try:+ skill = await database_sync_to_async(create_skill)(+ self._team,+ user=self._user,+ name=name,+ description=description,+ body=body,+ license=license,+ compatibility=compatibility,+ allowed_tools=allowed_tools,+ metadata=metadata,+ files=files,+ )+ except LLMSkillDuplicateNameConflictError:+ raise MaxToolFatalError(f"A skill named '{name}' already exists.")+ except LLMSkillFilePathConflictError:+ raise MaxToolFatalError("Duplicate file paths are not allowed in `files`.")+ except LLMSkillFileLimitError as err:+ raise MaxToolFatalError(f"Cannot attach more than {err.max_count} bundled files to a skill.")++ return (+ f"Created skill '{skill.name}' at v{skill.version}. It is now discoverable via `list_llm_skills`.",+ None,+ )+++class UpdateLLMSkillTool(MaxTool):+ name: str = AssistantTool.UPDATE_LLM_SKILL.value+ description: str = UPDATE_SKILL_DESCRIPTION+ args_schema: type[BaseModel] = UpdateSkillArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "editor")]++ async def _arun_impl(+ self,+ skill_name: str,+ base_version: int,+ body: str | None = None,+ edits: list[dict[str, str]] | None = None,+ description: str | None = None,+ license: str | None = None,+ compatibility: str | None = None,+ allowed_tools: list[str] | None = None,+ metadata: dict[str, Any] | None = None,+ file_edits: list[dict[str, Any]] | None = None,+ ) -> tuple[str, None]:+ if body is not None and edits is not None:+ raise MaxToolFatalError("Pass either `body` or `edits`, not both.")++ try:+ skill = await database_sync_to_async(publish_skill_version)(+ self._team,+ user=self._user,+ skill_name=skill_name,+ body=body,+ edits=edits,+ description=description,+ license=license,+ compatibility=compatibility,+ allowed_tools=allowed_tools,+ metadata=metadata,+ files=None,+ file_edits=file_edits,+ base_version=base_version,+ )+ except (+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ LLMSkillFileLimitError,+ LLMSkillEditError,+ ) as err:+ raise MaxToolFatalError(_publish_error_message(err, skill_name))++ return f"Updated skill '{skill.name}' — new version v{skill.version}.", None+++class ArchiveLLMSkillTool(MaxTool):+ name: str = AssistantTool.ARCHIVE_LLM_SKILL.value+ description: str = ARCHIVE_SKILL_DESCRIPTION+ args_schema: type[BaseModel] = ArchiveSkillArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("llm_skill", "editor")]++ async def _arun_impl(self, skill_name: str) -> tuple[str, None]:+ try:+ versions = await database_sync_to_async(archive_skill)(self._team, skill_name)+ except LLMSkillNotFoundError:+ raise MaxToolFatalError(+ f"Skill '{skill_name}' was not found. Use `list_llm_skills` to discover available skills."+ )++ return (+ f"Archived skill '{skill_name}' ({len(versions)} version(s) hidden). This cannot be undone.",+ None,+ )diff --git a/products/ai_observability/backend/tools/test_skills.py b/products/ai_observability/backend/tools/test_skills.pynew file mode 100644index 000000000000..369adb9223d1--- /dev/null+++ b/products/ai_observability/backend/tools/test_skills.py@@ -0,0 +1,294 @@+from posthog.test.base import BaseTest++from asgiref.sync import async_to_sync++from posthog.models import Team++from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile+from products.ai_observability.backend.tools.skills import (+ ArchiveLLMSkillTool,+ CreateLLMSkillTool,+ GetLLMSkillFileTool,+ GetLLMSkillTool,+ ListLLMSkillsTool,+ UpdateLLMSkillTool,+)++from ee.hogai.tool_errors import MaxToolFatalError+++def _run(tool, **kwargs):+ return async_to_sync(tool._arun_impl)(**kwargs)+++class TestListLLMSkillsTool(BaseTest):+ def _create_skill(self, name: str, description: str, body: str = "body") -> LLMSkill:+ return LLMSkill.objects.create(+ team=self.team,+ name=name,+ description=description,+ body=body,+ created_by=self.user,+ )++ def test_empty_team_returns_friendly_message(self):+ tool = ListLLMSkillsTool(team=self.team, user=self.user)+ result, artifact = _run(tool)+ assert "No shared skills" in result+ assert artifact is None++ def test_lists_skills_with_descriptions(self):+ self._create_skill("audit-error-tracking", "Audit recent error tracking issues.")+ self._create_skill("make-fractals", "Render fractal images.")+ tool = ListLLMSkillsTool(team=self.team, user=self.user)++ result, artifact = _run(tool)++ assert "audit-error-tracking" in result+ assert "Audit recent error tracking issues." in result+ assert "make-fractals" in result+ assert artifact is None++ def test_search_filters_by_name_and_description(self):+ self._create_skill("audit-error-tracking", "Audit recent error tracking issues.")+ self._create_skill("make-fractals", "Render fractal images.")++ tool = ListLLMSkillsTool(team=self.team, user=self.user)+ result, _ = _run(tool, search="fractal")++ assert "make-fractals" in result+ assert "audit-error-tracking" not in result++ def test_search_with_no_matches(self):+ self._create_skill("make-fractals", "Render fractal images.")+ tool = ListLLMSkillsTool(team=self.team, user=self.user)++ result, _ = _run(tool, search="nonexistent")++ assert "No shared skills matched" in result+ assert "nonexistent" in result++ def test_does_not_list_other_teams_skills(self):+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ other_team_skill = self._create_skill("private-skill", "Other team's skill.")+ other_team_skill.team = other_team+ other_team_skill.save()++ tool = ListLLMSkillsTool(team=self.team, user=self.user)+ result, _ = _run(tool)++ assert "private-skill" not in result+++class TestGetLLMSkillTool(BaseTest):+ def _create_skill_with_file(self) -> LLMSkill:+ skill = LLMSkill.objects.create(+ team=self.team,+ name="make-fractals",+ description="Render fractals.",+ body="# make-fractals\n\nFollow these steps:",+ license="MIT",+ compatibility="Python 3.10+",+ allowed_tools=["Bash", "Write"],+ metadata={"author": "posthog"},+ created_by=self.user,+ )+ LLMSkillFile.objects.create(+ skill=skill,+ path="scripts/mandelbrot.py",+ content="print('mandelbrot')",+ content_type="text/x-python",+ )+ return skill++ def test_returns_full_skill_with_file_manifest(self):+ self._create_skill_with_file()+ tool = GetLLMSkillTool(team=self.team, user=self.user)++ result, artifact = _run(tool, skill_name="make-fractals")++ assert artifact is None+ assert "make-fractals" in result+ assert "Render fractals." in result+ assert "License: MIT" in result+ assert "Compatibility: Python 3.10+" in result+ assert "Allowed tools: Bash, Write" in result+ assert "scripts/mandelbrot.py (text/x-python)" in result+ assert "Follow these steps:" in result+ # Body content is loaded but the file content is NOT — manifest only.+ assert "print('mandelbrot')" not in result++ def test_unknown_skill_returns_message_not_error(self):+ tool = GetLLMSkillTool(team=self.team, user=self.user)++ result, _ = _run(tool, skill_name="missing")++ assert "not found" in result+ assert "missing" in result+++class TestGetLLMSkillFileTool(BaseTest):+ def _create_skill_with_file(self) -> LLMSkill:+ skill = LLMSkill.objects.create(+ team=self.team,+ name="make-fractals",+ description="Render fractals.",+ body="body",+ created_by=self.user,+ )+ LLMSkillFile.objects.create(+ skill=skill,+ path="scripts/mandelbrot.py",+ content="print('mandelbrot')",+ content_type="text/x-python",+ )+ return skill++ def test_returns_file_content(self):+ self._create_skill_with_file()+ tool = GetLLMSkillFileTool(team=self.team, user=self.user)++ result, _ = _run(tool, skill_name="make-fractals", file_path="scripts/mandelbrot.py")++ assert "scripts/mandelbrot.py" in result+ assert "text/x-python" in result+ assert "print('mandelbrot')" in result++ def test_unknown_file_returns_message(self):+ self._create_skill_with_file()+ tool = GetLLMSkillFileTool(team=self.team, user=self.user)++ result, _ = _run(tool, skill_name="make-fractals", file_path="scripts/missing.py")++ assert "not found" in result+ assert "scripts/missing.py" in result++ def test_rejects_path_traversal(self):+ tool = GetLLMSkillFileTool(team=self.team, user=self.user)++ result, _ = _run(tool, skill_name="any", file_path="../etc/passwd")++ assert "Invalid file path" in result+++class TestCreateLLMSkillTool(BaseTest):+ def test_creates_skill_with_files(self):+ tool = CreateLLMSkillTool(team=self.team, user=self.user)++ result, _ = _run(+ tool,+ name="make-fractals",+ description="Render fractals.",+ body="# make-fractals\n\nFollow these steps.",+ files=[+ {"path": "scripts/mandelbrot.py", "content": "print('m')", "content_type": "text/x-python"},+ ],+ )++ assert "make-fractals" in result+ assert "v1" in result+ skill = LLMSkill.objects.get(team=self.team, name="make-fractals", is_latest=True)+ assert skill.description == "Render fractals."+ assert skill.files.count() == 1+ first_file = skill.files.first()+ assert first_file is not None+ assert first_file.path == "scripts/mandelbrot.py"++ def test_duplicate_name_raises_fatal(self):+ LLMSkill.objects.create(team=self.team, name="dup", description="d", body="b")++ tool = CreateLLMSkillTool(team=self.team, user=self.user)++ with self.assertRaisesRegex(MaxToolFatalError, "already exists"):+ _run(tool, name="dup", description="d2", body="b2")+++class TestUpdateLLMSkillTool(BaseTest):+ def _create_skill(self) -> LLMSkill:+ return LLMSkill.objects.create(+ team=self.team,+ name="make-fractals",+ description="Render fractals.",+ body="# Step 1\nDo a thing.\n# Step 2\nDo another.",+ created_by=self.user,+ )++ def test_full_body_replacement(self):+ existing = self._create_skill()+ tool = UpdateLLMSkillTool(team=self.team, user=self.user)++ result, _ = _run(+ tool,+ skill_name="make-fractals",+ base_version=existing.version,+ body="# brand new\nbody",+ )++ assert "v2" in result+ latest = LLMSkill.objects.get(team=self.team, name="make-fractals", is_latest=True)+ assert latest.body == "# brand new\nbody"+ assert latest.version == 2++ def test_incremental_edits(self):+ existing = self._create_skill()+ tool = UpdateLLMSkillTool(team=self.team, user=self.user)++ result, _ = _run(+ tool,+ skill_name="make-fractals",+ base_version=existing.version,+ edits=[{"old": "Do a thing.", "new": "Do the better thing."}],+ )++ assert "v2" in result+ latest = LLMSkill.objects.get(team=self.team, name="make-fractals", is_latest=True)+ assert "Do the better thing." in latest.body+ assert "Do a thing." not in latest.body++ def test_version_conflict_raises(self):+ existing = self._create_skill()+ tool = UpdateLLMSkillTool(team=self.team, user=self.user)++ with self.assertRaisesRegex(MaxToolFatalError, "modified"):+ _run(+ tool,+ skill_name="make-fractals",+ base_version=existing.version + 5,+ body="new body",+ )++ def test_body_and_edits_are_mutually_exclusive(self):+ existing = self._create_skill()+ tool = UpdateLLMSkillTool(team=self.team, user=self.user)++ with self.assertRaisesRegex(MaxToolFatalError, r"either `body` or `edits`"):+ _run(+ tool,+ skill_name="make-fractals",+ base_version=existing.version,+ body="full",+ edits=[{"old": "a", "new": "b"}],+ )+++class TestArchiveLLMSkillTool(BaseTest):+ def test_archives_all_versions(self):+ LLMSkill.objects.create(+ team=self.team, name="make-fractals", description="d", body="b1", version=1, is_latest=False+ )+ LLMSkill.objects.create(+ team=self.team, name="make-fractals", description="d", body="b2", version=2, is_latest=True+ )+ tool = ArchiveLLMSkillTool(team=self.team, user=self.user)++ result, _ = _run(tool, skill_name="make-fractals")++ assert "Archived skill 'make-fractals'" in result+ assert "2 version(s) hidden" in result+ assert LLMSkill.objects.filter(team=self.team, name="make-fractals", deleted=False).count() == 0++ def test_unknown_skill_raises_fatal(self):+ tool = ArchiveLLMSkillTool(team=self.team, user=self.user)++ with self.assertRaisesRegex(MaxToolFatalError, "missing"):+ _run(tool, skill_name="missing")