🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(skills): basic skill management (#17803)
tobi_kl8beb5be6a580
diff --git a/fern/apis/server/definition/unstable/skills.yml b/fern/apis/server/definition/unstable/skills.ymlnew file mode 100644index 0000000000..87a8ee36e4--- /dev/null+++ b/fern/apis/server/definition/unstable/skills.yml@@ -0,0 +1,183 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ pagination: ../utils/pagination.yml+service:+ auth: true+ base-path: /api/public/unstable+ endpoints:+ list:+ docs: List skills with metadata and timestamps from their latest version, shared tags, and the version assigned to production when present.+ method: GET+ path: /skills+ request:+ name: ListSkillsRequest+ query-parameters:+ name:+ type: optional<string>+ docs: Filter by exact skill name.+ search:+ type: optional<string>+ docs: Case-insensitive search across skill names and latest-version descriptions.+ tag:+ type: optional<string>+ docs: Filter by a shared skill tag.+ page: optional<integer>+ limit: optional<integer>+ fromUpdatedAt:+ type: optional<datetime>+ docs: Include skills whose latest version was updated at or after this timestamp.+ toUpdatedAt:+ type: optional<datetime>+ docs: Include skills whose latest version was updated before this timestamp.+ response: SkillMetaListResponse++ createVersion:+ docs: |+ Create skill version+ method: POST+ path: /skills+ request: CreateSkillVersionRequest+ response:+ status-code: 201+ type: SkillVersion++ get:+ docs: Resolve a skill's metadata and file manifest by version or label. Defaults to the production label. Use each file's id with getFileContent to read its text content.+ method: GET+ path: /skills/{skillName}+ path-parameters:+ skillName: string+ request:+ name: GetSkillRequest+ query-parameters:+ version: optional<integer>+ label: optional<string>+ response: SkillVersion++ update:+ docs: Replace the shared tags across all versions of a skill. An empty tags list clears all tags. Returns the latest skill version with the updated tags.+ method: PATCH+ path: /skills/{skillName}+ path-parameters:+ skillName: string+ request: UpdateSkillRequest+ response: SkillVersion++ getFileContent:+ docs: Read one text file from a persisted skill version using its file id, not its blob id. Returns JSON containing the text content with Cache-Control no-store.+ method: GET+ path: /skills/files/{fileId}/content+ path-parameters:+ fileId: string+ response: SkillFileContentResponse++ setLabels:+ docs: Replace the labels on a skill version and atomically move them from other versions.+ method: PATCH+ path: /skills/{skillName}/versions/{skillVersion}+ path-parameters:+ skillName: string+ skillVersion: integer+ request: UpdateSkillLabelsRequest+ response: SkillVersion++ deleteVersion:+ docs: Delete one immutable skill version. Unreferenced blobs are retained for asynchronous cleanup.+ method: DELETE+ path: /skills/{skillName}/versions/{skillVersion}+ path-parameters:+ skillName: string+ skillVersion: integer+ response: DeleteSkillVersionResponse++types:+ SkillMetaListResponse:+ properties:+ data: list<SkillMeta>+ meta: SkillListPagination++ SkillListPagination:+ extends: pagination.MetaResponse+ properties:+ hasNextPage: boolean++ SkillMeta:+ properties:+ name: string+ description: string+ tags: list<string>+ latestVersion: integer+ latestVersionCreatedAt: datetime+ latestVersionLastUpdatedAt: datetime+ productionVersion:+ type: nullable<integer>+ docs: Version assigned the production label, or null when no version is assigned.++ SkillVersionFileInput:+ properties:+ path: string+ content:+ type: string+ docs: UTF-8 text content. The server computes the hash and byte length.++ SkillVersionFileReference:+ properties:+ path: string+ sha256Hash:+ type: string+ docs: Canonical base64-encoded SHA-256 from a skill file manifest. The content must already exist in this project.++ SkillVersionFileCreateInput:+ docs: Provide exactly one of content or sha256Hash for each path.+ discriminated: false+ union:+ - SkillVersionFileInput+ - SkillVersionFileReference++ CreateSkillVersionRequest:+ properties:+ files: list<SkillVersionFileCreateInput>+ commitMessage: optional<nullable<string>>++ SkillFile:+ properties:+ id: string+ path: string+ blobId: string+ sha256Hash: string+ contentType: string+ contentLength: long++ SkillFileContentResponse:+ properties:+ content: string++ SkillVersion:+ properties:+ id: string+ createdAt: datetime+ updatedAt: datetime+ projectId: string+ createdBy: string+ name: string+ description: string+ frontmatter: unknown+ version: integer+ tags: list<string>+ labels: list<string>+ commitMessage: nullable<string>+ files: list<SkillFile>++ UpdateSkillRequest:+ properties:+ tags:+ type: list<string>+ docs: The complete set of tags to apply to every version of the skill. Pass an empty list to clear all tags.++ UpdateSkillLabelsRequest:+ properties:+ labels: list<string>++ DeleteSkillVersionResponse:+ properties:+ deleted: booleandiff --git a/packages/shared/prisma/migrations/20260924174440_skill_management/migration.sql b/packages/shared/prisma/migrations/20260924174440_skill_management/migration.sqlnew file mode 100644index 0000000000..a147109069--- /dev/null+++ b/packages/shared/prisma/migrations/20260924174440_skill_management/migration.sql@@ -0,0 +1,81 @@+-- CreateTable+CREATE TABLE "skills" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "created_by" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "frontmatter" JSONB NOT NULL DEFAULT '{}',+ "version" INTEGER NOT NULL,+ "tags" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "labels" TEXT[] DEFAULT ARRAY[]::TEXT[],+ "commit_message" TEXT,++ CONSTRAINT "skills_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "skill_files" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "skill_id" TEXT NOT NULL,+ "blob_id" TEXT NOT NULL,+ "path" TEXT NOT NULL,++ CONSTRAINT "skill_files_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "skill_blobs" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "sha_256_hash" CHAR(44) NOT NULL,+ "content_type" TEXT NOT NULL,+ "content_length" INTEGER NOT NULL,+ "content" TEXT NOT NULL,++ CONSTRAINT "skill_blobs_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "skills_created_at_idx" ON "skills"("created_at");++-- CreateIndex+CREATE INDEX "skills_updated_at_idx" ON "skills"("updated_at");++-- CreateIndex+CREATE INDEX "skills_tags_idx" ON "skills" USING GIN ("tags" array_ops);++-- CreateIndex+CREATE INDEX "skills_labels_idx" ON "skills" USING GIN ("labels" array_ops);++-- CreateIndex+CREATE UNIQUE INDEX "skills_project_id_name_version_key" ON "skills"("project_id", "name", "version");++-- CreateIndex+CREATE INDEX "skill_files_project_id_blob_id_idx" ON "skill_files"("project_id", "blob_id");++-- CreateIndex+CREATE UNIQUE INDEX "skill_files_project_id_skill_id_path_key" ON "skill_files"("project_id", "skill_id", "path");++-- CreateIndex+CREATE UNIQUE INDEX "skill_blobs_project_id_sha_256_hash_key" ON "skill_blobs"("project_id", "sha_256_hash");++-- AddForeignKey+ALTER TABLE "skills" ADD CONSTRAINT "skills_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "skill_files" ADD CONSTRAINT "skill_files_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "skill_files" ADD CONSTRAINT "skill_files_skill_id_fkey" FOREIGN KEY ("skill_id") REFERENCES "skills"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "skill_files" ADD CONSTRAINT "skill_files_blob_id_fkey" FOREIGN KEY ("blob_id") REFERENCES "skill_blobs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "skill_blobs" ADD CONSTRAINT "skill_blobs_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 0abf3fe4fb..ac463e5545 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -150,6 +150,9 @@ model Project {invitations MembershipInvitation[]sessions TraceSession[]Prompt Prompt[]+ Skill Skill[]+ SkillFile SkillFile[]+ SkillBlob SkillBlob[]Model Model[]EvalTemplate EvalTemplate[]JobConfiguration JobConfiguration[]@@ -841,6 +844,70 @@ model PromptProtectedLabels {@@map("prompt_protected_labels")}+model Skill {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ createdBy String @map("created_by")+ name String+ description String+ frontmatter Json @default("{}")+ version Int+ tags String[] @default([])+ labels String[] @default([])+ commitMessage String? @map("commit_message")+ files SkillFile[]++ @@unique([projectId, name, version])+ @@index([createdAt])+ @@index([updatedAt])+ @@index([tags(ops: ArrayOps)], type: Gin)+ @@index([labels(ops: ArrayOps)], type: Gin)+ @@map("skills")+}++model SkillFile {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ skillId String @map("skill_id")+ skill Skill @relation(fields: [skillId], references: [id], onDelete: Cascade)++ blobId String @map("blob_id")+ blob SkillBlob @relation(fields: [blobId], references: [id], onDelete: Restrict)++ path String++ @@unique([projectId, skillId, path])+ @@index([projectId, blobId])+ @@map("skill_files")+}++model SkillBlob {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ sha256Hash String @map("sha_256_hash") @db.Char(44)+ contentType String @map("content_type")+ contentLength Int @map("content_length")+ content String @db.Text++ files SkillFile[]++ @@unique([projectId, sha256Hash])+ @@map("skill_blobs")+}+// Update ObservationView below when making changes to this model!model Model {id String @id @default(cuid())diff --git a/packages/shared/src/features/rbac/projectAccessRights.ts b/packages/shared/src/features/rbac/projectAccessRights.tsindex f1aa73e65b..1c9aa09289 100644--- a/packages/shared/src/features/rbac/projectAccessRights.ts+++ b/packages/shared/src/features/rbac/projectAccessRights.ts@@ -36,6 +36,9 @@ export const projectScopes = ["prompts:read","promptProtectedLabels:CUD",+ "skills:CUD",+ "skills:read",+"dashboards:read","dashboards:CUD",@@ -121,6 +124,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"prompts:CUD","prompts:read","promptProtectedLabels:CUD",+ "skills:CUD",+ "skills:read","models:CUD","evaluator:CUD","evaluator:read",@@ -178,6 +183,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"prompts:CUD","prompts:read","promptProtectedLabels:CUD",+ "skills:CUD",+ "skills:read","models:CUD","evaluator:CUD","evaluator:read",@@ -229,6 +236,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"datasets:CUD","prompts:CUD","prompts:read",+ "skills:CUD",+ "skills:read","evaluator:CUD","evaluator:read","evaluationRule:read",@@ -262,6 +271,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {VIEWER: ["project:read","prompts:read",+ "skills:read","evaluator:read","scoreConfigs:read","evaluationRule:read",diff --git a/packages/shared/src/features/skills/constants.ts b/packages/shared/src/features/skills/constants.tsnew file mode 100644index 0000000000..e7ef695f1f--- /dev/null+++ b/packages/shared/src/features/skills/constants.ts@@ -0,0 +1,5 @@+export const SKILL_LATEST_LABEL = "latest";+export const SKILL_PRODUCTION_LABEL = "production";+export const MAX_SKILL_FILES = 200;+export const MAX_SKILL_PATH_LENGTH = 512;+export const MAX_SKILL_BYTES = 1_000_000;diff --git a/packages/shared/src/features/skills/types.ts b/packages/shared/src/features/skills/types.tsnew file mode 100644index 0000000000..6b8f9722ad--- /dev/null+++ b/packages/shared/src/features/skills/types.ts@@ -0,0 +1,301 @@+import { z } from "zod/v4";+import { jsonSchema } from "../../utils/zod";+import { PromptLabelSchema } from "../prompts/types";+import { COMMIT_MESSAGE_MAX_LENGTH } from "../prompts/constants";+import {+ MAX_SKILL_FILES,+ MAX_SKILL_BYTES,+ MAX_SKILL_PATH_LENGTH,+ SKILL_LATEST_LABEL,+} from "./constants";++export const SkillNameSchema = z+ .string()+ .trim()+ .min(1)+ .max(64)+ .regex(+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/,+ "Skill names may only contain lowercase letters, numbers, and single hyphens",+ );++export const SkillDescriptionSchema = z.string().trim().min(1).max(1024);++export const SkillFilePathSchema = z+ .string()+ .min(1)+ .max(MAX_SKILL_PATH_LENGTH)+ .superRefine((path, ctx) => {+ const segments = path.split("/");+ const hasControlCharacters = [...path].some((character) => {+ const code = character.charCodeAt(0);+ return code <= 31 || code === 127;+ });+ if (+ path.startsWith("/") ||+ path.endsWith("/") ||+ path.includes("\\") ||+ hasControlCharacters ||+ segments.some(+ (segment) => segment === "" || segment === "." || segment === "..",+ )+ ) {+ ctx.addIssue({+ code: "custom",+ message: "File paths must be normalized relative POSIX paths",+ });+ }+ });++export const SkillFileContentSchema = z+ .string()+ .transform((content) => content.replace(/^\uFEFF+/, ""))+ .superRefine((content, ctx) => {+ if (content.includes("\0")) {+ ctx.addIssue({+ code: "custom",+ message: "Skill files must not contain NUL characters",+ });+ }+ if (!content.isWellFormed()) {+ ctx.addIssue({+ code: "custom",+ message: "Skill files must contain well-formed Unicode text",+ });+ }+ if (new TextEncoder().encode(content).byteLength > MAX_SKILL_BYTES) {+ ctx.addIssue({+ code: "custom",+ message: `Skill files must not exceed ${MAX_SKILL_BYTES} UTF-8 bytes`,+ });+ }+ });++const SKILL_TEXT_FILE_EXTENSIONS = new Set([+ "md",+ "markdown",+ "mdx",+ "txt",+ "rst",+ "adoc",+ "json",+ "jsonc",+ "jsonl",+ "ndjson",+ "yaml",+ "yml",+ "toml",+ "xml",+ "csv",+ "tsv",+ "ini",+ "cfg",+ "conf",+ "properties",+ "log",+ "html",+ "htm",+ "css",+ "scss",+ "sass",+ "less",+ "js",+ "jsx",+ "mjs",+ "cjs",+ "ts",+ "tsx",+ "py",+ "pyi",+ "sh",+ "bash",+ "zsh",+ "fish",+ "ps1",+ "rb",+ "go",+ "rs",+ "java",+ "c",+ "h",+ "cc",+ "cpp",+ "hpp",+ "cs",+ "swift",+ "kt",+ "kts",+ "lua",+ "r",+ "pl",+ "php",+ "sql",+ "graphql",+ "gql",+ "tex",+]);++const SkillTextFilePathSchema = SkillFilePathSchema.refine((path) => {+ const filename = path.split("/").at(-1)!;+ const extension = filename.includes(".")+ ? filename.split(".").at(-1)!.toLowerCase()+ : "";+ return SKILL_TEXT_FILE_EXTENSIONS.has(extension);+}, "Skill files must use a supported text file extension");++export const SkillVersionFileInputSchema = z.object({+ path: SkillTextFilePathSchema,+ content: SkillFileContentSchema,+ sha256Hash: z.never().optional(),+});++export const SkillVersionFileReferenceSchema = z.object({+ path: SkillTextFilePathSchema,+ sha256Hash: z+ .string()+ .regex(+ /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/,+ "Must be a canonical base64 encoded SHA-256 hash",+ ),+ content: z.never().optional(),+});++export const SkillTagsSchema = z+ .array(z.string().trim().min(1).max(100))+ .max(50);++export const CreateSkillVersionBodySchema = z+ .object({+ files: z+ .array(+ z.union([SkillVersionFileInputSchema, SkillVersionFileReferenceSchema]),+ )+ .min(1)+ .max(MAX_SKILL_FILES),+ commitMessage: z.string().max(COMMIT_MESSAGE_MAX_LENGTH).nullish(),+ })+ .superRefine(({ files }, ctx) => {+ if (+ files.reduce(+ (total, file) =>+ total ++ (file.content !== undefined+ ? new TextEncoder().encode(file.content).byteLength+ : 0),+ 0,+ ) > MAX_SKILL_BYTES+ ) {+ ctx.addIssue({+ code: "custom",+ path: ["files"],+ message: `A skill must not exceed ${MAX_SKILL_BYTES} UTF-8 bytes in total`,+ });+ }+ const paths = files.map((file) => file.path);+ if (new Set(paths).size !== paths.length) {+ ctx.addIssue({+ code: "custom",+ path: ["files"],+ message: "Skill file paths must be unique",+ });+ }+ if (!paths.includes("SKILL.md")) {+ ctx.addIssue({+ code: "custom",+ path: ["files"],+ message: "Every skill version must contain a root SKILL.md file",+ });+ }+ });++export const SkillSelectorSchema = z+ .object({+ version: z.coerce.number().int().positive().optional(),+ label: PromptLabelSchema.optional(),+ })+ .refine(({ version, label }) => !(version && label), {+ message: "Specify either version or label, not both",+ });++export const ListSkillsQuerySchema = z.object({+ name: SkillNameSchema.optional(),+ search: z.string().max(1000).optional(),+ tag: z.string().optional(),+ page: z.coerce.number().int().min(1).default(1),+ limit: z.coerce.number().int().min(1).max(100).default(10),+ fromUpdatedAt: z.iso.datetime({ offset: true }).optional(),+ toUpdatedAt: z.iso.datetime({ offset: true }).optional(),+});++export const UpdateSkillLabelsBodySchema = z.object({+ labels: z+ .array(PromptLabelSchema)+ .refine((labels) => !labels.includes(SKILL_LATEST_LABEL), {+ message: `The '${SKILL_LATEST_LABEL}' label is managed by Langfuse`,+ }),+});++export const UpdateSkillTagsBodySchema = z.object({+ tags: SkillTagsSchema,+});++export const SkillFileSchema = z.object({+ id: z.string(),+ path: SkillFilePathSchema,+ blobId: z.string(),+ sha256Hash: z.string(),+ contentType: z.string(),+ contentLength: z.number().int(),+});++export const SkillFileContentResponseSchema = z.object({+ content: z.string(),+});++export const SkillVersionSchema = z.object({+ id: z.string(),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ projectId: z.string(),+ createdBy: z.string(),+ name: SkillNameSchema,+ description: SkillDescriptionSchema,+ frontmatter: jsonSchema,+ version: z.number().int().positive(),+ tags: z.array(z.string()),+ labels: z.array(PromptLabelSchema),+ commitMessage: z.string().nullable(),+ files: z.array(SkillFileSchema),+});++export const SkillMetaSchema = z.object({+ name: SkillNameSchema,+ description: SkillDescriptionSchema,+ tags: z.array(z.string()),+ latestVersion: z.number().int().positive(),+ latestVersionCreatedAt: z.coerce.date(),+ latestVersionLastUpdatedAt: z.coerce.date(),+ productionVersion: z.number().int().positive().nullable(),+});++export const ListSkillsResponseSchema = z.object({+ data: z.array(SkillMetaSchema),+ meta: z.object({+ page: z.number().int(),+ limit: z.number().int(),+ totalItems: z.number().int(),+ totalPages: z.number().int(),+ hasNextPage: z.boolean(),+ }),+});++export const DeleteSkillVersionResponseSchema = z.object({+ deleted: z.boolean(),+});++export type CreateSkillVersionBody = z.infer<+ typeof CreateSkillVersionBodySchema+>;+export type SkillSelector = z.infer<typeof SkillSelectorSchema>;+export type ListSkillsQuery = z.infer<typeof ListSkillsQuerySchema>;+export type SkillVersionResponse = z.infer<typeof SkillVersionSchema>;diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 9497bf09a5..a92b7ebd9e 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -96,6 +96,11 @@ export * from "./features/prompts/parsePromptDependencyTags";export * from "./features/prompts/validation";export * from "./features/prompts/types";export * from "./features/prompts/constants";++// skills+export * from "./features/skills/types";+export * from "./features/skills/constants";+export {compileChatMessages,compileChatMessagesWithIds,diff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.jsonindex 8c15f96908..6d0e8bb41c 100644--- a/packages/shared/tsconfig.json+++ b/packages/shared/tsconfig.json@@ -4,7 +4,7 @@"jsx": "react","moduleResolution": "NodeNext","module": "NodeNext",- "lib": ["es2023"],+ "lib": ["es2024"],"outDir": "./dist","types": ["node"],"target": "es2024",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1652a146d6..2b768ea561 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -532,6 +532,9 @@ importers:'@codemirror/language':specifier: ^6.12.3version: 6.12.3+ '@codemirror/legacy-modes':+ specifier: ^6.5.4+ version: 6.5.4'@codemirror/lint':specifier: ^6.9.5version: 6.9.6@@ -781,6 +784,9 @@ importers:fastest-levenshtein:specifier: ^1.0.16version: 1.0.16+ fflate:+ specifier: 0.8.3+ version: 0.8.3https-proxy-agent:specifier: ^7.0.6version: 7.0.6([email protected])@@ -1920,6 +1926,9 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew==}+'@codemirror/[email protected]':resolution: {integrity: sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==}@@ -13742,6 +13751,10 @@ snapshots:'@lezer/lr': 1.4.8style-mod: 4.1.3+ '@codemirror/[email protected]':+ dependencies:+ '@codemirror/language': 6.12.3+'@codemirror/[email protected]':dependencies:'@codemirror/state': 6.6.0@@ -20513,17 +20526,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected])([email protected]))([email protected]):- dependencies:- debug: 3.2.7([email protected])- optionalDependencies:- '@typescript-eslint/parser': 8.67.0([email protected]([email protected])([email protected]))([email protected])([email protected])- eslint: 10.8.0([email protected])([email protected])- eslint-import-resolver-node: 0.3.10([email protected])- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected])([email protected]))([email protected])- transitivePeerDependencies:- - supports-color-[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected])([email protected]))([email protected]):dependencies:debug: 3.2.7([email protected])@@ -20585,35 +20587,6 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected]([email protected])([email protected]))([email protected]):- dependencies:- '@rtsao/scc': 1.1.0- array-includes: 3.1.9- array.prototype.findlastindex: 1.2.6- array.prototype.flat: 1.3.3- array.prototype.flatmap: 1.3.3- debug: 3.2.7([email protected])- doctrine: 2.1.0- eslint: 10.8.0([email protected])([email protected])- eslint-import-resolver-node: 0.3.10([email protected])- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]([email protected])([email protected]))([email protected])- hasown: 2.0.4- is-core-module: 2.16.2- is-glob: 4.0.3- minimatch: 3.1.5- object.fromentries: 2.0.8- object.groupby: 1.0.3- object.values: 1.2.1- semver: 6.3.1- string.prototype.trimend: 1.0.9- tsconfig-paths: 3.15.0- optionalDependencies:- '@typescript-eslint/parser': 8.67.0([email protected]([email protected])([email protected]))([email protected])([email protected])- transitivePeerDependencies:- - eslint-import-resolver-typescript- - eslint-import-resolver-webpack- - supports-color-dependencies:aria-query: 5.3.2diff --git a/web/package.json b/web/package.jsonindex bf1e6bbd0d..bb90a409fa 100644--- a/web/package.json+++ b/web/package.json@@ -47,6 +47,7 @@"@codemirror/lang-json": "^6.0.2","@codemirror/lang-python": "^6.2.1","@codemirror/language": "^6.12.3",+ "@codemirror/legacy-modes": "^6.5.4","@codemirror/lint": "^6.9.5","@codemirror/search": "^6.7.0","@codemirror/state": "^6.6.0",@@ -130,6 +131,7 @@"elkjs": "^0.11.1","exponential-backoff": "^3.1.2","fastest-levenshtein": "^1.0.16",+ "fflate": "0.8.3","https-proxy-agent": "^7.0.6","ioredis": "^5.10.1","json-schema-faker": "0.6.1",diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 1d7eedfbfa..29a6bcef8e 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -8727,6 +8727,418 @@ paths:schema:$ref: '#/components/schemas/unstablePublicApiError'security: *ref_0+ /api/public/unstable/skills:+ get:+ description: >-+ List skills with metadata and timestamps from their latest version,+ shared tags, and the version assigned to production when present.+ operationId: unstable_skills_list+ tags:+ - UnstableSkills+ parameters:+ - name: name+ in: query+ description: Filter by exact skill name.+ required: false+ schema:+ type: string+ nullable: true+ - name: search+ in: query+ description: >-+ Case-insensitive search across skill names and latest-version+ descriptions.+ required: false+ schema:+ type: string+ nullable: true+ - name: tag+ in: query+ description: Filter by a shared skill tag.+ required: false+ schema:+ type: string+ nullable: true+ - name: page+ in: query+ required: false+ schema:+ type: integer+ nullable: true+ - name: limit+ in: query+ required: false+ schema:+ type: integer+ nullable: true+ - name: fromUpdatedAt+ in: query+ description: >-+ Include skills whose latest version was updated at or after this+ timestamp.+ required: false+ schema:+ type: string+ format: date-time+ nullable: true+ - name: toUpdatedAt+ in: query+ description: >-+ Include skills whose latest version was updated before this+ timestamp.+ required: false+ schema:+ type: string+ format: date-time+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillMetaListResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ post:+ description: Create skill version+ operationId: unstable_skills_createVersion+ tags:+ - UnstableSkills+ parameters: []+ responses:+ '201':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillVersion'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableCreateSkillVersionRequest'+ /api/public/unstable/skills/{skillName}:+ get:+ description: >-+ Resolve a skill's metadata and file manifest by version or label.+ Defaults to the production label. Use each file's id with getFileContent+ to read its text content.+ operationId: unstable_skills_get+ tags:+ - UnstableSkills+ parameters:+ - name: skillName+ in: path+ required: true+ schema:+ type: string+ - name: version+ in: query+ required: false+ schema:+ type: integer+ nullable: true+ - name: label+ in: query+ required: false+ schema:+ type: string+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillVersion'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ patch:+ description: >-+ Replace the shared tags across all versions of a skill. An empty tags+ list clears all tags. Returns the latest skill version with the updated+ tags.+ operationId: unstable_skills_update+ tags:+ - UnstableSkills+ parameters:+ - name: skillName+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillVersion'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableUpdateSkillRequest'+ /api/public/unstable/skills/files/{fileId}/content:+ get:+ description: >-+ Read one text file from a persisted skill version using its file id, not+ its blob id. Returns JSON containing the text content with Cache-Control+ no-store.+ operationId: unstable_skills_getFileContent+ tags:+ - UnstableSkills+ parameters:+ - name: fileId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillFileContentResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ /api/public/unstable/skills/{skillName}/versions/{skillVersion}:+ patch:+ description: >-+ Replace the labels on a skill version and atomically move them from+ other versions.+ operationId: unstable_skills_setLabels+ tags:+ - UnstableSkills+ parameters:+ - name: skillName+ in: path+ required: true+ schema:+ type: string+ - name: skillVersion+ in: path+ required: true+ schema:+ type: integer+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableSkillVersion'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableUpdateSkillLabelsRequest'+ delete:+ description: >-+ Delete one immutable skill version. Unreferenced blobs are retained for+ asynchronous cleanup.+ operationId: unstable_skills_deleteVersion+ tags:+ - UnstableSkills+ parameters:+ - name: skillName+ in: path+ required: true+ schema:+ type: string+ - name: skillVersion+ in: path+ required: true+ schema:+ type: integer+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableDeleteSkillVersionResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security: *ref_0components:schemas:AnnotationQueueStatus:@@ -17355,6 +17767,223 @@ components:required:- message- code+ unstableSkillMetaListResponse:+ title: unstableSkillMetaListResponse+ type: object+ properties:+ data:+ type: array+ items:+ $ref: '#/components/schemas/unstableSkillMeta'+ meta:+ $ref: '#/components/schemas/unstableSkillListPagination'+ required:+ - data+ - meta+ unstableSkillListPagination:+ title: unstableSkillListPagination+ type: object+ properties:+ hasNextPage:+ type: boolean+ required:+ - hasNextPage+ allOf:+ - $ref: '#/components/schemas/utilsMetaResponse'+ unstableSkillMeta:+ title: unstableSkillMeta+ type: object+ properties:+ name:+ type: string+ description:+ type: string+ tags:+ type: array+ items:+ type: string+ latestVersion:+ type: integer+ latestVersionCreatedAt:+ type: string+ format: date-time+ latestVersionLastUpdatedAt:+ type: string+ format: date-time+ productionVersion:+ type: integer+ nullable: true+ description: >-+ Version assigned the production label, or null when no version is+ assigned.+ required:+ - name+ - description+ - tags+ - latestVersion+ - latestVersionCreatedAt+ - latestVersionLastUpdatedAt+ - productionVersion+ unstableSkillVersionFileInput:+ title: unstableSkillVersionFileInput+ type: object+ properties:+ path:+ type: string+ content:+ type: string+ description: UTF-8 text content. The server computes the hash and byte length.+ required:+ - path+ - content+ unstableSkillVersionFileReference:+ title: unstableSkillVersionFileReference+ type: object+ properties:+ path:+ type: string+ sha256Hash:+ type: string+ description: >-+ Canonical base64-encoded SHA-256 from a skill file manifest. The+ content must already exist in this project.+ required:+ - path+ - sha256Hash+ unstableSkillVersionFileCreateInput:+ title: unstableSkillVersionFileCreateInput+ oneOf:+ - $ref: '#/components/schemas/unstableSkillVersionFileInput'+ - $ref: '#/components/schemas/unstableSkillVersionFileReference'+ description: Provide exactly one of content or sha256Hash for each path.+ unstableCreateSkillVersionRequest:+ title: unstableCreateSkillVersionRequest+ type: object+ properties:+ files:+ type: array+ items:+ $ref: '#/components/schemas/unstableSkillVersionFileCreateInput'+ commitMessage:+ type: string+ nullable: true+ required:+ - files+ unstableSkillFile:+ title: unstableSkillFile+ type: object+ properties:+ id:+ type: string+ path:+ type: string+ blobId:+ type: string+ sha256Hash:+ type: string+ contentType:+ type: string+ contentLength:+ type: integer+ format: int64+ required:+ - id+ - path+ - blobId+ - sha256Hash+ - contentType+ - contentLength+ unstableSkillFileContentResponse:+ title: unstableSkillFileContentResponse+ type: object+ properties:+ content:+ type: string+ required:+ - content+ unstableSkillVersion:+ title: unstableSkillVersion+ type: object+ properties:+ id:+ type: string+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-time+ projectId:+ type: string+ createdBy:+ type: string+ name:+ type: string+ description:+ type: string+ frontmatter: {}+ version:+ type: integer+ tags:+ type: array+ items:+ type: string+ labels:+ type: array+ items:+ type: string+ commitMessage:+ type: string+ nullable: true+ files:+ type: array+ items:+ $ref: '#/components/schemas/unstableSkillFile'+ required:+ - id+ - createdAt+ - updatedAt+ - projectId+ - createdBy+ - name+ - description+ - frontmatter+ - version+ - tags+ - labels+ - commitMessage+ - files+ unstableUpdateSkillRequest:+ title: unstableUpdateSkillRequest+ type: object+ properties:+ tags:+ type: array+ items:+ type: string+ description: >-+ The complete set of tags to apply to every version of the skill.+ Pass an empty list to clear all tags.+ required:+ - tags+ unstableUpdateSkillLabelsRequest:+ title: unstableUpdateSkillLabelsRequest+ type: object+ properties:+ labels:+ type: array+ items:+ type: string+ required:+ - labels+ unstableDeleteSkillVersionResponse:+ title: unstableDeleteSkillVersionResponse+ type: object+ properties:+ deleted:+ type: boolean+ required:+ - deletedutilsMetaResponse:title: utilsMetaResponsetype: objectdiff --git a/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snapindex e5302b88d2..68d643bb04 100644--- a/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap+++ b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap@@ -128,6 +128,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do"DELETE unstable/dashboards/[dashboardId]/placements/[placementId] | org/bearer": 401,"DELETE unstable/dashboards/[dashboardId]/placements/[placementId] | project/basic": 404,"DELETE unstable/dashboards/[dashboardId]/placements/[placementId] | project/bearer": 403,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | admin/admin": 401,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | agent/basic": 401,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | agent/bearer": 401,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | org/basic": 403,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | org/bearer": 401,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | project/basic": 400,+ "DELETE unstable/skills/[skillName]/versions/[skillVersion] | project/bearer": 403,"DELETE v2/evaluation-rules/[evaluationRuleId] | admin/admin": 401,"DELETE v2/evaluation-rules/[evaluationRuleId] | agent/basic": 401,"DELETE v2/evaluation-rules/[evaluationRuleId] | agent/bearer": 401,@@ -492,6 +499,27 @@ exports[`public-api auth parity > legacy matches the captured baseline except do"GET unstable/dashboards/index | org/bearer": 401,"GET unstable/dashboards/index | project/basic": 200,"GET unstable/dashboards/index | project/bearer": 403,+ "GET unstable/skills/[skillName]/index | admin/admin": 401,+ "GET unstable/skills/[skillName]/index | agent/basic": 401,+ "GET unstable/skills/[skillName]/index | agent/bearer": 401,+ "GET unstable/skills/[skillName]/index | org/basic": 403,+ "GET unstable/skills/[skillName]/index | org/bearer": 401,+ "GET unstable/skills/[skillName]/index | project/basic": 404,+ "GET unstable/skills/[skillName]/index | project/bearer": 403,+ "GET unstable/skills/files/[fileId]/content | admin/admin": 401,+ "GET unstable/skills/files/[fileId]/content | agent/basic": 401,+ "GET unstable/skills/files/[fileId]/content | agent/bearer": 401,+ "GET unstable/skills/files/[fileId]/content | org/basic": 403,+ "GET unstable/skills/files/[fileId]/content | org/bearer": 401,+ "GET unstable/skills/files/[fileId]/content | project/basic": 404,+ "GET unstable/skills/files/[fileId]/content | project/bearer": 403,+ "GET unstable/skills/index | admin/admin": 401,+ "GET unstable/skills/index | agent/basic": 401,+ "GET unstable/skills/index | agent/bearer": 401,+ "GET unstable/skills/index | org/basic": 403,+ "GET unstable/skills/index | org/bearer": 401,+ "GET unstable/skills/index | project/basic": 200,+ "GET unstable/skills/index | project/bearer": 403,"GET v2/datasets/[datasetName]/index | admin/admin": 401,"GET v2/datasets/[datasetName]/index | agent/basic": 401,"GET v2/datasets/[datasetName]/index | agent/bearer": 401,@@ -653,6 +681,20 @@ exports[`public-api auth parity > legacy matches the captured baseline except do"PATCH unstable/dashboards/[dashboardId]/placements/[placementId] | org/bearer": 401,"PATCH unstable/dashboards/[dashboardId]/placements/[placementId] | project/basic": 400,"PATCH unstable/dashboards/[dashboardId]/placements/[placementId] | project/bearer": 403,+ "PATCH unstable/skills/[skillName]/index | admin/admin": 401,+ "PATCH unstable/skills/[skillName]/index | agent/basic": 401,+ "PATCH unstable/skills/[skillName]/index | agent/bearer": 401,+ "PATCH unstable/skills/[skillName]/index | org/basic": 403,+ "PATCH unstable/skills/[skillName]/index | org/bearer": 401,+ "PATCH unstable/skills/[skillName]/index | project/basic": 400,+ "PATCH unstable/skills/[skillName]/index | project/bearer": 403,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | admin/admin": 401,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | agent/basic": 401,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | agent/bearer": 401,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | org/basic": 403,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | org/bearer": 401,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | project/basic": 400,+ "PATCH unstable/skills/[skillName]/versions/[skillVersion] | project/bearer": 403,"PATCH v2/evaluation-rules/[evaluationRuleId] | admin/admin": 401,"PATCH v2/evaluation-rules/[evaluationRuleId] | agent/basic": 401,"PATCH v2/evaluation-rules/[evaluationRuleId] | agent/bearer": 401,@@ -853,6 +895,13 @@ exports[`public-api auth parity > legacy matches the captured baseline except do"POST unstable/dashboards/index | org/bearer": 401,"POST unstable/dashboards/index | project/basic": 400,"POST unstable/dashboards/index | project/bearer": 403,+ "POST unstable/skills/index | admin/admin": 401,+ "POST unstable/skills/index | agent/basic": 401,+ "POST unstable/skills/index | agent/bearer": 401,+ "POST unstable/skills/index | org/basic": 403,+ "POST unstable/skills/index | org/bearer": 401,+ "POST unstable/skills/index | project/basic": 400,+ "POST unstable/skills/index | project/bearer": 403,"POST v2/datasets/index | admin/admin": 401,"POST v2/datasets/index | agent/basic": 401,"POST v2/datasets/index | agent/bearer": 401,diff --git a/web/src/__tests__/server/public-api-auth-parity.servertest.ts b/web/src/__tests__/server/public-api-auth-parity.servertest.tsindex dca012a9f6..f9fd6b2324 100644--- a/web/src/__tests__/server/public-api-auth-parity.servertest.ts+++ b/web/src/__tests__/server/public-api-auth-parity.servertest.ts@@ -118,6 +118,13 @@ const projectRoutes: Route[] = [route: "v2/prompts/[promptName]/versions/[promptVersion]",methods: ["PATCH"],},+ { route: "unstable/skills/index", methods: ["GET", "POST"] },+ { route: "unstable/skills/[skillName]/index", methods: ["GET", "PATCH"] },+ {+ route: "unstable/skills/[skillName]/versions/[skillVersion]",+ methods: ["PATCH", "DELETE"],+ },+ { route: "unstable/skills/files/[fileId]/content", methods: ["GET"] },];// Org and misc routes call shadowAuth directly from the handler body.diff --git a/web/src/__tests__/server/unit/in-app-agent-mcp-policy.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-mcp-policy.servertest.tsindex eff9ea03dc..83c945933a 100644--- a/web/src/__tests__/server/unit/in-app-agent-mcp-policy.servertest.ts+++ b/web/src/__tests__/server/unit/in-app-agent-mcp-policy.servertest.ts@@ -9,8 +9,15 @@ import {type McpToolName,} from "@/src/features/mcp/server/bootstrap";import { toolRegistry } from "@/src/features/mcp/server/registry";+import { skillsFeature } from "@/src/features/mcp/server/skills";describe("IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES", () => {+ it("keeps Skills MCP tools unregistered", () => {+ for (const { definition } of skillsFeature.tools) {+ expect(toolRegistry.getTool(definition.name)).toBeUndefined();+ }+ });+it("classifies every Langfuse MCP tool exactly once", () => {expect(bootstrapMcpFeatures).toBeTypeOf("function");expectTypeOf<InAppAgentLangfuseMcpToolName>().toEqualTypeOf<McpToolName>();diff --git a/web/src/__tests__/server/unit/skill-router.servertest.ts b/web/src/__tests__/server/unit/skill-router.servertest.tsnew file mode 100644index 0000000000..54f5c26c66--- /dev/null+++ b/web/src/__tests__/server/unit/skill-router.servertest.ts@@ -0,0 +1,216 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { skillRouter } from "@/src/features/skills/server/skill-router";+import { createInnerTRPCContext } from "@/src/server/api/trpc";++const mocks = vi.hoisted(() => ({+ get: vi.fn(),+ getFileContent: vi.fn(),+ createVersion: vi.fn(),+ setLabels: vi.fn(),+ setTags: vi.fn(),+ deleteVersion: vi.fn(),+ deleteSkill: vi.fn(),+ list: vi.fn(),+ filterOptions: vi.fn(),+ skillVersions: vi.fn(),+ findUsers: vi.fn(),+}));++vi.mock("@/src/server/auth", () => ({ getServerAuthSession: vi.fn() }));+vi.mock("@/src/features/posthog-analytics/server/backendActivity", () => ({+ recordBackendActivity: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@/src/features/skills/server/index", () => ({+ SkillService: class {+ get = mocks.get;+ getFileContent = mocks.getFileContent;+ createVersion = mocks.createVersion;+ setLabels = mocks.setLabels;+ setTags = mocks.setTags;+ deleteVersion = mocks.deleteVersion;+ deleteSkill = mocks.deleteSkill;+ list = mocks.list;+ filterOptions = mocks.filterOptions;+ skillVersions = mocks.skillVersions;+ },+}));++function createCaller(+ role: "ADMIN" | "MEMBER" | "VIEWER",+ projectId = "project",+) {+ const session: Session = {+ expires: "1",+ user: {+ id: "user",+ canCreateOrganizations: false,+ admin: false,+ organizations: [+ {+ id: "organization",+ name: "Organization",+ role,+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,+ projects: [+ {+ id: projectId,+ name: "Project",+ role,+ retentionDays: 30,+ deletedAt: null,+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,+ },+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: "cloud:hobby",+ },+ };++ return skillRouter.createCaller(+ createInnerTRPCContext({ session, headers: {} }),+ );+}++type Caller = ReturnType<typeof createCaller>;+const version = { projectId: "project", name: "my-skill", version: 1 };+const mutations = [+ {+ name: "delete a whole skill",+ mutate: (caller: Caller) =>+ caller.deleteSkill({ projectId: "project", name: "my-skill" }),+ write: mocks.deleteSkill,+ params: { projectId: "project", name: "my-skill" },+ },+ {+ name: "set labels",+ mutate: (caller: Caller) =>+ caller.setLabels({ ...version, labels: ["production"] }),+ write: mocks.setLabels,+ params: { ...version, labels: ["production"] },+ },+ {+ name: "delete a version",+ mutate: (caller: Caller) => caller.deleteVersion(version),+ write: mocks.deleteVersion,+ params: version,+ },+];++describe("skill mutation router", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(prisma.user, "findMany").mockImplementation(mocks.findUsers);+ mocks.createVersion.mockResolvedValue({ version: 1 });+ mocks.setLabels.mockResolvedValue({ version: 1 });+ mocks.setTags.mockResolvedValue({ version: 1 });+ mocks.deleteVersion.mockResolvedValue(undefined);+ mocks.skillVersions.mockResolvedValue({ items: [], nextCursor: undefined });+ mocks.findUsers.mockResolvedValue([]);+ });++ afterEach(() => vi.restoreAllMocks());++ it("validates bounded version history and checks project access", async () => {+ const caller = createCaller("VIEWER");+ const input = { projectId: "project", name: "my-skill" };+ await caller.skillVersions(input);+ expect(mocks.skillVersions).toHaveBeenCalledExactlyOnceWith({+ ...input,+ limit: 20,+ });++ for (const pagination of [+ { limit: 0 },+ { limit: 101 },+ { cursor: 0 },+ { cursor: 1.5 },+ ]) {+ await expect(+ caller.skillVersions({ ...input, ...pagination }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ }+ await expect(+ createCaller("ADMIN", "other-project").skillVersions(input),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });+ expect(mocks.skillVersions).toHaveBeenCalledOnce();+ });++ it.each(mutations)(+ "rejects a VIEWER trying to $name",+ async ({ mutate, write }) => {+ await expect(mutate(createCaller("VIEWER"))).rejects.toMatchObject({+ code: "FORBIDDEN",+ });+ expect(write).not.toHaveBeenCalled();+ },+ );++ it.each(mutations)(+ "passes the authenticated session to the service to $name",+ async ({ mutate, write, params }) => {+ await mutate(createCaller("MEMBER"));++ expect(write).toHaveBeenCalledExactlyOnceWith({+ ...params,+ actor: {+ session: expect.objectContaining({+ user: expect.objectContaining({ id: "user" }),+ }),+ },+ });+ expect(mocks.get).not.toHaveBeenCalled();+ },+ );++ it("rejects access to another project before calling the service", async () => {+ await expect(+ createCaller("ADMIN", "other-project").deleteVersion(version),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });++ expect(mocks.get).not.toHaveBeenCalled();+ expect(mocks.deleteVersion).not.toHaveBeenCalled();+ });++ it("rejects deleting a whole skill in another project", async () => {+ await expect(+ createCaller("ADMIN", "other-project").deleteSkill({+ projectId: "project",+ name: "my-skill",+ }),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });+ expect(mocks.deleteSkill).not.toHaveBeenCalled();+ });++ it("scopes filter options to the authenticated project", async () => {+ await createCaller("VIEWER").filterOptions({ projectId: "project" });+ expect(mocks.filterOptions).toHaveBeenCalledExactlyOnceWith({+ projectId: "project",+ });+ await expect(+ createCaller("ADMIN", "other-project").filterOptions({+ projectId: "project",+ }),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });+ expect(mocks.filterOptions).toHaveBeenCalledOnce();+ });+});diff --git a/web/src/__tests__/server/unit/skill-service.servertest.ts b/web/src/__tests__/server/unit/skill-service.servertest.tsnew file mode 100644index 0000000000..8985b500cf--- /dev/null+++ b/web/src/__tests__/server/unit/skill-service.servertest.ts@@ -0,0 +1,548 @@+import { createHash } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ProjectAuthedContext } from "@/src/server/api/trpc";+import type { PrismaClient } from "@langfuse/shared/src/db";+import { SkillService } from "@/src/features/skills/server/skill-service";+import { auditLog } from "@/src/features/audit-logs/server";++vi.mock("@/src/features/audit-logs/server", () => ({+ auditLog: vi.fn(),+}));++describe("SkillService versions", () => {+ beforeEach(() => vi.clearAllMocks());++ function sessionActor(role: "ADMIN" | "MEMBER") {+ return {+ session: {+ user: {+ admin: false,+ organizations: [{ projects: [{ id: "project", role }] }],+ },+ } as ProjectAuthedContext["session"],+ };+ }++ function setup() {+ const markdown =+ "---\nname: test-skill\ndescription: A test skill\n---\nInstructions";+ const blobs = [markdown, "Hello 🌍\n"].map((content, index) => ({+ id: `blob-${index}`,+ projectId: "project",+ createdAt: new Date(),+ sha256Hash: createHash("sha256").update(content).digest("base64"),+ contentType: "text/plain",+ contentLength: Buffer.byteLength(content, "utf8"),+ content,+ }));+ const files = [+ { path: "SKILL.md", content: markdown },+ { path: "reference.txt", content: blobs[1]!.content },+ { path: "copy.txt", content: blobs[1]!.content },+ ];+ const skill = {+ id: "skill",+ projectId: "project",+ createdBy: "user",+ createdAt: new Date(),+ updatedAt: new Date(),+ name: "test-skill",+ description: "A test skill",+ frontmatter: { name: "test-skill", description: "A test skill" },+ version: 1,+ tags: [] as string[],+ labels: [] as string[],+ commitMessage: null,+ files: files.map((file, index) => ({+ ...file,+ id: `file-${index}`,+ blobId: blobs[index === 0 ? 0 : 1]!.id,+ blob: blobs[index === 0 ? 0 : 1]!,+ })),+ };+ const create = vi.fn().mockResolvedValue(skill);+ const tx = {+ $executeRaw: vi.fn(),+ skillBlob: {+ createMany: vi+ .fn<+ (input: {+ data: unknown[];+ skipDuplicates: boolean;+ }) => Promise<{ count: number }>+ >()+ .mockResolvedValue({ count: 2 }),+ findMany: vi.fn().mockResolvedValue(blobs),+ },+ skill: {+ findFirst: vi.fn().mockResolvedValue(null),+ findFirstOrThrow: vi.fn().mockResolvedValue({ version: 1 }),+ findMany: vi.fn().mockResolvedValue([]),+ update: vi.fn(),+ updateMany: vi.fn(),+ delete: vi.fn(),+ deleteMany: vi.fn().mockResolvedValue({ count: 2 }),+ create,+ },+ };+ const transaction = vi.fn(+ async (callback: (tx: unknown) => Promise<string>) => {+ return callback(tx);+ },+ );+ const db = {+ promptProtectedLabels: { findMany: vi.fn().mockResolvedValue([]) },+ apiKey: {+ findUnique: vi.fn().mockResolvedValue({ isInAppAgentKey: false }),+ },+ user: {+ findUnique: vi.fn().mockResolvedValue({ id: "user", admin: false }),+ },+ organizationMembership: {+ findFirst: vi+ .fn()+ .mockResolvedValue({ id: "membership", role: "MEMBER" }),+ },+ projectMembership: { findFirst: vi.fn().mockResolvedValue(null) },+ skillFile: { findFirst: vi.fn().mockResolvedValue(skill.files[0]) },+ $transaction: transaction,+ skill: {+ findFirst: vi.fn().mockResolvedValue(skill),+ findMany: vi.fn().mockResolvedValue([skill]),+ count: vi.fn().mockResolvedValue(1),+ findUnique: vi.fn().mockResolvedValue(skill),+ findFirstOrThrow: vi.fn().mockResolvedValue({ version: 1 }),+ },+ };+ Object.assign(tx, {+ promptProtectedLabels: db.promptProtectedLabels,+ apiKey: db.apiKey,+ user: db.user,+ organizationMembership: db.organizationMembership,+ projectMembership: db.projectMembership,+ });+ const service = new SkillService(db as unknown as PrismaClient);+ const params = {+ projectId: "project",+ createdBy: "user",+ input: { files },+ actor: {+ projectId: "project",+ orgId: "org",+ apiKeyId: "api-key",+ accessLevel: "project" as const,+ },+ };+ return {+ service,+ params,+ blobs,+ transaction,+ create,+ skill,+ tx,+ db,+ };+ }++ it.each(["setLabels", "deleteVersion", "deleteSkill"] as const)(+ "checks labels added before the mutation lock during %s",+ async (operation) => {+ const test = setup();+ const lockedSkill = { ...test.skill, labels: ["production"] };+ test.tx.skill.findFirst.mockResolvedValue(lockedSkill);+ test.tx.skill.findMany.mockResolvedValue([lockedSkill]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);+ const params = {+ projectId: "project",+ name: "test-skill",+ version: 1,+ actor: sessionActor("MEMBER"),+ };+ const mutations = {+ setLabels: () => test.service.setLabels({ ...params, labels: [] }),+ deleteVersion: () => test.service.deleteVersion(params),+ deleteSkill: () => test.service.deleteSkill(params),+ };++ await expect(mutations[operation]()).rejects.toMatchObject({+ code: "FORBIDDEN",+ });+ expect(test.tx.skill.update).not.toHaveBeenCalled();+ expect(test.tx.skill.delete).not.toHaveBeenCalled();+ expect(test.tx.skill.deleteMany).not.toHaveBeenCalled();+ expect(auditLog).not.toHaveBeenCalled();+ },+ );++ it("cannot restore a protected label moved away before the mutation lock", async () => {+ const test = setup();+ test.skill.labels = ["production"];+ test.tx.skill.findFirst.mockResolvedValue({ ...test.skill, labels: [] });+ test.tx.skill.findMany.mockResolvedValue([+ { ...test.skill, labels: [] },+ { id: "other-version", labels: ["production"] },+ ]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);++ await expect(+ test.service.setLabels({+ projectId: "project",+ name: "test-skill",+ version: 1,+ labels: ["production", "stable"],+ actor: sessionActor("MEMBER"),+ }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(test.tx.skill.update).not.toHaveBeenCalled();+ expect(auditLog).not.toHaveBeenCalled();+ });++ it.each(["add", "remove", "delete"] as const)(+ "rejects a MEMBER attempting to %s a protected label through the service",+ async (operation) => {+ const test = setup();+ test.skill.labels = operation === "add" ? [] : ["production"];+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ test.tx.skill.findMany.mockResolvedValue([test.skill]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);+ const params = {+ projectId: "project",+ name: "test-skill",+ version: 1,+ actor: sessionActor("MEMBER"),+ };++ await expect(+ operation === "delete"+ ? test.service.deleteVersion(params)+ : test.service.setLabels({+ ...params,+ labels: operation === "add" ? ["production"] : [],+ }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(test.transaction).toHaveBeenCalledOnce();+ expect(test.tx.skill.update).not.toHaveBeenCalled();+ expect(test.tx.skill.delete).not.toHaveBeenCalled();+ expect(auditLog).not.toHaveBeenCalled();+ },+ );++ it.each(["setLabels", "deleteVersion"] as const)(+ "enforces API key creator permissions before %s",+ async (operation) => {+ const test = setup();+ test.skill.labels = ["production"];+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ test.tx.skill.findMany.mockResolvedValue([test.skill]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);+ test.db.apiKey.findUnique.mockResolvedValue({+ isInAppAgentKey: true,+ createdByUserId: "user",+ });+ const params = {+ projectId: "project",+ name: "test-skill",+ version: 1,+ actor: test.params.actor,+ };+ const mutate = () =>+ operation === "setLabels"+ ? test.service.setLabels({ ...params, labels: [] })+ : test.service.deleteVersion(params);++ await expect(mutate()).rejects.toMatchObject({ httpCode: 403 });+ expect(test.transaction).toHaveBeenCalledOnce();+ expect(auditLog).not.toHaveBeenCalled();++ test.db.projectMembership.findFirst.mockResolvedValue({ role: "ADMIN" });+ await mutate();+ expect(test.transaction).toHaveBeenCalledTimes(2);+ },+ );++ it.each(["session", "project-key"] as const)(+ "allows protected-label mutations by an authorized %s actor",+ async (kind) => {+ const test = setup();+ test.skill.labels = ["production"];+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ test.tx.skill.findMany.mockResolvedValue([test.skill]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);+ const params = {+ projectId: "project",+ name: "test-skill",+ version: 1,+ actor: kind === "session" ? sessionActor("ADMIN") : test.params.actor,+ };++ await test.service.setLabels({ ...params, labels: [] });+ await test.service.deleteVersion(params);+ expect(test.tx.skill.update).toHaveBeenCalledOnce();+ expect(test.tx.skill.delete).toHaveBeenCalledOnce();+ expect(test.db.user.findUnique).not.toHaveBeenCalled();+ },+ );++ it.each(["create", "setLabels", "setTags", "delete"] as const)(+ "waits for the skill mutation lock before reading versions during %s",+ async (operation) => {+ const test = setup();+ const lock = Promise.withResolvers<void>();+ test.tx.$executeRaw.mockReturnValue(lock.promise);+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ const selector = {+ projectId: "project",+ name: "test-skill",+ version: 1,+ actor: test.params.actor,+ };+ const mutations = {+ create: () => test.service.createVersion(test.params),+ setLabels: () => test.service.setLabels({ ...selector, labels: [] }),+ setTags: () => test.service.setTags({ ...selector, tags: [] }),+ delete: () => test.service.deleteVersion(selector),+ };+ const mutation = mutations[operation]();++ try {+ await vi.waitFor(() => {+ expect(test.tx.$executeRaw).toHaveBeenCalledOnce();+ });+ expect(test.tx.skill.findFirst).not.toHaveBeenCalled();+ } finally {+ lock.resolve();+ await mutation;+ }+ },+ );++ it("creates with only latest and leaves deployment labels on the previous version", async () => {+ const test = setup();+ const previous = {+ id: "previous",+ version: 1,+ labels: ["latest", "production", "stable"],+ };+ test.tx.skill.findFirst.mockResolvedValue(previous);+ test.tx.skill.findMany.mockResolvedValue([previous]);+ const params = {+ ...test.params,+ input: { ...test.params.input, labels: ["production"] },+ };++ await test.service.createVersion(params);++ expect(test.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ version: 2,+ labels: ["latest"],+ }),+ });+ expect(test.tx.skill.update).toHaveBeenCalledWith({+ where: { projectId: "project", id: "previous" },+ data: { labels: { set: ["production", "stable"] } },+ });+ });++ it("blocks whole-skill deletion when an older version has a protected label", async () => {+ const test = setup();+ test.tx.skill.findMany.mockResolvedValue([+ { ...test.skill, labels: ["latest"], version: 2 },+ { ...test.skill, labels: ["production"] },+ ]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);+ await expect(+ test.service.deleteSkill({+ projectId: "project",+ name: "test-skill",+ actor: sessionActor("MEMBER"),+ }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(test.transaction).toHaveBeenCalledOnce();+ expect(test.tx.skill.deleteMany).not.toHaveBeenCalled();+ });++ it("allows ordinary label changes while keeping a protected label", async () => {+ const test = setup();+ test.skill.labels = ["latest", "production", "old"];+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ test.tx.skill.findMany.mockResolvedValue([test.skill]);+ test.db.promptProtectedLabels.findMany.mockResolvedValue([+ { label: "production" },+ ]);++ await test.service.setLabels({+ projectId: "project",+ name: "test-skill",+ version: 1,+ labels: ["production", "stable"],+ actor: sessionActor("MEMBER"),+ });++ expect(test.tx.skill.update).toHaveBeenCalledExactlyOnceWith({+ where: { projectId: "project", id: "skill" },+ data: { labels: { set: ["production", "stable", "latest"] } },+ });+ });++ it("preserves latest when replacing user-managed labels", async () => {+ const test = setup();+ test.skill.labels = ["latest", "production"];+ test.tx.skill.findFirst.mockResolvedValue(test.skill);+ test.tx.skill.findMany.mockResolvedValue([+ test.skill,+ { id: "previous", labels: ["stable"] },+ ]);++ await test.service.setLabels({+ projectId: "project",+ name: "test-skill",+ version: 1,+ labels: ["stable"],+ actor: test.params.actor,+ });++ expect(test.tx.skill.update).toHaveBeenCalledWith({+ where: { projectId: "project", id: "skill" },+ data: { labels: { set: ["stable", "latest"] } },+ });+ expect(test.tx.skill.update).toHaveBeenCalledWith({+ where: { projectId: "project", id: "previous" },+ data: { labels: { set: [] } },+ });+ });++ it("deduplicates text and derives UTF-8 metadata inside the version transaction", async () => {+ const test = setup();++ const result = await test.service.createVersion(test.params);++ expect(test.tx.skillBlob.createMany).toHaveBeenCalledExactlyOnceWith({+ data: expect.arrayContaining(+ test.blobs.map(({ content, contentLength, sha256Hash }) =>+ expect.objectContaining({+ projectId: "project",+ content,+ contentLength,+ sha256Hash,+ }),+ ),+ ),+ skipDuplicates: true,+ });+ expect(test.tx.skillBlob.createMany.mock.calls[0]![0].data).toHaveLength(2);+ expect(test.tx.skillBlob.findMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ projectId: "project",+ sha256Hash: { in: test.blobs.map(({ sha256Hash }) => sha256Hash) },+ },+ }),+ );+ expect(test.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ name: "test-skill",+ description: "A test skill",+ frontmatter: { name: "test-skill", description: "A test skill" },+ files: {+ create: [+ expect.objectContaining({+ path: "SKILL.md",+ blob: { connect: { projectId: "project", id: "blob-0" } },+ }),+ expect.objectContaining({+ path: "reference.txt",+ blob: { connect: { projectId: "project", id: "blob-1" } },+ }),+ expect.objectContaining({+ path: "copy.txt",+ blob: { connect: { projectId: "project", id: "blob-1" } },+ }),+ ],+ },+ }),+ });+ expect(result.name).toBe("test-skill");+ expect(result.files.every((file) => !("content" in file))).toBe(true);+ });++ it("rejects invalid SKILL.md frontmatter before writing anything", async () => {+ const test = setup();+ test.params.input.files[0]!.content = "No frontmatter";++ await expect(test.service.createVersion(test.params)).rejects.toThrow(+ "SKILL.md must start with YAML frontmatter",+ );+ expect(test.transaction).not.toHaveBeenCalled();+ expect(test.create).not.toHaveBeenCalled();+ });++ it.each([+ { path: "reference.txt", content: "binary\0content" },+ { path: "reference.txt", content: "invalid\ud800" },+ { path: "image.svg", content: "<svg />" },+ { path: "archive.zip", content: "disguised archive" },+ { path: "resource.unknown", content: "plain text" },+ { path: "docs.md/README", content: "plain text" },+ { path: "resource.txt.exe", content: "plain text" },+ { path: "../secret.txt", content: "hello" },+ { path: "reference.txt", content: "🌍".repeat(250_001) },+ ])(+ "rejects invalid text or paths before creating blobs: $path",+ async (file) => {+ const test = setup();+ test.params.input.files[1] = file;++ await expect(test.service.createVersion(test.params)).rejects.toThrow();+ expect(test.transaction).not.toHaveBeenCalled();+ },+ );++ it("counts every file's UTF-8 bytes toward the version limit before deduplication", async () => {+ const test = setup();+ test.params.input.files[1]!.content = "🌍".repeat(125_000);+ test.params.input.files[2]!.content = test.params.input.files[1]!.content;++ await expect(test.service.createVersion(test.params)).rejects.toThrow(+ "in total",+ );+ expect(test.transaction).not.toHaveBeenCalled();+ });++ it("returns persisted text only after a project-scoped file lookup", async () => {+ const test = setup();+ await expect(+ test.service.getFileContent({ projectId: "project", fileId: "file-0" }),+ ).resolves.toEqual({ content: test.blobs[0]!.content });+ expect(test.db.skillFile.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { projectId: "project", id: "file-0" },+ }),+ );+ test.db.skillFile.findFirst.mockResolvedValue(null);+ await expect(+ test.service.getFileContent({+ projectId: "other-project",+ fileId: "file-0",+ }),+ ).rejects.toThrow("Skill file not found");+ expect(test.db.skillFile.findFirst).toHaveBeenLastCalledWith(+ expect.objectContaining({+ where: { projectId: "other-project", id: "file-0" },+ }),+ );+ });+});diff --git a/web/src/components/design-system/Dropzone/Dropzone.tsx b/web/src/components/design-system/Dropzone/Dropzone.tsxindex ea1af8db83..3e34984940 100644--- a/web/src/components/design-system/Dropzone/Dropzone.tsx+++ b/web/src/components/design-system/Dropzone/Dropzone.tsx@@ -3,7 +3,7 @@import { cva } from "class-variance-authority";import { PaperclipIcon, UploadIcon } from "lucide-react";import { useMemo } from "react";-import { useDropzone } from "react-dropzone";+import { DropzoneController } from "../DropzoneController/DropzoneController";import { cn } from "@/src/utils/tailwind";const renderBytes = (bytes: number) => {@@ -62,24 +62,6 @@ export const Dropzone = ({src,variant,}: DropzoneProps) => {- const { getRootProps, getInputProps, isDragActive } = useDropzone({- accept,- maxFiles,- maxSize,- minSize,- onError,- disabled: isDisabled,- onDrop: (acceptedFiles, fileRejections) => {- if (fileRejections.length > 0) {- const message = fileRejections.at(0)?.errors.at(0)?.message;- onError?.(new Error(message));- return;- }-- onDrop(acceptedFiles);- },- });-const contentText = useMemo(() => {if (variant === "compact") {if (!src?.length) {@@ -133,52 +115,64 @@ export const Dropzone = ({: emptyStateDescription;return (- <button- key={JSON.stringify(src)}- className={dropzoneVariants({ isDragActive, variant })}- disabled={isDisabled}- type="button"- {...getRootProps()}+ <DropzoneController+ accept={accept}+ maxFiles={maxFiles}+ maxSize={maxSize}+ minSize={minSize}+ onError={onError}+ isDisabled={isDisabled}+ onDrop={onDrop}>- <input {...getInputProps()} disabled={isDisabled} />- {variant === "compact" && (- <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">- <PaperclipIcon className="h-4 w-4" />- <span className="truncate" title={contentText}>- {contentText}- </span>- </div>- )}- {variant === "panel" && (- <div className="flex flex-col items-center justify-center">- <div className="bg-muted text-muted-foreground flex size-8 items-center justify-center rounded-md">- <UploadIcon size={16} />- </div>- <p- className={cn(- "my-2 w-full truncate text-sm font-bold",- !src?.length && "text-wrap",- )}- title={panelTitle}- >- {panelTitle}- </p>- <p- className={cn(- "text-muted-foreground w-full text-xs text-wrap",- !src?.length && "truncate",- )}- title={src?.length ? undefined : panelDescription}- >- {panelDescription}- </p>- {!src?.length && caption && (- <p className="text-muted-foreground text-xs text-wrap">- {caption}.- </p>+ {({ getRootProps, getInputProps, isDragActive }) => (+ <button+ key={JSON.stringify(src)}+ className={dropzoneVariants({ isDragActive, variant })}+ disabled={isDisabled}+ type="button"+ {...getRootProps()}+ >+ <input {...getInputProps()} disabled={isDisabled} />+ {variant === "compact" && (+ <div className="flex w-full cursor-pointer items-center justify-start gap-2 p-2 text-xs">+ <PaperclipIcon className="h-4 w-4" />+ <span className="truncate" title={contentText}>+ {contentText}+ </span>+ </div>+ )}+ {variant === "panel" && (+ <div className="flex flex-col items-center justify-center">+ <div className="bg-muted text-muted-foreground flex size-8 items-center justify-center rounded-md">+ <UploadIcon size={16} />+ </div>+ <p+ className={cn(+ "my-2 w-full truncate text-sm font-bold",+ !src?.length && "text-wrap",+ )}+ title={panelTitle}+ >+ {panelTitle}+ </p>+ <p+ className={cn(+ "text-muted-foreground w-full text-xs text-wrap",+ !src?.length && "truncate",+ )}+ title={src?.length ? undefined : panelDescription}+ >+ {panelDescription}+ </p>+ {!src?.length && caption && (+ <p className="text-muted-foreground text-xs text-wrap">+ {caption}.+ </p>+ )}+ </div>)}- </div>+ </button>)}- </button>+ </DropzoneController>);};diff --git a/web/src/components/design-system/DropzoneController/DropzoneController.tsx b/web/src/components/design-system/DropzoneController/DropzoneController.tsxnew file mode 100644index 0000000000..3e4accfd0a--- /dev/null+++ b/web/src/components/design-system/DropzoneController/DropzoneController.tsx@@ -0,0 +1,112 @@+"use client";++import { useState, type ReactNode } from "react";+import {+ useDropzone,+ type DropzoneState,+ type DropzoneOptions,+ type DropzoneRootProps,+ type DropzoneInputProps,+} from "react-dropzone";++type DropzoneControls = Pick<DropzoneState, "isDragActive" | "open"> & {+ getRootProps: (props?: DropzoneRootProps) => DropzoneRootProps;+ getInputProps: (props?: DropzoneInputProps) => DropzoneInputProps;+ openDirectory: () => void;+};++type DropzoneControllerProps = Pick<+ DropzoneOptions,+ "accept" | "maxFiles" | "minSize" | "maxSize" | "noClick" | "noKeyboard"+> & {+ isDisabled: boolean;+ onDrop: (files: File[]) => void | Promise<void>;+ onError: ((error: Error) => void) | undefined;+ onProcessingChange?: (isProcessing: boolean) => void;+ children: (controls: DropzoneControls) => ReactNode;+};++export function DropzoneController({+ isDisabled,+ onDrop,+ onError,+ onProcessingChange,+ children,+ ...options+}: DropzoneControllerProps) {+ const [isDragActive, setIsDragActive] = useState(false);+ const handleError = (error: Error) => {+ setIsDragActive(false);+ onProcessingChange?.(false);+ onError?.(error);+ };+ const zone = useDropzone({+ ...options,+ disabled: isDisabled,+ useFsAccessApi: false,+ onDragLeave: () => setIsDragActive(false),+ onError: handleError,+ onDrop: async (files, rejections) => {+ try {+ if (rejections.length) {+ throw new Error(+ rejections[0]?.errors[0]?.message ?? "Could not read files.",+ );+ }+ onProcessingChange?.(true);+ await onDrop(files);+ } catch (error) {+ onError?.(+ error instanceof Error ? error : new Error("Could not read files."),+ );+ } finally {+ onProcessingChange?.(false);+ }+ },+ });++ const openPicker = (directory: boolean) => {+ if (isDisabled) return;+ if (directory) zone.inputRef.current?.setAttribute("webkitdirectory", "");+ else zone.inputRef.current?.removeAttribute("webkitdirectory");+ zone.open();+ };++ return children({+ open: () => openPicker(false),+ openDirectory: () => openPicker(true),+ isDragActive: isDragActive && !isDisabled,+ getInputProps: (props) =>+ zone.getInputProps({+ ...props,+ onChange: (event) => {+ if (event.target.files?.length) onProcessingChange?.(true);+ props?.onChange?.(event);+ },+ }),+ getRootProps: (props) =>+ zone.getRootProps({+ ...props,+ onDragEnter: (event) => {+ if (event.dataTransfer.types.includes("Files")) setIsDragActive(true);+ props?.onDragEnter?.(event);+ },+ // Disabled dropzones must still suppress the browser's file navigation.+ onDragOverCapture: (event) => {+ if (event.dataTransfer.types.includes("Files"))+ event.preventDefault();+ },+ onDropCapture: (event) => {+ setIsDragActive(false);+ if (event.dataTransfer.types.includes("Files"))+ event.preventDefault();+ },+ onDrop: (event) => {+ event.preventDefault();+ if (event.dataTransfer.types.includes("Files"))+ onProcessingChange?.(true);+ props?.onDrop?.(event);+ },+ }),+ });+}diff --git a/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.tsindex ad0c709f3b..c2f73cc479 100644--- a/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts+++ b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts@@ -22,6 +22,7 @@ import type { NavigationFilterContext } from "../utils/navigationFilters.types";import { isPathActive } from "../utils/pathClassification";import { resolveRoutePathname } from "../utils/routePathname";import { api } from "@/src/utils/api";+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";/** Organization type from user session (can be null when not in project/org context) */type Organization =@@ -57,6 +58,7 @@ function groupNavigationItems(items: NavigationItem[]): GroupedNavigation {? [...(grouped[RouteGroup.Observability] || []),...(grouped[RouteGroup.PromptManagement] || []),+ ...(grouped[RouteGroup.ContextManagement] || []),...(grouped[RouteGroup.Evaluation] || []),]: [];@@ -103,6 +105,7 @@ export function useFilteredNavigation(cloudStatus?.status === "degraded" || cloudStatus?.status === "downtime";const routerProjectId = router.query.projectId as string | undefined;+ const internalFeaturesEnabled = useInternalFeaturesEnabled();const forceV3Experience = useForceV3Experience(routerProjectId);const routerOrganizationId = router.query.organizationId as| string@@ -122,6 +125,7 @@ export function useFilteredNavigation(isLangfuseCloud,hasActiveCloudIncident,forceV3Experience,+ internalFeaturesEnabled,currentPath: router.asPath,}),[@@ -134,6 +138,7 @@ export function useFilteredNavigation(isLangfuseCloud,hasActiveCloudIncident,forceV3Experience,+ internalFeaturesEnabled,],);diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.tsindex a67f40ba11..6fdda06e52 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.ts@@ -3,7 +3,7 @@* Each filter is a pure function that can be tested in isolation*/-import type { Route } from "@/src/components/layouts/routes";+import { RouteGroup, type Route } from "@/src/components/layouts/routes";import type { NavigationFilterContext } from "./navigationFilters.types";import { hasProjectAccess, hasOrganizationAccess } from "@/src/features/rbac";import type { Session } from "next-auth";@@ -71,6 +71,10 @@ const filters = {featureFlags: (route: Route, ctx: NavigationFilterContext): Route | null => {if (route.featureFlag === undefined) return route;+ if (route.featureFlag === "internalFeatures") {+ return ctx.internalFeaturesEnabled ? route : null;+ }+if (route.featureFlag === "experimentsV4Enabled") {return ctx.session?.user?.v4BetaEnabled === true ? route : null;}@@ -238,5 +242,10 @@ export function applyNavigationFilters(): Route[] {return routes.map((route) => applyFiltersToRoute(route, ctx, organization))- .filter((route): route is Route => route !== null);+ .filter((route): route is Route => route !== null)+ .map((route) =>+ ctx.internalFeaturesEnabled && route.group === RouteGroup.PromptManagement+ ? { ...route, group: RouteGroup.ContextManagement }+ : route,+ );}diff --git a/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts b/web/src/components/layouts/app-layout/utils/navigationFilters.types.tsindex 5172270803..4858dcba44 100644--- a/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts+++ b/web/src/components/layouts/app-layout/utils/navigationFilters.types.ts@@ -30,6 +30,7 @@ export type NavigationFilterContext = {hasActiveCloudIncident: boolean;/** Whether the current project must remain on the v3 experience */forceV3Experience: boolean;+ internalFeaturesEnabled: boolean;/** Current router path for active state detection */currentPath: string;};diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex 047cc5761b..37bcaecf79 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -14,6 +14,7 @@ import {Grid2X2,Sparkle,FileJson,+ FolderCode,Search,Home,SquarePercent,@@ -45,6 +46,7 @@ export enum RouteSection {export enum RouteGroup {Observability = "Observability",PromptManagement = "Prompt Management",+ ContextManagement = "Context Management",Evaluation = "Evaluation",}@@ -154,6 +156,16 @@ export const ROUTES: Route[] = [group: RouteGroup.Observability,section: RouteSection.Main,},+ {+ title: "Skills",+ featureFlag: "internalFeatures",+ href: "/project/[projectId]/skills",+ icon: FolderCode,+ projectRbacScopes: ["skills:read"],+ productModule: "prompt-management",+ group: RouteGroup.PromptManagement,+ section: RouteSection.Main,+ },{title: "Prompts",href: "/project/[projectId]/prompts",diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex de38e02b9a..18437b3c17 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -2,6 +2,7 @@ import {prisma as _prisma,type Role,AuditLogRecordType,+ type Prisma,} from "@langfuse/shared/src/db";type AuditableResource =@@ -26,6 +27,7 @@ type AuditableResource =| "notificationPreference"| "prompt"| "promptProtectedLabel"+ | "skill"| "session"| "apiKey"| "evalTemplate"@@ -85,7 +87,10 @@ type AuditLog = {});-export async function auditLog(log: AuditLog, prisma?: typeof _prisma) {+export async function auditLog(+ log: AuditLog,+ prisma?: typeof _prisma | Prisma.TransactionClient,+) {const db = prisma ?? _prisma;const shared = {resourceType: log.resourceType,diff --git a/web/src/features/feature-flags/hooks/useIsFeatureEnabled.clienttest.ts b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.clienttest.tsindex 3ee44d174a..9ee0f08b28 100644--- a/web/src/features/feature-flags/hooks/useIsFeatureEnabled.clienttest.ts+++ b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.clienttest.ts@@ -3,6 +3,7 @@ import { renderHook } from "@testing-library/react";import { useSession } from "next-auth/react";import useIsFeatureEnabled from "./useIsFeatureEnabled";+import { useInternalFeaturesEnabled } from "./useInternalFeaturesEnabled";import { INTERNAL_FEATURE_FLAG } from "../available-flags";vi.mock("next-auth/react", () => ({@@ -42,6 +43,34 @@ const mockSession = ({};describe("useIsFeatureEnabled", () => {+ it.each([+ {+ admin: true,+ internalFeatures: false,+ enableExperimentalFeatures: true,+ expected: false,+ },+ {+ admin: true,+ internalFeatures: true,+ enableExperimentalFeatures: false,+ expected: true,+ },+ {+ admin: false,+ internalFeatures: true,+ enableExperimentalFeatures: false,+ expected: false,+ },+ ])(+ "resolves internal view as $expected for $admin admin / $internalFeatures preference",+ ({ expected, ...options }) => {+ mockSession({ aiGateway: false, ...options });+ const { result } = renderHook(() => useInternalFeaturesEnabled());+ expect(result.current).toBe(expected);+ },+ );+it("does not let admin or experimental-feature overrides enable restricted flags", () => {mockSession({aiGateway: false,diff --git a/web/src/features/in-app-agent/components/utils/utils.ts b/web/src/features/in-app-agent/components/utils/utils.tsindex f7f406b6ba..82e60b9630 100644--- a/web/src/features/in-app-agent/components/utils/utils.ts+++ b/web/src/features/in-app-agent/components/utils/utils.ts@@ -73,6 +73,8 @@ const IN_APP_AGENT_TOOL_PROGRESS_LABEL_OVERRIDES: Record<string, string> = {getObservationFilterValues: "Looking up observation filters",getPromptUnresolved: "Inspecting prompt",listDashboardWidgets: "Browsing widgets",+ loadSkill: "Loading skill",+ loadSkillResource: "Loading skill resource",proposeRedirect: "Opening page",queryMetrics: "Checking metrics",read: "Reading file",diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.tsindex 63e24b1788..56c0ab4f9d 100644--- a/web/src/features/mcp/server/mcpServer.ts+++ b/web/src/features/mcp/server/mcpServer.ts@@ -128,7 +128,10 @@ export function createMcpServer(context: ServerContext): Server {content: [{type: "text",- text: JSON.stringify(result, null, 2),+ text:+ typeof result === "string"+ ? result+ : JSON.stringify(result, null, 2),},],};diff --git a/web/src/features/mcp/server/skills/index.ts b/web/src/features/mcp/server/skills/index.tsnew file mode 100644index 0000000000..f4cd61a8d2--- /dev/null+++ b/web/src/features/mcp/server/skills/index.ts@@ -0,0 +1,20 @@+import type { McpFeatureModule } from "../registry";+import { getSkillTool, handleGetSkill } from "./tools/getSkill";+import { listSkillsTool, handleListSkills } from "./tools/listSkills";+import { loadSkillTool, handleLoadSkill } from "./tools/loadSkill";+import {+ loadSkillResourceTool,+ handleLoadSkillResource,+} from "./tools/loadSkillResource";++export const skillsFeature = {+ name: "skills",+ description:+ "List skills, retrieve version manifests, and load text resources",+ tools: [+ { definition: listSkillsTool, handler: handleListSkills },+ { definition: getSkillTool, handler: handleGetSkill },+ { definition: loadSkillTool, handler: handleLoadSkill },+ { definition: loadSkillResourceTool, handler: handleLoadSkillResource },+ ],+} as const satisfies McpFeatureModule;diff --git a/web/src/features/mcp/server/skills/tools/getSkill.ts b/web/src/features/mcp/server/skills/tools/getSkill.tsnew file mode 100644index 0000000000..c5733e22f5--- /dev/null+++ b/web/src/features/mcp/server/skills/tools/getSkill.ts@@ -0,0 +1,36 @@+import { z } from "zod";+import { SkillNameSchema, SkillSelectorSchema } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { SkillService } from "@/src/features/skills/server";+import { defineTool } from "../../../core/define-tool";+import { runMcpTool } from "../../../core/run-mcp-tool";++const GetSkillBaseSchema = z.object({+ name: SkillNameSchema,+ ...SkillSelectorSchema.shape,+});++const GetSkillInputSchema = z+ .object({ name: SkillNameSchema })+ .and(SkillSelectorSchema);++export const [getSkillTool, handleGetSkill] = defineTool({+ name: "getSkill",+ description:+ "Get skill metadata and file paths, without file contents. Select a version or label; defaults to production.",+ action: "skills:read",+ baseSchema: GetSkillBaseSchema,+ inputSchema: GetSkillInputSchema,+ handler: async ({ name, ...selector }, context) =>+ runMcpTool({+ spanName: "mcp.skills.get",+ context,+ fn: async () =>+ new SkillService(prisma).get({+ projectId: context.projectId,+ name,+ selector,+ }),+ }),+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/server/skills/tools/listSkills.ts b/web/src/features/mcp/server/skills/tools/listSkills.tsnew file mode 100644index 0000000000..eb8be5e94c--- /dev/null+++ b/web/src/features/mcp/server/skills/tools/listSkills.ts@@ -0,0 +1,25 @@+import { ListSkillsQuerySchema } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { SkillService } from "@/src/features/skills/server";+import { defineTool } from "../../../core/define-tool";+import { runMcpTool } from "../../../core/run-mcp-tool";++export const [listSkillsTool, handleListSkills] = defineTool({+ name: "listSkills",+ description:+ "List and search project skills with tags and version summaries. Supports filtering and pagination.",+ action: "skills:read",+ baseSchema: ListSkillsQuerySchema,+ inputSchema: ListSkillsQuerySchema,+ handler: async (input, context) =>+ runMcpTool({+ spanName: "mcp.skills.list",+ context,+ fn: async () =>+ new SkillService(prisma).list({+ projectId: context.projectId,+ input,+ }),+ }),+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/server/skills/tools/loadSkill.ts b/web/src/features/mcp/server/skills/tools/loadSkill.tsnew file mode 100644index 0000000000..022c2e1157--- /dev/null+++ b/web/src/features/mcp/server/skills/tools/loadSkill.ts@@ -0,0 +1,37 @@+import { z } from "zod";+import { SkillNameSchema, SkillSelectorSchema } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { SkillService } from "@/src/features/skills/server";+import { defineTool } from "../../../core/define-tool";+import { runMcpTool } from "../../../core/run-mcp-tool";++const LoadSkillBaseSchema = z.object({+ name: SkillNameSchema,+ ...SkillSelectorSchema.shape,+});++const LoadSkillInputSchema = z+ .object({ name: SkillNameSchema })+ .and(SkillSelectorSchema);++export const [loadSkillTool, handleLoadSkill] = defineTool({+ name: "loadSkill",+ description:+ "Read a skill's SKILL.md as text. Select a version or label; defaults to production.",+ action: "skills:read",+ baseSchema: LoadSkillBaseSchema,+ inputSchema: LoadSkillInputSchema,+ handler: async ({ name, ...selector }, context) =>+ runMcpTool({+ spanName: "mcp.skills.load",+ context,+ fn: async () =>+ new SkillService(prisma).loadResource({+ projectId: context.projectId,+ name,+ selector,+ path: "SKILL.md",+ }),+ }),+ readOnlyHint: true,+});diff --git a/web/src/features/mcp/server/skills/tools/loadSkillResource.ts b/web/src/features/mcp/server/skills/tools/loadSkillResource.tsnew file mode 100644index 0000000000..74459e93a6--- /dev/null+++ b/web/src/features/mcp/server/skills/tools/loadSkillResource.ts@@ -0,0 +1,42 @@+import { z } from "zod";+import {+ SkillFilePathSchema,+ SkillNameSchema,+ SkillSelectorSchema,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { SkillService } from "@/src/features/skills/server";+import { defineTool } from "../../../core/define-tool";+import { runMcpTool } from "../../../core/run-mcp-tool";++const LoadSkillResourceBaseSchema = z.object({+ name: SkillNameSchema,+ path: SkillFilePathSchema,+ ...SkillSelectorSchema.shape,+});++const LoadSkillResourceInputSchema = z+ .object({ name: SkillNameSchema, path: SkillFilePathSchema })+ .and(SkillSelectorSchema);++export const [loadSkillResourceTool, handleLoadSkillResource] = defineTool({+ name: "loadSkillResource",+ description:+ "Read a skill file as text by path (see getSkill). Select a version or label; defaults to production.",+ action: "skills:read",+ baseSchema: LoadSkillResourceBaseSchema,+ inputSchema: LoadSkillResourceInputSchema,+ handler: async ({ name, path, ...selector }, context) =>+ runMcpTool({+ spanName: "mcp.skills.loadResource",+ context,+ fn: async () =>+ new SkillService(prisma).loadResource({+ projectId: context.projectId,+ name,+ selector,+ path,+ }),+ }),+ readOnlyHint: true,+});diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 78c17d5a98..9510cfabf3 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -155,6 +155,7 @@ const events = {"bulk_export","bulk_import_submit",],+ skills: ["new_form_open", "version_create", "version_download", "delete"],prompt_detail: ["test_in_playground_button_click","add_label_submit",diff --git a/web/src/features/projects/ProjectSettingsPage.tsx b/web/src/features/projects/ProjectSettingsPage.tsxindex b46029182b..397da3d5de 100644--- a/web/src/features/projects/ProjectSettingsPage.tsx+++ b/web/src/features/projects/ProjectSettingsPage.tsx@@ -233,9 +233,9 @@ const getProjectSettingsPages = ({content: <ModelsSettings projectId={project.id} />,},{- title: "Protected Prompt Labels",+ title: "Protected Labels",slug: "protected-prompt-labels",- cmdKKeywords: ["prompt", "label", "protect", "lock"],+ cmdKKeywords: ["prompt", "skill", "label", "protect", "lock"],content: <ProtectedLabelsSettings projectId={project.id} />,show: showProtectedLabelsSettings,},diff --git a/web/src/features/prompts/components/ProtectedLabelsSettings.tsx b/web/src/features/prompts/components/ProtectedLabelsSettings.tsxindex db437722f6..a2d5fcbf96 100644--- a/web/src/features/prompts/components/ProtectedLabelsSettings.tsx+++ b/web/src/features/prompts/components/ProtectedLabelsSettings.tsx@@ -13,6 +13,7 @@ import {import Header from "@/src/components/layouts/header";import { useHasProjectAccess } from "@/src/features/rbac";import { useHasEntitlement } from "@/src/features/entitlements";+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";import { XIcon, Check, ChevronsUpDown } from "lucide-react";@@ -54,6 +55,7 @@ export default function ProtectedLabelsSettings({scope: "promptProtectedLabels:CUD",});const hasEntitlement = useHasEntitlement("prompt-protected-labels");+ const skillsEnabled = useInternalFeaturesEnabled();const form = useForm({resolver: zodResolver(AddLabelFormSchema),@@ -108,12 +110,12 @@ export default function ProtectedLabelsSettings({return (<div>- <Header title="Protected Prompt Labels" />+ <Header title="Protected Labels" /><Card className="mb-4 p-3"><p className="text-primary mb-4 text-sm">Protected labels can only be modified by users with admin or owneraccess. This prevents other users from changing or removing these- labels from prompts.+ labels from {skillsEnabled ? "prompts and skills" : "prompts"}.</p><div className="mb-4 flex flex-wrap gap-2">{protectedLabels.map((label) => (diff --git a/web/src/features/prompts/server/prompt-api-service.ts b/web/src/features/prompts/server/prompt-api-service.tsindex 2aab87a7b9..c16c31169c 100644--- a/web/src/features/prompts/server/prompt-api-service.ts+++ b/web/src/features/prompts/server/prompt-api-service.ts@@ -1,34 +1,26 @@-import { prisma, Role } from "@langfuse/shared/src/db";+import { prisma } from "@langfuse/shared/src/db";import {type CreatePromptSchema,type GetPromptByNameSchema,type GetPromptsMetaSchema,type Prompt,- ForbiddenError,InvalidRequestError,LangfuseConflictError,LangfuseNotFoundError,- hasProjectAccessByRole,} from "@langfuse/shared";-import { type ApiAccessLevel } from "@langfuse/shared/src/server";import type { z } from "zod";import { auditLog } from "@/src/features/audit-logs/server";import { type AuthorizationContext } from "@/src/features/auth/policy/types";-import { shadowAuthorize } from "@/src/features/public-api/server";import { createPrompt } from "./actions/createPrompt";import { deletePrompt } from "./actions/deletePrompt";import { getPromptByName } from "./actions/getPromptByName";import { getPromptsMeta } from "./actions/getPromptsMeta";import { updatePrompt } from "./actions/updatePrompts";-import { checkHasProtectedLabels } from "./utils/checkHasProtectedLabels";--type ApiKeyProjectContext = {- projectId: string;- orgId: string;- apiKeyId: string;- accessLevel: ApiAccessLevel;-};+import {+ authorizeProtectedLabelMutation,+ type ApiKeyProjectContext,+} from "./utils/authorizeProtectedLabelMutation";type ListPromptsForApiInput = z.infer<typeof GetPromptsMetaSchema> & {projectId: string;@@ -46,140 +38,6 @@ export const getPromptForApi = async (input: GetPromptForApiInput) => {return await getPromptByName(input);};-/**- * Resolve the in-app-agent key creator's project role the same way the worker- * run executor does: user.admin bypasses membership; otherwise org membership- * is required and a project membership override wins. Fail closed on missing- * user, missing org membership, or NONE.- */-async function resolveApiKeyCreatorProjectAccess(params: {- userId: string;- projectId: string;- orgId: string;-}): Promise<{- projectRole?: Role;- isAdmin: boolean;-} | null> {- const user = await prisma.user.findUnique({- where: { id: params.userId },- select: { id: true, admin: true },- });-- if (!user) {- return null;- }-- if (user.admin) {- return { isAdmin: true };- }-- const orgMembership = await prisma.organizationMembership.findFirst({- where: { userId: params.userId, orgId: params.orgId },- });-- if (!orgMembership) {- return null;- }-- const projectMembership = await prisma.projectMembership.findFirst({- where: {- userId: params.userId,- projectId: params.projectId,- orgMembershipId: orgMembership.id,- },- });-- const projectRole = projectMembership?.role ?? orgMembership.role;-- if (projectRole === Role.NONE) {- return null;- }-- return {- projectRole,- isAdmin: false,- };-}--/**- * Ordinary project API keys may still promote protected labels (CI). Temporary- * in-app-agent keys must honor the creator's promptProtectedLabels:CUD right.- * Call after checkHasProtectedLabels; skip when that result is false.- */-async function assertInAppAgentMayMutateProtectedLabels(params: {- context: ApiKeyProjectContext;- protectedLabels: string[];- forbiddenErrorMessage: string;-}): Promise<void> {- const apiKey = await prisma.apiKey.findUnique({- where: { id: params.context.apiKeyId },- select: {- isInAppAgentKey: true,- createdByUserId: true,- },- });-- if (!apiKey?.isInAppAgentKey) {- return;- }-- const access = apiKey.createdByUserId- ? await resolveApiKeyCreatorProjectAccess({- userId: apiKey.createdByUserId,- projectId: params.context.projectId,- orgId: params.context.orgId,- })- : null;-- const mayMutateProtectedLabels =- access !== null &&- hasProjectAccessByRole({- role: access.projectRole ?? Role.MEMBER,- admin: access.isAdmin,- scope: "promptProtectedLabels:CUD",- });-- if (!mayMutateProtectedLabels) {- throw new ForbiddenError(- `${params.forbiddenErrorMessage}\n\n Protected labels are: ${params.protectedLabels.join(", ")}`,- );- }-}--/** authorizeProtectedLabelMutation runs the per-item seam and the in-app-agent creator check when the label set includes a protected label. */-async function authorizeProtectedLabelMutation(params: {- context: ApiKeyProjectContext;- ctx?: AuthorizationContext;- labelsToCheck: string[];- forbiddenErrorMessage: string;-}): Promise<void> {- const { hasProtectedLabels, protectedLabels } = await checkHasProtectedLabels(- {- prisma,- projectId: params.context.projectId,- labelsToCheck: params.labelsToCheck,- },- );-- if (!hasProtectedLabels) {- return;- }-- const decision = shadowAuthorize({- ctx: params.ctx,- action: "promptProtectedLabels:CUD",- resource: { projectId: params.context.projectId },- accessLevel: params.context.accessLevel,- });- if (!decision.success) throw decision.error;-- await assertInAppAgentMayMutateProtectedLabels({- context: params.context,- protectedLabels,- forbiddenErrorMessage: params.forbiddenErrorMessage,- });-}-export const createPromptForApi = async ({context,input,@@ -190,6 +48,7 @@ export const createPromptForApi = async ({ctx?: AuthorizationContext;}) => {await authorizeProtectedLabelMutation({+ prisma,context,ctx,labelsToCheck: input.labels ?? [],@@ -272,6 +131,7 @@ export const updatePromptLabelsForApi = async ({);await authorizeProtectedLabelMutation({+ prisma,context,ctx,labelsToCheck: addedLabels,@@ -326,6 +186,7 @@ export const deletePromptForApi = async ({const prompts = await prisma.prompt.findMany({ where });await authorizeProtectedLabelMutation({+ prisma,context,ctx,labelsToCheck: prompts.flatMap((prompt) => prompt.labels),diff --git a/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts b/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.tsnew file mode 100644index 0000000000..1ef10bdb47--- /dev/null+++ b/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts@@ -0,0 +1,152 @@+import { type Prisma, Role } from "@langfuse/shared/src/db";+import { ForbiddenError, hasProjectAccessByRole } from "@langfuse/shared";+import { type ApiAccessLevel } from "@langfuse/shared/src/server";+import { type AuthorizationContext } from "@/src/features/auth/policy/types";+import { shadowAuthorize } from "@/src/features/public-api/server";+import { checkHasProtectedLabels } from "./checkHasProtectedLabels";++export type ApiKeyProjectContext = {+ projectId: string;+ orgId: string;+ apiKeyId: string;+ accessLevel: ApiAccessLevel;+};++/**+ * Resolve the in-app-agent key creator's project role the same way the worker+ * run executor does: user.admin bypasses membership; otherwise org membership+ * is required and a project membership override wins. Fail closed on missing+ * user, missing org membership, or NONE.+ */+async function resolveApiKeyCreatorProjectAccess(params: {+ prisma: Prisma.TransactionClient;+ userId: string;+ projectId: string;+ orgId: string;+}): Promise<{+ projectRole?: Role;+ isAdmin: boolean;+} | null> {+ const user = await params.prisma.user.findUnique({+ where: { id: params.userId },+ select: { id: true, admin: true },+ });++ if (!user) {+ return null;+ }++ if (user.admin) {+ return { isAdmin: true };+ }++ const orgMembership = await params.prisma.organizationMembership.findFirst({+ where: { userId: params.userId, orgId: params.orgId },+ });++ if (!orgMembership) {+ return null;+ }++ const projectMembership = await params.prisma.projectMembership.findFirst({+ where: {+ userId: params.userId,+ projectId: params.projectId,+ orgMembershipId: orgMembership.id,+ },+ });++ const projectRole = projectMembership?.role ?? orgMembership.role;++ if (projectRole === Role.NONE) {+ return null;+ }++ return {+ projectRole,+ isAdmin: false,+ };+}++/**+ * Ordinary project API keys may still promote protected labels (CI). Temporary+ * in-app-agent keys must honor the creator's promptProtectedLabels:CUD right.+ * Call after checkHasProtectedLabels; skip when that result is false.+ */+async function assertInAppAgentMayMutateProtectedLabels(params: {+ prisma: Prisma.TransactionClient;+ context: ApiKeyProjectContext;+ protectedLabels: string[];+ forbiddenErrorMessage: string;+}): Promise<void> {+ const apiKey = await params.prisma.apiKey.findUnique({+ where: { id: params.context.apiKeyId },+ select: {+ isInAppAgentKey: true,+ createdByUserId: true,+ },+ });++ if (!apiKey?.isInAppAgentKey) {+ return;+ }++ const access = apiKey.createdByUserId+ ? await resolveApiKeyCreatorProjectAccess({+ prisma: params.prisma,+ userId: apiKey.createdByUserId,+ projectId: params.context.projectId,+ orgId: params.context.orgId,+ })+ : null;++ const mayMutateProtectedLabels =+ access !== null &&+ hasProjectAccessByRole({+ role: access.projectRole ?? Role.MEMBER,+ admin: access.isAdmin,+ scope: "promptProtectedLabels:CUD",+ });++ if (!mayMutateProtectedLabels) {+ throw new ForbiddenError(+ `${params.forbiddenErrorMessage}\n\n Protected labels are: ${params.protectedLabels.join(", ")}`,+ );+ }+}++/** Authorize protected-label mutations for project API keys and their creators. */+export async function authorizeProtectedLabelMutation(params: {+ prisma: Prisma.TransactionClient;+ context: ApiKeyProjectContext;+ ctx?: AuthorizationContext;+ labelsToCheck: string[];+ forbiddenErrorMessage: string;+}): Promise<void> {+ const { hasProtectedLabels, protectedLabels } = await checkHasProtectedLabels(+ {+ prisma: params.prisma,+ projectId: params.context.projectId,+ labelsToCheck: params.labelsToCheck,+ },+ );++ if (!hasProtectedLabels) {+ return;+ }++ const decision = shadowAuthorize({+ ctx: params.ctx,+ action: "promptProtectedLabels:CUD",+ resource: { projectId: params.context.projectId },+ accessLevel: params.context.accessLevel,+ });+ if (!decision.success) throw decision.error;++ await assertInAppAgentMayMutateProtectedLabels({+ prisma: params.prisma,+ context: params.context,+ protectedLabels,+ forbiddenErrorMessage: params.forbiddenErrorMessage,+ });+}diff --git a/web/src/features/prompts/server/utils/checkHasProtectedLabels.ts b/web/src/features/prompts/server/utils/checkHasProtectedLabels.tsindex 3e2f955f46..cf9e306952 100644--- a/web/src/features/prompts/server/utils/checkHasProtectedLabels.ts+++ b/web/src/features/prompts/server/utils/checkHasProtectedLabels.ts@@ -1,9 +1,9 @@-import { type PrismaClient } from "@langfuse/shared";+import { type Prisma } from "@langfuse/shared";type CheckHasProtectedLabelsParams = {labelsToCheck: string[];projectId: string;- prisma: PrismaClient;+ prisma: Prisma.TransactionClient;};export async function checkHasProtectedLabels(diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsindex a76b510728..29445fc04f 100644--- a/web/src/features/search-bar/lib/fields.ts+++ b/web/src/features/search-bar/lib/fields.ts@@ -95,6 +95,7 @@ export type FieldRegistry = {| "legacyEvaluators"| "evalLogs"| "prompts"+ | "skills"| "monitors"| "gatewayModels"| "experimentItems"diff --git a/web/src/features/skills/README.md b/web/src/features/skills/README.mdnew file mode 100644index 0000000000..820a925c22--- /dev/null+++ b/web/src/features/skills/README.md@@ -0,0 +1,31 @@+## REST++- `GET /api/public/unstable/skills`+- `POST /api/public/unstable/skills`+- `GET /api/public/unstable/skills/{skillName}`+- `PATCH /api/public/unstable/skills/{skillName}`+- `GET /api/public/unstable/skills/files/{fileId}/content`+- `PATCH /api/public/unstable/skills/{skillName}/versions/{skillVersion}`+- `DELETE /api/public/unstable/skills/{skillName}/versions/{skillVersion}`++## tRPC++- Query: `skills.all`+- Query: `skills.filterOptions`+- Query: `skills.byName`+- Query: `skills.fileContent`+- Query: `skills.skillVersions`+- Mutation: `skills.createVersion`+- Mutation: `skills.setLabels`+- Mutation: `skills.setTags`+- Mutation: `skills.deleteVersion`+- Mutation: `skills.deleteSkill`++## MCP++Tools at `/api/public/mcp`:++- `listSkills`+- `getSkill`+- `loadSkill`+- `loadSkillResource`diff --git a/web/src/features/skills/actions/createSkillVersion.ts b/web/src/features/skills/actions/createSkillVersion.tsnew file mode 100644index 0000000000..05f1c55086--- /dev/null+++ b/web/src/features/skills/actions/createSkillVersion.ts@@ -0,0 +1,26 @@+import { CreateSkillVersionBodySchema } from "@langfuse/shared";+import { type SkillEditorStore } from "@/src/features/skills/components/skillEditorStore";+import { type RouterInputs } from "@/src/utils/api";++export async function createSkillVersionFromDraft(params: {+ projectId: string;+ store: SkillEditorStore;+ createVersion: (+ input: RouterInputs["skills"]["createVersion"],+ ) => Promise<{ id: string; name: string; version: number }>;+}) {+ const draft = params.store.getState();+ const files = Object.values(draft.files);+ const input = CreateSkillVersionBodySchema.parse({+ files: files.map((file) =>+ file.source+ ? { path: file.path, sha256Hash: file.source.sha256Hash }+ : { path: file.path, content: file.content },+ ),+ commitMessage: draft.commitMessage.trim() || null,+ });+ return params.createVersion({+ ...input,+ projectId: params.projectId,+ });+}diff --git a/web/src/features/skills/actions/downloadSkillVersion.ts b/web/src/features/skills/actions/downloadSkillVersion.tsnew file mode 100644index 0000000000..a01f589095--- /dev/null+++ b/web/src/features/skills/actions/downloadSkillVersion.ts@@ -0,0 +1,60 @@+import { zipSync } from "fflate";++function saveArchive(archive: Blob, filename: string) {+ const url = URL.createObjectURL(archive);+ const link = document.createElement("a");+ link.href = url;+ link.download = filename;+ link.click();+ URL.revokeObjectURL(url);+}++export async function downloadSkillVersion(params: {+ projectId: string;+ name: string;+ version: number;+ getVersion: (input: {+ projectId: string;+ name: string;+ version: number;+ }) => Promise<{+ createdAt: Date;+ files: Array<{ id: string; path: string }>;+ }>;+ getFileContent: (input: {+ projectId: string;+ fileId: string;+ }) => Promise<{ content: string }>;+ saveArchive?: (archive: Blob, filename: string) => void;+}): Promise<{ fileCount: number }> {+ const skill = await params.getVersion({+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ });+ const files: Record<string, Uint8Array> = {};+ const pendingFiles = skill.files.values();+ await Promise.all(+ Array.from({ length: Math.min(4, skill.files.length) }, async () => {+ for (const file of pendingFiles) {+ const { content } = await params.getFileContent({+ projectId: params.projectId,+ fileId: file.id,+ });+ files[file.path] = new TextEncoder().encode(content);+ }+ }),+ );+ const archive = new Blob(+ [+ new Uint8Array(zipSync(files, { level: 6, mtime: skill.createdAt }))+ .buffer,+ ],+ { type: "application/zip" },+ );+ (params.saveArchive ?? saveArchive)(+ archive,+ `${params.name}-v${params.version}.zip`,+ );+ return { fileCount: skill.files.length };+}diff --git a/web/src/features/skills/actions/importSkillFiles.ts b/web/src/features/skills/actions/importSkillFiles.tsnew file mode 100644index 0000000000..cf598a30d6--- /dev/null+++ b/web/src/features/skills/actions/importSkillFiles.ts@@ -0,0 +1,136 @@+import {+ MAX_SKILL_BYTES,+ MAX_SKILL_FILES,+ SkillVersionFileInputSchema,+} from "@langfuse/shared";+import { unzipSync } from "fflate";+import { type FileWithPath } from "react-dropzone";+import { getParentFolderPaths } from "../components/skillFileTree";+import {+ type SkillDraftFile,+ type SkillEditorStore,+} from "../components/skillEditorStore";++export async function importSkillFiles(+ store: SkillEditorStore,+ files: FileWithPath[],+) {+ const imports: SkillDraftFile[] = [];+ let importedBytes = 0;+ const checkBudget = (size: number) => {+ if (imports.length >= MAX_SKILL_FILES) {+ throw new Error(`A skill can contain at most ${MAX_SKILL_FILES} files.`);+ }+ if (size > MAX_SKILL_BYTES) {+ throw new Error(`Files must be at most ${MAX_SKILL_BYTES} bytes.`);+ }+ importedBytes += size;+ if (importedBytes > MAX_SKILL_BYTES) {+ throw new Error(`A skill can contain at most ${MAX_SKILL_BYTES} bytes.`);+ }+ };+ const addTextFile = (path: string, bytes: Uint8Array) => {+ checkBudget(bytes.byteLength);+ let content: string;+ try {+ content = new TextDecoder("utf-8", {+ fatal: true,+ ignoreBOM: true,+ }).decode(bytes);+ } catch {+ throw new Error(`Only UTF-8 text files are supported: ${path}`);+ }+ const result = SkillVersionFileInputSchema.safeParse({ path, content });+ if (!result.success) {+ throw new Error(`${path}: ${result.error.issues[0]!.message}`);+ }+ imports.push({ ...result.data, contentType: "text/plain" });+ };+ for (const file of files) {+ // file-selector prefixes dropped paths with "/" or "./".+ const path = (+ file.webkitRelativePath ||+ file.relativePath ||+ file.path ||+ file.name+ ).replace(/^(\.\/|\/)/, "");+ if (file.size > MAX_SKILL_BYTES) {+ throw new Error(+ `Files must be at most ${MAX_SKILL_BYTES} bytes: ${path}`,+ );+ }+ const bytes = new Uint8Array(await file.arrayBuffer());+ if (/\.zip$/i.test(path)) {+ let expandedBytes = importedBytes;+ let expandedFiles = imports.length;+ const archivePaths = new Set<string>();+ const entries = unzipSync(bytes, {+ filter: (entry) => {+ if (entry.name.endsWith("/")) return false;+ if (archivePaths.has(entry.name)) {+ throw new Error(`Duplicate ZIP entry: ${entry.name}`);+ }+ archivePaths.add(entry.name);+ expandedBytes += entry.originalSize;+ expandedFiles += 1;+ // Check the expanded sizes before allocating decompression buffers.+ if (+ entry.originalSize > MAX_SKILL_BYTES ||+ expandedBytes > MAX_SKILL_BYTES ||+ expandedFiles > MAX_SKILL_FILES+ ) {+ throw new Error(+ "The ZIP exceeds the skill size or file count limit.",+ );+ }+ return true;+ },+ });+ for (const [entryPath, entryBytes] of Object.entries(entries)) {+ addTextFile(entryPath, entryBytes);+ }+ } else {+ addTextFile(path, bytes);+ }+ }+ if (!imports.length) return [];+ const state = store.getState();+ const nextFiles = { ...state.files };+ for (const file of imports) {+ if (+ state.folders.includes(file.path) ||+ Object.keys(nextFiles).some(+ (path) =>+ path.startsWith(`${file.path}/`) || file.path.startsWith(`${path}/`),+ )+ ) {+ throw new Error(+ `A file or folder already exists at ${file.path}. No files were added.`,+ );+ }+ nextFiles[file.path] = file;+ }+ if (Object.keys(nextFiles).length > MAX_SKILL_FILES) {+ throw new Error(`A skill can contain at most ${MAX_SKILL_FILES} files.`);+ }+ const totalBytes = Object.values(nextFiles).reduce(+ (total, file) =>+ total ++ (file.source?.contentLength ??+ new TextEncoder().encode(file.content).byteLength),+ 0,+ );+ if (totalBytes > MAX_SKILL_BYTES) {+ throw new Error(`A skill can contain at most ${MAX_SKILL_BYTES} bytes.`);+ }+ const paths = imports.map((file) => file.path);+ store.setState({+ files: nextFiles,+ folders: [+ ...new Set([...state.folders, ...getParentFolderPaths(paths)]),+ ].toSorted(),+ activePath: imports[0]!.path,+ dirty: true,+ });+ return paths;+}diff --git a/web/src/features/skills/actions/saveSkillLabels.ts b/web/src/features/skills/actions/saveSkillLabels.tsnew file mode 100644index 0000000000..e2ae123f46--- /dev/null+++ b/web/src/features/skills/actions/saveSkillLabels.ts@@ -0,0 +1,35 @@+import { type SkillEditorStore } from "@/src/features/skills/components/skillEditorStore";+import { SKILL_LATEST_LABEL } from "@langfuse/shared";++export async function saveSkillLabels(params: {+ projectId: string;+ name: string;+ version: number;+ labels: string[];+ store: SkillEditorStore;+ setLabels: (input: {+ projectId: string;+ name: string;+ version: number;+ labels: string[];+ }) => Promise<unknown>;+ invalidate: () => Promise<unknown>;+ getLabels: (version: number) => Promise<string[]>;+}) {+ await params.setLabels({+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ labels: params.labels,+ });+ await params.invalidate();+ const selectedVersion = params.store.getState().baseVersion;+ if (selectedVersion !== null) {+ const labels = await params.getLabels(selectedVersion);+ params.store+ .getState()+ .actions.syncLabels(+ labels.filter((label) => label !== SKILL_LATEST_LABEL),+ );+ }+}diff --git a/web/src/features/skills/actions/saveSkillTags.ts b/web/src/features/skills/actions/saveSkillTags.tsnew file mode 100644index 0000000000..d7976e0515--- /dev/null+++ b/web/src/features/skills/actions/saveSkillTags.ts@@ -0,0 +1,25 @@+import { type SkillEditorStore } from "@/src/features/skills/components/skillEditorStore";++export async function saveSkillTags(params: {+ projectId: string;+ name: string;+ version: number;+ tags: string[];+ store: SkillEditorStore;+ setTags: (input: {+ projectId: string;+ name: string;+ version: number;+ tags: string[];+ }) => Promise<unknown>;+ invalidate: () => Promise<unknown>;+}) {+ await params.setTags({+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ tags: params.tags,+ });+ params.store.getState().actions.syncTags(params.tags);+ await params.invalidate();+}diff --git a/web/src/features/skills/components/CreateSkillVersionDialog.tsx b/web/src/features/skills/components/CreateSkillVersionDialog.tsxnew file mode 100644index 0000000000..645ecaaa0f--- /dev/null+++ b/web/src/features/skills/components/CreateSkillVersionDialog.tsx@@ -0,0 +1,90 @@+import { useStore } from "zustand";+import { Save, TriangleAlert } from "lucide-react";+import { Alert } from "@/src/components/design-system/Alert/Alert";+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";+import { Label } from "@/src/components/ui/label";+import { Textarea } from "@/src/components/ui/textarea";+import { type SkillEditorStore } from "@/src/features/skills/components/skillEditorStore";++export function CreateSkillVersionDialog({+ store,+ name,+ isFirstVersion,+ isSaving,+ disabled,+ onConfirm,+}: {+ store: SkillEditorStore;+ name: string;+ isFirstVersion: boolean;+ isSaving: boolean;+ disabled: boolean;+ onConfirm: () => Promise<void>;+}) {+ const originalName = useStore(store, (state) =>+ state.baseVersion === null ? null : state.name,+ );+ const commitMessage = useStore(store, (state) => state.commitMessage);+ const setCommitMessage = useStore(+ store,+ (state) => state.actions.setCommitMessage,+ );++ return (+ <Dialog+ title={isFirstVersion ? "Create skill" : "Create new version"}+ actions={[+ {+ label: isFirstVersion ? "Create skill" : "Create version",+ icon: Save,+ loading: isSaving,+ disabled,+ onClick: onConfirm,+ },+ ]}+ >+ <Dialog.Body>+ <div className="ph-no-capture flex flex-col gap-4">+ <p className="text-muted-foreground">+ {isFirstVersion ? (+ <>+ Create <strong>{name}</strong> as a new skill using the current+ files.+ </>+ ) : (+ <>+ Commit the current draft of <strong>{name}</strong> as an+ immutable version.+ </>+ )}+ </p>+ {isFirstVersion && originalName ? (+ <Alert variant="warning" icon={TriangleAlert}>+ <Alert.Title>You are duplicating this skill</Alert.Title>+ <Alert.Description>+ This creates <strong>{name}</strong> as a separate skill,+ starting at version 1. <strong>{originalName}</strong> stays+ unchanged.+ </Alert.Description>+ </Alert>+ ) : null}+ <div className="grid gap-2">+ <Label htmlFor="skill-version-note">Version note</Label>+ <p className="text-muted-foreground text-sm">+ Describe the changes in this version to make the history easier to+ understand.+ </p>+ <Textarea+ id="skill-version-note"+ value={commitMessage}+ onChange={(event) => setCommitMessage(event.target.value)}+ placeholder="Add version note…"+ rows={5}+ autoFocus+ />+ </div>+ </div>+ </Dialog.Body>+ </Dialog>+ );+}diff --git a/web/src/features/skills/components/SkillEditor.tsx b/web/src/features/skills/components/SkillEditor.tsxnew file mode 100644index 0000000000..506ab700ac--- /dev/null+++ b/web/src/features/skills/components/SkillEditor.tsx@@ -0,0 +1,611 @@+import { type ComponentProps, useState } from "react";+import { useStore } from "zustand";+import { useMediaQuery } from "react-responsive";+import {+ Download,+ Loader2,+ Plus,+ TriangleAlert,+ RotateCcw,+ Save,+} from "lucide-react";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { CodeMirrorEditor } from "@/src/components/editor";+import Page from "@/src/components/layouts/page";+import { Button } from "@/src/components/ui/button";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/src/components/ui/resizable";+import { showErrorToast, showSuccessToast } from "@/src/features/notifications";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { createSkillVersionFromDraft } from "@/src/features/skills/actions/createSkillVersion";+import { downloadSkillVersion } from "@/src/features/skills/actions/downloadSkillVersion";+import { saveSkillLabels } from "@/src/features/skills/actions/saveSkillLabels";+import { saveSkillTags } from "@/src/features/skills/actions/saveSkillTags";+import { CreateSkillVersionDialog } from "@/src/features/skills/components/CreateSkillVersionDialog";+import { SkillFileExplorer } from "@/src/features/skills/components/SkillFileExplorer";+import { getSkillFileLanguageExtensions } from "@/src/features/skills/utils/getSkillFileLanguageExtensions";+import {+ type SkillDraftFile,+ type SkillEditorInitialValue,+ type SkillEditorStore,+} from "@/src/features/skills/components/skillEditorStore";+import {+ SkillLabelsSelect,+ SkillTagsSelect,+} from "@/src/features/skills/components/SkillMetadataSelect";+import { SkillVersionHistory } from "@/src/features/skills/components/SkillVersionHistory";+import { useSkillFileContents } from "@/src/features/skills/hooks/useSkillFileContents";+import {+ parseSkillFrontmatterMetadata,+ SKILL_NAME_RULES,+} from "@/src/features/skills/utils/parseSkillFrontmatterMetadata";+import { api } from "@/src/utils/api";++export function SkillEditor({+ projectId,+ store,+ canCreate,+ onCreated,+ history,+ metadataOptions,+ headerProps,+}: {+ headerProps: ComponentProps<typeof Page>["headerProps"];+ projectId: string;+ store: SkillEditorStore;+ canCreate: boolean;+ onCreated: (created: { name: string; version: number }) => Promise<void>;+ history:+ | { kind: "new" }+ | {+ kind: "versions";+ versions: Array<{+ version: number;+ labels: string[];+ commitMessage: string | null;+ createdAt: Date;+ createdBy: string;+ creator: string | null | undefined;+ }>;+ selectedVersion: number;+ hasMore: boolean;+ isLoadingMore: boolean;+ loadMoreError: boolean;+ onLoadMore: () => void;+ onSelect: (version: number) => Promise<void>;+ };+ metadataOptions: { labels: string[]; tags: string[] };+}) {+ const dirty = useStore(store, (state) => state.dirty);+ const isImporting = useStore(store, (state) => state.isImporting);+ const fileCount = useStore(store, (state) => Object.keys(state.files).length);+ const name = useStore(store, (state) => state.name);+ const baseVersion = useStore(store, (state) => state.baseVersion);+ const skillMarkdown = useStore(+ store,+ (state) => state.files["SKILL.md"]?.content,+ );+ const metadata =+ skillMarkdown === undefined+ ? null+ : parseSkillFrontmatterMetadata(skillMarkdown);+ const draftName = metadata?.name.trim() ?? name;+ let nameError: string | null = null;+ if (skillMarkdown !== undefined) {+ nameError = metadata+ ? metadata.nameError+ : `Add valid YAML frontmatter with a name in SKILL.md. ${SKILL_NAME_RULES}`;+ }+ const hasNameChanged =+ baseVersion !== null &&+ skillMarkdown !== undefined &&+ (metadata?.name.trim() ?? "") !== name;+ const createsNewSkill = baseVersion === null || hasNameChanged;+ const nameAvailability = api.skills.all.useQuery(+ { projectId, name: draftName, page: 1, limit: 1 },+ { enabled: createsNewSkill && !nameError && Boolean(draftName) },+ );+ const isCheckingName =+ createsNewSkill && !nameError && nameAvailability.isPending;+ let createDisabledReason = nameError;+ if (createsNewSkill && !nameError) {+ if (nameAvailability.data?.data.length) {+ createDisabledReason = `A skill named "${draftName}" already exists. Choose a different name.`;+ } else if (nameAvailability.isError) {+ createDisabledReason =+ "Could not check whether this skill name is available. Please try again.";+ }+ }+ const nameWarning = [+ hasNameChanged+ ? `Versions must keep the name "${name}". Reset the name or create a new skill.`+ : null,+ createDisabledReason,+ ]+ .filter(Boolean)+ .join(" ");+ const createVersion = api.skills.createVersion.useMutation();+ const setVersionLabels = api.skills.setLabels.useMutation();+ const setVersionTags = api.skills.setTags.useMutation();+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const [isSaving, setIsSaving] = useState(false);+ const [isDownloading, setIsDownloading] = useState(false);+ const [isDraft, setIsDraft] = useState(baseVersion === null);+ const canEditFiles = isDraft && canCreate && !isSaving;+ const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });+ const createButtonTitle = canCreate+ ? (createDisabledReason ??+ (baseVersion !== null && !dirty+ ? "Edit the skill to create a new version"+ : undefined))+ : "You do not have write access";++ const save = async (createNew: boolean): Promise<boolean> => {+ if (+ !canCreate ||+ !isDraft ||+ isSaving ||+ store.getState().isImporting ||+ createDisabledReason ||+ isCheckingName ||+ (!createNew && (hasNameChanged || !store.getState().dirty))+ )+ return false;+ setIsSaving(true);+ try {+ const created = await createSkillVersionFromDraft({+ projectId,+ store,+ createVersion: (input) => createVersion.mutateAsync(input),+ });+ capture("skills:version_create", {+ fileCount,+ isFirstVersion: createNew,+ });+ showSuccessToast({+ title: "Skill version created",+ description: `Version ${created.version} is now available.`,+ });+ await onCreated(created);+ return true;+ } catch (error) {+ showErrorToast(+ "Failed to create skill version",+ error instanceof Error ? error.message : "Please try again.",+ );+ return false;+ } finally {+ setIsSaving(false);+ }+ };++ const saveLabels = async (+ version: number,+ labels: string[],+ ): Promise<boolean> => {+ try {+ await saveSkillLabels({+ projectId,+ name,+ version,+ labels,+ store,+ setLabels: (input) => setVersionLabels.mutateAsync(input),+ getLabels: async (selectedVersion) =>+ (+ await utils.skills.byName.fetch({+ projectId,+ name,+ version: selectedVersion,+ })+ ).labels,+ invalidate: () =>+ Promise.all([+ utils.skills.all.invalidate(),+ utils.skills.byName.invalidate(),+ utils.skills.skillVersions.invalidate(),+ ]),+ });+ showSuccessToast({+ title: "Skill labels updated",+ description: `Version ${version} now uses the selected labels.`,+ });+ return true;+ } catch (error) {+ showErrorToast(+ "Failed to update skill labels",+ error instanceof Error ? error.message : "Please try again.",+ );+ return false;+ }+ };++ const saveTags = async (tags: string[]): Promise<boolean> => {+ if (baseVersion === null) return false;+ try {+ await saveSkillTags({+ projectId,+ name,+ version: baseVersion,+ tags,+ store,+ setTags: (input) => setVersionTags.mutateAsync(input),+ invalidate: () =>+ Promise.all([+ utils.skills.all.invalidate(),+ utils.skills.filterOptions.invalidate(),+ utils.skills.byName.invalidate(),+ utils.skills.skillVersions.invalidate(),+ ]),+ });+ showSuccessToast({+ title: "Skill tags updated",+ description: "All versions now use the selected tags.",+ });+ return true;+ } catch (error) {+ showErrorToast(+ "Failed to update skill tags",+ error instanceof Error ? error.message : "Please try again.",+ );+ return false;+ }+ };++ const download = async () => {+ if (baseVersion === null) return;+ setIsDownloading(true);+ try {+ const result = await downloadSkillVersion({+ projectId,+ name,+ version: baseVersion,+ getVersion: (input) => utils.client.skills.byName.query(input),+ getFileContent: (input) => utils.skills.fileContent.fetch(input),+ });+ capture("skills:version_download", { fileCount: result.fileCount });+ } catch {+ showErrorToast(+ "Download failed",+ "Could not download this skill version. Please try again.",+ );+ } finally {+ setIsDownloading(false);+ }+ };++ const renderHeaderActions = (+ openDialog: (createNew: boolean) => void,+ closeMenu?: () => void,+ ) => (+ <div className="flex max-w-full flex-wrap items-center justify-start gap-2 sm:justify-end">+ {baseVersion !== null ? (+ <>+ <SkillMetadataFields+ store={store}+ canEdit={canCreate}+ isSavingLabels={setVersionLabels.isPending}+ isSavingTags={setVersionTags.isPending}+ onSaveLabels={(labels) =>+ baseVersion === null+ ? Promise.resolve(false)+ : saveLabels(baseVersion, labels)+ }+ onSaveTags={saveTags}+ metadataOptions={metadataOptions}+ />+ <div className="bg-border hidden h-6 w-px sm:block" />+ </>+ ) : null}+ {baseVersion !== null ? (+ <Button+ type="button"+ variant="outline"+ onClick={download}+ disabled={isDownloading}+ aria-label={`Download version ${baseVersion}`}+ >+ {isDownloading ? (+ <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />+ ) : (+ <Download className="mr-1.5 h-4 w-4" />+ )}+ Download+ </Button>+ ) : null}+ {nameWarning ? (+ <Tooltip label={nameWarning}>+ {({ getTriggerProps }) => (+ <button+ type="button"+ aria-label="Skill name warning"+ className="text-dark-yellow flex shrink-0 items-center"+ {...getTriggerProps()}+ >+ <TriangleAlert className="h-4 w-4" />+ </button>+ )}+ </Tooltip>+ ) : null}+ {hasNameChanged ? (+ <Tooltip label={`Reset name to "${name}"`}>+ {({ getTriggerProps }) => (+ <IconButton+ {...getTriggerProps()}+ icon={RotateCcw}+ label="Reset skill name"+ size="sm"+ onClick={() => store.getState().actions.resetName()}+ />+ )}+ </Tooltip>+ ) : null}+ {!isDraft ? (+ <Button+ disabled={!canCreate}+ title={!canCreate ? "You do not have write access" : undefined}+ onClick={() => {+ closeMenu?.();+ setIsDraft(true);+ }}+ >+ <Plus className="mr-1.5 h-4 w-4" />+ New version+ </Button>+ ) : (+ <Button+ onClick={() => {+ closeMenu?.();+ openDialog(createsNewSkill);+ }}+ disabled={+ !canCreate ||+ isSaving ||+ isImporting ||+ (!createsNewSkill && !dirty) ||+ Boolean(createDisabledReason) ||+ isCheckingName+ }+ title={createButtonTitle}+ >+ <Save className="mr-1.5 h-4 w-4" />+ Save+ </Button>+ )}+ </div>+ );++ return (+ <DialogController<boolean>+ renderDialog={({ state: createNew, closeDialog }) => (+ <CreateSkillVersionDialog+ store={store}+ name={createNew ? draftName : name}+ isFirstVersion={createNew}+ isSaving={isSaving}+ disabled={+ isImporting ||+ Boolean(createDisabledReason) ||+ isCheckingName ||+ (!createNew && (hasNameChanged || !dirty))+ }+ onConfirm={async () => {+ if (await save(createNew)) closeDialog();+ }}+ />+ )}+ >+ {({ openDialog }) => (+ <Page+ headerProps={{+ ...headerProps,+ actionButtonsRight: renderHeaderActions(openDialog),+ actionButtonsMenu: ({ closeMenu }) =>+ renderHeaderActions(openDialog, () =>+ closeMenu({ handoffFocus: true }),+ ),+ }}+ >+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto md:overflow-hidden">+ <div className="flex min-h-[720px] flex-1 flex-col overflow-hidden border-t md:min-h-[560px] md:flex-row">+ {history.kind === "versions" ? (+ <SkillVersionHistory+ {...history}+ dirty={dirty}+ isDraft={isDraft}+ canEdit={canCreate}+ labelOptions={metadataOptions.labels}+ isSavingLabels={setVersionLabels.isPending}+ onSaveLabels={saveLabels}+ />+ ) : (+ <SkillVersionHistory kind="new" />+ )}+ <div className="min-h-[720px] min-w-0 flex-1 md:min-h-0">+ <ResizablePanelGroup+ key={isDesktop ? "desktop" : "mobile"}+ orientation={isDesktop ? "horizontal" : "vertical"}+ >+ <ResizablePanel+ defaultSize={isDesktop ? "28%" : "32%"}+ minSize={isDesktop ? "20%" : "24%"}+ maxSize={isDesktop ? "42%" : "50%"}+ >+ <SkillFileExplorer+ store={store}+ readOnly={!isDraft || !canCreate}+ disabled={isSaving}+ />+ </ResizablePanel>+ <ResizableHandle withHandle />+ <ResizablePanel+ defaultSize={isDesktop ? "72%" : "68%"}+ minSize={isDesktop ? "45%" : "42%"}+ >+ <SkillFileEditor+ projectId={projectId}+ store={store}+ editable={canEditFiles}+ />+ </ResizablePanel>+ </ResizablePanelGroup>+ </div>+ </div>+ </div>+ </Page>+ )}+ </DialogController>+ );+}++function SkillMetadataFields({+ store,+ canEdit,+ isSavingLabels,+ isSavingTags,+ onSaveLabels,+ onSaveTags,+ metadataOptions,+}: {+ store: SkillEditorStore;+ canEdit: boolean;+ isSavingLabels: boolean;+ isSavingTags: boolean;+ onSaveLabels: (labels: string[]) => Promise<boolean>;+ onSaveTags: (tags: string[]) => Promise<boolean>;+ metadataOptions: { labels: string[]; tags: string[] };+}) {+ const labels = useStore(store, (state) => state.labels);+ const tags = useStore(store, (state) => state.tags);++ return (+ <div className="ph-no-capture flex max-w-full flex-wrap items-center gap-2">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="text-muted-foreground text-xs">Labels</span>+ <SkillLabelsSelect+ showOnlyOnHover={false}+ value={labels}+ options={metadataOptions.labels}+ disabled={!canEdit}+ isSaving={isSavingLabels}+ onSave={onSaveLabels}+ />+ </div>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="text-muted-foreground text-xs">Tags</span>+ <SkillTagsSelect+ value={tags}+ options={metadataOptions.tags}+ disabled={!canEdit}+ isSaving={isSavingTags}+ onSave={onSaveTags}+ />+ </div>+ </div>+ );+}++function SkillFileEditor({+ projectId,+ store,+ editable,+}: {+ projectId: string;+ store: SkillEditorStore;+ editable: boolean;+}) {+ const activePath = useStore(store, (state) => state.activePath);+ const activeFile = useStore(store, (state) => state.files[state.activePath]!);+ const updateActiveFile = useStore(+ store,+ (state) => state.actions.updateActiveFile,+ );+ const fileContents = useSkillFileContents(projectId, activeFile);+ const content = activeFile.content ?? fileContents.data?.content;++ let editorContent;+ if (content === undefined && fileContents.isError) {+ editorContent = (+ <div className="flex flex-col items-start gap-2 text-sm">+ <p>{fileContents.error.message}</p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ fileContents.refetch();+ }}+ >+ Retry+ </Button>+ </div>+ );+ } else if (content === undefined) {+ editorContent = (+ <div role="status" className="flex items-center gap-2 text-sm">+ <Loader2 className="h-4 w-4 animate-spin" /> Loading file…+ </div>+ );+ } else {+ editorContent = (+ <CodeMirrorEditor+ key={activePath}+ value={content}+ onChange={editable ? updateActiveFile : undefined}+ editable={editable}+ mode="text"+ extensions={getSkillFileLanguageExtensions(activePath)}+ minHeight="500px"+ lineNumbers+ className="h-full"+ />+ );+ }++ return (+ <section className="ph-no-capture flex h-full min-w-0 flex-col">+ <div className="flex min-h-11 items-center justify-between gap-2 border-b px-3">+ <span className="min-w-0 truncate font-mono text-xs" title={activePath}>+ {activePath}+ </span>+ </div>+ <div className="min-h-0 flex-1 overflow-auto p-3">{editorContent}</div>+ </section>+ );+}++export const NEW_SKILL_INITIAL_VALUE: SkillEditorInitialValue = {+ name: "",+ baseVersion: null,+ labels: [],+ tags: [],+ files: [+ {+ path: "SKILL.md",+ content:+ "---\nname: my-skill\ndescription: Describe when and how to use this skill.\n---\n\n# Instructions\n\nAdd instructions for the agent here.\n",+ contentType: "text/markdown",+ },+ ],+};++export function toSkillEditorInitialValue(skill: {+ name: string;+ version: number;+ labels: string[];+ tags: string[];+ files: SkillDraftFile[];+}): SkillEditorInitialValue {+ return {+ name: skill.name,+ baseVersion: skill.version,+ labels: skill.labels,+ tags: skill.tags,+ files: skill.files,+ };+}diff --git a/web/src/features/skills/components/SkillEditorPage.tsx b/web/src/features/skills/components/SkillEditorPage.tsxnew file mode 100644index 0000000000..ee24ebd401--- /dev/null+++ b/web/src/features/skills/components/SkillEditorPage.tsx@@ -0,0 +1,230 @@+import { type ComponentProps, useState } from "react";+import { useRouter } from "next/router";+import { useStore } from "zustand";+import Page from "@/src/components/layouts/page";+import { Skeleton } from "@/src/components/ui/skeleton";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ NEW_SKILL_INITIAL_VALUE,+ SkillEditor,+ toSkillEditorInitialValue,+} from "@/src/features/skills/components/SkillEditor";+import {+ createSkillEditorStore,+ type SkillEditorInitialValue,+} from "@/src/features/skills/components/skillEditorStore";+import { parseSkillFrontmatterMetadata } from "@/src/features/skills/utils/parseSkillFrontmatterMetadata";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { api } from "@/src/utils/api";++export function NewSkillPage() {+ const router = useRouter();+ const projectId = useProjectIdFromURL();+ const canCreate = useHasProjectAccess({+ projectId: projectId ?? "",+ scope: "skills:CUD",+ });+ const utils = api.useUtils();+ const filterOptions = api.skills.filterOptions.useQuery(+ { projectId: projectId ?? "" },+ { enabled: Boolean(projectId), refetchOnWindowFocus: false },+ );+ const [store] = useState(() =>+ createSkillEditorStore(NEW_SKILL_INITIAL_VALUE),+ );+ const skillMarkdown = useStore(+ store,+ (state) => state.files["SKILL.md"]?.content ?? "",+ );+ const metadata = parseSkillFrontmatterMetadata(skillMarkdown);++ return (+ <SkillEditor+ headerProps={{+ title: metadata?.name.trim() ? metadata.name : "Create skill",+ help:+ metadata && !metadata.nameError+ ? {+ description:+ "The skill name and description are parsed from the frontmatter in SKILL.md.",+ }+ : undefined,+ breadcrumb: [+ { name: "Skills", href: `/project/${projectId}/skills` },+ { name: "New skill" },+ ],+ }}+ projectId={projectId ?? ""}+ store={store}+ canCreate={canCreate}+ history={{ kind: "new" }}+ metadataOptions={{+ labels: ["production"],+ tags: filterOptions.data?.tags.map((tag) => tag.value) ?? [],+ }}+ onCreated={async (created) => {+ await Promise.all([+ utils.skills.all.invalidate(),+ utils.skills.filterOptions.invalidate(),+ ]);+ await router.push(+ `/project/${projectId}/skills/${encodeURIComponent(created.name)}?version=${created.version}`,+ );+ }}+ />+ );+}++export function ExistingSkillPage() {+ const router = useRouter();+ const [editorSession, setEditorSession] = useState(0);+ const projectId = useProjectIdFromURL();+ const skillName =+ typeof router.query.skillName === "string" ? router.query.skillName : "";+ const requestedVersion =+ typeof router.query.version === "string"+ ? Number(router.query.version)+ : undefined;+ const version = Number.isInteger(requestedVersion)+ ? requestedVersion+ : undefined;+ const canCreate = useHasProjectAccess({+ projectId: projectId ?? "",+ scope: "skills:CUD",+ });+ const utils = api.useUtils();+ const filterOptions = api.skills.filterOptions.useQuery(+ {+ projectId: projectId ?? "",+ },+ {+ enabled: Boolean(projectId && skillName),+ refetchOnWindowFocus: false,+ },+ );+ const skill = api.skills.byName.useQuery(+ {+ projectId: projectId ?? "",+ name: skillName,+ ...(version ? { version } : { label: "latest" }),+ },+ {+ enabled: Boolean(projectId && skillName),+ refetchOnWindowFocus: false,+ },+ );++ const history = api.skills.skillVersions.useInfiniteQuery(+ { projectId: projectId ?? "", name: skillName, limit: 20 },+ {+ getNextPageParam: (page) => page.nextCursor,+ enabled: Boolean(projectId && skillName),+ refetchOnWindowFocus: false,+ },+ );+ const error =+ (skill.data ? null : skill.error) ?? (history.data ? null : history.error);++ const headerProps: ComponentProps<typeof Page>["headerProps"] = {+ title: skill.data?.name ?? skillName,+ help: skill.data+ ? {+ description: "Edit SKILL.md to change the skill name.",+ }+ : undefined,+ breadcrumb: [+ { name: "Skills", href: `/project/${projectId}/skills` },+ { name: "Editor" },+ ],+ };++ let content = <div className="p-6 text-sm">Skill version not found.</div>;+ if (error) {+ content = <div className="ph-no-capture p-6 text-sm">{error.message}</div>;+ } else if (skill.isPending || history.isPending) {+ content = (+ <div className="grid gap-3 p-3">+ <Skeleton className="h-10 w-full" />+ <Skeleton className="h-[600px] w-full" />+ </div>+ );+ } else if (skill.data && history.data) {+ return (+ <SkillEditorForInitialValue+ headerProps={headerProps}+ key={`${skill.data.id}:${editorSession}`}+ projectId={projectId ?? ""}+ initialValue={toSkillEditorInitialValue({+ ...skill.data,+ files: skill.data.files.map((file) => ({+ path: file.path,+ contentType: file.contentType,+ source: {+ fileId: file.id,+ contentLength: file.contentLength,+ sha256Hash: file.sha256Hash,+ },+ })),+ })}+ canCreate={canCreate}+ metadataOptions={{+ labels: [+ ...new Set([+ "production",+ ...skill.data.labels,+ ...history.data.pages.flatMap((page) =>+ page.items.flatMap((item) => item.labels),+ ),+ ]),+ ],+ tags: filterOptions.data?.tags.map((tag) => tag.value) ?? [],+ }}+ history={{+ kind: "versions",+ versions: history.data.pages.flatMap((page) => page.items),+ hasMore: history.hasNextPage,+ isLoadingMore: history.isFetchingNextPage,+ loadMoreError: history.isFetchNextPageError,+ onLoadMore: () => history.fetchNextPage(),+ selectedVersion: skill.data.version,+ onSelect: async (selectedVersion) => {+ await router.push({+ pathname: router.pathname,+ query: { projectId, skillName, version: selectedVersion },+ });+ setEditorSession((session) => session + 1);+ },+ }}+ onCreated={async (created) => {+ await Promise.all([+ utils.skills.all.invalidate(),+ utils.skills.filterOptions.invalidate(),+ utils.skills.byName.invalidate(),+ utils.skills.skillVersions.invalidate(),+ ]);+ await router.push({+ pathname: router.pathname,+ query: {+ projectId,+ skillName: created.name,+ version: created.version,+ },+ });+ }}+ />+ );+ }++ return <Page headerProps={headerProps}>{content}</Page>;+}++function SkillEditorForInitialValue({+ initialValue,+ ...props+}: Omit<ComponentProps<typeof SkillEditor>, "store"> & {+ initialValue: SkillEditorInitialValue;+}) {+ const [store] = useState(() => createSkillEditorStore(initialValue));++ return <SkillEditor {...props} store={store} />;+}diff --git a/web/src/features/skills/components/SkillFileExplorer.tsx b/web/src/features/skills/components/SkillFileExplorer.tsxnew file mode 100644index 0000000000..a0cb94a90b--- /dev/null+++ b/web/src/features/skills/components/SkillFileExplorer.tsx@@ -0,0 +1,671 @@+import { useId, useState, type ReactNode } from "react";+import { useStore } from "zustand";+import {+ DndContext,+ KeyboardSensor,+ PointerSensor,+ pointerWithin,+ rectIntersection,+ useDraggable,+ useDroppable,+ useSensor,+ useSensors,+ type CollisionDetection,+ type DragEndEvent,+} from "@dnd-kit/core";+import { CSS } from "@dnd-kit/utilities";+import {+ ChevronRight,+ Check,+ File,+ FileCode2,+ FilePlus2,+ Folder,+ FolderOpen,+ FolderPlus,+ Trash2,+ Upload,+ X,+} from "lucide-react";+import {+ MAX_SKILL_FILES,+ SkillFilePathSchema,+ SkillVersionFileInputSchema,+} from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { DropzoneController } from "@/src/components/design-system/DropzoneController/DropzoneController";+import { showErrorToast } from "@/src/features/notifications";+import { importSkillFiles } from "@/src/features/skills/actions/importSkillFiles";+import {+ buildSkillFileTree,+ getParentFolderPaths,+ type SkillFileTreeNode,+} from "@/src/features/skills/components/skillFileTree";+import { type SkillEditorStore } from "@/src/features/skills/components/skillEditorStore";+import { cn } from "@/src/utils/tailwind";++type PendingEntry = {+ kind: "file" | "folder";+ parentPath: string;+ name: string;+};++export function SkillFileExplorer({+ store,+ disabled = false,+ readOnly = false,+}: {+ store: SkillEditorStore;+ disabled?: boolean;+ readOnly?: boolean;+}) {+ const files = useStore(store, (state) => state.files);+ const folders = useStore(store, (state) => state.folders);+ const activePath = useStore(store, (state) => state.activePath);+ const actions = useStore(store, (state) => state.actions);+ const [selectedFolder, setSelectedFolder] = useState("");+ const [expandedFolders, setExpandedFolders] = useState(+ () => new Set(store.getState().folders),+ );+ const [pendingEntry, setPendingEntry] = useState<PendingEntry | null>(null);+ const isImporting = useStore(store, (state) => state.isImporting);+ const tree = buildSkillFileTree(Object.keys(files), folders);+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),+ useSensor(KeyboardSensor),+ );+ const moveDisabled = readOnly || disabled || isImporting;++ const handleDragEnd = ({ active, over }: DragEndEvent) => {+ const path = active.data.current?.path;+ const targetFolder = over?.data.current?.path;+ if (+ moveDisabled ||+ typeof path !== "string" ||+ typeof targetFolder !== "string"+ )+ return;+ const isFolder = active.data.current?.kind === "folder";+ const moved = isFolder+ ? actions.moveFolder(path, targetFolder)+ : actions.moveFile(path, targetFolder);+ if (!moved) {+ showErrorToast(+ `Could not move ${isFolder ? "folder" : "file"}`,+ "The destination conflicts with an existing file or folder, or the move is invalid.",+ );+ return;+ }+ const nextPath = joinPath(targetFolder, path.split("/").at(-1)!);+ setSelectedFolder(isFolder ? nextPath : targetFolder);+ setExpandedFolders(+ (current) =>+ new Set([+ ...[...current].map((folder) =>+ isFolder && (folder === path || folder.startsWith(`${path}/`))+ ? `${nextPath}${folder.slice(path.length)}`+ : folder,+ ),+ ...(targetFolder ? [targetFolder] : []),+ ]),+ );+ setPendingEntry(null);+ };++ const toggleFolder = (path: string) => {+ setSelectedFolder(path);+ setExpandedFolders((current) => {+ const next = new Set(current);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ return next;+ });+ };++ const startEntry = (kind: PendingEntry["kind"]) => {+ if (moveDisabled) return;+ const parentPath = selectedFolder;+ if (parentPath) {+ setExpandedFolders((current) => new Set([...current, parentPath]));+ }+ setPendingEntry({ kind, parentPath, name: "" });+ };++ const submitEntry = () => {+ if (!pendingEntry || moveDisabled) return;++ const name = pendingEntry.name.trim();+ const path = joinPath(pendingEntry.parentPath, name);+ const parsed =+ pendingEntry.kind === "folder"+ ? SkillFilePathSchema.safeParse(path)+ : SkillVersionFileInputSchema.safeParse({ path, content: "" });+ if (+ !parsed.success ||+ (pendingEntry.kind === "folder" && name.includes("/"))+ ) {+ const validationMessage = !parsed.success+ ? parsed.error.issues[0]?.message+ : "Use a relative file path, such as docs/readme.md.";+ showErrorToast(+ `Invalid ${pendingEntry.kind} name`,+ pendingEntry.kind === "folder"+ ? "Use a single normalized path segment."+ : validationMessage,+ );+ return;+ }++ if (+ pendingEntry.kind === "file" &&+ Object.keys(files).length >= MAX_SKILL_FILES+ ) {+ showErrorToast(+ "Could not add file",+ `A skill can contain at most ${MAX_SKILL_FILES} files.`,+ );+ return;+ }++ const created =+ pendingEntry.kind === "folder"+ ? actions.addFolder(path)+ : actions.addFile({+ path,+ content: "",+ contentType: getContentType(path),+ });+ if (!created) {+ showErrorToast(+ `${pendingEntry.kind === "folder" ? "Folder" : "File"} already exists`,+ path,+ );+ return;+ }++ setSelectedFolder(+ pendingEntry.kind === "folder" ? path : parentFolder(path),+ );+ setExpandedFolders(+ (current) =>+ new Set([+ ...current,+ ...getParentFolderPaths([path]),+ ...(pendingEntry.kind === "folder" ? [path] : []),+ ]),+ );+ setPendingEntry(null);+ };++ const renderPendingEntry = (parentPath: string): ReactNode => {+ if (!pendingEntry || pendingEntry.parentPath !== parentPath) return null;+ const label = pendingEntry.kind === "folder" ? "folder" : "file";++ return (+ <form+ className="flex min-w-0 items-center gap-1 py-0.5 pl-1"+ onSubmit={(event) => {+ event.preventDefault();+ submitEntry();+ }}+ >+ {pendingEntry.kind === "folder" ? (+ <Folder className="text-muted-foreground h-4 w-4 shrink-0" />+ ) : (+ <FileCode2 className="text-muted-foreground h-4 w-4 shrink-0" />+ )}+ <Input+ autoFocus+ value={pendingEntry.name}+ onChange={(event) =>+ setPendingEntry({ ...pendingEntry, name: event.target.value })+ }+ onKeyDown={(event) => {+ if (event.key === "Escape") setPendingEntry(null);+ }}+ aria-label={`New ${label} name${parentPath ? ` in ${parentPath}` : ""}`}+ disabled={moveDisabled}+ placeholder={+ pendingEntry.kind === "folder" ? "folder-name" : "docs/readme.md"+ }+ className="h-7 min-w-0 px-2 font-mono text-xs"+ />+ <Button+ type="submit"+ variant="ghost"+ size="icon-sm"+ aria-label={`Create new ${label}`}+ disabled={moveDisabled}+ >+ <Check className="h-3.5 w-3.5" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={`Cancel new ${label}`}+ onClick={() => setPendingEntry(null)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </form>+ );+ };++ const renderTree = (+ nodes: SkillFileTreeNode[],+ parentPath: string,+ ): ReactNode => (+ <>+ {renderPendingEntry(parentPath)}+ {nodes.map((node) => {+ if (node.kind === "file") {+ return (+ <DraggableSkillFile+ key={node.path}+ path={node.path}+ name={node.name}+ disabled={moveDisabled}+ active={activePath === node.path}+ onSelect={() => {+ actions.selectFile(node.path);+ setSelectedFolder(parentFolder(node.path));+ }}+ onDelete={() => actions.deleteFile(node.path)}+ />+ );+ }++ const isExpanded = expandedFolders.has(node.path);+ const isEmpty = node.children.length === 0;+ return (+ <div key={node.path}>+ <DraggableSkillFolder+ path={node.path}+ name={node.name}+ disabled={moveDisabled}+ selected={selectedFolder === node.path}+ expanded={isExpanded}+ empty={isEmpty}+ onToggle={() => toggleFolder(node.path)}+ onDelete={() => {+ if (actions.deleteFolder(node.path)) {+ setSelectedFolder(parentFolder(node.path));+ }+ }}+ />+ {isExpanded ? (+ <div className="border-border/70 ml-3 border-l pl-1.5">+ {renderTree(node.children, node.path)}+ </div>+ ) : null}+ </div>+ );+ })}+ </>+ );++ return (+ <div className="ph-no-capture h-full">+ <DndContext+ sensors={sensors}+ collisionDetection={skillMoveCollisionDetection}+ onDragEnd={handleDragEnd}+ >+ <DropzoneController+ noClick+ noKeyboard+ isDisabled={moveDisabled}+ onError={(error) =>+ showErrorToast("Could not add files", error.message)+ }+ onProcessingChange={(isImporting) => store.setState({ isImporting })}+ onDrop={async (droppedFiles) => {+ const paths = await importSkillFiles(store, droppedFiles);+ setExpandedFolders(+ (current) =>+ new Set([...current, ...getParentFolderPaths(paths)]),+ );+ setSelectedFolder("");+ setPendingEntry(null);+ }}+ >+ {({+ getRootProps,+ getInputProps,+ isDragActive,+ open,+ openDirectory,+ }) => (+ <aside+ {...getRootProps({+ role: "region",+ "aria-label": "Skill files",+ className: cn(+ "ph-no-capture bg-muted/20 relative flex h-full min-w-0 flex-col",+ isDragActive && "ring-primary ring-2 ring-inset",+ ),+ })}+ >+ <input {...getInputProps()} aria-label="Add files to draft" />+ <div className="flex min-h-11 items-center justify-between gap-2 border-b px-3">+ <SkillFolderDropTarget path="" disabled={moveDisabled}>+ <button+ type="button"+ aria-label="Root folder"+ title="Drop a file here to move it to the root"+ onClick={() => setSelectedFolder("")}+ className="flex items-center gap-2 rounded px-1 py-2 text-sm font-bold"+ >+ <FolderOpen className="h-4 w-4" /> Files+ </button>+ </SkillFolderDropTarget>+ {!readOnly ? (+ <div className="flex items-center gap-0.5">+ <DropdownMenu+ disabled={disabled || isImporting}+ items={[+ {+ id: "files",+ type: "item",+ title: "Add files",+ icon: FilePlus2,+ onClick: open,+ },+ {+ id: "folder",+ type: "item",+ title: "Add folder",+ icon: FolderPlus,+ onClick: openDirectory,+ },+ ]}+ >+ {({ getTriggerProps }) => (+ <IconButton+ {...getTriggerProps()}+ icon={Upload}+ label="Upload files or folder"+ size="sm"+ disabled={disabled || isImporting}+ />+ )}+ </DropdownMenu>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ title="New file"+ aria-label="New file"+ disabled={moveDisabled}+ onClick={() => startEntry("file")}+ >+ <FilePlus2 className="h-4 w-4" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ title="New folder"+ aria-label="New folder"+ disabled={moveDisabled}+ onClick={() => startEntry("folder")}+ >+ <FolderPlus className="h-4 w-4" />+ </Button>+ </div>+ ) : null}+ </div>+ <div className="flex flex-1 flex-col overflow-y-auto p-2">+ {renderTree(tree, "")}+ <SkillFolderDropTarget+ path=""+ disabled={moveDisabled}+ variant="empty-space"+ />+ </div>+ {isImporting ? (+ <p className="text-muted-foreground border-t px-3 py-2 text-xs leading-4">+ Adding files to draft…+ </p>+ ) : null}+ {isDragActive ? (+ <div className="bg-background/90 pointer-events-none absolute inset-0 flex items-center justify-center p-4 text-center text-sm font-bold">+ Drop files or folders to add to draft+ </div>+ ) : null}+ </aside>+ )}+ </DropzoneController>+ </DndContext>+ </div>+ );+}++const skillMoveCollisionDetection: CollisionDetection = (args) => {+ const source = args.active.data.current;+ const droppableContainers = args.droppableContainers.filter((container) => {+ const target = container.data.current?.path;+ return (+ source?.kind !== "folder" ||+ (target !== source.path && !target?.startsWith(`${source.path}/`))+ );+ });+ const candidates = { ...args, droppableContainers };+ return args.pointerCoordinates+ ? pointerWithin(candidates)+ : rectIntersection(candidates);+};++function DraggableSkillFile({+ path,+ name,+ disabled,+ active,+ onSelect,+ onDelete,+}: {+ path: string;+ name: string;+ disabled: boolean;+ active: boolean;+ onSelect: () => void;+ onDelete: () => void;+}) {+ const movable = path !== "SKILL.md";+ const draggable = movable && !disabled;+ const {+ attributes,+ listeners,+ setNodeRef,+ setActivatorNodeRef,+ transform,+ isDragging,+ } = useDraggable({+ id: `file:${path}`,+ data: { path },+ disabled: !draggable,+ });++ return (+ <div+ ref={setNodeRef}+ style={{ transform: CSS.Translate.toString(transform) }}+ className={cn(+ "group relative flex w-full items-center rounded text-sm",+ active ? "bg-accent text-accent-foreground" : "hover:bg-accent/60",+ isDragging && "z-1 opacity-60",+ )}+ >+ <button+ ref={setActivatorNodeRef}+ type="button"+ {...(draggable ? attributes : {})}+ {...(draggable ? listeners : {})}+ onClick={onSelect}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-2 px-1.5 py-1.5 text-left",+ draggable && "cursor-grab touch-none active:cursor-grabbing",+ )}+ >+ {path.endsWith(".md") ? (+ <FileCode2 className="h-4 w-4 shrink-0" />+ ) : (+ <File className="h-4 w-4 shrink-0" />+ )}+ <span className="min-w-0 flex-1 truncate" title={path}>+ {name}+ </span>+ </button>+ {movable && !disabled ? (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={`Delete ${path}`}+ onClick={onDelete}+ className="mr-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus:opacity-100"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ ) : null}+ </div>+ );+}++function DraggableSkillFolder({+ path,+ name,+ disabled,+ selected,+ expanded,+ empty,+ onToggle,+ onDelete,+}: {+ path: string;+ name: string;+ disabled: boolean;+ selected: boolean;+ expanded: boolean;+ empty: boolean;+ onToggle: () => void;+ onDelete: () => void;+}) {+ const {+ attributes,+ listeners,+ setNodeRef,+ setActivatorNodeRef,+ transform,+ isDragging,+ } = useDraggable({+ id: `folder-drag:${path}`,+ data: { path, kind: "folder" },+ disabled,+ });+ return (+ <SkillFolderDropTarget path={path} disabled={disabled}>+ <div+ ref={setNodeRef}+ style={{ transform: CSS.Translate.toString(transform) }}+ className={cn(+ "group relative flex w-full items-center rounded text-sm",+ selected+ ? "bg-accent/70 text-accent-foreground"+ : "hover:bg-accent/60",+ isDragging && "z-1 opacity-60",+ )}+ >+ <button+ ref={setActivatorNodeRef}+ type="button"+ {...(disabled ? {} : attributes)}+ {...(disabled ? {} : listeners)}+ aria-expanded={expanded}+ onClick={onToggle}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-1 px-1 py-1.5 text-left",+ !disabled && "cursor-grab touch-none active:cursor-grabbing",+ )}+ >+ <ChevronRight+ className={cn(+ "text-muted-foreground h-3.5 w-3.5 shrink-0 transition-transform",+ expanded && "rotate-90",+ )}+ />+ {expanded ? (+ <FolderOpen className="h-4 w-4 shrink-0" />+ ) : (+ <Folder className="h-4 w-4 shrink-0" />+ )}+ <span className="min-w-0 flex-1 truncate" title={path}>+ {name}+ </span>+ </button>+ {empty && !disabled ? (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={`Delete folder ${path}`}+ onClick={onDelete}+ className="mr-1 opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus:opacity-100"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ ) : null}+ </div>+ </SkillFolderDropTarget>+ );+}++function SkillFolderDropTarget({+ path,+ disabled,+ variant = "row",+ children,+}: {+ path: string;+ disabled: boolean;+ variant?: "row" | "empty-space";+ children?: ReactNode;+}) {+ const id = useId();+ const { setNodeRef, isOver } = useDroppable({+ id: `folder:${id}`,+ data: { path },+ disabled,+ });+ return (+ <div+ ref={setNodeRef}+ className={cn(+ "rounded",+ isOver && "ring-primary ring-2 ring-inset",+ variant === "empty-space" && "min-h-16 flex-1",+ )}+ >+ {children}+ </div>+ );+}++function joinPath(parentPath: string, name: string): string {+ return parentPath ? `${parentPath}/${name}` : name;+}++function parentFolder(path: string): string {+ const separator = path.lastIndexOf("/");+ return separator === -1 ? "" : path.slice(0, separator);+}++function getContentType(path: string): string {+ if (path.endsWith(".md")) return "text/markdown";+ if (path.endsWith(".json")) return "application/json";+ return "text/plain";+}diff --git a/web/src/features/skills/components/SkillMetadataSelect.tsx b/web/src/features/skills/components/SkillMetadataSelect.tsxnew file mode 100644index 0000000000..ee85743cf4--- /dev/null+++ b/web/src/features/skills/components/SkillMetadataSelect.tsx@@ -0,0 +1,407 @@+import { useId, useState } from "react";+import {+ CircleCheckIcon,+ CircleFadingArrowUp,+ CircleIcon,+ Plus,+ TagIcon,+ X,+} from "lucide-react";+import { PromptLabelSchema, SKILL_LATEST_LABEL } from "@langfuse/shared";+import { TruncatedLabels } from "@/src/components/TruncatedLabels";+import { Badge } from "@/src/components/ui/badge";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { PopoverController } from "@/src/components/ui/popover";+import { cn } from "@/src/utils/tailwind";++export function SkillLabelsSelect({+ value,+ options,+ disabled,+ isSaving,+ showOnlyOnHover,+ onSave,+}: {+ value: string[];+ options: string[];+ disabled: boolean;+ isSaving: boolean;+ showOnlyOnHover: boolean;+ onSave: (value: string[]) => Promise<boolean>;+}) {+ const [search, setSearch] = useState("");+ const editableLabels = value.filter((label) => label !== SKILL_LATEST_LABEL);+ const [pendingLabels, setPendingLabels] = useState(editableLabels);+ const listId = useId();+ const normalizedSearch = search.trim();+ const labels = [...new Set([...options, ...value, ...pendingLabels])]+ .filter((label) => label !== SKILL_LATEST_LABEL)+ .toSorted((left, right) => left.localeCompare(right));+ const customLabels = labels.filter((label) => label !== "production");+ const visibleLabels = customLabels.filter((label) =>+ label.toLowerCase().includes(normalizedSearch.toLowerCase()),+ );+ const canCreate =+ normalizedSearch.length > 0 &&+ normalizedSearch !== SKILL_LATEST_LABEL &&+ !labels.includes(normalizedSearch) &&+ PromptLabelSchema.safeParse(normalizedSearch).success;+ const labelsChanged =+ JSON.stringify([...pendingLabels].sort()) !==+ JSON.stringify([...editableLabels].sort());+ const isPromotingToProduction =+ !value.includes("production") && pendingLabels.includes("production");+ const isDemotingFromProduction =+ value.includes("production") && !pendingLabels.includes("production");+ let saveButtonCopy = "Save labels";+ if (isPromotingToProduction)+ saveButtonCopy = "Save and promote to production";+ else if (isDemotingFromProduction)+ saveButtonCopy = "Save and remove from production";++ const toggleLabel = (label: string) => {+ setPendingLabels(+ pendingLabels.includes(label)+ ? pendingLabels.filter((selected) => selected !== label)+ : [...pendingLabels, label],+ );+ };++ const createLabel = () => {+ if (!canCreate) return;+ setPendingLabels([...pendingLabels, normalizedSearch]);+ setSearch("");+ };++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ setPendingLabels(editableLabels);+ setSearch("");+ }+ };++ const saveLabels = async (closePopover: () => void) => {+ if (await onSave(pendingLabels)) closePopover();+ };++ return (+ <PopoverController+ align="start"+ contentClassName="ph-no-capture w-80 p-3"+ disabled={disabled}+ modal={false}+ onOpenChange={handleOpenChange}+ renderContent={({ closePopover }) => (+ <>+ <h2 className="mb-1 font-bold">Skill labels</h2>+ <p className="text-muted-foreground mb-3 text-xs">+ Use labels to identify deployment targets for this version.+ </p>+ <div className="border-y py-2">+ <p className="text-muted-foreground mb-1 px-2 text-xs font-bold">+ Promote to production?+ </p>+ <SelectionRow+ value="production"+ selected={pendingLabels.includes("production")}+ onSelect={() => toggleLabel("production")}+ />+ </div>+ <div className="pt-2">+ <p className="text-muted-foreground mb-2 px-2 text-xs font-bold">+ Custom labels+ </p>+ <Input+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && canCreate) {+ event.preventDefault();+ createLabel();+ }+ }}+ placeholder="Search or create label…"+ className="mb-2 h-8"+ />+ <div id={listId} className="max-h-52 overflow-y-auto">+ {visibleLabels.map((label) => (+ <SelectionRow+ key={label}+ value={label}+ selected={pendingLabels.includes(label)}+ onSelect={() => toggleLabel(label)}+ />+ ))}+ {canCreate ? (+ <CreateRow value={normalizedSearch} onCreate={createLabel} />+ ) : null}+ {visibleLabels.length === 0 && !canCreate ? (+ <EmptyOptions copy="No matching labels" />+ ) : null}+ </div>+ </div>+ <Button+ type="button"+ variant={+ isPromotingToProduction || isDemotingFromProduction+ ? "destructive"+ : "default"+ }+ loading={isSaving}+ disabled={!labelsChanged}+ className="mt-3 w-full"+ onClick={() => saveLabels(closePopover)}+ >+ {saveButtonCopy}+ </Button>+ </>+ )}+ >+ {({ Trigger, isOpen }) => (+ <Trigger asChild>+ <div+ role="combobox"+ aria-label="Labels"+ aria-controls={listId}+ aria-expanded={isOpen}+ aria-disabled={disabled}+ tabIndex={0}+ className={cn(+ "flex min-h-8 w-fit max-w-full flex-wrap items-center gap-1",+ disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",+ )}+ >+ <TruncatedLabels labels={value} maxVisibleLabels={5} />+ <Button+ type="button"+ variant="outline"+ size="icon"+ title="Add skill label"+ disabled={disabled}+ className={cn(+ "bg-muted-gray text-primary h-6 w-6",+ showOnlyOnHover &&+ !isOpen &&+ "opacity-0 group-focus-within/skill-version:opacity-100 group-hover/skill-version:opacity-100 [@media(hover:none)]:opacity-100",+ )}+ >+ <CircleFadingArrowUp className="h-3.5 w-3.5" />+ </Button>+ </div>+ </Trigger>+ )}+ </PopoverController>+ );+}++export function SkillTagsSelect({+ value,+ options,+ disabled,+ isSaving,+ onSave,+}: {+ value: string[];+ options: string[];+ disabled: boolean;+ isSaving: boolean;+ onSave: (value: string[]) => Promise<boolean>;+}) {+ const [search, setSearch] = useState("");+ const [pendingTags, setPendingTags] = useState(value);+ const listId = useId();+ const normalizedSearch = search.trim();+ const tags = [...new Set([...options, ...value, ...pendingTags])].toSorted(+ (left, right) => left.localeCompare(right),+ );+ const visibleTags = tags.filter(+ (tag) =>+ !pendingTags.includes(tag) &&+ tag.toLowerCase().includes(normalizedSearch.toLowerCase()),+ );+ const canCreate =+ normalizedSearch.length > 0 &&+ normalizedSearch.length <= 100 &&+ !tags.some((tag) => tag.toLowerCase() === normalizedSearch.toLowerCase());+ const tagsChanged =+ JSON.stringify([...pendingTags].sort()) !==+ JSON.stringify([...value].sort());++ const createTag = () => {+ if (!canCreate) return;+ setPendingTags([...pendingTags, normalizedSearch]);+ setSearch("");+ };++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ setPendingTags(value);+ setSearch("");+ }+ };++ const saveTags = async (closePopover: () => void) => {+ if (await onSave(pendingTags)) closePopover();+ };++ return (+ <PopoverController+ align="start"+ contentClassName="ph-no-capture w-72 p-3"+ disabled={disabled}+ modal={false}+ onOpenChange={handleOpenChange}+ renderContent={({ closePopover }) => (+ <>+ <h2 className="mb-2 font-bold">Skill tags</h2>+ <div className="mb-2 flex flex-wrap items-center gap-1 rounded-lg border px-2 py-1">+ {pendingTags.map((tag) => (+ <Button+ key={tag}+ type="button"+ variant="tertiary"+ size="icon-sm"+ onClick={() =>+ setPendingTags(+ pendingTags.filter((selected) => selected !== tag),+ )+ }+ >+ {tag}+ <X className="ml-1 h-3 w-3" />+ </Button>+ ))}+ <Input+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && canCreate) {+ event.preventDefault();+ createTag();+ }+ }}+ placeholder="Search or create tag…"+ className="h-8 min-w-36 flex-1 border-0 px-1 shadow-none focus-visible:ring-0"+ />+ </div>+ <div id={listId} className="max-h-52 overflow-y-auto">+ {visibleTags.map((tag) => (+ <Button+ key={tag}+ type="button"+ variant="ghost"+ className="w-full justify-start px-2 font-normal"+ onClick={() => setPendingTags([...pendingTags, tag])}+ >+ <Plus className="mr-2 h-4 w-4" />+ {tag}+ </Button>+ ))}+ {canCreate ? (+ <CreateRow value={normalizedSearch} onCreate={createTag} />+ ) : null}+ {visibleTags.length === 0 && !canCreate ? (+ <EmptyOptions copy="No available tags" />+ ) : null}+ </div>+ <Button+ type="button"+ loading={isSaving}+ disabled={!tagsChanged}+ className="mt-3 w-full"+ onClick={() => saveTags(closePopover)}+ >+ Save tags+ </Button>+ </>+ )}+ >+ {({ Trigger, isOpen }) => (+ <Trigger asChild>+ <div+ role="combobox"+ aria-label="Tags"+ aria-controls={listId}+ aria-expanded={isOpen}+ aria-disabled={disabled}+ tabIndex={0}+ className={cn(+ "flex min-h-8 w-fit max-w-full flex-wrap items-center gap-1",+ disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",+ )}+ >+ {value.map((tag) => (+ <Badge key={tag} variant="tertiary" className="h-6 gap-1">+ <TagIcon className="h-3 w-3" />+ <span className="max-w-36 truncate" title={tag}>+ {tag}+ </span>+ </Badge>+ ))}+ <Badge variant="tertiary" className="h-6">+ <TagIcon className="h-3.5 w-3.5" />+ </Badge>+ </div>+ </Trigger>+ )}+ </PopoverController>+ );+}++function SelectionRow({+ value,+ selected,+ onSelect,+}: {+ value: string;+ selected: boolean;+ onSelect: () => void;+}) {+ return (+ <Button+ type="button"+ variant="ghost"+ className={cn(+ "w-full justify-start px-2 py-1 text-sm",+ selected && "font-bold",+ )}+ onClick={onSelect}+ >+ {selected ? (+ <CircleCheckIcon className="mr-2 h-4 w-4" />+ ) : (+ <CircleIcon className="mr-2 h-4 w-4 opacity-20" />+ )}+ {value}+ </Button>+ );+}++function CreateRow({+ value,+ onCreate,+}: {+ value: string;+ onCreate: () => void;+}) {+ return (+ <Button+ type="button"+ variant="ghost"+ className="text-muted-foreground w-full justify-start px-2 font-normal"+ onClick={onCreate}+ >+ <Plus className="mr-2 h-4 w-4" />+ Create new: “{value}”+ </Button>+ );+}++function EmptyOptions({ copy }: { copy: string }) {+ return (+ <div className="text-muted-foreground px-2 py-4 text-center text-sm">+ {copy}+ </div>+ );+}diff --git a/web/src/features/skills/components/SkillVersionHistory.tsx b/web/src/features/skills/components/SkillVersionHistory.tsxnew file mode 100644index 0000000000..5ad2b95f71--- /dev/null+++ b/web/src/features/skills/components/SkillVersionHistory.tsx@@ -0,0 +1,217 @@+import { useState } from "react";+import { PanelLeftClose, PanelLeftOpen } from "lucide-react";+import { Badge } from "@/src/components/ui/badge";+import { Button } from "@/src/components/ui/button";+import {+ Timeline,+ TimelineItem,+} from "@/src/features/prompts/components/timeline";+import { cn } from "@/src/utils/tailwind";+import { SkillLabelsSelect } from "./SkillMetadataSelect";++export function SkillVersionHistory(+ props:+ | { kind: "new" }+ | {+ kind: "versions";+ versions: Array<{+ version: number;+ labels: string[];+ commitMessage: string | null;+ createdAt: Date;+ createdBy: string;+ creator: string | null | undefined;+ }>;+ selectedVersion: number;+ hasMore: boolean;+ isLoadingMore: boolean;+ loadMoreError: boolean;+ onLoadMore: () => void;+ dirty: boolean;+ isDraft: boolean;+ canEdit: boolean;+ labelOptions: string[];+ isSavingLabels: boolean;+ onSaveLabels: (version: number, labels: string[]) => Promise<boolean>;+ onSelect: (version: number) => Promise<void>;+ },+) {+ const [isCollapsed, setIsCollapsed] = useState(false);+ const sortedVersions =+ props.kind === "versions"+ ? [...props.versions].toSorted(+ (left, right) => right.version - left.version,+ )+ : [];+ const showDraft = props.kind === "new" || props.isDraft;++ const selectVersion = async (version: number) => {+ if (+ props.kind !== "versions" ||+ (!props.isDraft && version === props.selectedVersion)+ )+ return;+ if (+ props.dirty &&+ !window.confirm("Discard this unsaved draft and open another version?")+ ) {+ return;+ }+ await props.onSelect(version);+ };++ return (+ <aside+ className={cn(+ "ph-no-capture bg-muted/10 flex w-full shrink-0 flex-col border-b transition-[width,max-height] md:max-h-none md:border-r md:border-b-0",+ isCollapsed ? "max-h-11 md:w-11" : "max-h-56 md:w-56",+ )}+ >+ <div+ className={cn(+ "flex min-h-11 items-center border-b px-2",+ isCollapsed ? "justify-center" : "justify-between",+ )}+ >+ {isCollapsed ? null : (+ <span className="text-sm font-bold">Versions</span>+ )}+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={+ isCollapsed ? "Expand version history" : "Collapse version history"+ }+ aria-expanded={!isCollapsed}+ onClick={() => setIsCollapsed((collapsed) => !collapsed)}+ >+ {isCollapsed ? (+ <PanelLeftOpen className="h-4 w-4" />+ ) : (+ <PanelLeftClose className="h-4 w-4" />+ )}+ </Button>+ </div>+ {isCollapsed ? null : (+ <div className="overflow-y-auto p-2">+ <Timeline>+ {showDraft ? (+ <TimelineItem isActive>+ <div+ className="flex w-full flex-col gap-1 text-left"+ aria-current="page"+ >+ <Badge variant="outline" className="w-fit">+ Draft+ </Badge>+ <Badge+ variant="secondary"+ className="h-5 w-fit max-w-full truncate px-1.5 text-[10px]"+ title="Unreleased local changes"+ >+ Unreleased local changes+ </Badge>+ </div>+ </TimelineItem>+ ) : null}+ {props.kind === "versions"+ ? sortedVersions.map(+ ({+ version,+ labels,+ commitMessage,+ createdAt,+ createdBy,+ creator,+ }) => (+ <TimelineItem+ key={version}+ className="group/skill-version"+ isActive={+ !props.isDraft && version === props.selectedVersion+ }+ >+ <div className="flex flex-wrap items-center gap-1">+ <button+ type="button"+ aria-label={`Open version ${version}`}+ aria-current={+ !props.isDraft && version === props.selectedVersion+ ? "page"+ : undefined+ }+ onClick={() => selectVersion(version)}+ >+ <Badge+ variant="outline"+ className="bg-background/50 h-6 shrink-0"+ >+ # {version}+ </Badge>+ </button>+ <SkillLabelsSelect+ showOnlyOnHover+ value={labels}+ options={props.labelOptions}+ disabled={!props.canEdit || props.isSavingLabels}+ isSaving={props.isSavingLabels}+ onSave={(nextLabels) =>+ props.onSaveLabels(version, nextLabels)+ }+ />+ </div>+ <button+ type="button"+ className="flex w-full flex-col gap-1 text-left"+ aria-current={+ !props.isDraft && version === props.selectedVersion+ ? "page"+ : undefined+ }+ onClick={() => selectVersion(version)}+ >+ {commitMessage ? (+ <span+ className="text-muted-foreground max-w-full truncate text-xs"+ title={commitMessage}+ >+ {commitMessage}+ </span>+ ) : null}+ <span+ className="text-muted-foreground flex flex-wrap gap-1 text-xs break-words"+ title={`Created ${createdAt.toLocaleString()}`}+ >+ {createdAt.toLocaleString()} by {creator || createdBy}+ </span>+ </button>+ </TimelineItem>+ ),+ )+ : null}+ </Timeline>+ {props.kind === "versions" && props.hasMore ? (+ <div className="flex flex-col gap-2 pt-2">+ {props.loadMoreError ? (+ <p role="alert" className="text-destructive text-xs">+ Could not load older versions. Please try again.+ </p>+ ) : null}+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={props.isLoadingMore}+ loading={props.isLoadingMore}+ onClick={props.onLoadMore}+ >+ Load older versions+ </Button>+ </div>+ ) : null}+ </div>+ )}+ </aside>+ );+}diff --git a/web/src/features/skills/components/SkillsFeatureGate.tsx b/web/src/features/skills/components/SkillsFeatureGate.tsxnew file mode 100644index 0000000000..0680cac604--- /dev/null+++ b/web/src/features/skills/components/SkillsFeatureGate.tsx@@ -0,0 +1,13 @@+import { type ReactNode } from "react";+import { ErrorPage } from "@/src/components/error-page";+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";++export function SkillsFeatureGate({ children }: { children: ReactNode }) {+ const enabled = useInternalFeaturesEnabled();++ return enabled ? (+ children+ ) : (+ <ErrorPage title="Page not found" message="This page is not available." />+ );+}diff --git a/web/src/features/skills/components/SkillsPage.tsx b/web/src/features/skills/components/SkillsPage.tsxnew file mode 100644index 0000000000..4f2076ec82--- /dev/null+++ b/web/src/features/skills/components/SkillsPage.tsx@@ -0,0 +1,364 @@+import Link from "next/link";+import { FileCode2, Plus, Trash } from "lucide-react";+import { NumberParam, useQueryParams, withDefault } from "use-query-params";+import Page from "@/src/components/layouts/page";+import { Button } from "@/src/components/ui/button";+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { PaginationBar } from "@/src/components/design-system/PaginationBar/PaginationBar";+import {+ Table,+ type AsyncTableData,+} from "@/src/components/design-system/table/Table";+import { createLinkTableColumn } from "@/src/components/design-system/table/columns/createLinkTableColumn";+import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";+import { createNumberTableColumn } from "@/src/components/design-system/table/columns/createNumberTableColumn";+import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";+import { createBadgeListTableColumn } from "@/src/components/design-system/table/columns/createBadgeListTableColumn";+import {+ DataTableControls,+ DataTableControlsProvider,+} from "@/src/components/table/data-table-controls";+import { FilterToggleButton } from "@/src/components/table/FilterToggleButton";+import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";+import { useSidebarFilterState } from "@/src/features/filters";+import {+ TableSearchBar,+ toObservedOptions,+ useFullTextSearch,+} from "@/src/features/search-bar";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { InternalFeatureBadge } from "@/src/features/feature-flags";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { api } from "@/src/utils/api";+import { type RouterOutput } from "@/src/utils/types";+import {+ SKILLS_FIELD_REGISTRY,+ skillsFilterConfig,+} from "../constants/skillsFilterConfig";++type SkillRow = RouterOutput["skills"]["all"]["data"][number];++export function SkillsPage() {+ const projectId = useProjectIdFromURL() ?? "";+ const canCreate = useHasProjectAccess({ projectId, scope: "skills:CUD" });+ const capture = usePostHogClientCapture();+ const newSkillHref = `/project/${projectId}/skills/new`;++ return (+ <Page+ headerProps={{+ title: "Skills",+ titleBadges: <InternalFeatureBadge />,+ help: {+ description:+ "Create, version, and distribute reusable agent skills from one place.",+ href: "https://langfuse.com/docs",+ },+ actionButtonsRight: (+ <NewSkillButton+ canCreate={canCreate}+ href={newSkillHref}+ onOpen={() => capture("skills:new_form_open")}+ />+ ),+ }}+ >+ <SkillsList key={projectId} projectId={projectId} canDelete={canCreate} />+ </Page>+ );+}++function SkillsList({+ projectId,+ canDelete,+}: {+ projectId: string;+ canDelete: boolean;+}) {+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const [pagination, setPagination] = useQueryParams({+ pageIndex: withDefault(NumberParam, 0),+ pageSize: withDefault(NumberParam, 50),+ });+ const paginationState = {+ pageIndex: Number.isFinite(pagination.pageIndex)+ ? Math.max(0, Math.floor(pagination.pageIndex))+ : 0,+ pageSize: Number.isFinite(pagination.pageSize)+ ? Math.max(1, Math.min(100, Math.floor(pagination.pageSize)))+ : 50,+ };+ const { searchQuery, setSearchQuery } = useFullTextSearch({+ tableAllowsFullTextSearch: false,+ });+ const filterOptions = api.skills.filterOptions.useQuery(+ { projectId },+ { enabled: Boolean(projectId) },+ );+ const observedOptions = filterOptions.data ?? { tags: [] };+ const queryFilter = useSidebarFilterState(+ skillsFilterConfig,+ observedOptions,+ {+ stateLocation: "urlAndSessionStorage",+ sessionFilterContextId: projectId,+ loading: filterOptions.isPending,+ isV4: false,+ onExplicitFilterStateChange: () => setPagination({ pageIndex: 0 }),+ },+ );+ const skills = api.skills.all.useQuery(+ {+ projectId,+ page: paginationState.pageIndex + 1,+ limit: paginationState.pageSize,+ search: searchQuery || undefined,+ filter: queryFilter.filterState,+ },+ { enabled: Boolean(projectId) },+ );+ const deleteSkill = api.skills.deleteSkill.useMutation({+ onSuccess: async () => {+ capture("skills:delete");+ if (skills.data?.data.length === 1 && paginationState.pageIndex > 0) {+ setPagination({ pageIndex: paginationState.pageIndex - 1 });+ }+ await utils.skills.invalidate();+ },+ });++ let tableData: AsyncTableData<SkillRow[]> = { status: "loading" };+ if (skills.isError)+ tableData = { status: "error", error: skills.error.message };+ else if (skills.data)+ tableData = { status: "success", data: skills.data.data };+ const hasFilters = Boolean(searchQuery) || queryFilter.filterState.length > 0;+ const isEmptyProject =+ skills.data?.meta.totalItems === 0 &&+ !hasFilters &&+ paginationState.pageIndex === 0;+ const columns = [+ createLinkTableColumn<SkillRow>({+ accessorKey: "name",+ header: "Name",+ size: 220,+ cellClassName: "ph-no-capture",+ getCell: (name) =>+ name+ ? {+ type: "link",+ props: {+ value: name,+ path: `/project/${projectId}/skills/${encodeURIComponent(name)}`,+ },+ }+ : undefined,+ }),+ createTextTableColumn<SkillRow>({+ accessorKey: "description",+ header: "Description",+ size: 280,+ cellClassName: "ph-no-capture",+ }),+ createNumberTableColumn<SkillRow>({+ accessorKey: "latestVersion",+ header: "Latest version",+ size: 100,+ formatter: (version) => `v${version}`,+ }),+ createNumberTableColumn<SkillRow>({+ accessorKey: "productionVersion",+ header: "Production version",+ size: 140,+ formatter: (version) => `v${version}`,+ emptyValue: "Not set",+ }),+ createBadgeListTableColumn<SkillRow>({+ accessorKey: "tags",+ header: "Tags",+ size: 120,+ cellClassName: "ph-no-capture",+ }),+ createDateTableColumn<SkillRow>({+ accessorKey: "latestVersionCreatedAt",+ header: "Latest version created",+ size: 175,+ }),+ ];++ return (+ <DataTableControlsProvider tableName="skills" defaultSidebarCollapsed>+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex items-center gap-2 px-3 py-2">+ <div className="md:hidden">+ <FilterToggleButton filterState={queryFilter.filterState} />+ </div>+ <div className="min-w-0 flex-1">+ <TableSearchBar+ key={`${projectId}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName="skills"+ registry={SKILLS_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(+ observedOptions,+ filterOptions.isPending,+ )}+ isV4={false}+ search={{+ query: searchQuery,+ type: ["id"],+ setQuery: (query) => {+ setPagination({ pageIndex: 0 });+ setSearchQuery(query);+ },+ }}+ />+ </div>+ </div>+ <ResizableFilterLayout>+ <DataTableControls queryFilter={queryFilter} />+ <DialogController<string>+ onBeforeClose={() => !deleteSkill.isPending}+ onDismiss={deleteSkill.reset}+ renderDialog={({ state: name, closeDialog }) => (+ <Dialog+ title="Delete skill"+ actions={[+ {+ label: "Delete skill",+ variant: "destructive",+ disabled: !canDelete,+ loading: deleteSkill.isPending,+ onClick: async () => {+ try {+ await deleteSkill.mutateAsync({ projectId, name });+ closeDialog();+ } catch {+ // The mutation exposes its error in the dialog.+ }+ },+ },+ ]}+ >+ <Dialog.Body>+ <p className="text-muted-foreground">+ This permanently deletes{" "}+ <code className="ph-no-capture text-foreground font-bold break-all">+ {name}+ </code>+ , including all versions and labels. Requests to fetch any+ version of this skill will fail. This action cannot be+ undone.+ </p>+ {deleteSkill.error ? (+ <p+ role="alert"+ className="ph-no-capture text-destructive whitespace-pre-wrap"+ >+ {deleteSkill.error.message}+ </p>+ ) : null}+ </Dialog.Body>+ </Dialog>+ )}+ >+ {({ openDialog }) => (+ <div className="flex min-h-0 flex-1 flex-col">+ {isEmptyProject ? (+ <EmptySkills+ canCreate={canDelete}+ href={`/project/${projectId}/skills/new`}+ onOpen={() => capture("skills:new_form_open")}+ />+ ) : (+ <Table+ tableName="skills"+ columns={columns}+ data={tableData}+ loadingRowCount={Math.min(paginationState.pageSize, 8)}+ noResultsMessage="No skills match your search or filters."+ actions={(skill) => [+ {+ type: "item",+ id: "delete",+ title: "Delete skill",+ icon: Trash,+ variant: "destructive",+ disabled: canDelete+ ? undefined+ : { reason: "You do not have write access" },+ onClick: () => openDialog(skill.name),+ },+ ]}+ />+ )}+ <PaginationBar+ mode="offset"+ totalCount={skills.data?.meta.totalItems ?? null}+ state={paginationState}+ onChange={setPagination}+ />+ </div>+ )}+ </DialogController>+ </ResizableFilterLayout>+ </div>+ </DataTableControlsProvider>+ );+}++function NewSkillButton({+ canCreate,+ href,+ onOpen,+}: {+ canCreate: boolean;+ href: string;+ onOpen: () => void;+}) {+ if (!canCreate) {+ return (+ <Button disabled title="You do not have write access">+ <Plus className="mr-1.5 h-4 w-4" /> New skill+ </Button>+ );+ }+ return (+ <Button asChild>+ <Link href={href} onClick={onOpen}>+ <Plus className="mr-1.5 h-4 w-4" /> New skill+ </Link>+ </Button>+ );+}++function EmptySkills({+ canCreate,+ href,+ onOpen,+}: {+ canCreate: boolean;+ href: string;+ onOpen: () => void;+}) {+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-24 text-center">+ <FileCode2 className="text-muted-foreground h-9 w-9" />+ <div>+ <h2 className="font-bold">Create your first skill</h2>+ <p className="text-muted-foreground mt-1 text-sm">+ Skills bundle instructions and supporting files into immutable+ versions.+ </p>+ </div>+ {canCreate ? (+ <NewSkillButton canCreate={canCreate} href={href} onOpen={onOpen} />+ ) : null}+ </div>+ );+}diff --git a/web/src/features/skills/components/skillEditorStore.ts b/web/src/features/skills/components/skillEditorStore.tsnew file mode 100644index 0000000000..4f98209820--- /dev/null+++ b/web/src/features/skills/components/skillEditorStore.ts@@ -0,0 +1,272 @@+import { createStore, type StoreApi } from "zustand/vanilla";+import { SkillFilePathSchema } from "@langfuse/shared";+import { getParentFolderPaths } from "./skillFileTree";+import { resetSkillName } from "../utils/resetSkillName";++export type SkillDraftFile = {+ path: string;+ contentType: string;+} & (+ | { content: string; source?: never }+ | {+ content?: never;+ source: { fileId: string; contentLength: number; sha256Hash: string };+ }+);++export type SkillEditorInitialValue = {+ name: string;+ baseVersion: number | null;+ files: SkillDraftFile[];+ labels: string[];+ tags: string[];+};++type SkillEditorState = {+ name: string;+ baseVersion: number | null;+ files: Record<string, SkillDraftFile>;+ folders: string[];+ activePath: string;+ labels: string[];+ tags: string[];+ commitMessage: string;+ dirty: boolean;+ isImporting: boolean;+ actions: {+ selectFile: (path: string) => void;+ updateActiveFile: (content: string) => void;+ resetName: () => void;+ addFile: (file: SkillDraftFile) => boolean;+ moveFile: (path: string, targetFolder: string) => boolean;+ moveFolder: (path: string, targetFolder: string) => boolean;+ addFolder: (path: string) => boolean;+ deleteFile: (path: string) => void;+ deleteFolder: (path: string) => boolean;+ syncLabels: (labels: string[]) => void;+ syncTags: (tags: string[]) => void;+ setCommitMessage: (message: string) => void;+ };+};++export type SkillEditorStore = StoreApi<SkillEditorState>;++export function createSkillEditorStore(+ initialValue: SkillEditorInitialValue,+): SkillEditorStore {+ const files = Object.fromEntries(+ initialValue.files.map((file) => [file.path, file]),+ );+ const folders = getParentFolderPaths(+ initialValue.files.map(({ path }) => path),+ );++ return createStore<SkillEditorState>((set, get) => ({+ name: initialValue.name,+ baseVersion: initialValue.baseVersion,+ files,+ folders,+ activePath: files["SKILL.md"] ? "SKILL.md" : initialValue.files[0]!.path,+ labels: initialValue.labels.filter((label) => label !== "latest"),+ tags: initialValue.tags,+ commitMessage: "",+ dirty: false,+ isImporting: false,+ actions: {+ resetName: () => {+ const state = get();+ const file = state.files["SKILL.md"];+ if (!file || file.content === undefined) return;+ set({+ files: {+ ...state.files,+ "SKILL.md": {+ path: file.path,+ contentType: file.contentType,+ content: resetSkillName(file.content, state.name),+ },+ },+ dirty: true,+ });+ },+ selectFile: (path) => {+ if (get().files[path]) set({ activePath: path });+ },+ updateActiveFile: (content) =>+ set((state) => ({+ files: {+ ...state.files,+ [state.activePath]: {+ path: state.activePath,+ contentType: state.files[state.activePath]!.contentType,+ content,+ },+ },+ dirty: true,+ })),+ addFile: (file) => {+ const state = get();+ if (hasFilePathConflict(file.path, state.files, state.folders)) {+ return false;+ }+ set((state) => ({+ files: { ...state.files, [file.path]: file },+ folders: [+ ...new Set([+ ...state.folders,+ ...getParentFolderPaths([file.path]),+ ]),+ ].toSorted(),+ activePath: file.path,+ dirty: true,+ }));+ return true;+ },+ moveFile: (path, targetFolder) => {+ const state = get();+ const file = state.files[path];+ if (+ !file ||+ path === "SKILL.md" ||+ (targetFolder !== "" && !state.folders.includes(targetFolder))+ ) {+ return false;+ }+ const name = path.split("/").at(-1)!;+ const nextPath = targetFolder ? `${targetFolder}/${name}` : name;+ if (nextPath === path) return true;+ if (+ !SkillFilePathSchema.safeParse(nextPath).success ||+ hasFilePathConflict(nextPath, state.files, state.folders)+ ) {+ return false;+ }+ const { [path]: _, ...remainingFiles } = state.files;+ set({+ files: { ...remainingFiles, [nextPath]: { ...file, path: nextPath } },+ activePath: state.activePath === path ? nextPath : state.activePath,+ dirty: true,+ });+ return true;+ },+ moveFolder: (path, targetFolder) => {+ const state = get();+ if (+ !state.folders.includes(path) ||+ (targetFolder !== "" && !state.folders.includes(targetFolder)) ||+ targetFolder === path ||+ targetFolder.startsWith(`${path}/`)+ )+ return false;++ const name = path.split("/").at(-1)!;+ const nextPath = targetFolder ? `${targetFolder}/${name}` : name;+ if (nextPath === path) return true;+ if (hasFilePathConflict(nextPath, state.files, state.folders))+ return false;++ const relocate = (entryPath: string) =>+ entryPath === path || entryPath.startsWith(`${path}/`)+ ? `${nextPath}${entryPath.slice(path.length)}`+ : entryPath;+ const nextFolders = state.folders.map(relocate).toSorted();+ const nextFiles = Object.fromEntries(+ Object.entries(state.files).map(([filePath, file]) => {+ const movedPath = relocate(filePath);+ return [+ movedPath,+ movedPath === filePath ? file : { ...file, path: movedPath },+ ];+ }),+ );+ if (+ [...nextFolders, ...Object.keys(nextFiles)].some(+ (entryPath) => !SkillFilePathSchema.safeParse(entryPath).success,+ )+ )+ return false;++ set({+ files: nextFiles,+ folders: nextFolders,+ activePath: relocate(state.activePath),+ dirty: true,+ });+ return true;+ },+ addFolder: (path) => {+ const state = get();+ if (+ state.folders.includes(path) ||+ hasFileAtOrAbove(path, state.files)+ ) {+ return false;+ }+ set({+ folders: [+ ...new Set([+ ...state.folders,+ ...getParentFolderPaths([`${path}/placeholder`]),+ ]),+ ].toSorted(),+ dirty: true,+ });+ return true;+ },+ deleteFile: (path) => {+ if (path === "SKILL.md") return;+ set((state) => {+ const { [path]: _, ...remainingFiles } = state.files;+ return {+ files: remainingFiles,+ activePath:+ state.activePath === path ? "SKILL.md" : state.activePath,+ dirty: true,+ };+ });+ },+ deleteFolder: (path) => {+ const state = get();+ const isEmpty =+ !Object.keys(state.files).some((filePath) =>+ filePath.startsWith(`${path}/`),+ ) &&+ !state.folders.some(+ (folderPath) =>+ folderPath !== path && folderPath.startsWith(`${path}/`),+ );+ if (!isEmpty) return false;+ set({+ folders: state.folders.filter((folderPath) => folderPath !== path),+ dirty: true,+ });+ return true;+ },+ syncLabels: (labels) => set({ labels: [...new Set(labels)] }),+ syncTags: (tags) => set({ tags: [...new Set(tags)] }),+ setCommitMessage: (commitMessage) => set({ commitMessage, dirty: true }),+ },+ }));+}++function hasFileAtOrAbove(+ path: string,+ files: Record<string, SkillDraftFile>,+): boolean {+ const segments = path.split("/");+ return segments.some((_, index) =>+ Boolean(files[segments.slice(0, index + 1).join("/")]),+ );+}++function hasFilePathConflict(+ path: string,+ files: Record<string, SkillDraftFile>,+ folders: string[],+): boolean {+ return (+ hasFileAtOrAbove(path, files) ||+ folders.includes(path) ||+ Object.keys(files).some((filePath) => filePath.startsWith(`${path}/`))+ );+}diff --git a/web/src/features/skills/components/skillFileTree.ts b/web/src/features/skills/components/skillFileTree.tsnew file mode 100644index 0000000000..fef51c2733--- /dev/null+++ b/web/src/features/skills/components/skillFileTree.ts@@ -0,0 +1,97 @@+export type SkillFileTreeNode =+ | {+ kind: "folder";+ name: string;+ path: string;+ children: SkillFileTreeNode[];+ }+ | { kind: "file"; name: string; path: string };++type MutableFolder = {+ kind: "folder";+ name: string;+ path: string;+ children: Map<string, MutableTreeNode>;+};++type MutableTreeNode =+ | MutableFolder+ | { kind: "file"; name: string; path: string };++export function getParentFolderPaths(filePaths: string[]): string[] {+ const folders = new Set<string>();+ for (const filePath of filePaths) {+ const segments = filePath.split("/");+ for (let index = 1; index < segments.length; index += 1) {+ folders.add(segments.slice(0, index).join("/"));+ }+ }+ return [...folders].toSorted((left, right) => left.localeCompare(right));+}++export function buildSkillFileTree(+ filePaths: string[],+ folderPaths: string[],+): SkillFileTreeNode[] {+ const root: MutableFolder = {+ kind: "folder",+ name: "",+ path: "",+ children: new Map(),+ };++ for (const folderPath of [+ ...new Set([...folderPaths, ...getParentFolderPaths(filePaths)]),+ ].toSorted()) {+ ensureFolder(root, folderPath);+ }++ for (const filePath of filePaths) {+ const segments = filePath.split("/");+ const name = segments.pop()!;+ const parent = ensureFolder(root, segments.join("/"));+ parent.children.set(name, { kind: "file", name, path: filePath });+ }++ return serializeChildren(root.children);+}++function ensureFolder(root: MutableFolder, path: string): MutableFolder {+ if (!path) return root;++ let parent = root;+ let currentPath = "";+ for (const segment of path.split("/")) {+ currentPath = currentPath ? `${currentPath}/${segment}` : segment;+ const existing = parent.children.get(segment);+ if (existing?.kind === "folder") {+ parent = existing;+ continue;+ }++ const folder: MutableFolder = {+ kind: "folder",+ name: segment,+ path: currentPath,+ children: new Map(),+ };+ parent.children.set(segment, folder);+ parent = folder;+ }+ return parent;+}++function serializeChildren(+ children: Map<string, MutableTreeNode>,+): SkillFileTreeNode[] {+ return [...children.values()]+ .toSorted((left, right) => {+ if (left.kind !== right.kind) return left.kind === "folder" ? -1 : 1;+ return left.name.localeCompare(right.name);+ })+ .map((node) =>+ node.kind === "folder"+ ? { ...node, children: serializeChildren(node.children) }+ : node,+ );+}diff --git a/web/src/features/skills/constants/skillsFilterConfig.ts b/web/src/features/skills/constants/skillsFilterConfig.tsnew file mode 100644index 0000000000..1db7f42494--- /dev/null+++ b/web/src/features/skills/constants/skillsFilterConfig.ts@@ -0,0 +1,40 @@+import { type ColumnDefinition } from "@langfuse/shared";+import { type FilterConfig } from "@/src/features/filters/lib/filter-config";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++const columns: ColumnDefinition[] = [+ {+ id: "tags",+ name: "Tags",+ type: "arrayOptions",+ internal: "tags",+ options: [],+ },+];++export const skillsFilterConfig: FilterConfig = {+ tableName: "skills",+ columnDefinitions: columns,+ defaultExpanded: ["tags"],+ defaultSidebarCollapsed: true,+ facets: [+ {+ type: "categorical",+ column: "tags",+ label: "Tags",+ disableTextFilter: true,+ },+ ],+};++export const SKILLS_FIELD_REGISTRY = fieldRegistryFromColumns(columns, {+ id: "skills",+ allowFreeText: true,+ defaultSearchType: ["id"],+ freeTextScopeLabel: "skill names and descriptions",+ recentSearches: true,+ searchExamples: ["tags:support"],+ fields: {+ tags: { aliases: ["tag"] },+ },+});diff --git a/web/src/features/skills/hooks/useSkillFileContents.ts b/web/src/features/skills/hooks/useSkillFileContents.tsnew file mode 100644index 0000000000..fda1a624e8--- /dev/null+++ b/web/src/features/skills/hooks/useSkillFileContents.ts@@ -0,0 +1,14 @@+import { type SkillDraftFile } from "@/src/features/skills/components/skillEditorStore";+import { api } from "@/src/utils/api";++export function useSkillFileContents(projectId: string, file: SkillDraftFile) {+ return api.skills.fileContent.useQuery(+ { projectId, fileId: file.source?.fileId ?? "" },+ {+ enabled: Boolean(file.source),+ staleTime: Infinity,+ gcTime: 10 * 60 * 1000,+ meta: { silentAllErrors: true },+ },+ );+}diff --git a/web/src/features/skills/server/index.ts b/web/src/features/skills/server/index.tsnew file mode 100644index 0000000000..eb1a635f34--- /dev/null+++ b/web/src/features/skills/server/index.ts@@ -0,0 +1 @@+export { SkillService } from "./skill-service";diff --git a/web/src/features/skills/server/skill-router.ts b/web/src/features/skills/server/skill-router.tsnew file mode 100644index 0000000000..808f9d979c--- /dev/null+++ b/web/src/features/skills/server/skill-router.ts@@ -0,0 +1,231 @@+import { prisma } from "@langfuse/shared/src/db";+import { z } from "zod/v4";+import {+ CreateSkillVersionBodySchema,+ ListSkillsQuerySchema,+ SkillSelectorSchema,+ SkillNameSchema,+ UpdateSkillLabelsBodySchema,+ UpdateSkillTagsBodySchema,+ singleFilterList,+} from "@langfuse/shared";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { throwIfNoProjectAccess } from "@/src/features/rbac";+import { SkillService } from "./index";++const projectInput = z.object({ projectId: z.string() });++export const skillRouter = createTRPCRouter({+ all: protectedProjectProcedure+ .input(+ projectInput+ .extend({+ filter: singleFilterList+ .refine((filters) => filters.length <= 50, "Too many filters")+ .optional(),+ })+ .and(ListSkillsQuerySchema),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:read",+ });+ return new SkillService(prisma).list({+ projectId: input.projectId,+ input,+ });+ }),++ filterOptions: protectedProjectProcedure+ .input(projectInput)+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:read",+ });+ return new SkillService(prisma).filterOptions(input);+ }),++ deleteSkill: protectedProjectProcedure+ .input(projectInput.extend({ name: SkillNameSchema }))+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:CUD",+ });+ await new SkillService(prisma).deleteSkill({+ ...input,+ actor: { session: ctx.session },+ });+ return { deleted: true };+ }),++ byName: protectedProjectProcedure+ .input(+ projectInput.and(+ z.object({ name: SkillNameSchema }).and(SkillSelectorSchema),+ ),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:read",+ });+ return new SkillService(prisma).get({+ projectId: input.projectId,+ name: input.name,+ selector: input,+ });+ }),++ fileContent: protectedProjectProcedure+ .input(projectInput.extend({ fileId: z.string().min(1) }))+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:read",+ });+ return new SkillService(prisma).getFileContent(input);+ }),++ skillVersions: protectedProjectProcedure+ .input(+ projectInput.extend({+ name: SkillNameSchema,+ limit: z.number().int().min(1).max(100).default(20),+ cursor: z.number().int().positive().nullish(),+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:read",+ });+ const history = await new SkillService(prisma).skillVersions(input);+ const userIds = [+ ...new Set(history.items.map((item) => item.createdBy)),+ ].filter((id) => id !== "API");+ const users = userIds.length+ ? await ctx.prisma.user.findMany({+ select: { id: true, name: true },+ where: {+ id: { in: userIds },+ organizationMemberships: {+ some: { orgId: ctx.session.orgId },+ },+ },+ })+ : [];+ const namesById = new Map(users.map((user) => [user.id, user.name]));+ return {+ ...history,+ items: history.items.map((item) => ({+ ...item,+ creator:+ item.createdBy === "API" ? "API" : namesById.get(item.createdBy),+ })),+ };+ }),++ createVersion: protectedProjectProcedure+ .input(projectInput.and(CreateSkillVersionBodySchema))+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:CUD",+ });+ return new SkillService(prisma).createVersion({+ projectId: input.projectId,+ createdBy: ctx.session.user.id,+ input,+ actor: { session: ctx.session },+ });+ }),++ setLabels: protectedProjectProcedure+ .input(+ projectInput.and(+ z+ .object({+ name: SkillNameSchema,+ version: z.number().int().positive(),+ })+ .and(UpdateSkillLabelsBodySchema),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:CUD",+ });+ return new SkillService(prisma).setLabels({+ projectId: input.projectId,+ name: input.name,+ version: input.version,+ labels: input.labels,+ actor: { session: ctx.session },+ });+ }),++ setTags: protectedProjectProcedure+ .input(+ projectInput.and(+ z+ .object({+ name: SkillNameSchema,+ version: z.number().int().positive(),+ })+ .and(UpdateSkillTagsBodySchema),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:CUD",+ });+ return new SkillService(prisma).setTags({+ projectId: input.projectId,+ name: input.name,+ version: input.version,+ tags: input.tags,+ actor: { session: ctx.session },+ });+ }),++ deleteVersion: protectedProjectProcedure+ .input(+ projectInput.and(+ z.object({+ name: SkillNameSchema,+ version: z.number().int().positive(),+ }),+ ),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "skills:CUD",+ });+ await new SkillService(prisma).deleteVersion({+ projectId: input.projectId,+ name: input.name,+ version: input.version,+ actor: { session: ctx.session },+ });+ return { deleted: true };+ }),+});diff --git a/web/src/features/skills/server/skill-service.ts b/web/src/features/skills/server/skill-service.tsnew file mode 100644index 0000000000..244712516f--- /dev/null+++ b/web/src/features/skills/server/skill-service.ts@@ -0,0 +1,872 @@+import { createHash, randomUUID } from "node:crypto";+import { parseDocument } from "yaml";+import {+ CreateSkillVersionBodySchema,+ InvalidRequestError,+ LangfuseNotFoundError,+ ListSkillsResponseSchema,+ MAX_SKILL_BYTES,+ SKILL_LATEST_LABEL,+ SKILL_PRODUCTION_LABEL,+ SkillDescriptionSchema,+ SkillNameSchema,+ SkillVersionSchema,+ UpdateSkillLabelsBodySchema,+ UpdateSkillTagsBodySchema,+ type CreateSkillVersionBody,+ type ListSkillsQuery,+ type FilterState,+ type SkillSelector,+} from "@langfuse/shared";+import type { Prisma, PrismaClient, SkillBlob } from "@langfuse/shared/src/db";+import type { ProjectAuthedContext } from "@/src/server/api/trpc";+import type { AuthorizationContext } from "@/src/features/auth/policy/types";+import { auditLog } from "@/src/features/audit-logs/server";+import { throwIfNoProjectAccess } from "@/src/features/rbac";+import { checkHasProtectedLabels } from "@/src/features/prompts/server/utils/checkHasProtectedLabels";+import {+ authorizeProtectedLabelMutation,+ type ApiKeyProjectContext,+} from "@/src/features/prompts/server/utils/authorizeProtectedLabelMutation";++type SkillActor =+ | Pick<ProjectAuthedContext, "session">+ | (ApiKeyProjectContext & { ctx?: AuthorizationContext });++const skillFilesInclude = {+ files: {+ include: {+ blob: {+ select: { sha256Hash: true, contentType: true, contentLength: true },+ },+ },+ },+} satisfies Prisma.SkillInclude;++type SkillWithRelations = Prisma.SkillGetPayload<{+ include: typeof skillFilesInclude;+}>;++type HashedSkillFile = {+ path: string;+ sha256Hash: string;+} & ({ content: string } | { content?: never });++type ReferencedSkillBlob = Pick<+ SkillBlob,+ "id" | "sha256Hash" | "contentLength"+>;++function parseSkillFrontmatter(text: string): {+ name: string;+ description: string;+ frontmatter: Prisma.InputJsonObject;+} {+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);+ if (!match) {+ throw new InvalidRequestError(+ "SKILL.md must start with YAML frontmatter delimited by ---",+ );+ }++ const document = parseDocument(match[1] ?? "");+ if (document.errors.length > 0) {+ throw new InvalidRequestError(+ `SKILL.md frontmatter is invalid: ${document.errors[0]?.message ?? "unknown YAML error"}`,+ );+ }++ let value: unknown;+ try {+ value = document.toJS({ maxAliasCount: 0 });+ } catch {+ throw new InvalidRequestError("SKILL.md frontmatter is invalid");+ }+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new InvalidRequestError("SKILL.md frontmatter must be an object");+ }++ const frontmatter = value as Record<string, unknown>;+ const name = SkillNameSchema.parse(frontmatter.name);+ const description = SkillDescriptionSchema.parse(frontmatter.description);++ return {+ name,+ description,+ frontmatter: frontmatter as Prisma.InputJsonObject,+ };+}++function serializeVersion(skill: SkillWithRelations) {+ return SkillVersionSchema.parse({+ id: skill.id,+ createdAt: skill.createdAt,+ updatedAt: skill.updatedAt,+ projectId: skill.projectId,+ createdBy: skill.createdBy,+ name: skill.name,+ description: skill.description,+ frontmatter: skill.frontmatter,+ version: skill.version,+ tags: skill.tags,+ labels: skill.labels,+ commitMessage: skill.commitMessage,+ files: skill.files.map((file) => ({+ id: file.id,+ path: file.path,+ blobId: file.blobId,+ sha256Hash: file.blob.sha256Hash,+ contentType: file.blob.contentType,+ contentLength: file.blob.contentLength,+ })),+ });+}++export class SkillService {+ constructor(private readonly prisma: PrismaClient) {}++ async skillVersions(params: {+ projectId: string;+ name: string;+ limit: number;+ cursor?: number | null;+ }) {+ const versions = await this.prisma.skill.findMany({+ where: {+ projectId: params.projectId,+ name: params.name,+ ...(params.cursor != null ? { version: { lt: params.cursor } } : {}),+ },+ orderBy: { version: "desc" },+ take: params.limit + 1,+ select: {+ version: true,+ labels: true,+ commitMessage: true,+ createdAt: true,+ createdBy: true,+ },+ });+ const hasMore = versions.length > params.limit;+ const items = versions.slice(0, params.limit);+ return {+ items,+ nextCursor: hasMore ? items.at(-1)?.version : undefined,+ };+ }++ async createVersion(params: {+ projectId: string;+ createdBy: string;+ input: CreateSkillVersionBody;+ actor: SkillActor;+ }) {+ const input = CreateSkillVersionBodySchema.parse(params.input);+ const { files, referencedBlobs } = await this.prepareVersionFiles({+ projectId: params.projectId,+ files: input.files,+ });+ const frontmatter = await this.loadVersionFrontmatter({+ projectId: params.projectId,+ files,+ referencedBlobs,+ });+ const name = frontmatter.name;++ const skillId = await this.prisma.$transaction(async (tx) => {+ await this.lockSkill(tx, params.projectId, name);+ const latest = await tx.skill.findFirst({+ where: { projectId: params.projectId, name },+ orderBy: { version: "desc" },+ select: { id: true, version: true, labels: true, tags: true },+ });+ if (latest) {+ await this.removeLatestLabel({+ tx,+ projectId: params.projectId,+ latest,+ actor: params.actor,+ });+ }+ const versionFiles = await this.storeVersionFiles({+ tx,+ projectId: params.projectId,+ files,+ referencedBlobs,+ });+ const skill = await tx.skill.create({+ data: {+ id: randomUUID(),+ projectId: params.projectId,+ createdBy: params.createdBy,+ name,+ description: frontmatter.description,+ frontmatter: frontmatter.frontmatter,+ version: (latest?.version ?? 0) + 1,+ tags: latest?.tags ?? [],+ labels: [SKILL_LATEST_LABEL],+ commitMessage: input.commitMessage,+ files: {+ create: versionFiles.map((file) => ({+ project: { connect: { id: params.projectId } },+ path: file.path,+ blob: {+ connect: {+ projectId: params.projectId,+ id: file.blobId,+ },+ },+ })),+ },+ },+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "create",+ resourceId: skill.id,+ projectId: params.projectId,+ after: {+ name: skill.name,+ version: skill.version,+ labels: skill.labels,+ tags: skill.tags,+ files: versionFiles.map((file) => ({+ path: file.path,+ blobId: file.blobId,+ })),+ },+ },+ tx,+ );+ return skill.id;+ });++ return this.getById({ projectId: params.projectId, skillId });+ }++ async get(params: {+ projectId: string;+ name: string;+ selector: SkillSelector;+ }) {+ const skill = await this.findSkillVersion(params);+ return serializeVersion(skill);+ }++ async loadResource(params: {+ projectId: string;+ name: string;+ selector: SkillSelector;+ path: string;+ }): Promise<string> {+ const skill = await this.findSkillVersion(params);+ const file = skill.files.find(({ path }) => path === params.path);+ if (!file) throw new LangfuseNotFoundError("Skill resource not found");+ return (+ await this.getFileContent({+ projectId: params.projectId,+ fileId: file.id,+ })+ ).content;+ }++ async getFileContent(params: { projectId: string; fileId: string }) {+ const file = await this.prisma.skillFile.findFirst({+ where: { projectId: params.projectId, id: params.fileId },+ select: { blob: { select: { content: true } } },+ });+ if (!file) throw new LangfuseNotFoundError("Skill file not found");+ return { content: file.blob.content };+ }++ async list(params: {+ projectId: string;+ input: ListSkillsQuery & { filter?: FilterState };+ }) {+ const filters = this.listFilterConditions(params.input.filter ?? []);+ const where: Prisma.SkillWhereInput = {+ projectId: params.projectId,+ labels: { has: SKILL_LATEST_LABEL },+ ...(filters.length ? { AND: filters } : {}),+ ...(params.input.search+ ? {+ OR: [+ {+ name: {+ contains: params.input.search,+ mode: "insensitive" as const,+ },+ },+ {+ description: {+ contains: params.input.search,+ mode: "insensitive" as const,+ },+ },+ ],+ }+ : {}),+ ...(params.input.name ? { name: params.input.name } : {}),+ ...(params.input.tag ? { tags: { has: params.input.tag } } : {}),+ ...(params.input.fromUpdatedAt || params.input.toUpdatedAt+ ? {+ updatedAt: {+ ...(params.input.fromUpdatedAt+ ? { gte: new Date(params.input.fromUpdatedAt) }+ : {}),+ ...(params.input.toUpdatedAt+ ? { lt: new Date(params.input.toUpdatedAt) }+ : {}),+ },+ }+ : {}),+ };+ const [latestVersions, totalItems] = await Promise.all([+ this.prisma.skill.findMany({+ where,+ orderBy: [{ updatedAt: "desc" }, { name: "asc" }],+ skip: (params.input.page - 1) * params.input.limit,+ take: params.input.limit,+ select: {+ name: true,+ description: true,+ tags: true,+ version: true,+ createdAt: true,+ updatedAt: true,+ },+ }),+ this.prisma.skill.count({ where }),+ ]);+ const productionVersions = latestVersions.length+ ? await this.prisma.skill.findMany({+ where: {+ projectId: params.projectId,+ name: { in: latestVersions.map(({ name }) => name) },+ labels: { has: SKILL_PRODUCTION_LABEL },+ },+ select: { name: true, version: true },+ })+ : [];+ const productionVersionByName = new Map(+ productionVersions.map(({ name, version }) => [name, version]),+ );+ const totalPages = Math.ceil(totalItems / params.input.limit);++ return ListSkillsResponseSchema.parse({+ data: latestVersions.map((skill) => ({+ name: skill.name,+ description: skill.description,+ tags: skill.tags,+ latestVersion: skill.version,+ latestVersionCreatedAt: skill.createdAt,+ latestVersionLastUpdatedAt: skill.updatedAt,+ productionVersion: productionVersionByName.get(skill.name) ?? null,+ })),+ meta: {+ page: params.input.page,+ limit: params.input.limit,+ totalItems,+ totalPages,+ hasNextPage: params.input.page < totalPages,+ },+ });+ }++ private listFilterConditions(filters: FilterState): Prisma.SkillWhereInput[] {+ return filters.map((filter) => {+ if (filter.type !== "arrayOptions" || filter.column !== "tags") {+ throw new InvalidRequestError(+ `Unsupported skill filter: ${filter.column} (${filter.type})`,+ );+ }+ if (!filter.value.length) return {};+ switch (filter.operator) {+ case "any of":+ return { tags: { hasSome: filter.value } };+ case "all of":+ return { tags: { hasEvery: filter.value } };+ case "none of":+ return { NOT: { tags: { hasSome: filter.value } } };+ }+ });+ }++ async filterOptions(params: { projectId: string }) {+ const skills = await this.prisma.skill.findMany({+ where: {+ projectId: params.projectId,+ labels: { has: SKILL_LATEST_LABEL },+ },+ select: { tags: true },+ });+ const counts = new Map<string, number>();+ for (const skill of skills) {+ for (const tag of new Set(skill.tags)) {+ counts.set(tag, (counts.get(tag) ?? 0) + 1);+ }+ }+ return {+ tags: [...counts]+ .map(([value, count]) => ({ value, count }))+ .sort((a, b) => a.value.localeCompare(b.value)),+ };+ }++ async setLabels(params: {+ projectId: string;+ name: string;+ version: number;+ labels: string[];+ actor: SkillActor;+ }) {+ const input = UpdateSkillLabelsBodySchema.parse({ labels: params.labels });+ const skillId = await this.prisma.$transaction(async (tx) => {+ await this.lockSkill(tx, params.projectId, params.name);+ const target = await tx.skill.findFirst({+ where: {+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ },+ });+ if (!target) throw new LangfuseNotFoundError("Skill version not found");++ const changedLabels = [+ ...target.labels.filter((label) => !input.labels.includes(label)),+ ...input.labels.filter((label) => !target.labels.includes(label)),+ ];+ await this.requireProtectedLabelAccess({+ prisma: tx,+ projectId: params.projectId,+ labels: changedLabels,+ actor: params.actor,+ });++ const versions = await tx.skill.findMany({+ where: { projectId: params.projectId, name: params.name },+ select: { id: true, labels: true },+ });+ const nextLabels = [...new Set(input.labels)];+ for (const version of versions) {+ const labels =+ version.id === target.id+ ? [+ ...nextLabels,+ ...version.labels.filter(+ (label) => label === SKILL_LATEST_LABEL,+ ),+ ]+ : version.labels.filter((label) => !nextLabels.includes(label));+ if (version.labels.join("\0") === labels.join("\0")) continue;+ await tx.skill.update({+ where: {+ projectId: params.projectId,+ id: version.id,+ },+ data: { labels: { set: labels } },+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "setLabel",+ resourceId: version.id,+ projectId: params.projectId,+ before: version.labels,+ after: labels,+ },+ tx,+ );+ }+ return target.id;+ });+ return this.getById({ projectId: params.projectId, skillId });+ }++ async setTags(params: {+ projectId: string;+ name: string;+ version?: number;+ tags: string[];+ actor: SkillActor;+ }) {+ const input = UpdateSkillTagsBodySchema.parse({ tags: params.tags });+ const skillId = await this.prisma.$transaction(async (tx) => {+ await this.lockSkill(tx, params.projectId, params.name);+ const target = await tx.skill.findFirst({+ where: {+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ },+ orderBy: { version: "desc" },+ });+ if (!target) throw new LangfuseNotFoundError("Skill not found");++ const tags = [...new Set(input.tags)];+ await tx.skill.updateMany({+ where: { projectId: params.projectId, name: params.name },+ data: { tags: { set: tags } },+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "setTag",+ resourceId: params.name,+ projectId: params.projectId,+ after: tags,+ },+ tx,+ );+ return target.id;+ });+ return this.getById({ projectId: params.projectId, skillId });+ }++ async deleteSkill(params: {+ projectId: string;+ name: string;+ actor: SkillActor;+ }): Promise<void> {+ const where = { projectId: params.projectId, name: params.name };+ await this.prisma.$transaction(async (tx) => {+ await this.lockSkill(tx, params.projectId, params.name);+ const versions = await tx.skill.findMany({+ where,+ select: { version: true, labels: true, tags: true },+ orderBy: { version: "asc" },+ });+ if (!versions.length) throw new LangfuseNotFoundError("Skill not found");+ await this.requireProtectedLabelAccess({+ prisma: tx,+ projectId: params.projectId,+ labels: [...new Set(versions.flatMap(({ labels }) => labels))],+ actor: params.actor,+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "delete",+ resourceId: params.name,+ projectId: params.projectId,+ before: {+ name: params.name,+ versions: versions.map(({ version }) => version),+ labels: [...new Set(versions.flatMap(({ labels }) => labels))],+ tags: versions.at(-1)?.tags,+ },+ },+ tx,+ );+ await tx.skill.deleteMany({ where });+ });+ }++ async deleteVersion(params: {+ projectId: string;+ name: string;+ version: number;+ actor: SkillActor;+ }): Promise<void> {+ await this.prisma.$transaction(async (tx) => {+ await this.lockSkill(tx, params.projectId, params.name);+ const target = await tx.skill.findFirst({+ where: {+ projectId: params.projectId,+ name: params.name,+ version: params.version,+ },+ include: skillFilesInclude,+ });+ if (!target) throw new LangfuseNotFoundError("Skill version not found");+ await this.requireProtectedLabelAccess({+ prisma: tx,+ projectId: params.projectId,+ labels: target.labels,+ actor: params.actor,+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "delete",+ resourceId: target.id,+ projectId: params.projectId,+ before: serializeVersion(target),+ },+ tx,+ );+ await tx.skill.delete({+ where: { projectId: params.projectId, id: target.id },+ });+ if (target.labels.includes(SKILL_LATEST_LABEL)) {+ const latest = await tx.skill.findFirst({+ where: { projectId: params.projectId, name: params.name },+ orderBy: { version: "desc" },+ select: { id: true, labels: true },+ });+ if (latest) {+ const labels = [...new Set([...latest.labels, SKILL_LATEST_LABEL])];+ await tx.skill.update({+ where: {+ projectId: params.projectId,+ id: latest.id,+ },+ data: { labels: { set: labels } },+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "setLabel",+ resourceId: latest.id,+ projectId: params.projectId,+ before: latest.labels,+ after: labels,+ },+ tx,+ );+ }+ }+ });+ }++ private async prepareVersionFiles(params: {+ projectId: string;+ files: CreateSkillVersionBody["files"];+ }): Promise<{+ files: HashedSkillFile[];+ referencedBlobs: Map<string, ReferencedSkillBlob>;+ }> {+ const files = params.files.map((file) => ({+ ...file,+ sha256Hash:+ file.content !== undefined+ ? createHash("sha256").update(file.content, "utf8").digest("base64")+ : file.sha256Hash,+ }));+ const referencedHashes = [+ ...new Set(+ params.files.flatMap((file) =>+ file.sha256Hash !== undefined ? [file.sha256Hash] : [],+ ),+ ),+ ];+ const referencedBlobs = referencedHashes.length+ ? await this.prisma.skillBlob.findMany({+ where: {+ projectId: params.projectId,+ sha256Hash: { in: referencedHashes },+ },+ select: { id: true, sha256Hash: true, contentLength: true },+ })+ : [];+ const referencedBlobByHash = new Map(+ referencedBlobs.map((blob) => [blob.sha256Hash, blob]),+ );+ if (referencedHashes.some((hash) => !referencedBlobByHash.has(hash))) {+ throw new LangfuseNotFoundError(+ "One or more referenced skill blobs were not found",+ );+ }+ const totalBytes = files.reduce(+ (total, file) =>+ total ++ (file.content !== undefined+ ? Buffer.byteLength(file.content, "utf8")+ : referencedBlobByHash.get(file.sha256Hash)!.contentLength),+ 0,+ );+ if (totalBytes > MAX_SKILL_BYTES) {+ throw new InvalidRequestError(+ `A skill must not exceed ${MAX_SKILL_BYTES} bytes in total`,+ );+ }+ return { files, referencedBlobs: referencedBlobByHash };+ }++ private async loadVersionFrontmatter(params: {+ projectId: string;+ files: HashedSkillFile[];+ referencedBlobs: Map<string, ReferencedSkillBlob>;+ }): Promise<ReturnType<typeof parseSkillFrontmatter>> {+ const skillMd = params.files.find(({ path }) => path === "SKILL.md")!;+ let skillMdContent = skillMd.content;+ if (skillMdContent === undefined) {+ const blob = await this.prisma.skillBlob.findFirst({+ where: {+ projectId: params.projectId,+ id: params.referencedBlobs.get(skillMd.sha256Hash)!.id,+ },+ select: { content: true },+ });+ if (!blob)+ throw new LangfuseNotFoundError("Skill instructions were not found");+ skillMdContent = blob.content;+ }+ return parseSkillFrontmatter(skillMdContent);+ }++ private async removeLatestLabel(params: {+ tx: Prisma.TransactionClient;+ projectId: string;+ latest: { id: string; labels: string[] };+ actor: SkillActor;+ }): Promise<void> {+ const labels = params.latest.labels.filter(+ (label) => label !== SKILL_LATEST_LABEL,+ );+ await params.tx.skill.update({+ where: {+ projectId: params.projectId,+ id: params.latest.id,+ },+ data: { labels: { set: labels } },+ });+ await auditLog(+ {+ ...params.actor,+ resourceType: "skill",+ action: "setLabel",+ resourceId: params.latest.id,+ projectId: params.projectId,+ before: params.latest.labels,+ after: labels,+ },+ params.tx,+ );+ }++ private async storeVersionFiles(params: {+ tx: Prisma.TransactionClient;+ projectId: string;+ files: HashedSkillFile[];+ referencedBlobs: Map<string, ReferencedSkillBlob>;+ }): Promise<{ path: string; blobId: string }[]> {+ const uniqueFiles = [+ ...new Map(+ params.files+ .filter((file) => file.content !== undefined)+ .map((file) => [file.sha256Hash, file]),+ ).values(),+ ].sort((a, b) => a.sha256Hash.localeCompare(b.sha256Hash));+ if (uniqueFiles.length) {+ await params.tx.skillBlob.createMany({+ data: uniqueFiles.map((file) => ({+ id: randomUUID(),+ projectId: params.projectId,+ sha256Hash: file.sha256Hash,+ content: file.content,+ contentType: "text/plain",+ contentLength: Buffer.byteLength(file.content, "utf8"),+ })),+ skipDuplicates: true,+ });+ }+ const blobs = uniqueFiles.length+ ? await params.tx.skillBlob.findMany({+ where: {+ projectId: params.projectId,+ sha256Hash: { in: uniqueFiles.map((file) => file.sha256Hash) },+ },+ select: { id: true, sha256Hash: true },+ })+ : [];+ const blobIds = new Map(+ [...params.referencedBlobs.values(), ...blobs].map((blob) => [+ blob.sha256Hash,+ blob.id,+ ]),+ );+ return params.files.map((file) => ({+ path: file.path,+ blobId: blobIds.get(file.sha256Hash)!,+ }));+ }++ private async requireProtectedLabelAccess(params: {+ prisma: Prisma.TransactionClient;+ projectId: string;+ labels: string[];+ actor: SkillActor;+ }) {+ const labelsToCheck = params.labels.filter(+ (label) => label !== SKILL_LATEST_LABEL,+ );+ if ("session" in params.actor) {+ const { hasProtectedLabels, protectedLabels } =+ await checkHasProtectedLabels({+ prisma: params.prisma,+ projectId: params.projectId,+ labelsToCheck,+ });+ if (hasProtectedLabels) {+ throwIfNoProjectAccess({+ session: params.actor.session,+ projectId: params.projectId,+ scope: "promptProtectedLabels:CUD",+ forbiddenErrorMessage: `You do not have permission to mutate protected skill labels: ${protectedLabels.join(", ")}`,+ });+ }+ return;+ }++ await authorizeProtectedLabelMutation({+ prisma: params.prisma,+ context: { ...params.actor, projectId: params.projectId },+ ctx: params.actor.ctx,+ labelsToCheck,+ forbiddenErrorMessage:+ "You do not have permission to mutate protected skill labels.",+ });+ }++ private lockSkill(+ tx: Prisma.TransactionClient,+ projectId: string,+ name: string,+ ) {+ // Serialize metadata and version changes to preserve latest and shared tags.+ const key = JSON.stringify(["skills", projectId, name]);+ return tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${key}))`;+ }++ private async getById(params: { projectId: string; skillId: string }) {+ const skill = await this.prisma.skill.findUnique({+ where: {+ projectId: params.projectId,+ id: params.skillId,+ },+ include: skillFilesInclude,+ });+ if (!skill) throw new LangfuseNotFoundError("Skill version not found");+ return serializeVersion(skill);+ }++ private async findSkillVersion(params: {+ projectId: string;+ name: string;+ selector: SkillSelector;+ }): Promise<SkillWithRelations> {+ const selectorWhere: Prisma.SkillWhereInput = params.selector.version+ ? { version: params.selector.version }+ : { labels: { has: params.selector.label ?? SKILL_PRODUCTION_LABEL } };++ const skill = await this.prisma.skill.findFirst({+ where: {+ projectId: params.projectId,+ name: params.name,+ ...selectorWhere,+ },+ orderBy: { version: "desc" },+ include: skillFilesInclude,+ });+ if (!skill) throw new LangfuseNotFoundError("Skill version not found");+ return skill;+ }+}diff --git a/web/src/features/skills/utils/getSkillFileLanguageExtensions.ts b/web/src/features/skills/utils/getSkillFileLanguageExtensions.tsnew file mode 100644index 0000000000..05703d6bff--- /dev/null+++ b/web/src/features/skills/utils/getSkillFileLanguageExtensions.ts@@ -0,0 +1,28 @@+import { javascript } from "@codemirror/lang-javascript";+import { python } from "@codemirror/lang-python";+import { StreamLanguage } from "@codemirror/language";+import { shell } from "@codemirror/legacy-modes/mode/shell";+import { type Extension } from "@codemirror/state";++const javascriptExtensions: Extension[] = [javascript()];+const pythonExtensions: Extension[] = [python()];+const shellExtensions: Extension[] = [StreamLanguage.define(shell)];+const textExtensions: Extension[] = [];++export function getSkillFileLanguageExtensions(path: string): Extension[] {+ const extension = path.slice(path.lastIndexOf(".")).toLowerCase();+ switch (extension) {+ case ".js":+ case ".mjs":+ case ".cjs":+ return javascriptExtensions;+ case ".py":+ return pythonExtensions;+ case ".sh":+ case ".bash":+ case ".zsh":+ return shellExtensions;+ default:+ return textExtensions;+ }+}diff --git a/web/src/features/skills/utils/parseSkillFrontmatterMetadata.ts b/web/src/features/skills/utils/parseSkillFrontmatterMetadata.tsnew file mode 100644index 0000000000..7fc56089ea--- /dev/null+++ b/web/src/features/skills/utils/parseSkillFrontmatterMetadata.ts@@ -0,0 +1,57 @@+import { SkillDescriptionSchema, SkillNameSchema } from "@langfuse/shared";+import { isMap, isScalar, parseDocument } from "yaml";++export type SkillFrontmatterMetadata = {+ name: string;+ description?: string;+ nameError: string | null;+};++export const SKILL_NAME_RULES =+ "Use 1–64 characters: lowercase letters, numbers, and single hyphens between words. Names cannot start or end with a hyphen.";++export function parseSkillFrontmatterMetadata(+ markdown: string,+): SkillFrontmatterMetadata | null {+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown);+ if (!match) return null;++ const document = parseDocument(match[1] ?? "");+ const nameNode = isMap(document.contents)+ ? document.get("name", true)+ : undefined;+ let displayName = "";+ if (isScalar(nameNode)) {+ displayName =+ typeof nameNode.value === "string"+ ? nameNode.value+ : (nameNode.source ?? "");+ }+ const invalidFrontmatter = {+ name: displayName,+ nameError: `Fix the YAML frontmatter in SKILL.md. ${SKILL_NAME_RULES}`,+ };+ if (document.errors.length > 0) return invalidFrontmatter;++ try {+ const value: unknown = document.toJS({ maxAliasCount: 0 });+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return null;+ }++ const frontmatter = value as Record<string, unknown>;+ const name = SkillNameSchema.safeParse(frontmatter.name);+ const description = SkillDescriptionSchema.safeParse(+ frontmatter.description,+ );++ return {+ name:+ typeof frontmatter.name === "string" ? frontmatter.name : displayName,+ description: description.success ? description.data : undefined,+ nameError: name.success ? null : SKILL_NAME_RULES,+ };+ } catch {+ return invalidFrontmatter;+ }+}diff --git a/web/src/features/skills/utils/resetSkillName.ts b/web/src/features/skills/utils/resetSkillName.tsnew file mode 100644index 0000000000..19b7cbdd7e--- /dev/null+++ b/web/src/features/skills/utils/resetSkillName.ts@@ -0,0 +1,27 @@+import { isMap, isNode, parseDocument } from "yaml";++export function resetSkillName(markdown: string, name: string): string {+ const match = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(markdown);+ if (!match) return `---\nname: ${name}\n---\n${markdown}`;++ const frontmatter = match[2]!;+ const document = parseDocument(frontmatter);+ const nameNode = isMap(document.contents)+ ? document.get("name", true)+ : undefined;+ if (isNode(nameNode) && nameNode.range) {+ const start = match[1]!.length + nameNode.range[0];+ const end = match[1]!.length + nameNode.range[1];+ const trailingNewline =+ /\r?\n$/.exec(markdown.slice(start, end))?.[0] ?? "";+ return (+ markdown.slice(0, start) + name + trailingNewline + markdown.slice(end)+ );+ }++ const newline = match[1]!.endsWith("\r\n") ? "\r\n" : "\n";+ const start = match[1]!.length;+ return (+ markdown.slice(0, start) + `name: ${name}${newline}` + markdown.slice(start)+ );+}diff --git a/web/src/pages/api/public/unstable/skills/[skillName]/index.ts b/web/src/pages/api/public/unstable/skills/[skillName]/index.tsnew file mode 100644index 0000000000..0db85b3de7--- /dev/null+++ b/web/src/pages/api/public/unstable/skills/[skillName]/index.ts@@ -0,0 +1,54 @@+import { prisma } from "@langfuse/shared/src/db";+import { z } from "zod/v4";+import {+ SkillNameSchema,+ SkillSelectorSchema,+ SkillVersionSchema,+ UpdateSkillTagsBodySchema,+} from "@langfuse/shared";+import {+ createAuthedProjectAPIRoute,+ withMiddlewares,+} from "@/src/features/public-api/server";+import { SkillService } from "@/src/features/skills/server";++const querySchema = SkillSelectorSchema.and(+ z.object({ skillName: SkillNameSchema }),+);++export default withMiddlewares({+ PATCH: createAuthedProjectAPIRoute({+ name: "Update Skill",+ action: "skills:CUD",+ querySchema: z.object({ skillName: SkillNameSchema }),+ bodySchema: UpdateSkillTagsBodySchema,+ responseSchema: SkillVersionSchema,+ rateLimitResource: "public-api",+ fn: ({ query, body, auth, ctx }) =>+ new SkillService(prisma).setTags({+ projectId: auth.scope.projectId,+ name: query.skillName,+ tags: body.tags,+ actor: {+ apiKeyId: auth.scope.apiKeyId!,+ orgId: auth.scope.orgId,+ projectId: auth.scope.projectId,+ accessLevel: auth.scope.accessLevel,+ ctx,+ },+ }),+ }),+ GET: createAuthedProjectAPIRoute({+ name: "Get Skill",+ action: "skills:read",+ querySchema,+ responseSchema: SkillVersionSchema,+ rateLimitResource: "public-api",+ fn: async ({ query, auth }) =>+ new SkillService(prisma).get({+ projectId: auth.scope.projectId,+ name: query.skillName,+ selector: query,+ }),+ }),+});diff --git a/web/src/pages/api/public/unstable/skills/[skillName]/versions/[skillVersion].ts b/web/src/pages/api/public/unstable/skills/[skillName]/versions/[skillVersion].tsnew file mode 100644index 0000000000..95f09f5c5b--- /dev/null+++ b/web/src/pages/api/public/unstable/skills/[skillName]/versions/[skillVersion].ts@@ -0,0 +1,65 @@+import { prisma } from "@langfuse/shared/src/db";+import { z } from "zod/v4";+import {+ DeleteSkillVersionResponseSchema,+ SkillNameSchema,+ SkillVersionSchema,+ UpdateSkillLabelsBodySchema,+} from "@langfuse/shared";+import {+ createAuthedProjectAPIRoute,+ withMiddlewares,+} from "@/src/features/public-api/server";+import { SkillService } from "@/src/features/skills/server";++const versionQuerySchema = z.object({+ skillName: SkillNameSchema,+ skillVersion: z.coerce.number().int().positive(),+});++export default withMiddlewares({+ PATCH: createAuthedProjectAPIRoute({+ name: "Update Skill Version Labels",+ action: "skills:CUD",+ querySchema: versionQuerySchema,+ bodySchema: UpdateSkillLabelsBodySchema,+ responseSchema: SkillVersionSchema,+ rateLimitResource: "public-api",+ fn: ({ query, body, auth, ctx }) =>+ new SkillService(prisma).setLabels({+ projectId: auth.scope.projectId,+ name: query.skillName,+ version: query.skillVersion,+ labels: body.labels,+ actor: {+ apiKeyId: auth.scope.apiKeyId!,+ orgId: auth.scope.orgId,+ projectId: auth.scope.projectId,+ accessLevel: auth.scope.accessLevel,+ ctx,+ },+ }),+ }),+ DELETE: createAuthedProjectAPIRoute({+ name: "Delete Skill Version",+ action: "skills:CUD",+ querySchema: versionQuerySchema,+ responseSchema: DeleteSkillVersionResponseSchema,+ rateLimitResource: "public-api",+ fn: async ({ query, auth, ctx }) => {+ await new SkillService(prisma).deleteVersion({+ projectId: auth.scope.projectId,+ name: query.skillName,+ version: query.skillVersion,+ actor: {+ apiKeyId: auth.scope.apiKeyId!,+ orgId: auth.scope.orgId,+ projectId: auth.scope.projectId,+ accessLevel: auth.scope.accessLevel,+ ctx,+ },+ });+ return { deleted: true };+ },+ }),+});diff --git a/web/src/pages/api/public/unstable/skills/files/[fileId]/content.ts b/web/src/pages/api/public/unstable/skills/files/[fileId]/content.tsnew file mode 100644index 0000000000..dedc0dc2c1--- /dev/null+++ b/web/src/pages/api/public/unstable/skills/files/[fileId]/content.ts@@ -0,0 +1,25 @@+import { SkillFileContentResponseSchema } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { z } from "zod/v4";+import {+ createAuthedProjectAPIRoute,+ withMiddlewares,+} from "@/src/features/public-api/server";+import { SkillService } from "@/src/features/skills/server";++export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "Get Skill File Content",+ action: "skills:read",+ querySchema: z.object({ fileId: z.string().min(1) }),+ responseSchema: SkillFileContentResponseSchema,+ rateLimitResource: "public-api",+ fn: async ({ query, auth, res }) => {+ res.setHeader("Cache-Control", "no-store");+ return new SkillService(prisma).getFileContent({+ projectId: auth.scope.projectId,+ fileId: query.fileId,+ });+ },+ }),+});diff --git a/web/src/pages/api/public/unstable/skills/index.ts b/web/src/pages/api/public/unstable/skills/index.tsnew file mode 100644index 0000000000..100765ae4e--- /dev/null+++ b/web/src/pages/api/public/unstable/skills/index.ts@@ -0,0 +1,54 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ CreateSkillVersionBodySchema,+ ListSkillsQuerySchema,+ ListSkillsResponseSchema,+ SkillVersionSchema,+} from "@langfuse/shared";+import {+ createAuthedProjectAPIRoute,+ withMiddlewares,+} from "@/src/features/public-api/server";+import { SkillService } from "@/src/features/skills/server";++export const config = {+ api: {+ bodyParser: { sizeLimit: "4.5mb" },+ },+};++export default withMiddlewares({+ GET: createAuthedProjectAPIRoute({+ name: "List Skills",+ action: "skills:read",+ querySchema: ListSkillsQuerySchema,+ responseSchema: ListSkillsResponseSchema,+ rateLimitResource: "public-api",+ fn: ({ query, auth }) =>+ new SkillService(prisma).list({+ projectId: auth.scope.projectId,+ input: query,+ }),+ }),+ POST: createAuthedProjectAPIRoute({+ name: "Create Skill Version",+ action: "skills:CUD",+ bodySchema: CreateSkillVersionBodySchema,+ responseSchema: SkillVersionSchema,+ successStatusCode: 201,+ rateLimitResource: "public-api",+ fn: ({ body, auth, ctx }) =>+ new SkillService(prisma).createVersion({+ projectId: auth.scope.projectId,+ createdBy: "API",+ input: body,+ actor: {+ apiKeyId: auth.scope.apiKeyId!,+ orgId: auth.scope.orgId,+ projectId: auth.scope.projectId,+ accessLevel: auth.scope.accessLevel,+ ctx,+ },+ }),+ }),+});diff --git a/web/src/pages/project/[projectId]/skills/[skillName].tsx b/web/src/pages/project/[projectId]/skills/[skillName].tsxnew file mode 100644index 0000000000..3a7c127f28--- /dev/null+++ b/web/src/pages/project/[projectId]/skills/[skillName].tsx@@ -0,0 +1,10 @@+import { ExistingSkillPage } from "@/src/features/skills/components/SkillEditorPage";+import { SkillsFeatureGate } from "@/src/features/skills/components/SkillsFeatureGate";++export default function ExistingSkill() {+ return (+ <SkillsFeatureGate>+ <ExistingSkillPage />+ </SkillsFeatureGate>+ );+}diff --git a/web/src/pages/project/[projectId]/skills/index.tsx b/web/src/pages/project/[projectId]/skills/index.tsxnew file mode 100644index 0000000000..93ac7d1dd7--- /dev/null+++ b/web/src/pages/project/[projectId]/skills/index.tsx@@ -0,0 +1,10 @@+import { SkillsPage } from "@/src/features/skills/components/SkillsPage";+import { SkillsFeatureGate } from "@/src/features/skills/components/SkillsFeatureGate";++export default function Skills() {+ return (+ <SkillsFeatureGate>+ <SkillsPage />+ </SkillsFeatureGate>+ );+}diff --git a/web/src/pages/project/[projectId]/skills/new.tsx b/web/src/pages/project/[projectId]/skills/new.tsxnew file mode 100644index 0000000000..d302b1c625--- /dev/null+++ b/web/src/pages/project/[projectId]/skills/new.tsx@@ -0,0 +1,10 @@+import { NewSkillPage } from "@/src/features/skills/components/SkillEditorPage";+import { SkillsFeatureGate } from "@/src/features/skills/components/SkillsFeatureGate";++export default function NewSkill() {+ return (+ <SkillsFeatureGate>+ <NewSkillPage />+ </SkillsFeatureGate>+ );+}diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 7dc6e74986..a8722501a7 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -62,6 +62,7 @@ import { webCalloutsRouter } from "@/src/features/web-callouts/server/router";import { inAppAgentRouter } from "@/src/features/in-app-agent/server/router";import { v4TransitionRouter } from "@/src/features/v4/server/v4TransitionRouter";import { aiGatewayRouter } from "@/src/features/ai-gateway/server";+import { skillRouter } from "@/src/features/skills/server/skill-router";/*** This is the primary router for your server.@@ -132,6 +133,7 @@ export const appRouter = createTRPCRouter({inAppAgent: inAppAgentRouter,v4Transition: v4TransitionRouter,aiGateway: aiGatewayRouter,+ skills: skillRouter,});// export type definition of API