Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📜 feat: Skills UI + Initial E2E CRUD / Sharing (#12580)

Marco Berettaf6ee2ea0eef9
diff --git a/.github/workflows/backend-review.yml b/.github/workflows/backend-review.yml
index 9dd3905c0e..03b7c135d2 100644
--- a/.github/workflows/backend-review.yml
+++ b/.github/workflows/backend-review.yml
@@ -1,11 +1,6 @@
name: Backend Unit Tests
on:
pull_request:
- branches:
- - main
- - dev
- - dev-staging
- - release/*
paths:
- 'api/**'
- 'packages/**'
diff --git a/.github/workflows/frontend-review.yml b/.github/workflows/frontend-review.yml
index 9c2d4a37b1..05b3f4154f 100644
--- a/.github/workflows/frontend-review.yml
+++ b/.github/workflows/frontend-review.yml
@@ -2,11 +2,6 @@ name: Frontend Unit Tests
on:
pull_request:
- branches:
- - main
- - dev
- - dev-staging
- - release/*
paths:
- 'client/**'
- 'packages/data-provider/**'
diff --git a/api/server/routes/roles.js b/api/server/routes/roles.js
index 456d144af1..feed23f8dd 100644
--- a/api/server/routes/roles.js
+++ b/api/server/routes/roles.js
@@ -11,6 +11,7 @@ const {
marketplacePermissionsSchema,
peoplePickerPermissionsSchema,
remoteAgentsPermissionsSchema,
+ skillPermissionsSchema,
} = require('librechat-data-provider');
const { hasCapability, requireCapability } = require('~/server/middleware/roles/capabilities');
const { updateRoleByName, getRoleByName } = require('~/models');
@@ -60,6 +61,11 @@ const permissionConfigs = {
permissionType: PermissionTypes.REMOTE_AGENTS,
errorMessage: 'Invalid remote agents permissions.',
},
+ skills: {
+ schema: skillPermissionsSchema,
+ permissionType: PermissionTypes.SKILLS,
+ errorMessage: 'Invalid skill permissions.',
+ },
};
/**
@@ -177,4 +183,10 @@ router.put('/:roleName/marketplace', manageRoles, createPermissionUpdateHandler(
*/
router.put('/:roleName/remote-agents', manageRoles, createPermissionUpdateHandler('remote-agents'));
+/**
+ * PUT /api/roles/:roleName/skills
+ * Update skill permissions for a specific role
+ */
+router.put('/:roleName/skills', manageRoles, createPermissionUpdateHandler('skills'));
+
module.exports = router;
diff --git a/api/server/routes/skills.js b/api/server/routes/skills.js
index 38d4b38ca5..9e9676fb45 100644
--- a/api/server/routes/skills.js
+++ b/api/server/routes/skills.js
@@ -1,7 +1,19 @@
+const path = require('path');
+const crypto = require('crypto');
+const multer = require('multer');
const express = require('express');
-const { createSkillsHandlers, generateCheckAccess } = require('@librechat/api');
-const { isValidObjectIdString } = require('@librechat/data-schemas');
-const { PermissionBits, PermissionTypes, Permissions } = require('librechat-data-provider');
+const {
+ createSkillsHandlers,
+ createImportHandler,
+ generateCheckAccess,
+} = require('@librechat/api');
+const { isValidObjectIdString, logger } = require('@librechat/data-schemas');
+const {
+ PermissionBits,
+ PermissionTypes,
+ Permissions,
+ FileContext,
+} = require('librechat-data-provider');
const {
createSkill,
getSkillById,
@@ -9,21 +21,60 @@ const {
updateSkill,
deleteSkill,
listSkillFiles,
+ upsertSkillFile,
deleteSkillFile,
+ getSkillFileByPath,
+ updateSkillFileContent,
getRoleByName,
} = require('~/models');
const { requireJwtAuth, canAccessSkillResource } = require('~/server/middleware');
const {
findAccessibleResources,
findPubliclyAccessibleResources,
+ hasPublicPermission,
grantPermission,
} = require('~/server/services/PermissionService');
+const { getStrategyFunctions } = require('~/server/services/Files/strategies');
+const { createFileLimiters } = require('~/server/middleware/limiters/uploadLimiters');
+const configMiddleware = require('~/server/middleware/config/app');
+const { getFileStrategy } = require('~/server/utils/getFileStrategy');
const router = express.Router();
-// Role-based capability gates. Mirrors prompts.js — the ACL middleware on each
-// route handles per-resource permissions; these check that the caller's role
-// is even allowed to use / create skills at all.
+// ---------------------------------------------------------------------------
+// Multer: memory storage for skill imports (zip processed in-memory)
+// ---------------------------------------------------------------------------
+const ALLOWED_EXTENSIONS = new Set(['.md', '.zip', '.skill']);
+const MAX_IMPORT_SIZE = 50 * 1024 * 1024; // 50 MB
+
+const memoryStorage = multer.memoryStorage();
+
+const skillImportFilter = (_req, file, cb) => {
+ const ext = path.extname(file.originalname).toLowerCase();
+ if (ALLOWED_EXTENSIONS.has(ext)) {
+ cb(null, true);
+ } else {
+ // N.B. The error handler at the bottom of this file matches this "Only " prefix.
+ cb(new Error('Only .md, .zip, and .skill files are allowed'), false);
+ }
+};
+
+const skillUpload = multer({
+ storage: memoryStorage,
+ fileFilter: skillImportFilter,
+ limits: { fileSize: MAX_IMPORT_SIZE },
+});
+
+// Per-file upload (for adding individual files to an existing skill)
+const MAX_SINGLE_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
+const singleFileUpload = multer({
+ storage: memoryStorage,
+ limits: { fileSize: MAX_SINGLE_FILE_SIZE },
+});
+
+// ---------------------------------------------------------------------------
+// Role-based capability gates
+// ---------------------------------------------------------------------------
const checkSkillAccess = generateCheckAccess({
permissionType: PermissionTypes.SKILLS,
permissions: [Permissions.USE],
@@ -35,9 +86,18 @@ const checkSkillCreate = generateCheckAccess({
getRoleByName,
});
+// ---------------------------------------------------------------------------
+// Rate limiters (reuse existing file upload limiters)
+// ---------------------------------------------------------------------------
+const { fileUploadIpLimiter, fileUploadUserLimiter } = createFileLimiters();
+
router.use(requireJwtAuth);
+router.use(configMiddleware);
router.use(checkSkillAccess);
+// ---------------------------------------------------------------------------
+// CRUD handlers
+// ---------------------------------------------------------------------------
const handlers = createSkillsHandlers({
createSkill,
getSkillById,
@@ -46,12 +106,158 @@ const handlers = createSkillsHandlers({
deleteSkill,
listSkillFiles,
deleteSkillFile,
+ getSkillFileByPath,
+ updateSkillFileContent,
+ getStrategyFunctions,
findAccessibleResources,
findPubliclyAccessibleResources,
+ hasPublicPermission,
grantPermission,
isValidObjectIdString,
});
+// ---------------------------------------------------------------------------
+// File storage helper: resolve the active strategy's saveBuffer
+// ---------------------------------------------------------------------------
+function resolveSkillStorage(req, { isImage = false } = {}) {
+ const source = getFileStrategy(req.config, { context: FileContext.skill_file, isImage });
+ const strategy = getStrategyFunctions(source);
+ if (!strategy.saveBuffer) {
+ throw new Error(`Storage backend "${source}" does not support file writes`);
+ }
+ return { saveBuffer: strategy.saveBuffer, source };
+}
+
+// ---------------------------------------------------------------------------
+// Import handler (zip/md/skill → create skill + files)
+// ---------------------------------------------------------------------------
+const importHandler = createImportHandler({
+ createSkill,
+ getSkillById,
+ deleteSkill,
+ upsertSkillFile,
+ saveBuffer: (req, { userId, buffer, fileName, basePath, isImage }) => {
+ const storage = resolveSkillStorage(req, { isImage });
+ return storage.saveBuffer({ userId, buffer, fileName, basePath }).then((filepath) => ({
+ filepath,
+ source: storage.source,
+ }));
+ },
+ deleteFile: (req, file) => {
+ const { deleteFile } = getStrategyFunctions(file.source);
+ if (deleteFile) {
+ return deleteFile(req, file);
+ }
+ return Promise.resolve();
+ },
+ grantPermission,
+});
+
+// ---------------------------------------------------------------------------
+// Per-file upload handler (add a single file to an existing skill)
+// ---------------------------------------------------------------------------
+async function uploadFileHandler(req, res) {
+ try {
+ const { file } = req;
+ if (!file) {
+ return res.status(400).json({ error: 'No file provided' });
+ }
+
+ const skillId = req.params.id;
+ const relativePath = req.body.relativePath;
+ if (!relativePath) {
+ return res.status(400).json({ error: 'relativePath is required in form body' });
+ }
+ if (relativePath.toUpperCase() === 'SKILL.MD') {
+ return res.status(400).json({ error: 'SKILL.md is reserved; update the skill body instead' });
+ }
+ // Reject traversal, absolute paths, empty/dot segments — matches model-layer validator
+ // so storage writes don't happen before DB rejects the path.
+ if (
+ !/^[a-zA-Z0-9._\-/]+$/.test(relativePath) ||
+ /^\//.test(relativePath) ||
+ relativePath.split('/').some((s) => s === '' || s === '.' || s === '..')
+ ) {
+ return res.status(400).json({ error: 'Invalid file path' });
+ }
+
+ // Look up existing file before saving — needed to clean up old blob on replace
+ const existingFile = await getSkillFileByPath(skillId, relativePath);
+
+ const fileId = crypto.randomUUID();
+ const filename = file.originalname;
+ const storageFileName = `${fileId}__${filename}`;
+
+ const isImage = (file.mimetype || '').startsWith('image/');
+ const storage = resolveSkillStorage(req, { isImage });
+ const filepath = await storage.saveBuffer({
+ userId: req.user.id,
+ buffer: file.buffer,
+ fileName: storageFileName,
+ basePath: 'uploads',
+ });
+
+ let result;
+ try {
+ result = await upsertSkillFile({
+ skillId,
+ relativePath,
+ file_id: fileId,
+ filename,
+ filepath,
+ source: storage.source,
+ mimeType: file.mimetype || 'application/octet-stream',
+ bytes: file.size,
+ isExecutable: false,
+ author: req.user._id,
+ });
+ } catch (dbError) {
+ // Clean up the stored blob so it doesn't leak on DB failure
+ try {
+ const { deleteFile } = getStrategyFunctions(storage.source);
+ if (deleteFile) {
+ await deleteFile(req, { filepath });
+ }
+ } catch (cleanupErr) {
+ logger.error('[uploadFile] Failed to clean up orphaned blob:', cleanupErr);
+ }
+ throw dbError;
+ }
+
+ // Clean up old blob if this was a replace (different filepath means new storage object)
+ if (existingFile && existingFile.filepath !== filepath) {
+ const { deleteFile: delOld } = getStrategyFunctions(existingFile.source);
+ if (delOld) {
+ delOld(req, { filepath: existingFile.filepath }).catch((e) =>
+ logger.error('[uploadFile] Old blob cleanup failed:', e),
+ );
+ }
+ }
+
+ return res.status(200).json(result);
+ } catch (error) {
+ if (error.code === 'SKILL_FILE_VALIDATION_FAILED') {
+ return res.status(400).json({ error: error.message });
+ }
+ logger.error('[uploadFile] Error:', error);
+ return res.status(500).json({ error: 'Failed to upload file' });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Routes
+// ---------------------------------------------------------------------------
+
+// Import: accepts .md / .zip / .skill via multipart
+router.post(
+ '/import',
+ checkSkillCreate,
+ fileUploadIpLimiter,
+ fileUploadUserLimiter,
+ skillUpload.single('file'),
+ importHandler,
+);
+
router.get('/', handlers.list);
router.post('/', checkSkillCreate, handlers.create);
@@ -81,16 +287,20 @@ router.get(
handlers.listFiles,
);
+// Per-file upload (live — replaces 501 stub)
router.post(
'/:id/files',
canAccessSkillResource({ requiredPermission: PermissionBits.EDIT }),
- handlers.uploadFileStub,
+ fileUploadIpLimiter,
+ fileUploadUserLimiter,
+ singleFileUpload.single('file'),
+ uploadFileHandler,
);
router.get(
'/:id/files/:relativePath',
canAccessSkillResource({ requiredPermission: PermissionBits.VIEW }),
- handlers.downloadFileStub,
+ handlers.downloadFile,
);
router.delete(
@@ -99,4 +309,13 @@ router.delete(
handlers.deleteFile,
);
+// Multer + file-filter error handler — surface as 400, forward everything else
+
+router.use((err, _req, res, next) => {
+ if (err && (err.name === 'MulterError' || err.message?.startsWith('Only '))) {
+ return res.status(400).json({ error: err.message });
+ }
+ return next(err);
+});
+
module.exports = router;
diff --git a/api/server/routes/skills.test.js b/api/server/routes/skills.test.js
index c4b0c6b8c9..1a0a23c896 100644
--- a/api/server/routes/skills.test.js
+++ b/api/server/routes/skills.test.js
@@ -12,6 +12,35 @@ const {
jest.mock('~/server/services/Config', () => ({
getCachedTools: jest.fn().mockResolvedValue({}),
+ getAppConfig: jest.fn().mockResolvedValue({
+ fileStrategy: 'local',
+ paths: { uploads: '/tmp/uploads', images: '/tmp/images' },
+ }),
+}));
+
+jest.mock('~/server/middleware/config/app', () => (req, _res, next) => {
+ req.config = {
+ fileStrategy: 'local',
+ paths: { uploads: '/tmp/uploads', images: '/tmp/images' },
+ };
+ next();
+});
+
+jest.mock('~/server/services/Files/strategies', () => ({
+ getStrategyFunctions: jest.fn().mockReturnValue({
+ saveBuffer: jest.fn().mockResolvedValue('/uploads/test/file.txt'),
+ getDownloadStream: jest.fn().mockResolvedValue({
+ pipe: jest.fn(),
+ on: jest.fn(),
+ [Symbol.asyncIterator]: async function* () {
+ yield Buffer.from('test content');
+ },
+ }),
+ }),
+}));
+
+jest.mock('~/server/utils/getFileStrategy', () => ({
+ getFileStrategy: jest.fn().mockReturnValue('local'),
}));
jest.mock('~/models', () => {
@@ -381,22 +410,32 @@ describe('Skill routes', () => {
});
});
- describe('POST /api/skills/:id/files (stub)', () => {
- it('returns 501 with phase marker', async () => {
+ describe('POST /api/skills/:id/files (live)', () => {
+ it('returns 400 when no file is provided', async () => {
const created = await createSkillAsOwner();
const res = await request(app).post(`/api/skills/${created.body._id}/files`);
- expect(res.status).toBe(501);
- expect(res.body.phase).toBe(2);
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/no file/i);
});
});
- describe('GET /api/skills/:id/files/:relativePath (stub)', () => {
- it('returns 501 stub', async () => {
+ describe('GET /api/skills/:id/files/:relativePath', () => {
+ it('returns SKILL.md content from skill body', async () => {
+ const created = await createSkillAsOwner();
+ const res = await request(app).get(`/api/skills/${created.body._id}/files/SKILL.md`);
+ expect(res.status).toBe(200);
+ expect(res.body.mimeType).toBe('text/markdown');
+ expect(res.body.isBinary).toBe(false);
+ expect(res.body.filename).toBe('SKILL.md');
+ expect(res.body.content).toBeDefined();
+ });
+
+ it('returns 404 for a nonexistent file', async () => {
const created = await createSkillAsOwner();
const res = await request(app).get(
- `/api/skills/${created.body._id}/files/scripts%2Fparse.sh`,
+ `/api/skills/${created.body._id}/files/scripts%2Fmissing.sh`,
);
- expect(res.status).toBe(501);
+ expect(res.status).toBe(404);
});
});
diff --git a/api/server/utils/getFileStrategy.js b/api/server/utils/getFileStrategy.js
index 2e3dfdd79e..1bab7f2468 100644
--- a/api/server/utils/getFileStrategy.js
+++ b/api/server/utils/getFileStrategy.js
@@ -43,6 +43,10 @@ function getFileStrategy(appConfig, { isAvatar = false, isImage = false, context
if (isAvatar || context === FileContext.avatar) {
selectedStrategy = strategies.avatar || defaultStrategy;
+ } else if (context === FileContext.skill_file) {
+ // Skill files: explicit skills strategy → fall back by type → default
+ selectedStrategy =
+ strategies.skills || (isImage ? strategies.image : strategies.document) || defaultStrategy;
} else if (isImage || context === FileContext.image_generation) {
selectedStrategy = strategies.image || defaultStrategy;
} else {
diff --git a/client/package.json b/client/package.json
index 9765917a87..feb07b1937 100644
--- a/client/package.json
+++ b/client/package.json
@@ -7,7 +7,7 @@
"typecheck": "tsc --noEmit",
"data-provider": "cd .. && npm run build:data-provider",
"build:file": "cross-env NODE_ENV=production vite build --debug > vite-output.log 2>&1",
- "build": "cross-env NODE_ENV=production vite build && node ./scripts/post-build.cjs",
+ "build": "cross-env NODE_ENV=production NODE_OPTIONS=--max-old-space-size=8192 vite build && node ./scripts/post-build.cjs",
"build:ci": "cross-env NODE_ENV=development vite build --mode ci",
"dev": "cross-env NODE_ENV=development vite",
"preview-prod": "cross-env NODE_ENV=development vite preview",
@@ -101,6 +101,7 @@
"react-textarea-autosize": "^8.4.0",
"react-transition-group": "^4.4.5",
"react-virtualized": "^9.22.6",
+ "react-vtree": "^3.0.0",
"recoil": "^0.7.7",
"regenerator-runtime": "^0.14.1",
"rehype-highlight": "^6.0.0",
diff --git a/client/src/common/agents-types.ts b/client/src/common/agents-types.ts
index c3ea06f890..cd3e5e0f49 100644
--- a/client/src/common/agents-types.ts
+++ b/client/src/common/agents-types.ts
@@ -38,6 +38,7 @@ export type AgentForm = {
tools?: string[];
/** Per-tool configuration options (deferred loading, allowed callers, etc.) */
tool_options?: AgentToolOptions;
+ skills?: string[];
provider?: AgentProvider | OptionWithIcon;
/** @deprecated Use edges instead */
agent_ids?: string[];
diff --git a/client/src/components/Prompts/display/PromptTextCard.tsx b/client/src/components/Prompts/display/PromptTextCard.tsx
index 379dcab21f..7204c8a5ab 100644
--- a/client/src/components/Prompts/display/PromptTextCard.tsx
+++ b/client/src/components/Prompts/display/PromptTextCard.tsx
@@ -5,7 +5,7 @@ import rehypeKatex from 'rehype-katex';
import supersub from 'remark-supersub';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
-import { Copy, Check, FileText } from 'lucide-react';
+import { Copy, Check } from 'lucide-react';
import { Button, TooltipAnchor, useToastContext } from '@librechat/client';
import { codeNoExecution } from '~/components/Chat/Messages/Content/MarkdownComponents';
import { PromptVariableGfm } from '../editor/Markdown';
@@ -52,14 +52,8 @@ const PromptTextCard = ({ mainText }: PromptTextCardProps) => {
}, [mainText, showToast, localize, isCopied]);
return (
- <div className="flex h-full flex-col rounded-xl border border-border-medium bg-transparent">
- <header className="flex shrink-0 items-center justify-between border-b border-border-medium p-3">
- <div className="flex items-center gap-2">
- <FileText className="h-5 w-5 text-text-secondary" aria-hidden="true" />
- <h3 className="text-base font-semibold text-text-primary">
- {localize('com_ui_prompt_text')}
- </h3>
- </div>
+ <div className="relative flex h-full flex-col rounded-xl border border-border-medium bg-transparent">
+ <div className="absolute right-2 top-2 z-10">
<TooltipAnchor
description={isCopied ? localize('com_ui_copied') : localize('com_ui_copy')}
render={
@@ -81,7 +75,7 @@ const PromptTextCard = ({ mainText }: PromptTextCardProps) => {
</Button>
}
/>
- </header>
+ </div>
<div className="min-h-0 flex-1 overflow-y-auto p-3">
<ReactMarkdown
remarkPlugins={[
diff --git a/client/src/components/Prompts/editor/PromptEditor.tsx b/client/src/components/Prompts/editor/PromptEditor.tsx
index 8445e90e62..805e9f797b 100644
--- a/client/src/components/Prompts/editor/PromptEditor.tsx
+++ b/client/src/components/Prompts/editor/PromptEditor.tsx
@@ -5,7 +5,7 @@ import rehypeKatex from 'rehype-katex';
import supersub from 'remark-supersub';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
-import { EditIcon, FileText, Check } from 'lucide-react';
+import { EditIcon, Check } from 'lucide-react';
import { Controller, useFormContext } from 'react-hook-form';
import { TextareaAutosize, Button, TooltipAnchor } from '@librechat/client';
import type { PluggableList } from 'unified';
@@ -44,14 +44,13 @@ const PromptEditor: React.FC<Props> = ({ name, isEditing, setIsEditing }) => {
return (
<div className="flex max-h-[85vh] flex-col sm:max-h-[85vh]">
<h2 className="sr-only">{localize('com_ui_control_bar')}</h2>
- <header className="flex items-center justify-between rounded-t-xl border border-border-medium bg-transparent px-2 py-1.5">
- <div className="ml-1 flex items-center gap-2">
- <FileText className="size-4 text-text-secondary" aria-hidden="true" />
- <h3 className="text-sm font-semibold text-text-primary">
- {localize('com_ui_prompt_text')}
- </h3>
- </div>
- <div className="flex shrink-0 items-center gap-2">
+ <div
+ className={cn(
+ 'relative w-full flex-1 overflow-auto rounded-xl border border-border-medium p-3 text-left transition-all duration-200 sm:p-4',
+ isEditing ? '' : 'cursor-pointer hover:bg-surface-tertiary',
+ )}
+ >
+ <div className="absolute right-2 top-2 z-10 flex items-center gap-1">
<VariablesDropdown fieldName={name} />
<TooltipAnchor
description={isEditing ? localize('com_ui_save') : localize('com_ui_edit')}
@@ -70,18 +69,11 @@ const PromptEditor: React.FC<Props> = ({ name, isEditing, setIsEditing }) => {
}
/>
</div>
- </header>
- <div
- className={cn(
- 'relative w-full flex-1 overflow-auto rounded-b-xl border border-t-0 border-border-medium p-3 text-left transition-all duration-200 sm:p-4',
- isEditing ? '' : 'cursor-pointer hover:bg-surface-tertiary',
- )}
- >
{!isEditing && (
<button
type="button"
aria-label={localize('com_ui_edit')}
- className="absolute inset-0 z-0 rounded-b-xl focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ className="absolute inset-0 z-0 rounded-xl focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
onClick={() => setIsEditing(true)}
/>
)}
diff --git a/client/src/components/Prompts/sidebar/PromptsAccordion.tsx b/client/src/components/Prompts/sidebar/PromptsAccordion.tsx
index 6239e1562b..de3cedc2a1 100644
--- a/client/src/components/Prompts/sidebar/PromptsAccordion.tsx
+++ b/client/src/components/Prompts/sidebar/PromptsAccordion.tsx
@@ -8,7 +8,7 @@ import FilterPrompts from './FilterPrompts';
export default function PromptsAccordion() {
const { user } = useAuthContext();
return (
- <PromptSidePanel className="space-y-2">
+ <PromptSidePanel className="space-y-2 pt-2">
<FilterPrompts />
{user?.role === SystemRoles.ADMIN && <AdminSettings />}
<AutoSendPrompt />
diff --git a/client/src/components/Sharing/PublicSharingToggle.tsx b/client/src/components/Sharing/PublicSharingToggle.tsx
index 3f68d4fdf6..87896cf8fd 100644
--- a/client/src/components/Sharing/PublicSharingToggle.tsx
+++ b/client/src/components/Sharing/PublicSharingToggle.tsx
@@ -18,11 +18,13 @@ interface PublicSharingToggleProps {
const accessDescriptions: Record<
ResourceType,
- 'com_ui_agent' | 'com_ui_prompt' | 'com_ui_mcp_server'
+ 'com_ui_agent' | 'com_ui_prompt' | 'com_ui_mcp_server' | 'com_ui_skill'
> = {
[ResourceType.AGENT]: 'com_ui_agent',
[ResourceType.PROMPTGROUP]: 'com_ui_prompt',
[ResourceType.MCPSERVER]: 'com_ui_mcp_server',
+ [ResourceType.REMOTE_AGENT]: 'com_ui_agent',
+ [ResourceType.SKILL]: 'com_ui_skill',
};
export default function PublicSharingToggle({
@@ -88,6 +90,17 @@ export default function PublicSharingToggle({
isPublic ? 'max-h-32 opacity-100' : 'max-h-0 opacity-0',
)}
style={{ overflow: isPublic ? 'visible' : 'hidden' }}
+ aria-hidden={!isPublic}
+ ref={(el) => {
+ if (!el) {
+ return;
+ }
+ if (isPublic) {
+ el.removeAttribute('inert');
+ } else {
+ el.setAttribute('inert', '');
+ }
+ }}
>
<div
className={cn(
diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsx
index 5b1a0595c5..2ac6bc7b48 100644
--- a/client/src/components/SidePanel/Agents/AgentConfig.tsx
+++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx
@@ -1,7 +1,13 @@
import React, { useState, useMemo, useCallback } from 'react';
+import { X } from 'lucide-react';
import { useToastContext } from '@librechat/client';
import { Controller, useWatch, useFormContext } from 'react-hook-form';
-import { EModelEndpoint, getEndpointField } from 'librechat-data-provider';
+import {
+ EModelEndpoint,
+ PermissionTypes,
+ Permissions,
+ getEndpointField,
+} from 'librechat-data-provider';
import type { AgentForm, IconComponentTypes } from '~/common';
import {
removeFocusOutlines,
@@ -12,13 +18,14 @@ import {
cn,
} from '~/utils';
import { ToolSelectDialog, MCPToolSelectDialog } from '~/components/Tools';
+import { SkillSelectDialog } from '~/components/Skills/dialogs';
import useAgentCapabilities from '~/hooks/Agents/useAgentCapabilities';
import { useFileMapContext, useAgentPanelContext } from '~/Providers';
import AgentCategorySelector from './AgentCategorySelector';
import Action from '~/components/SidePanel/Builder/Action';
-import { useLocalize, useVisibleTools } from '~/hooks';
+import { useLocalize, useVisibleTools, useHasAccess } from '~/hooks';
import { Panel, isEphemeralAgent } from '~/common';
-import { useGetAgentFiles } from '~/data-provider';
+import { useListSkillsQuery, useGetAgentFiles } from '~/data-provider';
import { icons } from '~/hooks/Endpoint/Icons';
import Instructions from './Instructions';
import AgentAvatar from './AgentAvatar';
@@ -44,6 +51,7 @@ export default function AgentConfig() {
const methods = useFormContext<AgentForm>();
const [showToolDialog, setShowToolDialog] = useState(false);
const [showMCPToolDialog, setShowMCPToolDialog] = useState(false);
+ const [showSkillDialog, setShowSkillDialog] = useState(false);
const {
actions,
setAction,
@@ -63,8 +71,26 @@ export default function AgentConfig() {
const model = useWatch({ control, name: 'model' });
const agent = useWatch({ control, name: 'agent' });
const tools = useWatch({ control, name: 'tools' });
+ const skills = useWatch({ control, name: 'skills' });
const agent_id = useWatch({ control, name: 'id' });
+ const hasSkillsAccess = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.USE,
+ });
+ const { data: skillsData } = useListSkillsQuery({ limit: 100 }, { enabled: false });
+ const skillsMap = useMemo(() => {
+ const map = new Map<string, string>();
+ // Backend list response: `{ skills: TSkillSummary[]; ... }` (renamed
+ // from `.data` in the CRUD PR). This integration is gated behind
+ // `false &&` below so this map is currently unreachable — kept here
+ // so the section compiles for when agent-skills wiring lands.
+ for (const skill of skillsData?.skills ?? []) {
+ map.set(skill._id, skill.name);
+ }
+ return map;
+ }, [skillsData?.skills]);
+
const { data: agentFiles = [] } = useGetAgentFiles(agent_id);
const mergedFileMap = useMemo(() => {
@@ -202,17 +228,19 @@ export default function AgentConfig() {
id="name"
type="text"
placeholder={localize('com_agents_name_placeholder')}
- aria-label="Agent name"
+ aria-label={localize('com_ui_agent_name')}
+ aria-invalid={!!errors.name}
+ aria-describedby={errors.name ? 'agent-name-error' : undefined}
/>
- <div
- className={cn(
- 'mt-1 w-56 text-sm text-red-500',
- errors.name ? 'visible h-auto' : 'invisible h-0',
- )}
- role="alert"
- >
- {errors.name ? errors.name.message : ' '}
- </div>
+ {errors.name && (
+ <div
+ id="agent-name-error"
+ className="mt-1 w-56 text-sm text-red-500"
+ role="alert"
+ >
+ {errors.name.message}
+ </div>
+ )}
</>
)}
/>
@@ -243,7 +271,7 @@ export default function AgentConfig() {
id="description"
type="text"
placeholder={localize('com_agents_description_placeholder')}
- aria-label="Agent description"
+ aria-label={localize('com_ui_agent_description')}
/>
)}
/>
@@ -266,8 +294,6 @@ export default function AgentConfig() {
type="button"
onClick={() => setActivePanel(Panel.model)}
className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"
- aria-haspopup="true"
- aria-expanded="false"
>
<div className="flex w-full items-center gap-2">
{Icon && (
@@ -314,6 +340,59 @@ export default function AgentConfig() {
/>
)}
+ {/* WIP: Skills — remove `false &&` to re-enable */}
+ {false && hasSkillsAccess && (
+ <div className="mb-4">
+ <label className="text-token-text-primary mb-2 block text-sm font-medium">
+ {localize('com_ui_skills')}
+ </label>
+ <div>
+ <div className="mb-1">
+ {(skills ?? []).map((skillId) => {
+ const skillName = skillsMap.get(skillId);
+ if (!skillName) {
+ return null;
+ }
+ return (
+ <div
+ key={skillId}
+ className="mb-1 flex items-center justify-between rounded-md border border-border-light px-3 py-2 text-sm"
+ >
+ <span className="truncate text-text-primary">{skillName}</span>
+ <button
+ type="button"
+ onClick={() => {
+ const current: string[] = methods.getValues('skills') ?? [];
+ methods.setValue(
+ 'skills',
+ current.filter((id) => id !== skillId),
+ );
+ }}
+ className="ml-2 flex-shrink-0 text-text-secondary transition-colors hover:text-text-primary"
+ aria-label={localize('com_ui_remove_skill_var', { 0: skillName })}
+ >
+ <X className="h-4 w-4" aria-hidden="true" />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ <div className="mt-2">
+ <button
+ type="button"
+ onClick={() => setShowSkillDialog(true)}
+ className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"
+ aria-haspopup="dialog"
+ >
+ <div className="flex w-full items-center justify-center gap-2">
+ {localize('com_ui_add_skills')}
+ </div>
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
{/* Agent Tools & Actions */}
<div className="mb-4">
<label className={labelClass}>
@@ -425,7 +504,7 @@ export default function AgentConfig() {
id="support-contact-name"
type="text"
placeholder={localize('com_ui_support_contact_name_placeholder')}
- aria-label="Support contact name"
+ aria-label={localize('com_ui_support_contact_name')}
aria-invalid={error ? 'true' : 'false'}
aria-describedby={error ? 'support-contact-name-error' : undefined}
/>
@@ -467,7 +546,7 @@ export default function AgentConfig() {
id="support-contact-email"
type="email"
placeholder={localize('com_ui_support_contact_email_placeholder')}
- aria-label="Support contact email"
+ aria-label={localize('com_ui_support_contact_email')}
aria-invalid={error ? 'true' : 'false'}
aria-describedby={error ? 'support-contact-email-error' : undefined}
/>
@@ -502,6 +581,10 @@ export default function AgentConfig() {
endpoint={EModelEndpoint.agents}
/>
)}
+ {/* WIP: Skills — remove `false &&` to re-enable */}
+ {false && hasSkillsAccess && (
+ <SkillSelectDialog isOpen={showSkillDialog} setIsOpen={setShowSkillDialog} />
+ )}
</>
);
}
diff --git a/client/src/components/SidePanel/Agents/AgentPanel.tsx b/client/src/components/SidePanel/Agents/AgentPanel.tsx
index 7b985eff55..b258c1ad19 100644
--- a/client/src/components/SidePanel/Agents/AgentPanel.tsx
+++ b/client/src/components/SidePanel/Agents/AgentPanel.tsx
@@ -480,7 +480,7 @@ export default function AgentPanel() {
<FormProvider {...methods}>
<form
onSubmit={handleSubmit(onSubmit)}
- className="scrollbar-gutter-stable flex flex-1 flex-col px-3 pb-3"
+ className="scrollbar-gutter-stable flex flex-1 flex-col px-3 pb-3 pt-2"
aria-label="Agent configuration form"
>
<div className="flex-1">
diff --git a/client/src/components/SidePanel/Bookmarks/BookmarkPanel.tsx b/client/src/components/SidePanel/Bookmarks/BookmarkPanel.tsx
index 342886810a..3e3947bdf6 100644
--- a/client/src/components/SidePanel/Bookmarks/BookmarkPanel.tsx
+++ b/client/src/components/SidePanel/Bookmarks/BookmarkPanel.tsx
@@ -6,7 +6,7 @@ const BookmarkPanel = () => {
const { data } = useConversationTagsQuery();
return (
- <div className="h-auto max-w-full overflow-x-visible">
+ <div className="h-auto max-w-full overflow-x-visible pt-2">
<BookmarkContext.Provider value={{ bookmarks: data || [] }}>
<BookmarkTable />
</BookmarkContext.Provider>
diff --git a/client/src/components/SidePanel/Builder/AssistantPanel.tsx b/client/src/components/SidePanel/Builder/AssistantPanel.tsx
index 588f55c92f..25e850323f 100644
--- a/client/src/components/SidePanel/Builder/AssistantPanel.tsx
+++ b/client/src/components/SidePanel/Builder/AssistantPanel.tsx
@@ -215,7 +215,7 @@ export default function AssistantPanel({
<FormProvider {...methods}>
<form
onSubmit={handleSubmit(onSubmit)}
- className="h-auto w-full flex-shrink-0 overflow-x-hidden"
+ className="h-auto w-full flex-shrink-0 overflow-x-hidden pt-2"
>
<div className="flex w-full flex-wrap">
<Controller
diff --git a/client/src/components/SidePanel/Files/Panel.tsx b/client/src/components/SidePanel/Files/Panel.tsx
index 530be3fe4d..f3b2dbfd2c 100644
--- a/client/src/components/SidePanel/Files/Panel.tsx
+++ b/client/src/components/SidePanel/Files/Panel.tsx
@@ -7,7 +7,7 @@ export default function FilesPanel() {
const { data: files = [] } = useGetFiles<TFile[]>();
return (
- <div className="h-auto w-full px-3 pb-3">
+ <div className="h-auto w-full px-3 pb-3 pt-2">
<DataTable columns={columns} data={files} />
</div>
);
diff --git a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
index 3dd5a70814..80cf8f4b9e 100644
--- a/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
+++ b/client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx
@@ -36,7 +36,7 @@ export default function MCPBuilderPanel() {
}, [availableMCPServers, searchQuery]);
return (
- <div className="flex h-auto w-full flex-col px-3 pb-3">
+ <div className="flex h-auto w-full flex-col px-3 pb-3 pt-2">
<div role="region" aria-label={localize('com_ui_mcp_servers')} className="space-y-2">
{/* Toolbar: Search + Add Button */}
<div className="flex items-center gap-2">
diff --git a/client/src/components/SidePanel/Memories/MemoryPanel.tsx b/client/src/components/SidePanel/Memories/MemoryPanel.tsx
index e25228fd3f..0b9c932547 100644
--- a/client/src/components/SidePanel/Memories/MemoryPanel.tsx
+++ b/client/src/components/SidePanel/Memories/MemoryPanel.tsx
@@ -121,7 +121,7 @@ export default function MemoryPanel() {
const totalPages = Math.ceil(filteredMemories.length / pageSize);
return (
- <div className="flex h-auto w-full flex-col px-3 pb-3">
+ <div className="flex h-auto w-full flex-col px-3 pb-3 pt-2">
<div role="region" aria-label={localize('com_ui_memories')} className="space-y-2">
{/* Header: Filter + Create Button */}
<div className="flex items-center gap-2">
diff --git a/client/src/components/SidePanel/Nav.tsx b/client/src/components/SidePanel/Nav.tsx
index 903b32f49b..33e8b8345d 100644
--- a/client/src/components/SidePanel/Nav.tsx
+++ b/client/src/components/SidePanel/Nav.tsx
@@ -5,7 +5,7 @@ export default function Nav({ links }: { links: NavLink[] }) {
const { active } = useActivePanel();
const effectiveActive = resolveActivePanel(active, links);
return (
- <div className="flex h-full min-h-0 flex-col overflow-y-auto overflow-x-hidden pt-2 text-text-primary">
+ <div className="flex h-full min-h-0 flex-col overflow-y-auto overflow-x-hidden text-text-primary">
{links.map((link) =>
link.id === effectiveActive && link.Component ? <link.Component key={link.id} /> : null,
)}
diff --git a/client/src/components/Skills/buttons/AdminSettings.tsx b/client/src/components/Skills/buttons/AdminSettings.tsx
new file mode 100644
index 0000000000..de8b5f766a
--- /dev/null
+++ b/client/src/components/Skills/buttons/AdminSettings.tsx
@@ -0,0 +1,39 @@
+import { useToastContext } from '@librechat/client';
+import { Permissions, PermissionTypes } from 'librechat-data-provider';
+import type { PermissionConfig } from '~/components/ui';
+import { useUpdateSkillPermissionsMutation } from '~/data-provider';
+import { AdminSettingsDialog } from '~/components/ui';
+import { useLocalize } from '~/hooks';
+
+const permissions: PermissionConfig[] = [
+ { permission: Permissions.USE, labelKey: 'com_ui_skills_allow_use' },
+ { permission: Permissions.CREATE, labelKey: 'com_ui_skills_allow_create' },
+ { permission: Permissions.SHARE, labelKey: 'com_ui_skills_allow_share' },
+ { permission: Permissions.SHARE_PUBLIC, labelKey: 'com_ui_skills_allow_share_public' },
+];
+
+const AdminSettings = () => {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+
+ const mutation = useUpdateSkillPermissionsMutation({
+ onSuccess: () => {
+ showToast({ status: 'success', message: localize('com_ui_saved') });
+ },
+ onError: () => {
+ showToast({ status: 'error', message: localize('com_ui_error_save_admin_settings') });
+ },
+ });
+
+ return (
+ <AdminSettingsDialog
+ permissionType={PermissionTypes.SKILLS}
+ sectionKey="com_ui_skills"
+ permissions={permissions}
+ menuId="skill-role-dropdown"
+ mutation={mutation}
+ />
+ );
+};
+
+export default AdminSettings;
diff --git a/client/src/components/Skills/buttons/CreateSkillMenu.tsx b/client/src/components/Skills/buttons/CreateSkillMenu.tsx
new file mode 100644
index 0000000000..a61dd7fd92
--- /dev/null
+++ b/client/src/components/Skills/buttons/CreateSkillMenu.tsx
@@ -0,0 +1,55 @@
+import { useCallback, useMemo, useState } from 'react';
+import { Plus, PenLine, Upload } from 'lucide-react';
+import { Dropdown } from '@librechat/client';
+import type { Option } from '~/common';
+import { CreateSkillDialog, UploadSkillDialog } from '../dialogs';
+import { useLocalize } from '~/hooks';
+
+const WRITE = 'write';
+const UPLOAD_SKILL = 'upload';
+
+export default function CreateSkillMenu() {
+ const localize = useLocalize();
+ const [writeOpen, setWriteOpen] = useState(false);
+ const [uploadOpen, setUploadOpen] = useState(false);
+
+ const options = useMemo<Option[]>(
+ () => [
+ {
+ value: WRITE,
+ label: localize('com_ui_skill_write_instructions'),
+ icon: <PenLine className="size-4 text-text-primary" />,
+ },
+ {
+ value: UPLOAD_SKILL,
+ label: localize('com_ui_skill_upload'),
+ icon: <Upload className="size-4 text-text-primary" />,
+ },
+ ],
+ [localize],
+ );
+
+ const handleSelect = useCallback((value: string) => {
+ if (value === WRITE) {
+ setWriteOpen(true);
+ } else if (value === UPLOAD_SKILL) {
+ setUploadOpen(true);
+ }
+ }, []);
+
+ return (
+ <>
+ <Dropdown
+ value=""
+ onChange={handleSelect}
+ options={options}
+ className="shrink-0 rounded-lg bg-transparent"
+ icon={<Plus className="size-5" />}
+ ariaLabel={localize('com_ui_create_skill')}
+ iconOnly
+ />
+ <CreateSkillDialog isOpen={writeOpen} setIsOpen={setWriteOpen} />
+ <UploadSkillDialog isOpen={uploadOpen} setIsOpen={setUploadOpen} />
+ </>
+ );
+}
diff --git a/client/src/components/Skills/buttons/ShareSkill.tsx b/client/src/components/Skills/buttons/ShareSkill.tsx
new file mode 100644
index 0000000000..2121de4824
--- /dev/null
+++ b/client/src/components/Skills/buttons/ShareSkill.tsx
@@ -0,0 +1,58 @@
+import { memo } from 'react';
+import { Share2Icon } from 'lucide-react';
+import { Button, TooltipAnchor } from '@librechat/client';
+import { Permissions, ResourceType, PermissionTypes } from 'librechat-data-provider';
+import type { TSkill } from 'librechat-data-provider';
+import { useHasAccess, useLocalize, useSkillPermissions } from '~/hooks';
+import { GenericGrantAccessDialog } from '~/components/Sharing';
+
+// Memoed because it renders inside `SkillForm`'s header, which re-renders on
+// every keystroke via react-hook-form state updates. The `skill` prop stays
+// referentially stable between renders as long as the server-side version
+// hasn't changed, so the memo skips that work.
+
+interface ShareSkillProps {
+ skill: TSkill;
+ disabled?: boolean;
+}
+
+function ShareSkill({ skill, disabled }: ShareSkillProps) {
+ const localize = useLocalize();
+ const permissions = useSkillPermissions(skill);
+
+ const hasAccessToShareSkills = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.SHARE,
+ });
+
+ if (permissions.isLoading || !hasAccessToShareSkills || !permissions.canShare) {
+ return null;
+ }
+
+ return (
+ <GenericGrantAccessDialog
+ resourceDbId={skill._id}
+ resourceName={skill.name}
+ resourceType={ResourceType.SKILL}
+ disabled={disabled}
+ >
+ <TooltipAnchor
+ description={localize('com_ui_share')}
+ side="bottom"
+ render={
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-9 border-border-medium"
+ aria-label={localize('com_ui_share')}
+ disabled={disabled}
+ >
+ <Share2Icon className="size-5" aria-hidden="true" />
+ </Button>
+ }
+ />
+ </GenericGrantAccessDialog>
+ );
+}
+
+export default memo(ShareSkill);
diff --git a/client/src/components/Skills/buttons/index.ts b/client/src/components/Skills/buttons/index.ts
new file mode 100644
index 0000000000..2ce3a1af96
--- /dev/null
+++ b/client/src/components/Skills/buttons/index.ts
@@ -0,0 +1,3 @@
+export { default as AdminSettings } from './AdminSettings';
+export { default as ShareSkill } from './ShareSkill';
+export { default as CreateSkillMenu } from './CreateSkillMenu';
diff --git a/client/src/components/Skills/dialogs/CreateSkillDialog.tsx b/client/src/components/Skills/dialogs/CreateSkillDialog.tsx
new file mode 100644
index 0000000000..ed8041423d
--- /dev/null
+++ b/client/src/components/Skills/dialogs/CreateSkillDialog.tsx
@@ -0,0 +1,190 @@
+import { useForm } from 'react-hook-form';
+import { useNavigate } from 'react-router-dom';
+import {
+ Button,
+ OGDialog,
+ OGDialogContent,
+ TextareaAutosize,
+ useToastContext,
+} from '@librechat/client';
+import {
+ SKILL_NAME_PATTERN,
+ SKILL_NAME_MAX_LENGTH,
+ SKILL_DESCRIPTION_MAX_LENGTH,
+} from 'librechat-data-provider';
+import { useCreateSkillMutation } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface CreateSkillDialogProps {
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+ defaultName?: string;
+ defaultDescription?: string;
+ defaultBody?: string;
+}
+
+interface FormValues {
+ name: string;
+ description: string;
+ body: string;
+}
+
+/**
+ * Minimal create-skill dialog matching Claude.ai's "Write skill instructions"
+ * modal: name, description, instructions. No category, no invocation mode.
+ */
+export default function CreateSkillDialog({
+ isOpen,
+ setIsOpen,
+ defaultName = '',
+ defaultDescription = '',
+ defaultBody = '',
+}: CreateSkillDialogProps) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { showToast } = useToastContext();
+
+ const {
+ register,
+ handleSubmit,
+ reset,
+ formState: { isValid, isSubmitting, errors },
+ } = useForm<FormValues>({
+ defaultValues: { name: defaultName, description: defaultDescription, body: defaultBody },
+ mode: 'onChange',
+ });
+
+ const createSkill = useCreateSkillMutation({
+ onSuccess: (skill) => {
+ showToast({ status: 'success', message: localize('com_ui_skill_created') });
+ setIsOpen(false);
+ reset();
+ navigate(`/skills/${skill._id}`);
+ },
+ onError: (error: unknown) => {
+ const message =
+ (error as { response?: { data?: { message?: string } } })?.response?.data?.message ??
+ localize('com_ui_skill_create_error');
+ showToast({ status: 'error', message });
+ },
+ });
+
+ const onSubmit = (data: FormValues) => {
+ if (createSkill.isLoading) {
+ return;
+ }
+ createSkill.mutate({
+ name: data.name.trim(),
+ description: data.description.trim(),
+ body: data.body,
+ });
+ };
+
+ const handleClose = () => {
+ setIsOpen(false);
+ reset();
+ };
+
+ const submitDisabled = !isValid || isSubmitting || createSkill.isLoading;
+
+ return (
+ <OGDialog open={isOpen} onOpenChange={setIsOpen}>
+ <OGDialogContent className="w-11/12 max-w-5xl overflow-hidden">
+ <form
+ onSubmit={handleSubmit(onSubmit)}
+ className="flex max-h-[80vh] min-w-0 flex-col gap-3 overflow-hidden p-1 sm:gap-4 sm:p-2"
+ >
+ <h2 className="text-lg font-bold text-text-primary">
+ {localize('com_ui_skill_write_instructions')}
+ </h2>
+
+ {/* Skill name */}
+ <div className="flex flex-col gap-1.5">
+ <label htmlFor="create-skill-name" className="text-sm font-medium text-text-secondary">
+ {localize('com_ui_name')}
+ </label>
+ <input
+ id="create-skill-name"
+ placeholder={localize('com_ui_skill_name_placeholder')}
+ aria-invalid={errors.name ? 'true' : 'false'}
+ autoComplete="off"
+ className="flex h-10 w-full rounded-xl border border-border-medium bg-transparent px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:cursor-not-allowed disabled:opacity-50"
+ {...register('name', {
+ required: localize('com_ui_skill_name_required'),
+ pattern: {
+ value: SKILL_NAME_PATTERN,
+ message: localize('com_ui_skill_name_invalid'),
+ },
+ maxLength: {
+ value: SKILL_NAME_MAX_LENGTH,
+ message: localize('com_ui_skill_name_too_long', {
+ 0: String(SKILL_NAME_MAX_LENGTH),
+ }),
+ },
+ })}
+ />
+ {errors.name && <p className="text-xs text-red-500">{errors.name.message}</p>}
+ </div>
+
+ {/* Description */}
+ <div className="flex flex-col gap-1.5">
+ <label
+ htmlFor="create-skill-description"
+ className="text-sm font-medium text-text-secondary"
+ >
+ {localize('com_ui_description')}
+ </label>
+ <TextareaAutosize
+ id="create-skill-description"
+ minRows={2}
+ maxRows={4}
+ placeholder={localize('com_ui_skill_description_placeholder')}
+ aria-label={localize('com_ui_description')}
+ className="w-full resize-none rounded-xl border border-border-medium bg-transparent px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ {...register('description', {
+ required: localize('com_ui_skill_description_required'),
+ maxLength: {
+ value: SKILL_DESCRIPTION_MAX_LENGTH,
+ message: localize('com_ui_skill_description_too_long', {
+ 0: String(SKILL_DESCRIPTION_MAX_LENGTH),
+ }),
+ },
+ })}
+ />
+ </div>
+
+ {/* Instructions (body) */}
+ <div className="flex flex-col gap-1.5">
+ <label htmlFor="create-skill-body" className="text-sm font-medium text-text-secondary">
+ {localize('com_ui_skill_instructions')}
+ </label>
+ <TextareaAutosize
+ id="create-skill-body"
+ minRows={6}
+ maxRows={12}
+ placeholder={localize('com_ui_skill_instructions_placeholder')}
+ aria-label={localize('com_ui_skill_instructions')}
+ className="w-full resize-none rounded-xl border border-border-medium bg-transparent px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ {...register('body')}
+ />
+ </div>
+
+ {/* Actions */}
+ <div className="flex items-center justify-end gap-2 pt-2">
+ <Button type="button" variant="outline" onClick={handleClose}>
+ {localize('com_ui_cancel')}
+ </Button>
+ <Button
+ type="submit"
+ disabled={submitDisabled}
+ className={cn(submitDisabled && 'opacity-50')}
+ >
+ {localize('com_ui_create')}
+ </Button>
+ </div>
+ </form>
+ </OGDialogContent>
+ </OGDialog>
+ );
+}
diff --git a/client/src/components/Skills/dialogs/DeleteSkill.tsx b/client/src/components/Skills/dialogs/DeleteSkill.tsx
new file mode 100644
index 0000000000..2734ac1d54
--- /dev/null
+++ b/client/src/components/Skills/dialogs/DeleteSkill.tsx
@@ -0,0 +1,93 @@
+import { memo } from 'react';
+import { Trash2 } from 'lucide-react';
+import {
+ Button,
+ OGDialog,
+ TooltipAnchor,
+ OGDialogTrigger,
+ OGDialogTemplate,
+ useToastContext,
+} from '@librechat/client';
+import { useDeleteSkillMutation } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+
+// Memoed because it renders inside `SkillForm`'s header, which re-renders on
+// every keystroke via react-hook-form state updates. Props (`skillId`,
+// `skillName`) are stable strings, so the memo skips all of those re-renders.
+
+interface DeleteSkillProps {
+ skillId: string;
+ skillName: string;
+ disabled?: boolean;
+ onDelete?: () => void;
+}
+
+function DeleteSkill({ skillId, skillName, disabled, onDelete }: DeleteSkillProps) {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const deleteSkill = useDeleteSkillMutation({
+ onSuccess: () => {
+ showToast({ status: 'success', message: localize('com_ui_skill_deleted') });
+ onDelete?.();
+ },
+ onError: () => {
+ showToast({ status: 'error', message: localize('com_ui_skill_delete_error') });
+ },
+ });
+
+ /**
+ * No `useCallback` here — `deleteSkill` is a new object on every render
+ * (React Query mutation results are unstable references), so the dependency
+ * array would invalidate every render and the memoized callback would be
+ * recreated anyway, adding overhead for no benefit.
+ */
+ const handleDelete = () => {
+ if (deleteSkill.isLoading) {
+ return;
+ }
+ deleteSkill.mutate({ id: skillId });
+ };
+
+ const triggerDisabled = disabled || deleteSkill.isLoading;
+
+ return (
+ <OGDialog>
+ <OGDialogTrigger asChild>
+ <TooltipAnchor
+ description={localize('com_ui_delete')}
+ side="bottom"
+ render={
+ <Button
+ variant="destructive"
+ size="icon"
+ className="size-9"
+ aria-label={localize('com_ui_delete')}
+ disabled={triggerDisabled}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Trash2 className="size-5" aria-hidden="true" />
+ </Button>
+ }
+ />
+ </OGDialogTrigger>
+ <OGDialogTemplate
+ showCloseButton={false}
+ title={localize('com_ui_delete')}
+ className="max-w-[450px]"
+ main={
+ <p className="text-left text-sm text-text-primary">
+ {localize('com_ui_skill_delete_confirm', { 0: skillName })}
+ </p>
+ }
+ selection={{
+ selectHandler: handleDelete,
+ selectClasses:
+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-white',
+ selectText: localize('com_ui_delete'),
+ }}
+ />
+ </OGDialog>
+ );
+}
+
+export default memo(DeleteSkill);
diff --git a/client/src/components/Skills/dialogs/SkillSelectDialog.tsx b/client/src/components/Skills/dialogs/SkillSelectDialog.tsx
new file mode 100644
index 0000000000..5fd4fa3f42
--- /dev/null
+++ b/client/src/components/Skills/dialogs/SkillSelectDialog.tsx
@@ -0,0 +1,367 @@
+import { useState, useMemo, useCallback } from 'react';
+import { Search, Check, EarthIcon, User, Plus, Star, ListFilter, X } from 'lucide-react';
+import { useFormContext, useWatch } from 'react-hook-form';
+import { useNavigate } from 'react-router-dom';
+import { OGDialog, OGDialogContent } from '@librechat/client';
+import { PermissionTypes, Permissions, SystemCategories } from 'librechat-data-provider';
+import type { TSkillSummary } from 'librechat-data-provider';
+import type { AgentForm } from '~/common';
+import {
+ useLocalize,
+ useAuthContext,
+ useCategories,
+ useHasAccess,
+ useSkillFavorites,
+} from '~/hooks';
+import { useListSkillsQuery } from '~/data-provider';
+import { CategoryIcon } from '~/components/Prompts';
+import { cn } from '~/utils';
+
+interface SkillSelectDialogProps {
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+interface SkillCategory {
+ value: string;
+ label: string;
+ icon?: React.ReactNode;
+}
+
+const SKILL_MY = '__skill_filter_my__';
+const SKILL_FAVORITES = '__skill_filter_favorites__';
+const LIST_QUERY_OPTIONS = { limit: 100 } as const;
+
+interface SidebarItemProps {
+ value: string;
+ label: string;
+ icon: React.ReactNode;
+ active: boolean;
+ onSelect: (value: string) => void;
+}
+
+function SidebarItem({ value, label, icon, active, onSelect }: SidebarItemProps) {
+ return (
+ <button
+ type="button"
+ onClick={() => onSelect(value)}
+ className={cn(
+ 'flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors',
+ active
+ ? 'bg-surface-active text-text-primary'
+ : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',
+ )}
+ aria-pressed={active}
+ >
+ <span className="flex size-4 shrink-0 items-center justify-center">{icon}</span>
+ <span className="truncate">{label}</span>
+ </button>
+ );
+}
+
+interface SkillCardProps {
+ skill: TSkillSummary;
+ selected: boolean;
+ isFavorite: boolean;
+ isShared: boolean;
+ isPublic: boolean;
+ onToggle: (skillId: string) => void;
+ onToggleFavorite: (skillId: string) => void;
+ localize: ReturnType<typeof useLocalize>;
+}
+
+function SkillCard({
+ skill,
+ selected,
+ isFavorite,
+ isShared,
+ isPublic,
+ onToggle,
+ onToggleFavorite,
+ localize,
+}: SkillCardProps) {
+ return (
+ <button
+ type="button"
+ onClick={() => onToggle(skill._id)}
+ onMouseDown={(e) => e.preventDefault()}
+ aria-pressed={selected}
+ className={cn(
+ 'group relative flex h-32 cursor-pointer flex-col rounded-xl border p-3.5 text-left transition-all duration-200',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',
+ selected
+ ? 'border-green-500/70 bg-green-500/[0.06]'
+ : 'border-border-light hover:border-border-medium hover:bg-surface-tertiary',
+ )}
+ >
+ <div className="flex w-full items-start gap-2">
+ <p className="min-w-0 flex-1 truncate pr-1 text-sm font-semibold text-text-primary">
+ {skill.name}
+ </p>
+ <span
+ role="button"
+ tabIndex={0}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleFavorite(skill._id);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ e.stopPropagation();
+ onToggleFavorite(skill._id);
+ }
+ }}
+ className={cn(
+ 'flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg transition-colors',
+ isFavorite
+ ? 'text-yellow-500 hover:bg-yellow-500/10'
+ : 'text-text-tertiary opacity-0 hover:bg-surface-hover hover:text-text-primary group-hover:opacity-100 group-focus-visible:opacity-100',
+ )}
+ aria-label={isFavorite ? localize('com_ui_unfavorite') : localize('com_ui_favorite')}
+ aria-pressed={isFavorite}
+ >
+ <Star className={cn('size-4', isFavorite && 'fill-current')} aria-hidden="true" />
+ </span>
+ </div>
+ {skill.description && (
+ <p className="mt-1 line-clamp-2 text-xs leading-relaxed text-text-secondary">
+ {skill.description}
+ </p>
+ )}
+ <div className="mt-auto flex w-full items-center gap-1.5 pt-2">
+ {skill.category && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2 py-0.5 text-[10px] text-text-tertiary">
+ <CategoryIcon category={skill.category} className="size-2.5" />
+ {skill.category}
+ </span>
+ )}
+ {isShared && (
+ <span
+ className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-1.5 py-0.5 text-text-tertiary"
+ title={skill.authorName}
+ aria-label={skill.authorName}
+ >
+ <User className="size-2.5" aria-hidden="true" />
+ </span>
+ )}
+ {isPublic && (
+ <span
+ className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-1.5 py-0.5 text-text-tertiary"
+ title={localize('com_ui_sr_public_skill')}
+ aria-label={localize('com_ui_sr_public_skill')}
+ >
+ <EarthIcon className="size-2.5" aria-hidden="true" />
+ </span>
+ )}
+ <span
+ className={cn(
+ 'ml-auto flex size-5 shrink-0 items-center justify-center rounded-full transition-all duration-200',
+ selected ? 'scale-100 bg-green-500 text-white opacity-100' : 'scale-75 opacity-0',
+ )}
+ aria-hidden="true"
+ >
+ <Check className="size-3" strokeWidth={3} />
+ </span>
+ </div>
+ </button>
+ );
+}
+
+function SkillSelectDialog({ isOpen, setIsOpen }: SkillSelectDialogProps) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { user } = useAuthContext();
+ const { control, setValue } = useFormContext<AgentForm>();
+ const [searchValue, setSearchValue] = useState('');
+ const [activeFilter, setActiveFilter] = useState<string>(SystemCategories.ALL);
+ const { isFavorite: isFavoriteSkill, toggle: toggleFavoriteSkill } = useSkillFavorites();
+
+ const hasCreateAccess = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.CREATE,
+ });
+
+ const { data: skillsData } = useListSkillsQuery(LIST_QUERY_OPTIONS);
+ const { categories } = useCategories({ className: 'size-4', hasAccess: true });
+ const typedCategories = categories as SkillCategory[] | undefined;
+
+ const allSkills = useMemo(() => skillsData?.skills ?? [], [skillsData?.skills]);
+
+ const watchedSkills = useWatch({ control, name: 'skills' });
+ const selectedSet = useMemo(
+ () => new Set<string>(Array.isArray(watchedSkills) ? watchedSkills : []),
+ [watchedSkills],
+ );
+
+ const handleToggleSkill = useCallback(
+ (skillId: string) => {
+ const current = Array.isArray(watchedSkills) ? watchedSkills : [];
+ if (current.includes(skillId)) {
+ setValue(
+ 'skills',
+ current.filter((id) => id !== skillId),
+ { shouldDirty: true },
+ );
+ } else {
+ setValue('skills', [...current, skillId], { shouldDirty: true });
+ }
+ },
+ [watchedSkills, setValue],
+ );
+
+ const handleClose = useCallback(() => {
+ setIsOpen(false);
+ setSearchValue('');
+ setActiveFilter(SystemCategories.ALL);
+ }, [setIsOpen]);
+
+ const handleCreate = useCallback(() => {
+ setIsOpen(false);
+ navigate('/skills/new');
+ }, [navigate, setIsOpen]);
+
+ const visibleSkills = useMemo(() => {
+ const term = searchValue.toLowerCase();
+ const result: TSkillSummary[] = [];
+ for (const skill of allSkills) {
+ if (activeFilter === SKILL_MY) {
+ if (skill.author !== user?.id) continue;
+ } else if (activeFilter === SKILL_FAVORITES) {
+ if (!isFavoriteSkill(skill._id)) continue;
+ } else if (activeFilter === SystemCategories.NO_CATEGORY) {
+ if (skill.category) continue;
+ } else if (activeFilter !== SystemCategories.ALL) {
+ if (skill.category !== activeFilter) continue;
+ }
+ if (term && !skill.name.toLowerCase().includes(term)) continue;
+ result.push(skill);
+ }
+ return result;
+ }, [allSkills, activeFilter, searchValue, user?.id, isFavoriteSkill]);
+
+ return (
+ <OGDialog open={isOpen} onOpenChange={setIsOpen}>
+ <OGDialogContent
+ className="w-11/12 max-w-[1024px] overflow-hidden rounded-2xl border-border-medium p-0 shadow-xl md:max-h-[85vh]"
+ showCloseButton={false}
+ >
+ <div className="flex h-[80vh] max-h-[720px]">
+ <aside className="flex w-56 shrink-0 flex-col gap-1 border-r border-border-light bg-surface-primary-alt p-3">
+ <h2 className="px-2.5 pb-1.5 pt-1 text-base font-bold text-text-primary">
+ {localize('com_ui_add_skills')}
+ </h2>
+ {hasCreateAccess && (
+ <button
+ type="button"
+ onClick={handleCreate}
+ className="mb-1 flex w-full items-center justify-center gap-2 rounded-lg border border-border-light bg-transparent px-2.5 py-1.5 text-center text-sm text-text-primary transition-colors hover:border-border-medium hover:bg-surface-hover"
+ aria-label={localize('com_ui_create_skill')}
+ >
+ <Plus className="size-4 shrink-0" aria-hidden="true" />
+ <span className="truncate">{localize('com_ui_create_skill')}</span>
+ </button>
+ )}
+ <SidebarItem
+ value={SKILL_MY}
+ label={localize('com_ui_my_skills')}
+ icon={<User className="size-4 text-text-secondary" />}
+ active={activeFilter === SKILL_MY}
+ onSelect={setActiveFilter}
+ />
+ <SidebarItem
+ value={SKILL_FAVORITES}
+ label={localize('com_ui_favorites')}
+ icon={<Star className="size-4 text-text-secondary" />}
+ active={activeFilter === SKILL_FAVORITES}
+ onSelect={setActiveFilter}
+ />
+ <div className="my-2 h-px bg-border-light" />
+ <SidebarItem
+ value={SystemCategories.ALL}
+ label={localize('com_ui_all_proper')}
+ icon={<ListFilter className="size-4 text-text-secondary" />}
+ active={activeFilter === SystemCategories.ALL}
+ onSelect={setActiveFilter}
+ />
+ {typedCategories?.map((category) => {
+ if (!category.value) {
+ return null;
+ }
+ return (
+ <SidebarItem
+ key={category.value}
+ value={category.value}
+ label={category.label}
+ icon={category.icon ?? <ListFilter className="size-4 text-text-secondary" />}
+ active={activeFilter === category.value}
+ onSelect={setActiveFilter}
+ />
+ );
+ })}
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-2 px-6 py-4">
+ <div className="relative flex-1">
+ <Search
+ className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-text-tertiary"
+ aria-hidden="true"
+ />
+ <input
+ type="text"
+ value={searchValue}
+ onChange={(e) => setSearchValue(e.target.value)}
+ placeholder={localize('com_ui_search_skills')}
+ aria-label={localize('com_ui_search_skills')}
+ className="h-10 w-full rounded-xl border border-border-light bg-transparent pl-9 pr-3 text-sm text-text-primary placeholder:text-text-tertiary focus:border-border-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={handleClose}
+ className="flex size-10 shrink-0 items-center justify-center rounded-xl border border-border-light bg-transparent text-text-secondary transition-colors hover:border-border-medium hover:bg-surface-hover hover:text-text-primary"
+ aria-label={localize('com_ui_close')}
+ >
+ <X className="size-4" aria-hidden="true" />
+ </button>
+ </div>
+
+ <div
+ className="flex-1 overflow-y-auto p-4"
+ role="group"
+ aria-label={localize('com_ui_add_skills')}
+ >
+ {visibleSkills.length > 0 ? (
+ <div className="grid grid-cols-2 gap-2">
+ {visibleSkills.map((skill) => (
+ <SkillCard
+ key={skill._id}
+ skill={skill}
+ selected={selectedSet.has(skill._id)}
+ isFavorite={isFavoriteSkill(skill._id)}
+ isShared={skill.author !== user?.id && Boolean(skill.authorName)}
+ isPublic={skill.isPublic === true}
+ onToggle={handleToggleSkill}
+ onToggleFavorite={toggleFavoriteSkill}
+ localize={localize}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="flex flex-col items-center justify-center py-16 text-center">
+ <Search className="size-8 text-text-tertiary opacity-40" aria-hidden="true" />
+ <p className="mt-3 text-sm text-text-secondary">
+ {localize('com_ui_no_skills_found')}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </OGDialogContent>
+ </OGDialog>
+ );
+}
+
+export default SkillSelectDialog;
diff --git a/client/src/components/Skills/dialogs/UploadSkillDialog.tsx b/client/src/components/Skills/dialogs/UploadSkillDialog.tsx
new file mode 100644
index 0000000000..d1d917ae2f
--- /dev/null
+++ b/client/src/components/Skills/dialogs/UploadSkillDialog.tsx
@@ -0,0 +1,128 @@
+import { useRef, useCallback, useState } from 'react';
+import { Upload } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { OGDialog, OGDialogContent, Spinner, useToastContext } from '@librechat/client';
+import { useImportSkillMutation } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface UploadSkillDialogProps {
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDialogProps) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { showToast } = useToastContext();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [isDragging, setIsDragging] = useState(false);
+
+ const importMutation = useImportSkillMutation({
+ onSuccess: (skill) => {
+ showToast({ status: 'success', message: localize('com_ui_skill_created') });
+ setIsOpen(false);
+ navigate(`/skills/${skill._id}`);
+ },
+ onError: (error: unknown) => {
+ const errData = (error as { response?: { data?: { error?: string; message?: string } } })
+ ?.response?.data;
+ const message =
+ errData?.message ?? errData?.error ?? localize('com_ui_create_skill_upload_error');
+ showToast({ status: 'error', message });
+ },
+ });
+
+ const handleFile = useCallback(
+ (file: File) => {
+ if (importMutation.isLoading) {
+ return;
+ }
+ const formData = new FormData();
+ formData.append('file', file, file.name);
+ importMutation.mutate(formData);
+ },
+ [importMutation],
+ );
+
+ const handleFileInput = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (file) {
+ handleFile(file);
+ }
+ event.target.value = '';
+ },
+ [handleFile],
+ );
+
+ const handleDrop = useCallback(
+ (event: React.DragEvent) => {
+ event.preventDefault();
+ setIsDragging(false);
+ const file = event.dataTransfer.files?.[0];
+ if (file) {
+ handleFile(file);
+ }
+ },
+ [handleFile],
+ );
+
+ return (
+ <OGDialog open={isOpen} onOpenChange={setIsOpen}>
+ <OGDialogContent className="w-11/12 max-w-lg overflow-hidden">
+ <div className="flex flex-col gap-6 p-1 sm:p-2">
+ <h2 className="text-lg font-bold text-text-primary">
+ {localize('com_ui_skill_upload_title')}
+ </h2>
+
+ <div className="flex flex-col gap-3">
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setIsDragging(true);
+ }}
+ onDragLeave={() => setIsDragging(false)}
+ onDrop={handleDrop}
+ disabled={importMutation.isLoading}
+ className={cn(
+ 'flex h-[120px] w-full cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-dashed text-sm text-text-secondary transition-colors',
+ isDragging
+ ? 'border-border-heavy bg-surface-hover'
+ : 'border-border-medium hover:bg-surface-hover',
+ importMutation.isLoading && 'cursor-wait opacity-50',
+ )}
+ >
+ {importMutation.isLoading ? (
+ <Spinner className="size-8" />
+ ) : (
+ <Upload className="size-8 text-text-secondary" aria-hidden="true" />
+ )}
+ {localize('com_ui_skill_upload_drag')}
+ </button>
+
+ <div className="flex flex-col gap-3 text-xs text-text-secondary">
+ <div>
+ <p className="font-medium">{localize('com_ui_skill_upload_requirements')}</p>
+ <ul className="mt-1 list-inside list-disc">
+ <li>{localize('com_ui_skill_upload_req_md')}</li>
+ <li>{localize('com_ui_skill_upload_req_zip')}</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".zip,.skill,.md"
+ className="hidden"
+ onChange={handleFileInput}
+ />
+ </div>
+ </OGDialogContent>
+ </OGDialog>
+ );
+}
diff --git a/client/src/components/Skills/dialogs/index.ts b/client/src/components/Skills/dialogs/index.ts
new file mode 100644
index 0000000000..e992915c90
--- /dev/null
+++ b/client/src/components/Skills/dialogs/index.ts
@@ -0,0 +1,4 @@
+export { default as CreateSkillDialog } from './CreateSkillDialog';
+export { default as DeleteSkill } from './DeleteSkill';
+export { default as SkillSelectDialog } from './SkillSelectDialog';
+export { default as UploadSkillDialog } from './UploadSkillDialog';
diff --git a/client/src/components/Skills/display/SkillDetail.tsx b/client/src/components/Skills/display/SkillDetail.tsx
new file mode 100644
index 0000000000..1dab6c4b0a
--- /dev/null
+++ b/client/src/components/Skills/display/SkillDetail.tsx
@@ -0,0 +1,185 @@
+import React, { useState, useMemo } from 'react';
+import { format } from 'date-fns';
+import { Eye, Code, User, Calendar, EarthIcon, ScrollText } from 'lucide-react';
+import { TooltipAnchor } from '@librechat/client';
+import type { TSkill } from 'librechat-data-provider';
+import { useLocalize, useAuthContext, useSkillPermissions } from '~/hooks';
+import SkillMarkdownRenderer from './SkillMarkdownRenderer';
+import { parseFrontmatter } from '../utils';
+import DeleteSkill from '../dialogs/DeleteSkill';
+import { ShareSkill } from '../buttons';
+import { cn } from '~/utils';
+
+interface SkillDetailProps {
+ skill: TSkill;
+ onEdit?: () => void;
+ onDelete?: () => void;
+}
+
+const SKIP_KEYS = new Set(['name', 'description']);
+
+function ViewToggle({
+ viewMode,
+ setViewMode,
+ localize,
+}: {
+ viewMode: 'rendered' | 'source';
+ setViewMode: (mode: 'rendered' | 'source') => void;
+ localize: ReturnType<typeof useLocalize>;
+}) {
+ return (
+ <div
+ role="group"
+ className="inline-flex h-7 rounded-lg bg-surface-tertiary p-0.5 text-sm font-medium"
+ >
+ <button
+ type="button"
+ onClick={() => setViewMode('rendered')}
+ className={cn(
+ 'flex items-center justify-center rounded-md px-1.5 transition-colors',
+ viewMode === 'rendered'
+ ? 'bg-surface-primary text-text-primary shadow-sm'
+ : 'text-text-secondary hover:text-text-primary',
+ )}
+ aria-label={localize('com_ui_skill_view_rendered')}
+ aria-pressed={viewMode === 'rendered'}
+ >
+ <Eye className="size-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setViewMode('source')}
+ className={cn(
+ 'flex items-center justify-center rounded-md px-1.5 transition-colors',
+ viewMode === 'source'
+ ? 'bg-surface-primary text-text-primary shadow-sm'
+ : 'text-text-secondary hover:text-text-primary',
+ )}
+ aria-label={localize('com_ui_skill_view_source')}
+ aria-pressed={viewMode === 'source'}
+ >
+ <Code className="size-4" />
+ </button>
+ </div>
+ );
+}
+
+export default function SkillDetail({ skill, onEdit, onDelete }: SkillDetailProps) {
+ const localize = useLocalize();
+ const { user } = useAuthContext();
+ const permissions = useSkillPermissions(skill);
+ const [viewMode, setViewMode] = useState<'rendered' | 'source'>('rendered');
+
+ const isPublic = skill.isPublic === true;
+ const isShared = skill.author !== user?.id && Boolean(skill.authorName);
+ const addedBy = isShared ? skill.authorName : localize('com_ui_you');
+ const updatedDate = skill.updatedAt
+ ? format(new Date(skill.updatedAt), 'MMM d, yyyy')
+ : undefined;
+
+ const { fields: frontmatterFields, body: cleanBody } = useMemo(
+ () => parseFrontmatter(skill.body ?? '', SKIP_KEYS),
+ [skill.body],
+ );
+
+ return (
+ <article
+ className="flex h-full min-w-0 flex-col gap-2 overflow-y-auto px-5 pb-5"
+ aria-label={skill.name}
+ >
+ {/* Header row */}
+ <div className="flex flex-col gap-3 pb-1 sm:flex-row sm:items-center sm:gap-4">
+ <div className="min-w-0 flex-1 overflow-hidden">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-surface-secondary">
+ <ScrollText className="size-6 text-text-secondary" aria-hidden="true" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2 className="truncate text-xl font-bold text-text-primary" title={skill.name}>
+ {skill.name}
+ </h2>
+ {isPublic && (
+ <TooltipAnchor
+ description={localize('com_ui_skill_sr_public')}
+ side="top"
+ render={
+ <EarthIcon
+ className="size-5 shrink-0 text-green-400"
+ aria-label={localize('com_ui_skill_sr_public')}
+ />
+ }
+ />
+ )}
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-3 text-xs text-text-secondary">
+ <span className="flex items-center gap-1">
+ <User className="size-3" aria-hidden="true" />
+ {addedBy}
+ </span>
+ {updatedDate && (
+ <span className="flex items-center gap-1">
+ <Calendar className="size-3" aria-hidden="true" />
+ {updatedDate}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Actions */}
+ <div className="flex shrink-0 items-center gap-2">
+ <ShareSkill skill={skill} />
+ {permissions.canEdit && onEdit && (
+ <button
+ type="button"
+ onClick={onEdit}
+ className="inline-flex h-9 items-center justify-center rounded-md border border-border-medium px-3 text-xs font-semibold text-text-primary transition-colors hover:bg-surface-hover"
+ >
+ {localize('com_ui_edit')}
+ </button>
+ )}
+ {permissions.canDelete && onDelete && (
+ <DeleteSkill skillId={skill._id} skillName={skill.name} onDelete={onDelete} />
+ )}
+ </div>
+ </div>
+
+ {/* Description */}
+ <div className="flex flex-col gap-1">
+ <h3 className="text-xs leading-4 text-text-secondary">{localize('com_ui_description')}</h3>
+ <p className="whitespace-pre-wrap text-sm text-text-secondary">{skill.description}</p>
+ </div>
+
+ {/* Divider with view toggle */}
+ <div className="flex items-center gap-3 py-1">
+ <hr className="flex-1 border-border-medium" />
+ <ViewToggle viewMode={viewMode} setViewMode={setViewMode} localize={localize} />
+ </div>
+
+ {/* Frontmatter metadata */}
+ {viewMode === 'rendered' && frontmatterFields.length > 0 && (
+ <div className="grid grid-cols-[max-content_1fr] items-baseline gap-x-8 gap-y-2 pb-2">
+ {frontmatterFields.map(({ key, value }) => (
+ <React.Fragment key={key}>
+ <span className="text-xs text-text-secondary">{key}</span>
+ <span className="text-sm text-text-primary">{value}</span>
+ </React.Fragment>
+ ))}
+ </div>
+ )}
+
+ {/* Content — fills remaining space, no card wrapper */}
+ <div className="min-h-0 flex-1 overflow-auto">
+ {viewMode === 'rendered' ? (
+ <SkillMarkdownRenderer content={cleanBody} />
+ ) : (
+ <pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">
+ {skill.body ?? ''}
+ </pre>
+ )}
+ </div>
+ </article>
+ );
+}
diff --git a/client/src/components/Skills/display/SkillDetailHeader.tsx b/client/src/components/Skills/display/SkillDetailHeader.tsx
new file mode 100644
index 0000000000..405e4ce54a
--- /dev/null
+++ b/client/src/components/Skills/display/SkillDetailHeader.tsx
@@ -0,0 +1,108 @@
+import { format } from 'date-fns';
+import { useNavigate } from 'react-router-dom';
+import { Button, TooltipAnchor } from '@librechat/client';
+import { Pencil, User, Calendar, EarthIcon, Sparkles } from 'lucide-react';
+import { InvocationMode } from 'librechat-data-provider';
+import type { TSkill } from 'librechat-data-provider';
+import type { TranslationKeys } from '~/hooks';
+import { useLocalize, useAuthContext } from '~/hooks';
+import DeleteSkill from '../dialogs/DeleteSkill';
+import { ShareSkill } from '../buttons';
+
+const invocationLabelMap: Record<InvocationMode, TranslationKeys> = {
+ [InvocationMode.auto]: 'com_ui_invocation_auto',
+ [InvocationMode.manual]: 'com_ui_invocation_manual',
+ [InvocationMode.both]: 'com_ui_invocation_both',
+};
+
+interface SkillDetailHeaderProps {
+ skill: TSkill;
+ showActions?: boolean;
+}
+
+const SkillDetailHeader = ({ skill, showActions = true }: SkillDetailHeaderProps) => {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { user } = useAuthContext();
+ const formattedDate = skill.createdAt ? format(new Date(skill.createdAt), 'MMM d, yyyy') : null;
+ const isOwner = skill.author === user?.id;
+ const isShared = !isOwner && Boolean(skill.authorName);
+ const isPublic = skill.isPublic === true;
+
+ return (
+ <div className="flex flex-col gap-3 py-2 sm:flex-row sm:items-center sm:gap-4">
+ <div className="min-w-0 flex-1 overflow-hidden">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2 className="truncate text-xl font-bold text-text-primary" title={skill.name}>
+ {skill.name}
+ </h2>
+ {isPublic && (
+ <TooltipAnchor
+ description={localize('com_ui_sr_public_skill')}
+ side="top"
+ render={
+ <EarthIcon
+ className="h-5 w-5 shrink-0 text-green-400"
+ aria-label={localize('com_ui_sr_public_skill')}
+ />
+ }
+ />
+ )}
+ </div>
+ {skill.description && (
+ <p className="text-sm text-text-secondary sm:truncate">{skill.description}</p>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-3 text-xs text-text-secondary">
+ {isShared && (
+ <span className="flex items-center gap-1">
+ <User className="h-3 w-3 text-text-secondary" aria-hidden="true" />
+ {localize('com_ui_by_author', { 0: skill.authorName })}
+ </span>
+ )}
+ <span className="flex items-center gap-1">
+ <Sparkles className="h-3 w-3" aria-hidden="true" />
+ {localize('com_ui_invoked_by')}:{' '}
+ {localize(invocationLabelMap[skill.invocationMode ?? InvocationMode.auto])}
+ </span>
+ {formattedDate && (
+ <time className="flex items-center gap-1" dateTime={skill.createdAt}>
+ <Calendar className="h-3 w-3" aria-hidden="true" />
+ {formattedDate}
+ </time>
+ )}
+ </div>
+ </div>
+ {showActions && (
+ <div className="flex shrink-0 items-center gap-2">
+ <ShareSkill skill={skill} />
+ {isOwner && (
+ <>
+ <TooltipAnchor
+ description={localize('com_ui_edit')}
+ side="bottom"
+ render={
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-9"
+ aria-label={localize('com_ui_edit_skill')}
+ onClick={() => navigate(`/skills/${skill._id}/edit`)}
+ >
+ <Pencil className="size-5" aria-hidden="true" />
+ </Button>
+ }
+ />
+ <DeleteSkill
+ skillId={skill._id}
+ skillName={skill.name}
+ onDelete={() => navigate('/skills')}
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default SkillDetailHeader;
diff --git a/client/src/components/Skills/display/SkillFileViewer.tsx b/client/src/components/Skills/display/SkillFileViewer.tsx
new file mode 100644
index 0000000000..9f51193398
--- /dev/null
+++ b/client/src/components/Skills/display/SkillFileViewer.tsx
@@ -0,0 +1,226 @@
+import React, { memo, useMemo, useState, useCallback, useRef } from 'react';
+import { ArrowLeft, Eye, Code, Copy, Check, FileText, FileQuestion } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { Spinner, TooltipAnchor, useToastContext } from '@librechat/client';
+import { apiBaseUrl } from 'librechat-data-provider';
+import { useGetSkillFileContentQuery } from '~/data-provider';
+import SkillMarkdownRenderer from './SkillMarkdownRenderer';
+import { parseFrontmatter } from '../utils';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface SkillFileViewerProps {
+ skillId: string;
+ relativePath: string;
+}
+
+const SKILL_MD_SKIP_KEYS = new Set(['name', 'description']);
+
+function SkillFileViewer({ skillId, relativePath }: SkillFileViewerProps) {
+ const navigate = useNavigate();
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const { data, isLoading, isError } = useGetSkillFileContentQuery(skillId, relativePath);
+ const [viewMode, setViewMode] = useState<'rendered' | 'source'>('rendered');
+ const [isCopied, setIsCopied] = useState(false);
+ const copyTimeout = useRef<NodeJS.Timeout | null>(null);
+
+ const isMarkdown = relativePath.endsWith('.md');
+ const isImage = data?.mimeType?.startsWith('image/') ?? false;
+ const isSkillMd = relativePath === 'SKILL.md';
+ const isText = data != null && !data.isBinary && data.content != null;
+
+ const rawUrl = useMemo(
+ () =>
+ `${apiBaseUrl()}/api/skills/${skillId}/files/${encodeURIComponent(relativePath)}?raw=true`,
+ [skillId, relativePath],
+ );
+
+ const parsed = useMemo(() => {
+ if (!isMarkdown || !data?.content) {
+ return null;
+ }
+ return parseFrontmatter(data.content, isSkillMd ? SKILL_MD_SKIP_KEYS : undefined);
+ }, [isMarkdown, isSkillMd, data?.content]);
+
+ const handleCopy = useCallback(async () => {
+ if (isCopied || !data?.content) {
+ return;
+ }
+ try {
+ await navigator.clipboard.writeText(data.content);
+ setIsCopied(true);
+ showToast({ message: localize('com_ui_copied_to_clipboard'), status: 'success' });
+ if (copyTimeout.current) {
+ clearTimeout(copyTimeout.current);
+ }
+ copyTimeout.current = setTimeout(() => setIsCopied(false), 2000);
+ } catch {
+ showToast({ message: localize('com_ui_copy_failed'), status: 'error' });
+ }
+ }, [data?.content, isCopied, showToast, localize]);
+
+ return (
+ <div className="flex h-full flex-col">
+ {/* Header — fixed h-10 prevents layout shift when toggle appears/disappears */}
+ <div className="flex h-10 items-center gap-2 border-b border-border-medium px-4">
+ <button
+ type="button"
+ onClick={() => navigate(`/skills/${skillId}`)}
+ className="rounded-md p-1 text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary"
+ aria-label={localize('com_ui_back')}
+ >
+ <ArrowLeft className="size-4" />
+ </button>
+ <FileText className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-text-primary">
+ {data?.filename ?? relativePath}
+ </span>
+
+ {/* Actions — right side */}
+ <div className="flex shrink-0 items-center gap-1">
+ {/* Copy (text files only) */}
+ {isText && (
+ <TooltipAnchor
+ description={isCopied ? localize('com_ui_copied') : localize('com_ui_copy')}
+ render={
+ <button
+ type="button"
+ onClick={handleCopy}
+ className="rounded-md p-1 text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary"
+ aria-label={localize('com_ui_copy_to_clipboard')}
+ >
+ {isCopied ? <Check className="size-4" /> : <Copy className="size-4" />}
+ </button>
+ }
+ />
+ )}
+
+ {/* View toggle (markdown only) */}
+ {isMarkdown && isText && (
+ <div
+ role="group"
+ className="inline-flex h-7 rounded-lg bg-surface-tertiary p-0.5 text-sm font-medium"
+ >
+ <button
+ type="button"
+ onClick={() => setViewMode('rendered')}
+ className={cn(
+ 'flex items-center justify-center rounded-md px-1.5 transition-colors',
+ viewMode === 'rendered'
+ ? 'bg-surface-primary text-text-primary shadow-sm'
+ : 'text-text-secondary hover:text-text-primary',
+ )}
+ aria-pressed={viewMode === 'rendered'}
+ >
+ <Eye className="size-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setViewMode('source')}
+ className={cn(
+ 'flex items-center justify-center rounded-md px-1.5 transition-colors',
+ viewMode === 'source'
+ ? 'bg-surface-primary text-text-primary shadow-sm'
+ : 'text-text-secondary hover:text-text-primary',
+ )}
+ aria-pressed={viewMode === 'source'}
+ >
+ <Code className="size-4" />
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Content — fills remaining space */}
+ <div className="flex-1 overflow-y-auto px-5 py-4">
+ {isLoading && (
+ <div className="flex items-center justify-center py-12">
+ <Spinner className="size-6 text-text-secondary" />
+ </div>
+ )}
+
+ {isError && (
+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">
+ <FileQuestion className="size-8" />
+ <p className="text-sm">{localize('com_ui_skill_file_load_error')}</p>
+ </div>
+ )}
+
+ {data && !isLoading && !isError && (
+ <>
+ {data.isBinary && isImage && (
+ <img
+ src={rawUrl}
+ alt={data.filename}
+ className="max-h-[600px] max-w-full rounded-lg object-contain"
+ />
+ )}
+
+ {data.isBinary && !isImage && (
+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">
+ <FileQuestion className="size-8" />
+ <p className="text-sm">{localize('com_ui_skill_file_binary')}</p>
+ <a
+ href={rawUrl}
+ download
+ className="text-sm text-text-primary underline hover:no-underline"
+ >
+ {localize('com_ui_skill_file_download')}
+ </a>
+ </div>
+ )}
+
+ {/* Markdown — frontmatter grid + rendered/source body */}
+ {isText && isMarkdown && parsed && (
+ <>
+ {viewMode === 'rendered' && parsed.fields.length > 0 && (
+ <div className="mb-3 grid grid-cols-[max-content_1fr] items-baseline gap-x-8 gap-y-2">
+ {parsed.fields.map(({ key, value }) => (
+ <React.Fragment key={key}>
+ <span className="text-xs capitalize text-text-secondary">{key}</span>
+ <span className="text-sm text-text-primary">{value}</span>
+ </React.Fragment>
+ ))}
+ </div>
+ )}
+ {viewMode === 'rendered' ? (
+ <SkillMarkdownRenderer content={parsed.body} />
+ ) : (
+ <pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">
+ {data.content}
+ </pre>
+ )}
+ </>
+ )}
+
+ {/* Non-markdown text */}
+ {isText && !isMarkdown && (
+ <pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">
+ {data.content}
+ </pre>
+ )}
+
+ {/* Text file too large for JSON response — offer download */}
+ {!data.isBinary && data.content == null && (
+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">
+ <FileText className="size-8" />
+ <p className="text-sm">{localize('com_ui_skill_file_download')}</p>
+ <a
+ href={rawUrl}
+ download
+ className="text-sm text-text-primary underline hover:no-underline"
+ >
+ {localize('com_ui_skill_file_download')}
+ </a>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default memo(SkillFileViewer);
diff --git a/client/src/components/Skills/display/SkillMarkdownRenderer.tsx b/client/src/components/Skills/display/SkillMarkdownRenderer.tsx
new file mode 100644
index 0000000000..c79bebdba2
--- /dev/null
+++ b/client/src/components/Skills/display/SkillMarkdownRenderer.tsx
@@ -0,0 +1,55 @@
+import { memo } from 'react';
+import remarkGfm from 'remark-gfm';
+import remarkMath from 'remark-math';
+import rehypeKatex from 'rehype-katex';
+import supersub from 'remark-supersub';
+import ReactMarkdown from 'react-markdown';
+import rehypeHighlight from 'rehype-highlight';
+import type { PluggableList } from 'unified';
+import { codeNoExecution } from '~/components/Chat/Messages/Content/MarkdownComponents';
+import { langSubset } from '~/utils';
+
+const REMARK_PLUGINS: PluggableList = [
+ supersub,
+ remarkGfm,
+ [remarkMath, { singleDollarTextMath: false }],
+];
+
+const REHYPE_PLUGINS: PluggableList = [
+ [rehypeKatex],
+ [
+ rehypeHighlight,
+ {
+ detect: true,
+ ignoreMissing: true,
+ subset: langSubset,
+ },
+ ],
+];
+
+const MARKDOWN_COMPONENTS = { code: codeNoExecution };
+
+interface SkillMarkdownRendererProps {
+ content: string;
+ className?: string;
+}
+
+function SkillMarkdownRenderer({ content, className }: SkillMarkdownRendererProps) {
+ return (
+ <ReactMarkdown
+ /** @ts-ignore - PluggableList vs Pluggable[] shape drift */
+ remarkPlugins={REMARK_PLUGINS}
+ /** @ts-ignore - PluggableList vs Pluggable[] shape drift */
+ rehypePlugins={REHYPE_PLUGINS}
+ components={MARKDOWN_COMPONENTS as unknown as Record<string, React.ElementType>}
+ className={
+ className ??
+ 'markdown prose dark:prose-invert light w-full break-words leading-[1.65rem] text-text-primary'
+ }
+ >
+ {content}
+ </ReactMarkdown>
+ );
+}
+
+export default memo(SkillMarkdownRenderer);
diff --git a/client/src/components/Skills/display/SkillState.tsx b/client/src/components/Skills/display/SkillState.tsx
new file mode 100644
index 0000000000..b1408ee080
--- /dev/null
+++ b/client/src/components/Skills/display/SkillState.tsx
@@ -0,0 +1,66 @@
+import { TriangleAlert, MousePointerClick } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import { Button } from '@librechat/client';
+import { cn } from '~/utils';
+
+type SkillStateVariant = 'empty' | 'error';
+
+interface SkillStateProps {
+ title: string;
+ description: string;
+ actionLabel?: string;
+ onAction?: () => void;
+ variant?: SkillStateVariant;
+ className?: string;
+}
+
+const icons: Record<SkillStateVariant, LucideIcon> = {
+ empty: MousePointerClick,
+ error: TriangleAlert,
+};
+
+const styles: Record<SkillStateVariant, { icon: string; wrap: string }> = {
+ empty: {
+ icon: 'text-text-primary',
+ wrap: 'bg-surface-tertiary',
+ },
+ error: {
+ icon: 'text-amber-500',
+ wrap: 'bg-amber-500/10',
+ },
+};
+
+export default function SkillState({
+ title,
+ description,
+ actionLabel,
+ onAction,
+ variant = 'empty',
+ className = '',
+}: SkillStateProps) {
+ const Icon = icons[variant];
+ const style = styles[variant];
+
+ return (
+ <div className={cn('flex h-full w-full items-center justify-center px-6 py-12', className)}>
+ <div className="flex max-w-sm flex-col items-center text-center">
+ <div className={cn('mb-4 flex size-12 items-center justify-center rounded-xl', style.wrap)}>
+ <Icon className={cn('size-6', style.icon)} aria-hidden="true" />
+ </div>
+ <p className="text-[15px] font-semibold text-text-primary">{title}</p>
+ <p className="mt-1.5 text-sm leading-relaxed text-text-secondary">{description}</p>
+ {actionLabel && onAction && (
+ <Button
+ type="button"
+ variant="outline"
+ className="mt-5"
+ aria-label={actionLabel}
+ onClick={onAction}
+ >
+ {actionLabel}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/display/index.ts b/client/src/components/Skills/display/index.ts
new file mode 100644
index 0000000000..d96577a210
--- /dev/null
+++ b/client/src/components/Skills/display/index.ts
@@ -0,0 +1,5 @@
+export { default as SkillDetail } from './SkillDetail';
+export { default as SkillDetailHeader } from './SkillDetailHeader';
+export { default as SkillFileViewer } from './SkillFileViewer';
+export { default as SkillMarkdownRenderer } from './SkillMarkdownRenderer';
+export { default as SkillState } from './SkillState';
diff --git a/client/src/components/Skills/forms/CategorySelector.tsx b/client/src/components/Skills/forms/CategorySelector.tsx
new file mode 100644
index 0000000000..a247a59436
--- /dev/null
+++ b/client/src/components/Skills/forms/CategorySelector.tsx
@@ -0,0 +1,81 @@
+import React, { useMemo, useState } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { DropdownPopup } from '@librechat/client';
+import { useFormContext, Controller } from 'react-hook-form';
+import type { MenuItemProps } from '@librechat/client';
+import type { ReactNode } from 'react';
+import { useCategories, useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface CategorySelectorProps {
+ className?: string;
+}
+
+const CategorySelector: React.FC<CategorySelectorProps> = ({ className = '' }) => {
+ const localize = useLocalize();
+ const { control, watch, setValue } = useFormContext();
+ const [isOpen, setIsOpen] = useState(false);
+ const { categories, emptyCategory } = useCategories({ hasAccess: true });
+
+ const watchedCategory = watch('category') as string | undefined;
+
+ const categoryOption = useMemo(
+ () => (categories ?? []).find((c) => c.value === watchedCategory) ?? emptyCategory,
+ [categories, watchedCategory, emptyCategory],
+ );
+
+ const menuItems: MenuItemProps[] = useMemo(() => {
+ if (!categories) {
+ return [];
+ }
+ return categories.map((category: { value: string; label: string; icon?: ReactNode }) => ({
+ id: category.value,
+ label: category.label,
+ icon: category.icon,
+ onClick: () => {
+ setValue('category', category.value || '', { shouldDirty: true });
+ setIsOpen(false);
+ },
+ }));
+ }, [categories, setValue]);
+
+ const trigger = (
+ <Ariakit.MenuButton
+ className={cn(
+ 'focus:ring-offset-ring-offset relative inline-flex h-9 items-center justify-between rounded-xl border border-border-medium bg-transparent px-3 text-sm text-text-primary transition-all duration-200 ease-in-out hover:bg-accent hover:text-accent-foreground focus:ring-ring-primary',
+ 'gap-2 sm:w-fit',
+ className,
+ )}
+ onClick={() => setIsOpen(!isOpen)}
+ aria-label={localize('com_ui_category')}
+ >
+ <div className="flex items-center space-x-2">
+ {'icon' in categoryOption && categoryOption.icon != null && (
+ <span>{categoryOption.icon as ReactNode}</span>
+ )}
+ <span>{categoryOption.value ? categoryOption.label : localize('com_ui_category')}</span>
+ </div>
+ <Ariakit.MenuButtonArrow />
+ </Ariakit.MenuButton>
+ );
+
+ return (
+ <Controller
+ name="category"
+ control={control}
+ render={() => (
+ <DropdownPopup
+ trigger={trigger}
+ items={menuItems}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ menuId="skill-category-selector-menu"
+ className="mt-2"
+ portal={true}
+ />
+ )}
+ />
+ );
+};
+
+export default CategorySelector;
diff --git a/client/src/components/Skills/forms/CreateSkillForm.tsx b/client/src/components/Skills/forms/CreateSkillForm.tsx
new file mode 100644
index 0000000000..fa06f8c2e3
--- /dev/null
+++ b/client/src/components/Skills/forms/CreateSkillForm.tsx
@@ -0,0 +1,289 @@
+import { useState } from 'react';
+import { AlertTriangle } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { useForm, Controller, FormProvider } from 'react-hook-form';
+import { Input, Button, TextareaAutosize, useToastContext } from '@librechat/client';
+import {
+ InvocationMode,
+ SKILL_NAME_PATTERN,
+ SKILL_NAME_MAX_LENGTH,
+ SKILL_DESCRIPTION_MAX_LENGTH,
+} from 'librechat-data-provider';
+import type { TSkill, TCreateSkill, TSkillWarning } from 'librechat-data-provider';
+import { useCreateSkillMutation } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import SkillContentEditor from './SkillContentEditor';
+import InvocationModePicker from './InvocationModePicker';
+import CategorySelector from './CategorySelector';
+import { cn } from '~/utils';
+
+const DEFAULT_BODY = `# Overview
+
+Describe what this skill does and how it should be applied.
+
+## When to use
+
+- List concrete signals that should trigger this skill
+- Add examples that make the trigger unambiguous
+
+## How to apply
+
+Walk through the steps the agent should take.
+`;
+
+interface CreateSkillFormValues {
+ name: string;
+ description: string;
+ body: string;
+ category: string;
+ invocationMode: InvocationMode;
+}
+
+const DEFAULT_VALUES: CreateSkillFormValues = {
+ name: '',
+ description: '',
+ body: DEFAULT_BODY,
+ category: '',
+ invocationMode: InvocationMode.auto,
+};
+
+interface CreateSkillFormProps {
+ /**
+ * Pre-populated field values — used by the upload path to seed the form
+ * with parsed SKILL.md frontmatter. Shape is a subset of the form values
+ * (partial) because the upload parser may only extract `name` +
+ * `description`; `invocationMode` is accepted for shape compatibility
+ * with the original UI PR but ignored for now (the backend doesn't
+ * persist it yet).
+ */
+ defaultValues?: Partial<CreateSkillFormValues> & { invocationMode?: unknown };
+ onCancel?: () => void;
+ onSuccess?: (skill: TSkill) => void;
+}
+
+export default function CreateSkillForm({
+ defaultValues,
+ onCancel,
+ onSuccess,
+}: CreateSkillFormProps) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { showToast } = useToastContext();
+ const [isEditingContent, setIsEditingContent] = useState(true);
+
+ const methods = useForm<CreateSkillFormValues>({
+ defaultValues: { ...DEFAULT_VALUES, ...defaultValues },
+ mode: 'onChange',
+ });
+ const {
+ control,
+ handleSubmit,
+ setError,
+ formState: { isSubmitting, isValid, errors },
+ } = methods;
+
+ const createSkill = useCreateSkillMutation({
+ onSuccess: (skill) => {
+ const warnings: TSkillWarning[] | undefined = skill.warnings;
+ showToast({
+ status: warnings && warnings.length > 0 ? 'warning' : 'success',
+ message: localize('com_ui_skill_created'),
+ });
+ if (onSuccess) {
+ onSuccess(skill);
+ } else {
+ navigate(`/skills/${skill._id}`);
+ }
+ },
+ onError: (error: unknown) => {
+ const message =
+ (error as { response?: { data?: { message?: string } } })?.response?.data?.message ??
+ localize('com_ui_skill_create_error');
+ showToast({ status: 'error', message });
+ },
+ });
+
+ // `useCallback` would be a no-op here: `createSkill` is a React Query
+ // mutation result with an unstable identity, and `handleSubmit` from
+ // react-hook-form doesn't use `onSubmit` as a dependency anywhere.
+ const onSubmit = (values: CreateSkillFormValues) => {
+ if (createSkill.isLoading) {
+ return;
+ }
+ const payload: TCreateSkill = {
+ name: values.name.trim(),
+ description: values.description.trim(),
+ body: values.body,
+ category: values.category || undefined,
+ // `invocationMode` is deliberately NOT forwarded — phase 1 backend
+ // doesn't persist it. Kept in form state only so the picker has a
+ // selection.
+ };
+
+ if (!SKILL_NAME_PATTERN.test(payload.name)) {
+ setError('name', { message: localize('com_ui_skill_name_invalid') });
+ return;
+ }
+
+ createSkill.mutate(payload);
+ };
+
+ const handleCancel = () => {
+ if (onCancel) {
+ onCancel();
+ } else {
+ navigate(-1);
+ }
+ };
+
+ const createDisabled = !isValid || isSubmitting || createSkill.isLoading;
+
+ return (
+ <FormProvider {...methods}>
+ <form
+ onSubmit={handleSubmit(onSubmit)}
+ className="w-full px-4 py-2"
+ aria-label={localize('com_ui_skill_create_title')}
+ >
+ <h1 className="sr-only">{localize('com_ui_skill_create_title')}</h1>
+ <div className="mb-1 flex flex-col items-center justify-between font-bold sm:text-xl md:mb-0 md:text-2xl">
+ <div className="flex w-full flex-col items-center justify-between sm:flex-row">
+ <Controller
+ name="name"
+ control={control}
+ rules={{
+ required: localize('com_ui_skill_name_required'),
+ pattern: {
+ value: SKILL_NAME_PATTERN,
+ message: localize('com_ui_skill_name_invalid'),
+ },
+ maxLength: {
+ value: SKILL_NAME_MAX_LENGTH,
+ message: localize('com_ui_skill_name_too_long', {
+ 0: String(SKILL_NAME_MAX_LENGTH),
+ }),
+ },
+ }}
+ render={({ field }) => (
+ <div className="relative mb-1 flex w-full flex-col sm:w-auto md:mb-0">
+ <Input
+ {...field}
+ id="skill-name"
+ type="text"
+ className="peer mr-2 w-full border border-border-medium p-2 text-2xl text-text-primary"
+ placeholder=" "
+ tabIndex={0}
+ aria-label={localize('com_ui_name')}
+ aria-required="true"
+ aria-invalid={errors.name ? 'true' : 'false'}
+ aria-describedby={errors.name ? 'skill-name-error' : undefined}
+ />
+ <label
+ htmlFor="skill-name"
+ className="pointer-events-none absolute -top-1 left-3 origin-[0] translate-y-3 scale-100 rounded bg-presentation px-1 text-base text-text-secondary transition-transform duration-200 peer-placeholder-shown:translate-y-3 peer-placeholder-shown:scale-100 peer-focus:-translate-y-2 peer-focus:scale-75 peer-focus:text-text-primary peer-[:not(:placeholder-shown)]:-translate-y-2 peer-[:not(:placeholder-shown)]:scale-75"
+ >
+ {localize('com_ui_name')}*
+ </label>
+ <div
+ id="skill-name-error"
+ className={cn(
+ 'mt-1 w-56 text-sm text-red-500',
+ errors.name ? 'visible h-auto' : 'invisible h-0',
+ )}
+ role={errors.name ? 'alert' : undefined}
+ >
+ {errors.name ? errors.name.message : ' '}
+ </div>
+ </div>
+ )}
+ />
+ <div className="flex items-center gap-2">
+ <CategorySelector />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex w-full flex-col gap-4 md:mt-[1.075rem]">
+ <Controller
+ name="description"
+ control={control}
+ rules={{
+ required: localize('com_ui_skill_description_required'),
+ maxLength: {
+ value: SKILL_DESCRIPTION_MAX_LENGTH,
+ message: localize('com_ui_skill_description_too_long', {
+ 0: String(SKILL_DESCRIPTION_MAX_LENGTH),
+ }),
+ },
+ }}
+ render={({ field }) => (
+ <div className="flex flex-col">
+ <label
+ htmlFor="skill-description"
+ className="mb-1 text-sm font-medium text-text-secondary"
+ >
+ {localize('com_ui_description')}
+ <span className="ml-0.5 text-red-500">*</span>
+ </label>
+ <TextareaAutosize
+ {...field}
+ id="skill-description"
+ minRows={2}
+ maxRows={6}
+ placeholder={localize('com_ui_skill_description_placeholder')}
+ aria-label={localize('com_ui_description')}
+ aria-invalid={errors.description ? 'true' : 'false'}
+ aria-describedby={errors.description ? 'skill-description-error' : undefined}
+ className="w-full resize-none rounded-xl border border-border-medium bg-transparent p-3 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ />
+ <p className="mt-1 text-xs text-text-secondary">
+ {localize('com_ui_skill_description_field_hint')}
+ </p>
+ {errors.description && (
+ <p
+ id="skill-description-error"
+ className="mt-1 text-sm text-red-500"
+ role="alert"
+ >
+ {errors.description.message}
+ </p>
+ )}
+ </div>
+ )}
+ />
+
+ <SkillContentEditor
+ name="body"
+ isEditing={isEditingContent}
+ setIsEditing={setIsEditingContent}
+ />
+
+ {createSkill.error != null && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-md border border-red-500/40 bg-red-500/5 p-3 text-sm text-red-500"
+ >
+ <AlertTriangle className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
+ <span>{localize('com_ui_skill_create_error')}</span>
+ </div>
+ )}
+
+ <div className="mt-4 flex items-center justify-end gap-2">
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ {localize('com_ui_cancel')}
+ </Button>
+ <Button
+ aria-label={localize('com_ui_skill_create_title')}
+ type="submit"
+ disabled={createDisabled}
+ aria-disabled={createDisabled || undefined}
+ className={cn('w-full sm:w-auto', createDisabled && 'opacity-50')}
+ >
+ {localize('com_ui_skill_create_title')}
+ </Button>
+ </div>
+ </div>
+ </form>
+ </FormProvider>
+ );
+}
diff --git a/client/src/components/Skills/forms/InvocationModePicker.tsx b/client/src/components/Skills/forms/InvocationModePicker.tsx
new file mode 100644
index 0000000000..21e3e4b1b7
--- /dev/null
+++ b/client/src/components/Skills/forms/InvocationModePicker.tsx
@@ -0,0 +1,84 @@
+import { useState, useMemo } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { ChevronDown } from 'lucide-react';
+import { DropdownPopup } from '@librechat/client';
+import { InvocationMode } from 'librechat-data-provider';
+import type { MenuItemProps } from '@librechat/client';
+import type { TranslationKeys } from '~/hooks';
+import { useLocalize } from '~/hooks';
+
+const invocationLabels: Record<InvocationMode, TranslationKeys> = {
+ [InvocationMode.auto]: 'com_ui_invocation_auto',
+ [InvocationMode.manual]: 'com_ui_invocation_manual',
+ [InvocationMode.both]: 'com_ui_invocation_both',
+};
+
+const invocationDescriptions: Record<InvocationMode, TranslationKeys> = {
+ [InvocationMode.auto]: 'com_ui_invocation_auto_info',
+ [InvocationMode.manual]: 'com_ui_invocation_manual_info',
+ [InvocationMode.both]: 'com_ui_invocation_both_info',
+};
+
+const modes = [InvocationMode.auto, InvocationMode.manual, InvocationMode.both];
+
+interface InvocationModePickerProps {
+ value: InvocationMode;
+ onChange: (mode: InvocationMode) => void;
+}
+
+export default function InvocationModePicker({ value, onChange }: InvocationModePickerProps) {
+ const localize = useLocalize();
+ const [isOpen, setIsOpen] = useState(false);
+
+ const menuItems: MenuItemProps[] = useMemo(
+ () =>
+ modes.map((mode) => ({
+ id: mode,
+ label: localize(invocationLabels[mode]),
+ onClick: () => {
+ onChange(mode);
+ setIsOpen(false);
+ },
+ render: (props) => (
+ <button {...props}>
+ <div className="flex flex-col items-start gap-0.5 text-left">
+ <span className="font-medium text-text-primary">
+ {localize(invocationLabels[mode])}
+ </span>
+ <span className="text-xs text-text-secondary">
+ {localize(invocationDescriptions[mode])}
+ </span>
+ </div>
+ </button>
+ ),
+ })),
+ [localize, onChange],
+ );
+
+ return (
+ <div className="flex flex-col">
+ <label className="mb-1 text-sm font-medium text-text-secondary">
+ {localize('com_ui_invocation_mode')}
+ </label>
+ <DropdownPopup
+ menuId="invocation-mode-menu"
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ trigger={
+ <Ariakit.MenuButton
+ aria-label={localize('com_ui_invocation_mode')}
+ className="flex w-fit items-center justify-between gap-2 rounded-xl border border-border-medium bg-transparent px-3 py-2 text-sm text-text-primary transition-colors hover:bg-surface-tertiary"
+ >
+ <span className="font-medium text-text-primary">
+ {localize(invocationLabels[value])}
+ </span>
+ <ChevronDown className="size-4 text-text-secondary" aria-hidden="true" />
+ </Ariakit.MenuButton>
+ }
+ items={menuItems}
+ className="w-[280px]"
+ portal={true}
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/forms/SkillContentEditor.tsx b/client/src/components/Skills/forms/SkillContentEditor.tsx
new file mode 100644
index 0000000000..614ba1cd0b
--- /dev/null
+++ b/client/src/components/Skills/forms/SkillContentEditor.tsx
@@ -0,0 +1,156 @@
+import { memo } from 'react';
+import remarkGfm from 'remark-gfm';
+import remarkMath from 'remark-math';
+import rehypeKatex from 'rehype-katex';
+import supersub from 'remark-supersub';
+import ReactMarkdown from 'react-markdown';
+import rehypeHighlight from 'rehype-highlight';
+import { EditIcon, Check } from 'lucide-react';
+import { Controller, useFormContext } from 'react-hook-form';
+import { TextareaAutosize, Button, TooltipAnchor } from '@librechat/client';
+import type { RegisterOptions } from 'react-hook-form';
+import type { PluggableList } from 'unified';
+import { codeNoExecution } from '~/components/Chat/Messages/Content/MarkdownComponents';
+import { cn, langSubset } from '~/utils';
+import { useLocalize } from '~/hooks';
+
+const REMARK_PLUGINS: PluggableList = [
+ supersub,
+ remarkGfm,
+ [remarkMath, { singleDollarTextMath: false }],
+];
+
+const REHYPE_PLUGINS: PluggableList = [
+ [rehypeKatex],
+ [
+ rehypeHighlight,
+ {
+ detect: true,
+ ignoreMissing: true,
+ subset: langSubset,
+ },
+ ],
+];
+
+const MARKDOWN_COMPONENTS = { code: codeNoExecution };
+
+interface SkillContentEditorProps {
+ name: string;
+ isEditing: boolean;
+ setIsEditing: React.Dispatch<React.SetStateAction<boolean>>;
+ rules?: RegisterOptions;
+}
+
+const SkillContentEditor: React.FC<SkillContentEditorProps> = ({
+ name,
+ isEditing,
+ setIsEditing,
+ rules,
+}) => {
+ const localize = useLocalize();
+ const {
+ control,
+ formState: { errors },
+ } = useFormContext();
+
+ const EditorIcon = isEditing ? Check : EditIcon;
+
+ return (
+ <div className="flex max-h-[85vh] flex-col sm:max-h-[85vh]">
+ <h2 className="sr-only">{localize('com_ui_skill_content')}</h2>
+ <div
+ className={cn(
+ 'relative w-full flex-1 overflow-auto rounded-xl border border-border-medium p-3 text-left transition-all duration-200 sm:p-4',
+ isEditing ? '' : 'cursor-pointer hover:bg-surface-tertiary',
+ )}
+ >
+ <div className="absolute right-2 top-2 z-10">
+ <TooltipAnchor
+ description={isEditing ? localize('com_ui_save') : localize('com_ui_edit')}
+ render={
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setIsEditing((prev) => !prev)}
+ aria-label={isEditing ? localize('com_ui_save') : localize('com_ui_edit')}
+ className="size-8 p-0 hover:bg-surface-tertiary"
+ >
+ <EditorIcon className="size-4 text-text-secondary" aria-hidden="true" />
+ </Button>
+ }
+ />
+ </div>
+ {!isEditing && (
+ <button
+ type="button"
+ aria-label={localize('com_ui_edit')}
+ className="absolute inset-0 z-10 rounded-xl focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ onClick={() => setIsEditing(true)}
+ />
+ )}
+ <Controller
+ name={name}
+ control={control}
+ rules={rules}
+ render={({ field }) =>
+ isEditing ? (
+ <TextareaAutosize
+ {...field}
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ autoFocus
+ className="w-full resize-none overflow-y-auto bg-transparent font-mono text-sm leading-relaxed text-text-primary placeholder:text-text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary sm:text-base"
+ minRows={4}
+ maxRows={16}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ setIsEditing(false);
+ }
+ }}
+ placeholder={localize('com_ui_skill_content_placeholder')}
+ aria-label={localize('com_ui_skill_content')}
+ />
+ ) : (
+ <div
+ className="group/preview relative min-h-[6rem] overflow-y-auto text-sm sm:text-base"
+ style={{ maxHeight: '24rem' }}
+ >
+ {!field.value ? (
+ <p className="italic text-text-secondary">{localize('com_ui_click_to_edit')}</p>
+ ) : (
+ <ReactMarkdown
+ /** @ts-ignore - PluggableList vs Pluggable[] shape drift */
+ remarkPlugins={REMARK_PLUGINS}
+ /** @ts-ignore - PluggableList vs Pluggable[] shape drift */
+ rehypePlugins={REHYPE_PLUGINS}
+ components={MARKDOWN_COMPONENTS as unknown as Record<string, React.ElementType>}
+ className="markdown prose dark:prose-invert light w-full break-words text-text-primary"
+ >
+ {field.value}
+ </ReactMarkdown>
+ )}
+ <div className="pointer-events-none sticky bottom-1/2 z-10 flex translate-y-1/2 items-center justify-center opacity-0 transition-all duration-200 group-hover/preview:opacity-100">
+ <div className="flex items-center gap-2 rounded-lg border border-border-light bg-surface-primary px-3 py-1.5 shadow-md">
+ <EditIcon className="size-4 text-text-secondary" aria-hidden="true" />
+ <span className="text-sm font-medium text-text-primary">
+ {localize('com_ui_click_to_edit')}
+ </span>
+ </div>
+ </div>
+ </div>
+ )
+ }
+ />
+ {errors[name] && (
+ <p className="mt-1 text-sm text-red-500" role="alert">
+ {errors[name]?.message as string}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default memo(SkillContentEditor);
diff --git a/client/src/components/Skills/forms/SkillForm.tsx b/client/src/components/Skills/forms/SkillForm.tsx
new file mode 100644
index 0000000000..f162a3e132
--- /dev/null
+++ b/client/src/components/Skills/forms/SkillForm.tsx
@@ -0,0 +1,347 @@
+import { useEffect, useMemo, useState } from 'react';
+import { Info, AlertTriangle } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { useForm, Controller, FormProvider } from 'react-hook-form';
+import { Input, Button, Skeleton, TextareaAutosize, useToastContext } from '@librechat/client';
+import {
+ InvocationMode,
+ SKILL_NAME_PATTERN,
+ SKILL_NAME_MAX_LENGTH,
+ SKILL_DESCRIPTION_MAX_LENGTH,
+} from 'librechat-data-provider';
+import type { TSkill, TSkillWarning, TUpdateSkillPayload } from 'librechat-data-provider';
+import { useGetSkillQuery, useUpdateSkillMutation } from '~/data-provider';
+import { useLocalize, useSkillPermissions } from '~/hooks';
+import SkillContentEditor from './SkillContentEditor';
+import InvocationModePicker from './InvocationModePicker';
+import CategorySelector from './CategorySelector';
+import DeleteSkill from '../dialogs/DeleteSkill';
+import { ShareSkill } from '../buttons';
+import { cn } from '~/utils';
+
+interface SkillFormValues {
+ name: string;
+ description: string;
+ body: string;
+ category: string;
+ invocationMode: InvocationMode;
+}
+
+interface SkillFormProps {
+ skillId: string;
+}
+
+function toValues(skill: TSkill | undefined): SkillFormValues | undefined {
+ if (!skill) {
+ return undefined;
+ }
+ return {
+ name: skill.name,
+ description: skill.description,
+ body: skill.body ?? '',
+ category: skill.category ?? '',
+ // Phase 1: backend doesn't persist invocationMode yet — default to `auto`
+ // so the picker has a selection. UI state only; discarded on save until
+ // the backend lands the column.
+ invocationMode: skill.invocationMode ?? InvocationMode.auto,
+ };
+}
+
+export default function SkillForm({ skillId }: SkillFormProps) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const { showToast } = useToastContext();
+ const [warnings, setWarnings] = useState<TSkillWarning[] | null>(null);
+
+ const skillQuery = useGetSkillQuery(skillId);
+ const skill = skillQuery.data;
+ const permissions = useSkillPermissions(skill);
+
+ const values = useMemo(() => toValues(skill), [skill]);
+ const [isEditingContent, setIsEditingContent] = useState(false);
+
+ const methods = useForm<SkillFormValues>({
+ defaultValues: {
+ name: '',
+ description: '',
+ body: '',
+ category: '',
+ invocationMode: InvocationMode.auto,
+ },
+ values,
+ mode: 'onChange',
+ });
+ const {
+ control,
+ handleSubmit,
+ reset,
+ setError,
+ formState: { isDirty, isValid, isSubmitting, errors },
+ } = methods;
+
+ useEffect(() => {
+ setWarnings(null);
+ }, [skillId]);
+
+ const updateSkill = useUpdateSkillMutation({
+ onSuccess: (updated) => {
+ showToast({
+ status: updated.warnings && updated.warnings.length > 0 ? 'warning' : 'success',
+ message: localize('com_ui_skill_updated'),
+ });
+ setWarnings(updated.warnings ?? null);
+ reset(toValues(updated));
+ },
+ onError: (error: unknown) => {
+ const status = (error as { response?: { status?: number } })?.response?.status;
+ if (status === 409) {
+ showToast({ status: 'warning', message: localize('com_ui_skill_update_conflict') });
+ skillQuery.refetch();
+ return;
+ }
+ const message =
+ (error as { response?: { data?: { message?: string } } })?.response?.data?.message ??
+ localize('com_ui_skill_update_error');
+ showToast({ status: 'error', message });
+ },
+ });
+
+ // `useCallback` would be a no-op: `updateSkill` is a React Query mutation
+ // result with an unstable identity, and `handleSubmit` doesn't use
+ // `onSubmit` as a memo dependency.
+ const onSubmit = (data: SkillFormValues) => {
+ if (!skill || updateSkill.isLoading) {
+ return;
+ }
+ const trimmedName = data.name.trim();
+ if (!SKILL_NAME_PATTERN.test(trimmedName)) {
+ setError('name', { message: localize('com_ui_skill_name_invalid') });
+ return;
+ }
+ const payload: TUpdateSkillPayload = {
+ name: trimmedName,
+ description: data.description.trim(),
+ body: data.body,
+ category: data.category || undefined,
+ // `invocationMode` is deliberately NOT forwarded to the backend: the
+ // column doesn't exist yet. Phase 2 will promote it to a first-class
+ // payload field.
+ };
+ updateSkill.mutate({
+ id: skill._id,
+ expectedVersion: skill.version,
+ payload,
+ });
+ };
+
+ if (skillQuery.isLoading || permissions.isLoading) {
+ return (
+ <div className="w-full px-4 py-2">
+ <Skeleton className="mb-3 h-10 w-72" />
+ <Skeleton className="mb-3 h-20 w-full" />
+ <Skeleton className="h-64 w-full" />
+ </div>
+ );
+ }
+
+ if (skillQuery.isError || !skill) {
+ return (
+ <div className="w-full px-4 py-6 text-sm text-text-secondary">
+ <p className="font-medium text-text-primary">{localize('com_ui_skill_not_found')}</p>
+ <p>{localize('com_ui_skill_not_found_description')}</p>
+ </div>
+ );
+ }
+
+ const readOnly = !permissions.canEdit;
+ const saveDisabled = !isDirty || !isValid || isSubmitting || updateSkill.isLoading;
+
+ return (
+ <FormProvider {...methods}>
+ <form
+ onSubmit={handleSubmit(onSubmit)}
+ className="w-full px-4 py-2"
+ aria-label={localize('com_ui_skill_edit_title')}
+ >
+ <h1 className="sr-only">{localize('com_ui_skill_edit_title')}</h1>
+
+ <div className="mb-1 flex flex-col items-center justify-between font-bold sm:text-xl md:mb-0 md:text-2xl">
+ <div className="flex w-full flex-col items-start justify-between gap-2 sm:flex-row sm:items-center">
+ <Controller
+ name="name"
+ control={control}
+ rules={{
+ required: localize('com_ui_skill_name_required'),
+ pattern: {
+ value: SKILL_NAME_PATTERN,
+ message: localize('com_ui_skill_name_invalid'),
+ },
+ maxLength: {
+ value: SKILL_NAME_MAX_LENGTH,
+ message: localize('com_ui_skill_name_too_long', {
+ 0: String(SKILL_NAME_MAX_LENGTH),
+ }),
+ },
+ }}
+ render={({ field }) => (
+ <div className="relative mb-1 flex w-full flex-col sm:w-auto md:mb-0">
+ <Input
+ {...field}
+ id="skill-name"
+ type="text"
+ readOnly={readOnly}
+ className="peer mr-2 w-full border border-border-medium p-2 text-2xl text-text-primary"
+ placeholder=" "
+ tabIndex={0}
+ aria-label={localize('com_ui_name')}
+ aria-required="true"
+ aria-invalid={errors.name ? 'true' : 'false'}
+ aria-describedby={errors.name ? 'skill-name-error' : undefined}
+ />
+ <label
+ htmlFor="skill-name"
+ className="pointer-events-none absolute -top-1 left-3 origin-[0] translate-y-3 scale-100 rounded bg-presentation px-1 text-base text-text-secondary transition-transform duration-200 peer-placeholder-shown:translate-y-3 peer-placeholder-shown:scale-100 peer-focus:-translate-y-2 peer-focus:scale-75 peer-focus:text-text-primary peer-[:not(:placeholder-shown)]:-translate-y-2 peer-[:not(:placeholder-shown)]:scale-75"
+ >
+ {localize('com_ui_name')}*
+ </label>
+ <div
+ id="skill-name-error"
+ className={cn(
+ 'mt-1 w-56 text-sm text-red-500',
+ errors.name ? 'visible h-auto' : 'invisible h-0',
+ )}
+ role={errors.name ? 'alert' : undefined}
+ >
+ {errors.name ? errors.name.message : ' '}
+ </div>
+ </div>
+ )}
+ />
+ <div className="flex shrink-0 items-center gap-2">
+ <CategorySelector />
+ <ShareSkill skill={skill} />
+ {permissions.canDelete && (
+ <DeleteSkill
+ skillId={skill._id}
+ skillName={skill.name}
+ onDelete={() => navigate('/skills', { replace: true })}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-1 flex items-center gap-2 text-xs text-text-secondary">
+ <span>{localize('com_ui_skill_version', { 0: String(skill.version) })}</span>
+ <span aria-hidden="true">·</span>
+ <span>{skill.authorName}</span>
+ </div>
+
+ {readOnly && (
+ <div
+ role="note"
+ className="mt-4 flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-sm text-amber-600 dark:text-amber-400"
+ >
+ <Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
+ <span>{localize('com_ui_skill_no_edit_permission')}</span>
+ </div>
+ )}
+
+ {warnings && warnings.length > 0 && (
+ <div
+ role="alert"
+ className="mt-4 flex flex-col gap-1 rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-sm text-amber-600 dark:text-amber-400"
+ >
+ <div className="flex items-center gap-2 font-semibold">
+ <AlertTriangle className="size-4" aria-hidden="true" />
+ {localize('com_ui_skill_warnings')}
+ </div>
+ <ul className="ml-6 list-disc">
+ {warnings.map((w) => (
+ <li key={`${w.field}:${w.code}`}>{w.message}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ <div className="mt-4 flex w-full flex-col gap-4">
+ <Controller
+ name="description"
+ control={control}
+ rules={{
+ required: localize('com_ui_skill_description_required'),
+ maxLength: {
+ value: SKILL_DESCRIPTION_MAX_LENGTH,
+ message: localize('com_ui_skill_description_too_long', {
+ 0: String(SKILL_DESCRIPTION_MAX_LENGTH),
+ }),
+ },
+ }}
+ render={({ field }) => (
+ <div className="flex flex-col">
+ <label
+ htmlFor="skill-description"
+ className="mb-1 text-sm font-medium text-text-secondary"
+ >
+ {localize('com_ui_description')}
+ <span className="ml-0.5 text-red-500">*</span>
+ </label>
+ <TextareaAutosize
+ {...field}
+ id="skill-description"
+ readOnly={readOnly}
+ minRows={2}
+ maxRows={6}
+ aria-label={localize('com_ui_description')}
+ aria-invalid={errors.description ? 'true' : 'false'}
+ aria-describedby={errors.description ? 'skill-description-error' : undefined}
+ className="w-full resize-none rounded-xl border border-border-medium bg-transparent p-3 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"
+ />
+ <p className="mt-1 text-xs text-text-secondary">
+ {localize('com_ui_skill_description_field_hint')}
+ </p>
+ {errors.description && (
+ <p
+ id="skill-description-error"
+ className="mt-1 text-sm text-red-500"
+ role="alert"
+ >
+ {errors.description.message}
+ </p>
+ )}
+ </div>
+ )}
+ />
+
+ <SkillContentEditor
+ name="body"
+ isEditing={isEditingContent}
+ setIsEditing={setIsEditingContent}
+ />
+
+ {!readOnly && (
+ <div className="mt-4 flex items-center justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => reset(values)}
+ disabled={!isDirty}
+ className={cn(!isDirty && 'opacity-50')}
+ >
+ {localize('com_ui_reset')}
+ </Button>
+ <Button
+ type="submit"
+ disabled={saveDisabled}
+ aria-disabled={saveDisabled || undefined}
+ className={cn('w-full sm:w-auto', saveDisabled && 'opacity-50')}
+ >
+ {localize('com_ui_save')}
+ </Button>
+ </div>
+ )}
+ </div>
+ </form>
+ </FormProvider>
+ );
+}
diff --git a/client/src/components/Skills/forms/index.ts b/client/src/components/Skills/forms/index.ts
new file mode 100644
index 0000000000..22bbf8c00e
--- /dev/null
+++ b/client/src/components/Skills/forms/index.ts
@@ -0,0 +1,4 @@
+export { default as CategorySelector } from './CategorySelector';
+export { default as CreateSkillForm } from './CreateSkillForm';
+export { default as SkillContentEditor } from './SkillContentEditor';
+export { default as SkillForm } from './SkillForm';
diff --git a/client/src/components/Skills/index.ts b/client/src/components/Skills/index.ts
new file mode 100644
index 0000000000..dcf7a32137
--- /dev/null
+++ b/client/src/components/Skills/index.ts
@@ -0,0 +1,9 @@
+export * from './buttons';
+export * from './dialogs';
+export * from './display';
+export * from './forms';
+export * from './layouts';
+export * from './lists';
+export * from './sidebar';
+export * from './tree';
+export * from './utils';
diff --git a/client/src/components/Skills/layouts/SkillsView.tsx b/client/src/components/Skills/layouts/SkillsView.tsx
new file mode 100644
index 0000000000..961a275107
--- /dev/null
+++ b/client/src/components/Skills/layouts/SkillsView.tsx
@@ -0,0 +1,115 @@
+import { Navigate, useNavigate, useParams, useLocation, useSearchParams } from 'react-router-dom';
+import { Spinner } from '@librechat/client';
+import { PermissionTypes, Permissions } from 'librechat-data-provider';
+import { useGetSkillByIdQuery } from '~/data-provider';
+import { useHasAccess, useAuthContext, useLocalize } from '~/hooks';
+import SkillFileViewer from '~/components/Skills/display/SkillFileViewer';
+import SkillDetail from '~/components/Skills/display/SkillDetail';
+import SkillState from '~/components/Skills/display/SkillState';
+import { SkillForm } from '~/components/Skills/forms';
+
+/**
+ * Skill detail / edit route content.
+ *
+ * Reader-first: the default `/skills/:skillId` shows the read-only
+ * `SkillDetail` view (rendered markdown, metadata, source toggle).
+ * Edit is reached via `/skills/:skillId/edit` or the Edit button.
+ * Create is a dialog triggered from the sidebar, not a route.
+ */
+export default function SkillsView() {
+ const { skillId } = useParams();
+ const location = useLocation();
+ const localize = useLocalize();
+ const { user, roles } = useAuthContext();
+
+ const hasAccess = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.USE,
+ });
+
+ const isEdit = location.pathname.endsWith('/edit');
+
+ const rolesLoaded = user?.role != null && roles?.[user.role] != null;
+ if (!rolesLoaded) {
+ return (
+ <div className="flex h-full w-full items-center justify-center bg-presentation">
+ <Spinner className="text-text-secondary" aria-label={localize('com_ui_loading')} />
+ </div>
+ );
+ }
+
+ if (!hasAccess) {
+ return <Navigate to="/c/new" replace />;
+ }
+
+ // No skill selected — empty state
+ if (!skillId) {
+ return (
+ <div className="flex h-full w-full flex-col items-center justify-center bg-presentation">
+ <SkillState
+ title={localize('com_ui_skill_no_selection')}
+ description={localize('com_ui_skill_no_selection_desc')}
+ />
+ </div>
+ );
+ }
+
+ return isEdit ? <EditView skillId={skillId} /> : <DetailView skillId={skillId} />;
+}
+
+/** Read-only detail view — the default when clicking a skill. */
+function DetailView({ skillId }: { skillId: string }) {
+ const localize = useLocalize();
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const activeFile = searchParams.get('file');
+ const skillQuery = useGetSkillByIdQuery(skillId, { enabled: !!skillId });
+
+ // Show file content when a file is selected from the sidebar tree
+ if (activeFile) {
+ return (
+ <div className="flex h-full w-full flex-col bg-presentation">
+ <SkillFileViewer skillId={skillId} relativePath={activeFile} />
+ </div>
+ );
+ }
+
+ if (skillQuery.isLoading) {
+ return (
+ <div className="flex h-full w-full items-center justify-center bg-presentation">
+ <Spinner className="text-text-secondary" aria-label={localize('com_ui_loading')} />
+ </div>
+ );
+ }
+
+ if (skillQuery.isError || !skillQuery.data) {
+ return (
+ <div className="flex h-full w-full flex-col bg-presentation">
+ <SkillState
+ variant="error"
+ title={localize('com_ui_skill_not_found')}
+ description={localize('com_ui_skill_not_found_description')}
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full w-full flex-col bg-presentation">
+ <SkillDetail
+ skill={skillQuery.data}
+ onEdit={() => navigate(`/skills/${skillId}/edit`)}
+ onDelete={() => navigate('/skills', { replace: true })}
+ />
+ </div>
+ );
+}
+
+/** Edit form — reached via the Edit button or `/skills/:id/edit` URL. */
+function EditView({ skillId }: { skillId: string }) {
+ return (
+ <div className="flex h-full w-full flex-col overflow-y-auto bg-presentation">
+ <SkillForm skillId={skillId} />
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/layouts/index.ts b/client/src/components/Skills/layouts/index.ts
new file mode 100644
index 0000000000..5c2b36bdc5
--- /dev/null
+++ b/client/src/components/Skills/layouts/index.ts
@@ -0,0 +1 @@
+export { default as SkillsView } from './SkillsView';
diff --git a/client/src/components/Skills/lists/SkillList.tsx b/client/src/components/Skills/lists/SkillList.tsx
new file mode 100644
index 0000000000..5d7314c575
--- /dev/null
+++ b/client/src/components/Skills/lists/SkillList.tsx
@@ -0,0 +1,80 @@
+import { useState } from 'react';
+import { ChevronRight } from 'lucide-react';
+import { useSearchParams } from 'react-router-dom';
+import { Skeleton } from '@librechat/client';
+import type { TSkill } from 'librechat-data-provider';
+import SkillListItem from './SkillListItem';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface SkillListProps {
+ skills: TSkill[];
+ isLoading: boolean;
+ activeSkillId?: string;
+}
+
+/**
+ * Claude.ai–style skill list with a collapsible "Personal skills" section.
+ */
+export default function SkillList({ skills, isLoading, activeSkillId }: SkillListProps) {
+ const localize = useLocalize();
+ const [searchParams] = useSearchParams();
+ const activeFile = searchParams.get('file');
+ const [sectionOpen, setSectionOpen] = useState(true);
+ const [expandedSkillId, setExpandedSkillId] = useState<string | null>(activeSkillId ?? null);
+
+ if (isLoading) {
+ return (
+ <div className="flex flex-col gap-2 px-2 pt-2">
+ <Skeleton className="h-8 w-full rounded-lg" />
+ <Skeleton className="h-8 w-full rounded-lg" />
+ <Skeleton className="h-8 w-full rounded-lg" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-px">
+ {/* Section header */}
+ <div className="flex items-center justify-between px-2 pb-2">
+ <button
+ type="button"
+ onClick={() => setSectionOpen((prev) => !prev)}
+ className="flex cursor-pointer items-center gap-1.5"
+ aria-expanded={sectionOpen}
+ >
+ <ChevronRight
+ className={cn(
+ 'size-3 shrink-0 text-text-secondary transition-transform duration-200',
+ sectionOpen && 'rotate-90',
+ )}
+ aria-hidden="true"
+ />
+ <span className="text-xs text-text-secondary">{localize('com_ui_my_skills')}</span>
+ </button>
+ </div>
+
+ {/* Skill items */}
+ {sectionOpen && (
+ <div className="flex flex-col gap-px">
+ {skills.length === 0 ? (
+ <p className="px-3 py-4 text-center text-xs text-text-secondary">
+ {localize('com_ui_skills_empty')}
+ </p>
+ ) : (
+ skills.map((skill) => (
+ <SkillListItem
+ key={skill._id}
+ skill={skill}
+ isActive={skill._id === activeSkillId}
+ isExpanded={skill._id === expandedSkillId}
+ activeFile={skill._id === activeSkillId ? activeFile : null}
+ onToggleExpand={(id) => setExpandedSkillId((prev) => (prev === id ? null : id))}
+ />
+ ))
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/lists/SkillListItem.tsx b/client/src/components/Skills/lists/SkillListItem.tsx
new file mode 100644
index 0000000000..923f2a1243
--- /dev/null
+++ b/client/src/components/Skills/lists/SkillListItem.tsx
@@ -0,0 +1,360 @@
+import { memo, useState, useMemo, useCallback } from 'react';
+import { ScrollText, ChevronDown, ChevronRight, Folder } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+import { FixedSizeTree } from 'react-vtree';
+import type { FixedSizeNodeData, TreeWalkerValue, TreeWalker } from 'react-vtree';
+import type { TSkill, TSkillFile } from 'librechat-data-provider';
+import { useListSkillFilesQuery } from '~/data-provider';
+import { cn } from '~/utils';
+
+interface SkillListItemProps {
+ skill: TSkill;
+ isActive: boolean;
+ isExpanded: boolean;
+ activeFile: string | null;
+ onToggleExpand: (skillId: string) => void;
+}
+
+/* -------------------------------------------------------------------------- */
+/* Tree data model */
+/* -------------------------------------------------------------------------- */
+
+interface TreeEntry {
+ name: string;
+ type: 'file' | 'folder';
+ path: string;
+ children?: TreeEntry[];
+}
+
+interface FileNodeData extends FixedSizeNodeData {
+ name: string;
+ nodeType: 'file' | 'folder';
+ path: string;
+ depth: number;
+ isLeaf: boolean;
+}
+
+interface NodeMeta {
+ entry: TreeEntry;
+ depth: number;
+}
+
+interface TreeItemCallbacks {
+ onFileClick: (path: string) => void;
+ onToggle: (id: string, isOpen: boolean) => void;
+ activeFile: string | null;
+}
+
+const ITEM_SIZE = 28;
+const MAX_HEIGHT = 350;
+
+/** Build a nested tree from flat TSkillFile paths. Always includes SKILL.md. */
+function buildFileTree(files: TSkillFile[]): TreeEntry[] {
+ const root: TreeEntry[] = [];
+ const folderMap = new Map<string, TreeEntry>();
+
+ root.push({ name: 'SKILL.md', type: 'file', path: 'SKILL.md' });
+
+ const sorted = [...files].sort((a, b) => a.relativePath.localeCompare(b.relativePath));
+
+ for (const file of sorted) {
+ const segments = file.relativePath.split('/').filter(Boolean);
+ if (segments.length === 0) {
+ continue;
+ }
+ if (segments.length === 1) {
+ root.push({ name: segments[0], type: 'file', path: file.relativePath });
+ } else {
+ let parentList = root;
+ let parentPath = '';
+ for (let i = 0; i < segments.length - 1; i++) {
+ const folderName = segments[i];
+ const folderPath = parentPath ? `${parentPath}/${folderName}` : folderName;
+ let folder = folderMap.get(folderPath);
+ if (!folder) {
+ folder = { name: folderName, type: 'folder', path: folderPath, children: [] };
+ folderMap.set(folderPath, folder);
+ parentList.push(folder);
+ }
+ parentList = folder.children!;
+ parentPath = folderPath;
+ }
+ parentList.push({
+ name: segments[segments.length - 1],
+ type: 'file',
+ path: file.relativePath,
+ });
+ }
+ }
+
+ return root;
+}
+
+/** Count visible nodes for dynamic height calculation. */
+function countVisible(entries: TreeEntry[], openIds: Set<string>): number {
+ let n = 0;
+ for (const entry of entries) {
+ n++;
+ if (entry.type === 'folder' && openIds.has(entry.path) && entry.children) {
+ n += countVisible(entry.children, openIds);
+ }
+ }
+ return n;
+}
+
+function getNodeData(entry: TreeEntry, depth: number): TreeWalkerValue<FileNodeData, NodeMeta> {
+ return {
+ data: {
+ id: entry.path,
+ isOpenByDefault: false,
+ name: entry.name,
+ nodeType: entry.type,
+ path: entry.path,
+ depth,
+ isLeaf: entry.type === 'file',
+ },
+ entry,
+ depth,
+ };
+}
+
+/* -------------------------------------------------------------------------- */
+/* Node renderer */
+/* -------------------------------------------------------------------------- */
+
+function FileTreeNode({
+ data,
+ isOpen,
+ setOpen,
+ style,
+ treeData,
+}: {
+ style?: React.CSSProperties;
+ data: FileNodeData;
+ isOpen: boolean;
+ setOpen: (state: boolean) => Promise<void>;
+ treeData?: TreeItemCallbacks;
+}) {
+ const isFolder = data.nodeType === 'folder';
+ const isFileActive = !isFolder && treeData?.activeFile === data.path;
+ const indent = data.depth * 16 + (isFolder ? 8 : 24);
+
+ return (
+ <button
+ type="button"
+ style={{ ...style, paddingLeft: `${indent}px` }}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (isFolder) {
+ const next = !isOpen;
+ setOpen(next);
+ treeData?.onToggle(data.id, next);
+ } else {
+ treeData?.onFileClick(data.path);
+ }
+ }}
+ className={cn(
+ 'flex w-full select-none items-center gap-1.5 rounded-lg text-sm transition-colors',
+ isFileActive
+ ? 'bg-surface-active font-medium text-text-primary'
+ : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',
+ )}
+ aria-expanded={isFolder ? isOpen : undefined}
+ >
+ {isFolder && (
+ <>
+ <ChevronRight
+ className={cn(
+ 'size-3 shrink-0 transition-transform duration-150',
+ isOpen && 'rotate-90',
+ )}
+ aria-hidden="true"
+ />
+ <Folder className="size-3.5 shrink-0" aria-hidden="true" />
+ </>
+ )}
+ <span className="min-w-0 truncate">{data.name}</span>
+ </button>
+ );
+}
+
+/* -------------------------------------------------------------------------- */
+/* Inline virtualized file tree */
+/* -------------------------------------------------------------------------- */
+
+function InlineFileTree({
+ files,
+ activeFile,
+ onFileClick,
+}: {
+ files: TSkillFile[];
+ activeFile: string | null;
+ onFileClick: (path: string) => void;
+}) {
+ const treeEntries = useMemo(() => buildFileTree(files), [files]);
+ const [openIds, setOpenIds] = useState<Set<string>>(new Set());
+
+ const visibleCount = useMemo(() => countVisible(treeEntries, openIds), [treeEntries, openIds]);
+
+ const height = Math.min(visibleCount * ITEM_SIZE, MAX_HEIGHT);
+
+ const handleToggle = useCallback((id: string, isOpen: boolean) => {
+ setOpenIds((prev) => {
+ const next = new Set(prev);
+ if (isOpen) {
+ next.add(id);
+ } else {
+ next.delete(id);
+ }
+ return next;
+ });
+ }, []);
+
+ const callbacks = useMemo<TreeItemCallbacks>(
+ () => ({ onFileClick, onToggle: handleToggle, activeFile }),
+ [onFileClick, handleToggle, activeFile],
+ );
+
+ type WalkerReturn = ReturnType<TreeWalker<FileNodeData, NodeMeta>>;
+
+ const treeWalker = useMemo<TreeWalker<FileNodeData, NodeMeta>>(() => {
+ const walker: TreeWalker<FileNodeData, NodeMeta> = function* (): WalkerReturn {
+ for (const entry of treeEntries) {
+ yield getNodeData(entry, 0);
+ }
+ while (true) {
+ const parent: TreeWalkerValue<FileNodeData, NodeMeta> = yield;
+ for (const child of parent.entry.children ?? []) {
+ yield getNodeData(child, parent.depth + 1);
+ }
+ }
+ };
+ return walker;
+ }, [treeEntries]);
+
+ if (treeEntries.length === 0) {
+ return null;
+ }
+
+ return (
+ <FixedSizeTree<FileNodeData>
+ treeWalker={treeWalker}
+ itemSize={ITEM_SIZE}
+ height={height}
+ width="100%"
+ itemData={callbacks}
+ >
+ {FileTreeNode}
+ </FixedSizeTree>
+ );
+}
+
+/* -------------------------------------------------------------------------- */
+/* Main component */
+/* -------------------------------------------------------------------------- */
+
+function SkillListItem({
+ skill,
+ isActive,
+ isExpanded,
+ activeFile,
+ onToggleExpand,
+}: SkillListItemProps) {
+ const navigate = useNavigate();
+
+ // Fetch files for active skill (always, since cached fileCount may be stale)
+ // or expanded skills. The response is small (metadata only, no content).
+ const filesQuery = useListSkillFilesQuery(skill._id, {
+ enabled: isActive || (skill.fileCount > 0 && isExpanded),
+ });
+ const files = useMemo(() => filesQuery.data?.files ?? [], [filesQuery.data]);
+ const hasFiles = files.length > 0 || skill.fileCount > 0;
+ const expanded = hasFiles && isExpanded;
+
+ const handleSkillClick = useCallback(() => {
+ navigate(`/skills/${skill._id}`);
+ if (hasFiles && !isExpanded) {
+ onToggleExpand(skill._id);
+ }
+ }, [navigate, skill._id, hasFiles, isExpanded, onToggleExpand]);
+
+ const handleChevronClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ onToggleExpand(skill._id);
+ },
+ [skill._id, onToggleExpand],
+ );
+
+ const handleFileClick = useCallback(
+ (path: string) => {
+ navigate(`/skills/${skill._id}?file=${encodeURIComponent(path)}`);
+ },
+ [navigate, skill._id],
+ );
+
+ return (
+ <div className="flex flex-col gap-px">
+ {/* Skill row */}
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={handleSkillClick}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ handleSkillClick();
+ }
+ }}
+ className={cn(
+ 'flex w-full cursor-pointer select-none items-center gap-3 rounded-lg px-3 py-1.5 text-left text-sm text-text-primary transition-colors',
+ isActive && !activeFile && 'bg-surface-active',
+ !isActive && 'hover:bg-surface-hover',
+ )}
+ aria-current={isActive ? 'true' : undefined}
+ aria-expanded={hasFiles ? expanded : undefined}
+ >
+ <span className="flex size-6 shrink-0 items-center justify-center">
+ <span className="flex size-6 items-center justify-center rounded-md border border-border-light bg-surface-primary shadow-sm">
+ <ScrollText className="size-3.5 text-text-secondary" aria-hidden="true" />
+ </span>
+ </span>
+
+ <span className="min-w-0 flex-1">
+ <span className={cn('truncate', isActive && 'font-semibold')}>{skill.name}</span>
+ </span>
+
+ {hasFiles && (
+ <button
+ type="button"
+ onClick={handleChevronClick}
+ className="-mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-text-secondary hover:text-text-primary"
+ aria-label="Toggle files"
+ tabIndex={-1}
+ >
+ <ChevronDown
+ className={cn(
+ 'size-3.5 transition-transform duration-200',
+ !expanded && '-rotate-90',
+ )}
+ />
+ </button>
+ )}
+ </div>
+
+ {/* Inline file tree */}
+ <div
+ className={cn(
+ 'ml-5 overflow-hidden transition-all duration-200 ease-in-out',
+ expanded && hasFiles ? 'opacity-100' : 'max-h-0 opacity-0',
+ )}
+ style={expanded && hasFiles ? { maxHeight: `${MAX_HEIGHT}px` } : undefined}
+ inert={!expanded ? '' : undefined}
+ >
+ <InlineFileTree files={files} activeFile={activeFile} onFileClick={handleFileClick} />
+ </div>
+ </div>
+ );
+}
+
+export default memo(SkillListItem);
diff --git a/client/src/components/Skills/lists/index.ts b/client/src/components/Skills/lists/index.ts
new file mode 100644
index 0000000000..9a8e94e695
--- /dev/null
+++ b/client/src/components/Skills/lists/index.ts
@@ -0,0 +1,2 @@
+export { default as SkillList } from './SkillList';
+export { default as SkillListItem } from './SkillListItem';
diff --git a/client/src/components/Skills/sidebar/FilterSkills.tsx b/client/src/components/Skills/sidebar/FilterSkills.tsx
new file mode 100644
index 0000000000..c2ae229764
--- /dev/null
+++ b/client/src/components/Skills/sidebar/FilterSkills.tsx
@@ -0,0 +1,43 @@
+import React from 'react';
+import { FilterInput } from '@librechat/client';
+import { SystemRoles, PermissionTypes, Permissions } from 'librechat-data-provider';
+import { AdminSettings, CreateSkillMenu } from '~/components/Skills/buttons';
+import { useHasAccess, useAuthContext, useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+export default function FilterSkills({
+ searchTerm,
+ onSearchChange,
+ className = '',
+}: {
+ searchTerm: string;
+ onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ className?: string;
+}) {
+ const localize = useLocalize();
+ const { user } = useAuthContext();
+ const hasCreateAccess = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.CREATE,
+ });
+
+ return (
+ <div className={cn('flex flex-col gap-2', className)}>
+ <div role="search" className="flex items-center gap-2">
+ <FilterInput
+ inputId="skills-filter"
+ label={localize('com_ui_filter_skills_name')}
+ value={searchTerm}
+ onChange={onSearchChange}
+ containerClassName="flex-1"
+ />
+ {hasCreateAccess && <CreateSkillMenu />}
+ </div>
+ {user?.role === SystemRoles.ADMIN && (
+ <div className="flex w-full items-center justify-end">
+ <AdminSettings />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/sidebar/SkillsAccordion.tsx b/client/src/components/Skills/sidebar/SkillsAccordion.tsx
new file mode 100644
index 0000000000..adf92c9aaf
--- /dev/null
+++ b/client/src/components/Skills/sidebar/SkillsAccordion.tsx
@@ -0,0 +1,9 @@
+import SkillsSidePanel from './SkillsSidePanel';
+
+export default function SkillsAccordion() {
+ return (
+ <div className="flex h-auto w-full flex-col">
+ <SkillsSidePanel className="h-auto border-r-0" />
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/sidebar/SkillsSidePanel.tsx b/client/src/components/Skills/sidebar/SkillsSidePanel.tsx
new file mode 100644
index 0000000000..c403b27f8b
--- /dev/null
+++ b/client/src/components/Skills/sidebar/SkillsSidePanel.tsx
@@ -0,0 +1,103 @@
+import { useState, useMemo } from 'react';
+import { Search, X } from 'lucide-react';
+import { useParams } from 'react-router-dom';
+import { PermissionTypes, Permissions } from 'librechat-data-provider';
+import { useListSkillsQuery } from '~/data-provider';
+import { useDebounce, useHasAccess, useLocalize } from '~/hooks';
+import { CreateSkillMenu } from '../buttons';
+import SkillListPanel from '../lists/SkillList';
+import { cn } from '~/utils';
+
+interface SkillsSidePanelProps {
+ className?: string;
+}
+
+/**
+ * Claude.ai–style skills sidebar panel.
+ * Header: "Skills" title + search icon + create menu (+ dropdown).
+ * Body: "My Skills" collapsible section with skill list.
+ */
+export default function SkillsSidePanel({ className }: SkillsSidePanelProps) {
+ const localize = useLocalize();
+ const { skillId: activeSkillId } = useParams();
+ const [searchOpen, setSearchOpen] = useState(false);
+ const [searchTerm, setSearchTerm] = useState('');
+ const debouncedSearch = useDebounce(searchTerm, 250);
+
+ const hasCreateAccess = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.CREATE,
+ });
+
+ const listQuery = useListSkillsQuery({ search: debouncedSearch || undefined, limit: 50 });
+ const skills = useMemo(() => listQuery.data?.skills ?? [], [listQuery.data]);
+
+ const handleCloseSearch = () => {
+ setSearchOpen(false);
+ setSearchTerm('');
+ };
+
+ return (
+ <div
+ className={cn(
+ 'flex h-full w-full flex-col overflow-hidden border-r border-border-light',
+ className,
+ )}
+ >
+ {/* Header — title+icons or inline search input */}
+ <div className="flex items-center justify-between px-4 py-2">
+ {searchOpen ? (
+ <>
+ <div className="relative flex-1">
+ <Search className="absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-text-secondary" />
+ <input
+ type="text"
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder={localize('com_ui_search')}
+ aria-label={localize('com_ui_search_skills')}
+ className="h-8 w-full rounded-md border border-border-light bg-transparent pl-8 pr-3 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring-primary"
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ autoFocus
+ />
+ </div>
+ <button
+ type="button"
+ onClick={handleCloseSearch}
+ className="ml-2 inline-flex size-8 shrink-0 items-center justify-center rounded-md text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary"
+ aria-label={localize('com_ui_close')}
+ >
+ <X className="size-4" />
+ </button>
+ </>
+ ) : (
+ <>
+ <h2 className="truncate text-lg font-bold text-text-primary">
+ {localize('com_ui_skills')}
+ </h2>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => setSearchOpen(true)}
+ className="inline-flex size-8 items-center justify-center rounded-md text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary"
+ aria-label={localize('com_ui_search')}
+ >
+ <Search className="size-4" />
+ </button>
+ {hasCreateAccess && <CreateSkillMenu />}
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Skill list */}
+ <div className="flex-1 overflow-y-auto px-4">
+ <SkillListPanel
+ skills={skills as unknown as import('librechat-data-provider').TSkill[]}
+ isLoading={listQuery.isLoading}
+ activeSkillId={activeSkillId}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/sidebar/index.ts b/client/src/components/Skills/sidebar/index.ts
new file mode 100644
index 0000000000..e567572362
--- /dev/null
+++ b/client/src/components/Skills/sidebar/index.ts
@@ -0,0 +1,3 @@
+export { default as FilterSkills } from './FilterSkills';
+export { default as SkillsAccordion } from './SkillsAccordion';
+export { default as SkillsSidePanel } from './SkillsSidePanel';
diff --git a/client/src/components/Skills/tree/SkillFileEditor.tsx b/client/src/components/Skills/tree/SkillFileEditor.tsx
new file mode 100644
index 0000000000..8691748c1c
--- /dev/null
+++ b/client/src/components/Skills/tree/SkillFileEditor.tsx
@@ -0,0 +1,128 @@
+import { useState, useCallback, useRef } from 'react';
+import { Save, FileText, Circle } from 'lucide-react';
+import { Button, Spinner } from '@librechat/client';
+import { useGetSkillNodeContentQuery, useUpdateSkillNodeContentMutation } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface SkillFileEditorProps {
+ skillId: string;
+ nodeId: string;
+ fileName: string;
+}
+
+export default function SkillFileEditor({ skillId, nodeId, fileName }: SkillFileEditorProps) {
+ const localize = useLocalize();
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const [localContent, setLocalContent] = useState<string | null>(null);
+ const [isDirty, setIsDirty] = useState(false);
+
+ const { data, isLoading } = useGetSkillNodeContentQuery(skillId, nodeId);
+ const updateContent = useUpdateSkillNodeContentMutation(skillId);
+
+ const serverContent = data?.content ?? '';
+ const displayContent = localContent ?? serverContent;
+
+ const prevNodeIdRef = useRef(nodeId);
+ if (prevNodeIdRef.current !== nodeId) {
+ prevNodeIdRef.current = nodeId;
+ setLocalContent(null);
+ setIsDirty(false);
+ }
+
+ const handleChange = useCallback(
+ (e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = e.target.value;
+ setLocalContent(newValue);
+ setIsDirty(newValue !== serverContent);
+ },
+ [serverContent],
+ );
+
+ const handleSave = useCallback(() => {
+ if (!isDirty || localContent === null) {
+ return;
+ }
+ updateContent.mutate(
+ { skillId, nodeId, content: localContent },
+ {
+ onSuccess: () => {
+ setIsDirty(false);
+ },
+ },
+ );
+ }, [skillId, nodeId, localContent, isDirty, updateContent]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 's') {
+ e.preventDefault();
+ handleSave();
+ }
+ },
+ [handleSave],
+ );
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full items-center justify-center bg-presentation">
+ <Spinner className="text-text-tertiary" />
+ </div>
+ );
+ }
+
+ const lineCount = displayContent.split('\n').length;
+
+ return (
+ <div className="flex h-full flex-col bg-presentation" onKeyDown={handleKeyDown}>
+ <div className="flex items-center gap-2 border-b border-border-light px-4 py-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <FileText className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="truncate text-sm font-medium text-text-primary">{fileName}</span>
+ <Circle
+ className={cn(
+ 'size-2 shrink-0 transition-[opacity,color] duration-200',
+ isDirty ? 'fill-current text-yellow-500 opacity-100' : 'opacity-0',
+ )}
+ aria-hidden="true"
+ />
+ </div>
+ <Button
+ type="button"
+ variant={isDirty ? 'submit' : 'outline'}
+ size="sm"
+ disabled={!isDirty || updateContent.isLoading}
+ onClick={handleSave}
+ aria-label={localize('com_ui_save')}
+ className="h-7 gap-1.5 px-2.5 text-xs"
+ >
+ <Save className="size-3" />
+ {localize('com_ui_save')}
+ </Button>
+ </div>
+ <div className="relative flex-1 overflow-hidden">
+ <textarea
+ ref={textareaRef}
+ value={displayContent}
+ onChange={handleChange}
+ spellCheck={false}
+ className={cn(
+ 'size-full resize-none bg-transparent px-4 py-3 font-mono text-[13px] leading-6 text-text-primary outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary',
+ 'selection:bg-blue-500/20',
+ )}
+ aria-label={`${localize('com_ui_edit')} ${fileName}`}
+ />
+ </div>
+ <div className="flex items-center justify-between border-t border-border-light px-4 py-1">
+ <span className="text-[11px] text-text-secondary">
+ {lineCount === 1
+ ? localize('com_ui_line_count', { 0: String(lineCount) })
+ : localize('com_ui_lines_count', { 0: String(lineCount) })}
+ </span>
+ <span className="text-[11px] text-text-secondary">
+ {isDirty ? localize('com_ui_file_modified') : localize('com_ui_saved')}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/tree/SkillFilePreview.tsx b/client/src/components/Skills/tree/SkillFilePreview.tsx
new file mode 100644
index 0000000000..285e2c9414
--- /dev/null
+++ b/client/src/components/Skills/tree/SkillFilePreview.tsx
@@ -0,0 +1,101 @@
+import { Download, FileImage, File } from 'lucide-react';
+import { Button, Spinner } from '@librechat/client';
+import { useGetSkillNodeContentQuery } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface SkillFilePreviewProps {
+ skillId: string;
+ nodeId: string;
+ fileName: string;
+}
+
+export default function SkillFilePreview({ skillId, nodeId, fileName }: SkillFilePreviewProps) {
+ const localize = useLocalize();
+ const { data, isLoading } = useGetSkillNodeContentQuery(skillId, nodeId);
+
+ const isImage = data?.mimeType?.startsWith('image/');
+ const downloadUrl = (data as { downloadUrl?: string } | undefined)?.downloadUrl;
+ const ext = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full items-center justify-center bg-surface-primary">
+ <Spinner className="text-text-tertiary" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full flex-col bg-surface-primary">
+ <div className="flex items-center gap-2 border-b border-border-light px-4 py-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {isImage ? (
+ <FileImage className="size-4 shrink-0 text-pink-400" aria-hidden="true" />
+ ) : (
+ <File className="size-4 shrink-0 text-text-tertiary" aria-hidden="true" />
+ )}
+ <span className="truncate text-sm font-medium text-text-primary">{fileName}</span>
+ {ext && (
+ <span className="rounded bg-surface-tertiary px-1.5 py-0.5 text-[11px] font-medium uppercase tracking-wide text-text-tertiary">
+ {ext}
+ </span>
+ )}
+ </div>
+ {downloadUrl && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 px-2.5 text-xs"
+ asChild
+ >
+ <a
+ href={downloadUrl}
+ download={fileName}
+ aria-label={`${localize('com_ui_download')} ${fileName}`}
+ >
+ <Download className="size-3" />
+ {localize('com_ui_download')}
+ </a>
+ </Button>
+ )}
+ </div>
+ <div
+ className={cn(
+ 'flex flex-1 items-center justify-center overflow-auto p-8',
+ isImage &&
+ 'bg-[repeating-conic-gradient(var(--surface-tertiary)_0%_25%,transparent_0%_50%)] bg-[length:16px_16px]',
+ )}
+ >
+ {isImage && downloadUrl ? (
+ <img
+ src={downloadUrl}
+ alt={fileName}
+ className="max-h-full max-w-full rounded-lg object-contain shadow-lg"
+ />
+ ) : (
+ <div className="flex flex-col items-center gap-3 text-center">
+ <div className="flex size-14 items-center justify-center rounded-2xl bg-surface-tertiary">
+ <File className="size-7 text-text-tertiary" aria-hidden="true" />
+ </div>
+ <div>
+ <p className="text-sm font-medium text-text-primary">{fileName}</p>
+ <p className="mt-0.5 text-xs text-text-tertiary">
+ {data?.mimeType ?? localize('com_ui_unknown_file_type')}
+ </p>
+ </div>
+ {downloadUrl && (
+ <Button type="button" variant="outline" size="sm" className="mt-1 gap-1.5" asChild>
+ <a href={downloadUrl} download={fileName}>
+ <Download className="size-3.5" />
+ {localize('com_ui_download')}
+ </a>
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Skills/tree/TreeToolbar.tsx b/client/src/components/Skills/tree/TreeToolbar.tsx
new file mode 100644
index 0000000000..a2a3d7a1ef
--- /dev/null
+++ b/client/src/components/Skills/tree/TreeToolbar.tsx
@@ -0,0 +1,51 @@
+import { memo } from 'react';
+import { FilePlus, FolderPlus, Upload } from 'lucide-react';
+import { useLocalize } from '~/hooks';
+
+interface TreeToolbarProps {
+ onNewFile: () => void;
+ onNewFolder: () => void;
+ onUpload: () => void;
+}
+
+function TreeToolbar({ onNewFile, onNewFolder, onUpload }: TreeToolbarProps) {
+ const localize = useLocalize();
+
+ return (
+ <div
+ className="flex items-center gap-0.5 px-1.5 py-1"
+ role="toolbar"
+ aria-label={localize('com_ui_skill_content')}
+ >
+ <button
+ type="button"
+ className="rounded-md bg-transparent p-1 text-text-tertiary transition-colors duration-100 hover:bg-surface-hover hover:text-text-secondary"
+ onClick={onNewFile}
+ aria-label={localize('com_ui_skill_new_file')}
+ title={localize('com_ui_skill_new_file')}
+ >
+ <FilePlus className="size-3.5" aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ className="rounded-md bg-transparent p-1 text-text-tertiary transition-colors duration-100 hover:bg-surface-hover hover:text-text-secondary"
+ onClick={onNewFolder}
+ aria-label={localize('com_ui_skill_new_folder')}
+ title={localize('com_ui_skill_new_folder')}
+ >
+ <FolderPlus className="size-3.5" aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ className="rounded-md bg-transparent p-1 text-text-tertiary transition-colors duration-100 hover:bg-surface-hover hover:text-text-secondary"
+ onClick={onUpload}
+ aria-label={localize('com_ui_skill_upload_file')}
+ title={localize('com_ui_skill_upload_file')}
+ >
+ <Upload className="size-3.5" aria-hidden="true" />
+ </button>
+ </div>
+ );
+}
+
+export default memo(TreeToolbar);
diff --git a/client/src/components/Skills/tree/index.ts b/client/src/components/Skills/tree/index.ts
new file mode 100644
index 0000000000..85ae8d2760
--- /dev/null
+++ b/client/src/components/Skills/tree/index.ts
@@ -0,0 +1,3 @@
+export { default as TreeToolbar } from './TreeToolbar';
+export { default as SkillFileEditor } from './SkillFileEditor';
+export { default as SkillFilePreview } from './SkillFilePreview';
diff --git a/client/src/components/Skills/utils/frontmatter.ts b/client/src/components/Skills/utils/frontmatter.ts
new file mode 100644
index 0000000000..634114cf85
--- /dev/null
+++ b/client/src/components/Skills/utils/frontmatter.ts
@@ -0,0 +1,71 @@
+export interface FrontmatterField {
+ key: string;
+ value: string;
+}
+
+export interface ParsedFrontmatter {
+ fields: FrontmatterField[];
+ body: string;
+}
+
+/**
+ * Strip YAML frontmatter (`---\n...\n---`) from markdown content and return
+ * the frontmatter fields as key-value pairs + the remaining body.
+ *
+ * @param raw The raw markdown string (may or may not have frontmatter).
+ * @param skipKeys Optional set of lowercase key names to exclude from fields
+ * (e.g. `new Set(['name', 'description'])` to avoid duplicating
+ * fields already shown in the header).
+ */
+export function parseFrontmatter(raw: string, skipKeys?: Set<string>): ParsedFrontmatter {
+ const trimmed = raw.trim();
+ if (!trimmed.startsWith('---')) {
+ return { fields: [], body: raw };
+ }
+ const after = trimmed.slice(3);
+ const closingIdx = after.indexOf('\n---');
+ if (closingIdx === -1) {
+ return { fields: [], body: raw };
+ }
+
+ const block = after.slice(0, closingIdx);
+ const body = after.slice(closingIdx + 4).trim();
+
+ const fields: FrontmatterField[] = [];
+ const lines = block.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const colon = line.indexOf(':');
+ if (colon === -1) {
+ continue;
+ }
+ const key = line.slice(0, colon).trim();
+ if (!key) {
+ continue;
+ }
+ let value = line.slice(colon + 1).trim();
+ // Consume multi-line YAML list items regardless of whether the key is
+ // skipped — otherwise the list lines leak into subsequent key parsing.
+ if (!value) {
+ const items: string[] = [];
+ while (i + 1 < lines.length) {
+ const next = lines[i + 1];
+ const item = next.trim();
+ if (!item.startsWith('-')) {
+ break;
+ }
+ items.push(item.slice(1).trim());
+ i++;
+ }
+ value = items.join(',');
+ }
+ if (skipKeys?.has(key.toLowerCase())) {
+ continue;
+ }
+ if (value) {
+ fields.push({ key, value });
+ }
+ }
+
+ return { fields, body };
+}
diff --git a/client/src/components/Skills/utils/index.ts b/client/src/components/Skills/utils/index.ts
new file mode 100644
index 0000000000..a93e1715d5
--- /dev/null
+++ b/client/src/components/Skills/utils/index.ts
@@ -0,0 +1,4 @@
+export { parseFrontmatter } from './frontmatter';
+export { parseSkillMd } from './parseSkillMd';
+export type { FrontmatterField, ParsedFrontmatter } from './frontmatter';
+export type { ParsedSkillMd } from './parseSkillMd';
diff --git a/client/src/components/Skills/utils/parseSkillMd.ts b/client/src/components/Skills/utils/parseSkillMd.ts
new file mode 100644
index 0000000000..671cf209d4
--- /dev/null
+++ b/client/src/components/Skills/utils/parseSkillMd.ts
@@ -0,0 +1,33 @@
+import { InvocationMode } from 'librechat-data-provider';
+import { parseFrontmatter } from './frontmatter';
+
+export interface ParsedSkillMd {
+ name: string;
+ description: string;
+ invocationMode: InvocationMode | '';
+}
+
+const VALID_INVOCATION_MODES = new Set<string>(Object.values(InvocationMode));
+
+/**
+ * Parses a SKILL.md file's YAML frontmatter into structured fields.
+ * Delegates to the shared `parseFrontmatter` utility and maps the
+ * generic fields to the typed `ParsedSkillMd` shape.
+ */
+export function parseSkillMd(raw: string): ParsedSkillMd {
+ const { fields } = parseFrontmatter(raw);
+ const result: ParsedSkillMd = { name: '', description: '', invocationMode: '' };
+
+ for (const { key, value } of fields) {
+ const lower = key.toLowerCase();
+ if (lower === 'name') {
+ result.name = value;
+ } else if (lower === 'description') {
+ result.description = value;
+ } else if (lower === 'invocationmode') {
+ result.invocationMode = VALID_INVOCATION_MODES.has(value) ? (value as InvocationMode) : '';
+ }
+ }
+
+ return result;
+}
diff --git a/client/src/data-provider/Favorites.ts b/client/src/data-provider/Favorites.ts
index 655a371363..19571a1887 100644
--- a/client/src/data-provider/Favorites.ts
+++ b/client/src/data-provider/Favorites.ts
@@ -1,4 +1,4 @@
-import { dataService } from 'librechat-data-provider';
+import { dataService, QueryKeys } from 'librechat-data-provider';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type { UseQueryOptions } from '@tanstack/react-query';
import type { FavoritesState } from '~/store/favorites';
@@ -7,7 +7,7 @@ export const useGetFavoritesQuery = (
config?: Omit<UseQueryOptions<FavoritesState, Error>, 'queryKey' | 'queryFn'>,
) => {
return useQuery<FavoritesState, Error>(
- ['favorites'],
+ [QueryKeys.favorites],
() => dataService.getFavorites() as Promise<FavoritesState>,
{
refetchOnWindowFocus: false,
@@ -25,18 +25,51 @@ export const useUpdateFavoritesMutation = () => {
dataService.updateFavorites(favorites) as Promise<FavoritesState>,
{
// Optimistic update to prevent UI flickering when toggling favorites
- // Sets query cache immediately before the request completes
onMutate: async (newFavorites) => {
- await queryClient.cancelQueries(['favorites']);
-
- const previousFavorites = queryClient.getQueryData<FavoritesState>(['favorites']);
- queryClient.setQueryData(['favorites'], newFavorites);
-
+ await queryClient.cancelQueries([QueryKeys.favorites]);
+ const previousFavorites = queryClient.getQueryData<FavoritesState>([QueryKeys.favorites]);
+ queryClient.setQueryData([QueryKeys.favorites], newFavorites);
return { previousFavorites };
},
onError: (_err, _newFavorites, context) => {
if (context?.previousFavorites) {
- queryClient.setQueryData(['favorites'], context.previousFavorites);
+ queryClient.setQueryData([QueryKeys.favorites], context.previousFavorites);
+ }
+ },
+ },
+ );
+};
+
+export const useGetSkillFavoritesQuery = (
+ config?: Omit<UseQueryOptions<string[], Error>, 'queryKey' | 'queryFn'>,
+) => {
+ return useQuery<string[], Error>(
+ [QueryKeys.skillFavorites],
+ () => dataService.getSkillFavorites() as Promise<string[]>,
+ {
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ refetchOnMount: false,
+ ...config,
+ },
+ );
+};
+
+export const useUpdateSkillFavoritesMutation = () => {
+ const queryClient = useQueryClient();
+ return useMutation(
+ (skillFavorites: string[]) =>
+ dataService.updateSkillFavorites(skillFavorites) as Promise<string[]>,
+ {
+ onMutate: async (newFavorites) => {
+ await queryClient.cancelQueries([QueryKeys.skillFavorites]);
+ const previous = queryClient.getQueryData<string[]>([QueryKeys.skillFavorites]);
+ queryClient.setQueryData([QueryKeys.skillFavorites], newFavorites);
+ return { previous };
+ },
+ onError: (_err, _newFavorites, context) => {
+ if (context?.previous !== undefined) {
+ queryClient.setQueryData([QueryKeys.skillFavorites], context.previous);
}
},
},
diff --git a/client/src/data-provider/Skills/index.ts b/client/src/data-provider/Skills/index.ts
index d0720956a0..83306f85bf 100644
--- a/client/src/data-provider/Skills/index.ts
+++ b/client/src/data-provider/Skills/index.ts
@@ -1,2 +1,4 @@
export * from './queries';
export * from './mutations';
+export * from './tree-queries';
+export * from './tree-mutations';
diff --git a/client/src/data-provider/Skills/mutations.ts b/client/src/data-provider/Skills/mutations.ts
index 473d13ff54..ff0b6c1876 100644
--- a/client/src/data-provider/Skills/mutations.ts
+++ b/client/src/data-provider/Skills/mutations.ts
@@ -18,6 +18,7 @@ import type {
UpdateSkillOptions,
DeleteSkillOptions,
UploadSkillFileOptions,
+ ImportSkillOptions,
DeleteSkillFileOptions,
} from 'librechat-data-provider';
@@ -126,6 +127,26 @@ export const useCreateSkillMutation = (
});
};
+/**
+ * Import a skill from a .md, .zip, or .skill file. On success, writes the
+ * new skill into both the detail and list caches.
+ */
+export const useImportSkillMutation = (
+ options?: ImportSkillOptions,
+): UseMutationResult<TSkill, unknown, FormData> => {
+ const queryClient = useQueryClient();
+ const { onSuccess, ...rest } = options ?? {};
+ return useMutation({
+ mutationFn: (formData: FormData) => dataService.importSkill(formData),
+ ...rest,
+ onSuccess: (skill, variables, context) => {
+ queryClient.setQueryData<TSkill>([QueryKeys.skill, skill._id], skill);
+ addSkillToCachedLists(queryClient, skill);
+ if (onSuccess) onSuccess(skill, variables, context);
+ },
+ });
+};
+
/**
* Update a skill. Uses optimistic updates mirroring `useUpdatePromptGroup`:
* - cancel in-flight queries so a late refetch can't clobber the optimistic state
diff --git a/client/src/data-provider/Skills/queries.ts b/client/src/data-provider/Skills/queries.ts
index ecbad1a342..07aa61c0fe 100644
--- a/client/src/data-provider/Skills/queries.ts
+++ b/client/src/data-provider/Skills/queries.ts
@@ -10,6 +10,7 @@ import type {
TSkillListRequest,
TSkillListResponse,
TListSkillFilesResponse,
+ TSkillFileContentResponse,
} from 'librechat-data-provider';
/**
@@ -93,6 +94,13 @@ export const useGetSkillQuery = (
});
};
+/**
+ * Alias kept for the original UI PR's call surface — components that still
+ * import `useGetSkillByIdQuery` (e.g. `SkillsView`, `SkillForm`) resolve to
+ * the same hook as `useGetSkillQuery`.
+ */
+export const useGetSkillByIdQuery = useGetSkillQuery;
+
/**
* List file metadata for a single skill. In phase 1 this returns an empty array for
* skills that have only an inline `SKILL.md`; multi-file skills arrive in phase 2.
@@ -115,3 +123,29 @@ export const useListSkillFilesQuery = (
},
);
};
+
+/**
+ * Fetch a single skill file's content. Returns cached text from the DB when
+ * available; otherwise the backend reads from storage, caches, and returns it.
+ * Uses `staleTime: Infinity` because file content is cached server-side.
+ */
+export const useGetSkillFileContentQuery = (
+ skillId: string | null | undefined,
+ relativePath: string | null | undefined,
+ config?: UseQueryOptions<TSkillFileContentResponse>,
+): QueryObserverResult<TSkillFileContentResponse> => {
+ const enabled = !!skillId && !!relativePath;
+ return useQuery<TSkillFileContentResponse>(
+ [QueryKeys.skillFileContent, skillId, relativePath],
+ () => dataService.getSkillFileContent(skillId as string, relativePath as string),
+ {
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ refetchOnMount: false,
+ retry: false,
+ staleTime: Infinity,
+ ...config,
+ enabled: enabled && (config?.enabled ?? true),
+ },
+ );
+};
diff --git a/client/src/data-provider/Skills/tree-mutations.ts b/client/src/data-provider/Skills/tree-mutations.ts
new file mode 100644
index 0000000000..2b238deb58
--- /dev/null
+++ b/client/src/data-provider/Skills/tree-mutations.ts
@@ -0,0 +1,71 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { QueryKeys, dataService } from 'librechat-data-provider';
+import type { UseMutationResult } from '@tanstack/react-query';
+import type * as t from 'librechat-data-provider';
+
+export const useCreateSkillNodeMutation = (
+ skillId: string,
+ options?: t.CreateSkillNodeOptions,
+): UseMutationResult<t.TSkillNode, Error, t.CreateSkillNodeBody> => {
+ const queryClient = useQueryClient();
+ return useMutation(
+ (body: t.CreateSkillNodeBody) => dataService.createSkillNode(body.skillId, body.data),
+ {
+ onMutate: (variables) => options?.onMutate?.(variables),
+ onError: (error, variables, context) => options?.onError?.(error, variables, context),
+ onSuccess: (newNode, variables, context) => {
+ queryClient.invalidateQueries([QueryKeys.skillTree, skillId]);
+ return options?.onSuccess?.(newNode, variables, context);
+ },
+ },
+ );
+};
+
+export const useUpdateSkillNodeMutation = (
+ skillId: string,
+ options?: t.UpdateSkillNodeOptions,
+): UseMutationResult<t.TSkillNode, Error, t.UpdateSkillNodeVariables> => {
+ const queryClient = useQueryClient();
+ return useMutation((vars: t.UpdateSkillNodeVariables) => dataService.updateSkillNode(vars), {
+ onMutate: (variables) => options?.onMutate?.(variables),
+ onError: (error, variables, context) => options?.onError?.(error, variables, context),
+ onSuccess: (updated, variables, context) => {
+ queryClient.invalidateQueries([QueryKeys.skillTree, skillId]);
+ queryClient.invalidateQueries([QueryKeys.skillNodeContent, skillId, variables.nodeId]);
+ return options?.onSuccess?.(updated, variables, context);
+ },
+ });
+};
+
+export const useDeleteSkillNodeMutation = (
+ skillId: string,
+ options?: t.DeleteSkillNodeOptions,
+): UseMutationResult<void, Error, t.DeleteSkillNodeBody> => {
+ const queryClient = useQueryClient();
+ return useMutation((vars: t.DeleteSkillNodeBody) => dataService.deleteSkillNode(vars), {
+ onMutate: (variables) => options?.onMutate?.(variables),
+ onError: (error, variables, context) => options?.onError?.(error, variables, context),
+ onSuccess: (result, variables, context) => {
+ queryClient.invalidateQueries([QueryKeys.skillTree, skillId]);
+ return options?.onSuccess?.(result, variables, context);
+ },
+ });
+};
+
+export const useUpdateSkillNodeContentMutation = (
+ skillId: string,
+ options?: t.UpdateSkillNodeContentOptions,
+): UseMutationResult<t.TSkillNode, Error, t.UpdateSkillNodeContentVariables> => {
+ const queryClient = useQueryClient();
+ return useMutation(
+ (vars: t.UpdateSkillNodeContentVariables) => dataService.updateSkillNodeContent(vars),
+ {
+ onMutate: (variables) => options?.onMutate?.(variables),
+ onError: (error, variables, context) => options?.onError?.(error, variables, context),
+ onSuccess: (updated, variables, context) => {
+ queryClient.invalidateQueries([QueryKeys.skillNodeContent, skillId, variables.nodeId]);
+ return options?.onSuccess?.(updated, variables, context);
+ },
+ },
+ );
+};
diff --git a/client/src/data-provider/Skills/tree-queries.ts b/client/src/data-provider/Skills/tree-queries.ts
new file mode 100644
index 0000000000..fea74a9d92
--- /dev/null
+++ b/client/src/data-provider/Skills/tree-queries.ts
@@ -0,0 +1,43 @@
+import { useQuery } from '@tanstack/react-query';
+import { QueryKeys, dataService } from 'librechat-data-provider';
+import type { QueryObserverResult, UseQueryOptions } from '@tanstack/react-query';
+import type { TSkillTreeResponse } from 'librechat-data-provider';
+
+export const useGetSkillTreeQuery = (
+ skillId: string | null | undefined,
+ config?: UseQueryOptions<TSkillTreeResponse>,
+): QueryObserverResult<TSkillTreeResponse> => {
+ return useQuery<TSkillTreeResponse>(
+ [QueryKeys.skillTree, skillId],
+ () => dataService.getSkillTree(skillId as string),
+ {
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ refetchOnMount: true,
+ enabled: !!skillId && (config?.enabled ?? true),
+ ...config,
+ },
+ );
+};
+
+export const useGetSkillNodeContentQuery = (
+ skillId: string | null | undefined,
+ nodeId: string | null | undefined,
+ config?: UseQueryOptions<{ content: string; mimeType: string }>,
+): QueryObserverResult<{ content: string; mimeType: string }> => {
+ return useQuery<{ content: string; mimeType: string }>(
+ [QueryKeys.skillNodeContent, skillId, nodeId],
+ () =>
+ dataService.getSkillNodeContent({
+ skillId: skillId as string,
+ nodeId: nodeId as string,
+ }),
+ {
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ refetchOnMount: false,
+ enabled: !!skillId && !!nodeId && (config?.enabled ?? true),
+ ...config,
+ },
+ );
+};
diff --git a/client/src/data-provider/index.ts b/client/src/data-provider/index.ts
index 8d1e38f3a5..4a16792080 100644
--- a/client/src/data-provider/index.ts
+++ b/client/src/data-provider/index.ts
@@ -1,6 +1,7 @@
export * from './Auth';
export * from './Agents';
export * from './Endpoints';
+export * from './Skills';
export * from './Files';
/* Memories */
export * from './Memories';
@@ -12,7 +13,6 @@ export * from './Favorites';
export * from './mutations';
export * from './prompts';
export * from './queries';
-export * from './Skills';
export * from './roles';
export * from './tags';
export * from './MCP';
diff --git a/client/src/data-provider/roles.ts b/client/src/data-provider/roles.ts
index 88c79433f5..bc847fdfc6 100644
--- a/client/src/data-provider/roles.ts
+++ b/client/src/data-provider/roles.ts
@@ -3,6 +3,7 @@ import {
QueryKeys,
dataService,
promptPermissionsSchema,
+ skillPermissionsSchema,
memoryPermissionsSchema,
mcpServersPermissionsSchema,
marketplacePermissionsSchema,
@@ -113,6 +114,42 @@ export const useUpdateAgentPermissionsMutation = (
);
};
+export const useUpdateSkillPermissionsMutation = (
+ options?: t.UpdateSkillPermOptions,
+): UseMutationResult<
+ t.UpdatePermResponse,
+ t.TError | undefined,
+ t.UpdateSkillPermVars,
+ unknown
+> => {
+ const queryClient = useQueryClient();
+ const { onMutate, onSuccess, onError } = options ?? {};
+ return useMutation(
+ (variables) => {
+ skillPermissionsSchema.partial().parse(variables.updates);
+ return dataService.updateSkillPermissions(variables);
+ },
+ {
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries([QueryKeys.roles, variables.roleName]);
+ if (onSuccess) {
+ onSuccess(data, variables, context);
+ }
+ },
+ onError: (...args) => {
+ const error = args[0];
+ if (error != null) {
+ console.error('Failed to update skill permissions:', error);
+ }
+ if (onError) {
+ onError(...args);
+ }
+ },
+ onMutate,
+ },
+ );
+};
+
export const useUpdateMemoryPermissionsMutation = (
options?: t.UpdateMemoryPermOptions,
): UseMutationResult<
diff --git a/client/src/hooks/Generic/useUnsavedChangesPrompt.ts b/client/src/hooks/Generic/useUnsavedChangesPrompt.ts
new file mode 100644
index 0000000000..cf285a0375
--- /dev/null
+++ b/client/src/hooks/Generic/useUnsavedChangesPrompt.ts
@@ -0,0 +1,39 @@
+import { useCallback } from 'react';
+import { unstable_usePrompt, useBeforeUnload } from 'react-router-dom';
+
+interface UseUnsavedChangesPromptParams {
+ when: boolean;
+ message: string;
+}
+
+export default function useUnsavedChangesPrompt({ when, message }: UseUnsavedChangesPromptParams) {
+ useBeforeUnload(
+ useCallback(
+ (event: BeforeUnloadEvent) => {
+ if (!when) {
+ return;
+ }
+
+ event.preventDefault();
+ event.returnValue = message;
+ },
+ [message, when],
+ ),
+ { capture: true },
+ );
+
+ unstable_usePrompt({
+ message,
+ when: ({ currentLocation, nextLocation }) => {
+ if (!when) {
+ return false;
+ }
+
+ return (
+ currentLocation.pathname !== nextLocation.pathname ||
+ currentLocation.search !== nextLocation.search ||
+ currentLocation.hash !== nextLocation.hash
+ );
+ },
+ });
+}
diff --git a/client/src/hooks/Nav/useSideNavLinks.ts b/client/src/hooks/Nav/useSideNavLinks.ts
index f1fbb3f029..ee0212e5e8 100644
--- a/client/src/hooks/Nav/useSideNavLinks.ts
+++ b/client/src/hooks/Nav/useSideNavLinks.ts
@@ -5,6 +5,7 @@ import {
Brain,
Bookmark,
NotebookPen,
+ ScrollText,
ArrowRightToLine,
SlidersHorizontal,
} from 'lucide-react';
@@ -27,6 +28,7 @@ import { MemoryPanel } from '~/components/SidePanel/Memories';
import FilesPanel from '~/components/SidePanel/Files/Panel';
import { useHasAccess, useMCPServerManager } from '~/hooks';
import { PromptsAccordion } from '~/components/Prompts';
+import { SkillsAccordion } from '~/components/Skills';
export default function useSideNavLinks({
hidePanel,
@@ -49,6 +51,10 @@ export default function useSideNavLinks({
permissionType: PermissionTypes.PROMPTS,
permission: Permissions.USE,
});
+ const hasAccessToSkills = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.USE,
+ });
const hasAccessToBookmarks = useHasAccess({
permissionType: PermissionTypes.BOOKMARKS,
permission: Permissions.USE,
@@ -116,6 +122,16 @@ export default function useSideNavLinks({
});
}
+ if (hasAccessToSkills) {
+ links.push({
+ title: 'com_ui_skills',
+ label: '',
+ icon: ScrollText,
+ id: 'skills',
+ Component: SkillsAccordion,
+ });
+ }
+
if (hasAccessToPrompts) {
links.push({
title: 'com_ui_prompts',
@@ -200,6 +216,7 @@ export default function useSideNavLinks({
hasAccessToAgents,
hasAccessToCreateAgents,
hasAccessToPrompts,
+ hasAccessToSkills,
hasAccessToMemories,
hasAccessToReadMemories,
interfaceConfig.parameters,
diff --git a/client/src/hooks/Skills/__tests__/useSkillPermissions.test.ts b/client/src/hooks/Skills/__tests__/useSkillPermissions.test.ts
new file mode 100644
index 0000000000..cc304b07fe
--- /dev/null
+++ b/client/src/hooks/Skills/__tests__/useSkillPermissions.test.ts
@@ -0,0 +1,129 @@
+import { renderHook } from '@testing-library/react';
+import { PermissionBits, SystemRoles } from 'librechat-data-provider';
+import type { TSkill } from 'librechat-data-provider';
+import useSkillPermissions from '../useSkillPermissions';
+
+jest.mock('~/hooks/useResourcePermissions', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+jest.mock('~/hooks/AuthContext', () => ({
+ useAuthContext: jest.fn(),
+}));
+
+import useResourcePermissions from '~/hooks/useResourcePermissions';
+import { useAuthContext } from '~/hooks/AuthContext';
+
+const useResourcePermissionsMock = useResourcePermissions as unknown as jest.Mock;
+const useAuthContextMock = useAuthContext as unknown as jest.Mock;
+
+function makeSkill(overrides: Partial<TSkill> = {}): TSkill {
+ return {
+ _id: 'skill-1',
+ name: 'example-skill',
+ description: 'A skill for the test.',
+ body: '# Overview',
+ author: 'user-owner',
+ authorName: 'Owner',
+ version: 1,
+ source: 'inline',
+ fileCount: 0,
+ createdAt: '2024-01-01T00:00:00.000Z',
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ ...overrides,
+ };
+}
+
+function mockUser(id: string, role: SystemRoles = SystemRoles.USER) {
+ useAuthContextMock.mockReturnValue({
+ user: { id, role },
+ roles: { [role]: {} },
+ });
+}
+
+function mockPermissions(bits: number, isLoading = false) {
+ useResourcePermissionsMock.mockReturnValue({
+ hasPermission: (required: number) => (bits & required) === required,
+ isLoading,
+ permissionBits: bits,
+ });
+}
+
+describe('useSkillPermissions', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('grants full control to the skill author regardless of ACL bits', () => {
+ mockUser('user-owner');
+ mockPermissions(0);
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.isOwner).toBe(true);
+ expect(result.current.canEdit).toBe(true);
+ expect(result.current.canDelete).toBe(true);
+ expect(result.current.canShare).toBe(true);
+ });
+
+ it('grants full control to an admin regardless of ownership', () => {
+ mockUser('user-other', SystemRoles.ADMIN);
+ mockPermissions(0);
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.isOwner).toBe(false);
+ expect(result.current.isAdmin).toBe(true);
+ expect(result.current.canEdit).toBe(true);
+ expect(result.current.canDelete).toBe(true);
+ expect(result.current.canShare).toBe(true);
+ });
+
+ it('grants EDIT without DELETE/SHARE when the ACL only carries EDIT bits', () => {
+ mockUser('user-editor');
+ mockPermissions(PermissionBits.VIEW | PermissionBits.EDIT);
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.isOwner).toBe(false);
+ expect(result.current.isAdmin).toBe(false);
+ expect(result.current.canEdit).toBe(true);
+ expect(result.current.canDelete).toBe(false);
+ expect(result.current.canShare).toBe(false);
+ });
+
+ it('grants view-only when the ACL only carries VIEW bits', () => {
+ mockUser('user-viewer');
+ mockPermissions(PermissionBits.VIEW);
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.canEdit).toBe(false);
+ expect(result.current.canDelete).toBe(false);
+ expect(result.current.canShare).toBe(false);
+ });
+
+ it('grants DELETE + SHARE when the ACL owner role bits are present', () => {
+ mockUser('user-owner-acl');
+ mockPermissions(
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
+ );
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.canEdit).toBe(true);
+ expect(result.current.canDelete).toBe(true);
+ expect(result.current.canShare).toBe(true);
+ });
+
+ it('returns denied permissions while the ACL query is still loading', () => {
+ mockUser('user-other');
+ mockPermissions(0, /* isLoading */ true);
+ const { result } = renderHook(() => useSkillPermissions(makeSkill()));
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.canEdit).toBe(false);
+ expect(result.current.canDelete).toBe(false);
+ expect(result.current.canShare).toBe(false);
+ });
+
+ it('handles an undefined skill gracefully', () => {
+ mockUser('user-other');
+ mockPermissions(0);
+ const { result } = renderHook(() => useSkillPermissions(undefined));
+ expect(result.current.isOwner).toBe(false);
+ expect(result.current.canEdit).toBe(false);
+ expect(result.current.canDelete).toBe(false);
+ expect(result.current.canShare).toBe(false);
+ });
+});
diff --git a/client/src/hooks/Skills/index.ts b/client/src/hooks/Skills/index.ts
new file mode 100644
index 0000000000..335975c5e8
--- /dev/null
+++ b/client/src/hooks/Skills/index.ts
@@ -0,0 +1,2 @@
+export { default as useSkillPermissions } from './useSkillPermissions';
+export type { SkillPermissions } from './useSkillPermissions';
diff --git a/client/src/hooks/Skills/useSkillPermissions.ts b/client/src/hooks/Skills/useSkillPermissions.ts
new file mode 100644
index 0000000000..9157b6ad6a
--- /dev/null
+++ b/client/src/hooks/Skills/useSkillPermissions.ts
@@ -0,0 +1,49 @@
+import { useMemo } from 'react';
+import { ResourceType, PermissionBits, SystemRoles } from 'librechat-data-provider';
+import type { TSkill, TSkillSummary } from 'librechat-data-provider';
+import useResourcePermissions from '~/hooks/useResourcePermissions';
+import { useAuthContext } from '~/hooks/AuthContext';
+
+export interface SkillPermissions {
+ /** Permission query is still resolving */
+ isLoading: boolean;
+ /** Caller is the original author */
+ isOwner: boolean;
+ /** Caller has the ADMIN system role */
+ isAdmin: boolean;
+ /** Caller can modify the skill body/description/name */
+ canEdit: boolean;
+ /** Caller can delete the skill entirely */
+ canDelete: boolean;
+ /** Caller can grant ACL access to other principals */
+ canShare: boolean;
+}
+
+/**
+ * Single source of truth for per-skill permission checks. Used by every
+ * edit/delete/share/file-tree UI so the permission model stays consistent.
+ *
+ * Precedence: owner or admin → full control. Otherwise falls back to the
+ * ACL bits returned by `useResourcePermissions`.
+ */
+export default function useSkillPermissions(
+ skill: TSkill | TSkillSummary | undefined,
+): SkillPermissions {
+ const { user } = useAuthContext();
+ const { hasPermission, isLoading } = useResourcePermissions(ResourceType.SKILL, skill?._id ?? '');
+
+ return useMemo<SkillPermissions>(() => {
+ const isOwner = skill != null && skill.author === user?.id;
+ const isAdmin = user?.role === SystemRoles.ADMIN;
+ const privileged = isOwner || isAdmin;
+
+ return {
+ isLoading,
+ isOwner,
+ isAdmin,
+ canEdit: privileged || hasPermission(PermissionBits.EDIT),
+ canDelete: privileged || hasPermission(PermissionBits.DELETE),
+ canShare: privileged || hasPermission(PermissionBits.SHARE),
+ };
+ }, [skill, user?.id, user?.role, hasPermission, isLoading]);
+}
diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.ts
index 2cab4fa6a9..87c62f1728 100644
--- a/client/src/hooks/index.ts
+++ b/client/src/hooks/index.ts
@@ -15,6 +15,7 @@ export * from './Plugins';
export * from './Prompts';
export * from './Roles';
export * from './Sharing';
+export * from './Skills';
export * from './SSE';
export * from './AuthContext';
export * from './ScreenshotContext';
@@ -28,6 +29,7 @@ export { default as useNewConvo } from './useNewConvo';
export { default as useLocalize } from './useLocalize';
export { default as useFocusTrap } from './useFocusTrap';
export { default as useFavorites } from './useFavorites';
+export { default as useSkillFavorites } from './useSkillFavorites';
export { default as useChatBadges } from './useChatBadges';
export { default as useScrollToRef } from './useScrollToRef';
export { default as useIsActiveItem } from './useIsActiveItem';
diff --git a/client/src/hooks/useSkillFavorites.ts b/client/src/hooks/useSkillFavorites.ts
new file mode 100644
index 0000000000..b88c15df18
--- /dev/null
+++ b/client/src/hooks/useSkillFavorites.ts
@@ -0,0 +1,96 @@
+import { useCallback, useMemo } from 'react';
+import { useToastContext } from '@librechat/client';
+import { useGetSkillFavoritesQuery, useUpdateSkillFavoritesMutation } from '~/data-provider';
+import { getFavoritesErrorMessage, logger } from '~/utils';
+import { useLocalize } from '~/hooks';
+
+/** Maximum number of skills a user can favorite (must match backend MAX_SKILL_FAVORITES). */
+const MAX_SKILL_FAVORITES = 50;
+const EMPTY_FAVORITES: string[] = [];
+
+/**
+ * Hook for managing user skill favorites.
+ *
+ * Skill favorites are a flat array of skill ObjectId strings, persisted via
+ * `/api/user/settings/favorites/skills`. React Query is the single source of
+ * truth — toggling drives an optimistic mutation that updates the cache,
+ * eliminating the need for a separate atom mirror.
+ */
+export default function useSkillFavorites() {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const getQuery = useGetSkillFavoritesQuery();
+ const updateMutation = useUpdateSkillFavoritesMutation();
+
+ const favorites = useMemo(
+ () => (Array.isArray(getQuery.data) ? getQuery.data : EMPTY_FAVORITES),
+ [getQuery.data],
+ );
+
+ const favoriteSet = useMemo(() => new Set(favorites), [favorites]);
+
+ const save = useCallback(
+ async (next: string[]) => {
+ const deduped = Array.from(new Set(next));
+ try {
+ await updateMutation.mutateAsync(deduped);
+ } catch (error) {
+ logger.error('Error updating skill favorites:', error);
+ showToast({
+ message: getFavoritesErrorMessage(error, localize, MAX_SKILL_FAVORITES),
+ status: 'error',
+ });
+ }
+ },
+ [updateMutation, showToast, localize],
+ );
+
+ const isFavorite = useCallback(
+ (skillId: string | undefined | null): boolean => {
+ if (!skillId) {
+ return false;
+ }
+ return favoriteSet.has(skillId);
+ },
+ [favoriteSet],
+ );
+
+ const add = useCallback(
+ (skillId: string) => {
+ if (favoriteSet.has(skillId)) {
+ return;
+ }
+ save([...favorites, skillId]);
+ },
+ [favorites, favoriteSet, save],
+ );
+
+ const remove = useCallback(
+ (skillId: string) => {
+ save(favorites.filter((id) => id !== skillId));
+ },
+ [favorites, save],
+ );
+
+ const toggle = useCallback(
+ (skillId: string) => {
+ if (favoriteSet.has(skillId)) {
+ remove(skillId);
+ } else {
+ add(skillId);
+ }
+ },
+ [favoriteSet, add, remove],
+ );
+
+ return {
+ favorites,
+ isFavorite,
+ add,
+ remove,
+ toggle,
+ isLoading: getQuery.isLoading,
+ isError: getQuery.isError,
+ isUpdating: updateMutation.isLoading,
+ };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 74c668038b..1095c0b6e8 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -656,6 +656,7 @@
"com_ui_add_first_mcp_server": "Create your first MCP server to get started",
"com_ui_add_first_prompt": "Create your first prompt to get started",
"com_ui_add_labels": "Add Labels",
+ "com_ui_add_skills": "Add Skills",
"com_ui_add_mcp": "Add MCP",
"com_ui_add_mcp_server": "Add MCP Server",
"com_ui_add_model_preset": "Add a model or preset for an additional response",
@@ -699,6 +700,8 @@
"com_ui_agent_handoff_prompt_key_placeholder": "Label the content passed (default: 'instructions')",
"com_ui_agent_handoff_prompt_placeholder": "Tell this agent what content to generate and pass to the handoff agent. You need to add something here to enable this feature",
"com_ui_agent_handoffs": "Agent Handoffs",
+ "com_ui_agent_description": "Agent description",
+ "com_ui_agent_name": "Agent name",
"com_ui_agent_name_is_required": "Agent name is required",
"com_ui_agent_recursion_limit": "Max Agent Steps",
"com_ui_agent_recursion_limit_info": "Limits how many steps the agent can take in a run before giving a final response. Default is 25 steps. A step is either an AI API request or a tool usage round. For example, a basic tool interaction takes 3 steps: initial request, tool usage, and follow-up request.",
@@ -883,6 +886,9 @@
"com_ui_create_new_agent": "Create New Agent",
"com_ui_create_prompt": "Create Prompt",
"com_ui_create_prompt_page": "New Prompt Configuration Page",
+ "com_ui_create_skill": "Create Skill",
+ "com_ui_create_skill_upload": "Upload SKILL.md",
+ "com_ui_create_skill_upload_error": "Failed to read the uploaded file",
"com_ui_created": "Created",
"com_ui_creating": "Creating...",
"com_ui_creating_image": "Creating image. May take a moment",
@@ -968,6 +974,7 @@
"com_ui_edit_memory": "Edit Memory",
"com_ui_edit_preset_title": "Edit Preset - {{title}}",
"com_ui_edit_prompt_page": "Edit Prompt Page",
+ "com_ui_edit_skill": "Edit Skill",
"com_ui_editable_message": "Editable Message",
"com_ui_editor_instructions": "Drag the image to reposition • Use zoom slider or buttons to adjust size",
"com_ui_empty_category": "-",
@@ -1012,8 +1019,11 @@
"com_ui_feedback_tag_unjustified_refusal": "Refused without reason",
"com_ui_field_max_length": "{{field}} must be less than {{length}} characters",
"com_ui_field_required": "This field is required",
+ "com_ui_favorite": "Add to favorites",
+ "com_ui_favorites": "Favorites",
"com_ui_file": "File",
"com_ui_file_input_avatar_label": "File input for avatar",
+ "com_ui_file_modified": "Modified",
"com_ui_file_size": "File Size",
"com_ui_file_token_limit": "File Token Limit",
"com_ui_file_token_limit_desc": "Set maximum token limit for file processing to control costs and resource usage",
@@ -1021,6 +1031,7 @@
"com_ui_filter_mcp_servers": "Filter MCP servers by name",
"com_ui_filter_prompts": "Filter Prompts",
"com_ui_filter_prompts_name": "Filter prompts by name",
+ "com_ui_filter_skills_name": "Filter skills by name",
"com_ui_final_touch": "Final touch",
"com_ui_finance": "Finance",
"com_ui_fork": "Fork",
@@ -1089,12 +1100,22 @@
"com_ui_initializing": "Initializing...",
"com_ui_input": "Input",
"com_ui_instructions": "Instructions",
+ "com_ui_invocation_auto": "Auto",
+ "com_ui_invocation_auto_info": "The skill is automatically applied by the agent when relevant to the conversation",
+ "com_ui_invocation_both": "Both",
+ "com_ui_invocation_both_info": "The skill can be triggered automatically or invoked manually by the user",
+ "com_ui_invocation_manual": "Manual",
+ "com_ui_invocation_manual_info": "The skill is only used when explicitly invoked by the user",
+ "com_ui_invocation_mode": "Invocation Mode",
+ "com_ui_invoked_by": "Invoked by",
"com_ui_key": "Key",
"com_ui_key_required": "API key is required",
"com_ui_labels": "Labels",
"com_ui_last_used": "Last used",
"com_ui_late_night": "Happy late night",
"com_ui_latest": "latest",
+ "com_ui_line_count": "{0} line",
+ "com_ui_lines_count": "{0} lines",
"com_ui_latest_footer": "Every AI for Everyone.",
"com_ui_latest_version": "Latest version",
"com_ui_leave_blank_to_keep": "Leave blank to keep existing",
@@ -1202,6 +1223,7 @@
"com_ui_model_spec": "Model Spec",
"com_ui_more_info": "More info",
"com_ui_my_prompts": "My Prompts",
+ "com_ui_my_skills": "My Skills",
"com_ui_name": "Name",
"com_ui_name_sort": "Sort by Name",
"com_ui_navigate_results": "Navigate results",
@@ -1229,6 +1251,7 @@
"com_ui_no_personalization_available": "No personalization options are currently available",
"com_ui_no_prompts_title": "No prompts yet",
"com_ui_no_read_access": "You don't have permission to view memories",
+ "com_ui_no_skills_found": "No skills found",
"com_ui_no_results_found": "No results found",
"com_ui_no_terms_content": "No terms and conditions content to display",
"com_ui_none": "None",
@@ -1330,6 +1353,7 @@
"com_ui_remote_agents_allow_share_public": "Allow users to grant API access to agents to all users",
"com_ui_remote_agents_allow_use": "Allow users to create API keys and query agents remotely",
"com_ui_remove_agent_from_chain": "Remove {{0}} from chain",
+ "com_ui_remove_skill_var": "Remove {{0}}",
"com_ui_remove_user": "Remove {{0}}",
"com_ui_rename": "Rename",
"com_ui_rename_conversation": "Rename Conversation",
@@ -1388,6 +1412,7 @@
"com_ui_search_default_placeholder": "Search by name or email (min 2 chars)",
"com_ui_search_people_placeholder": "Search for people or groups by name or email",
"com_ui_search_result_count": "{{count}} result found",
+ "com_ui_search_skills": "Search skills...",
"com_ui_search_results_count": "{{count}} results found",
"com_ui_searching_files": "Searching your files",
"com_ui_seconds": "seconds",
@@ -1433,6 +1458,62 @@
"com_ui_simple": "Simple",
"com_ui_size": "Size",
"com_ui_size_sort": "Sort by Size",
+ "com_ui_skill": "Skill",
+ "com_ui_skill_content": "Skill Content",
+ "com_ui_skill_content_placeholder": "Enter your skill instructions in markdown...",
+ "com_ui_skill_create_error": "Failed to create skill",
+ "com_ui_skill_create_title": "Create skill",
+ "com_ui_skill_created": "Skill created",
+ "com_ui_skill_delete_confirm": "Are you sure you want to delete \"{{0}}\"? This action cannot be undone.",
+ "com_ui_skill_delete_error": "Failed to delete skill",
+ "com_ui_skill_deleted": "Skill deleted",
+ "com_ui_skill_description_field_hint": "Be specific about when this skill should apply.",
+ "com_ui_skill_description_placeholder": "Apply Acme Corp brand guidelines to presentations and documents...",
+ "com_ui_skill_description_required": "Description is required",
+ "com_ui_skill_description_too_long": "Description must be {{0}} characters or fewer",
+ "com_ui_skill_edit_title": "Edit skill",
+ "com_ui_skill_file_binary": "Binary file — cannot preview inline",
+ "com_ui_skill_file_download": "Download",
+ "com_ui_skill_file_load_error": "Failed to load file content",
+ "com_ui_skill_instructions": "Instructions",
+ "com_ui_skill_instructions_placeholder": "Enter your skill instructions in markdown...",
+ "com_ui_skill_name_invalid": "Use lowercase letters, digits, and dashes only (kebab-case)",
+ "com_ui_skill_name_placeholder": "brand-guidelines",
+ "com_ui_skill_name_required": "Name is required",
+ "com_ui_skill_name_too_long": "Name must be {{0}} characters or fewer",
+ "com_ui_skill_new_file": "New File",
+ "com_ui_skill_new_folder": "New Folder",
+ "com_ui_skill_no_edit_permission": "You don't have permission to edit this skill",
+ "com_ui_skill_no_selection": "Select a skill",
+ "com_ui_skill_no_selection_desc": "Choose a skill from the sidebar to view its details.",
+ "com_ui_skill_not_found": "Skill not found",
+ "com_ui_skill_not_found_description": "It may have been deleted or you may no longer have access to it.",
+ "com_ui_skill_role_editor_desc": "Can view and edit the skill",
+ "com_ui_skill_role_owner_desc": "Full control over the skill including sharing and deletion",
+ "com_ui_skill_role_viewer_desc": "Can view and use the skill but cannot edit it",
+ "com_ui_skill_sr_public": "Public skill",
+ "com_ui_skill_update_conflict": "Another edit was saved before yours. Reloading the latest version.",
+ "com_ui_skill_update_error": "Failed to save skill",
+ "com_ui_skill_updated": "Skill saved",
+ "com_ui_skill_upload": "Upload a skill",
+ "com_ui_skill_upload_drag": "Drag and drop or click to upload",
+ "com_ui_skill_upload_file": "Upload File",
+ "com_ui_skill_upload_req_md": ".md file must contain skill name and description formatted in YAML",
+ "com_ui_skill_upload_req_zip": ".zip or .skill file must include a SKILL.md file",
+ "com_ui_skill_upload_requirements": "File requirements",
+ "com_ui_skill_upload_title": "Upload skill",
+ "com_ui_skill_version": "v{{0}}",
+ "com_ui_skill_view_rendered": "View rendered",
+ "com_ui_skill_view_source": "View source",
+ "com_ui_skill_warnings": "Heads up",
+ "com_ui_skill_write_instructions": "Write skill instructions",
+ "com_ui_skills": "Skills",
+ "com_ui_skills_allow_create": "Allow creating Skills",
+ "com_ui_skills_allow_share": "Allow sharing Skills",
+ "com_ui_skills_allow_share_public": "Allow sharing Skills publicly",
+ "com_ui_skills_allow_use": "Allow using Skills",
+ "com_ui_skills_empty": "No skills yet",
+ "com_ui_sr_public_skill": "Public skill",
"com_ui_special": "special",
"com_ui_special_var_current_date": "Current Date",
"com_ui_special_var_current_datetime": "Current Date & Time",
@@ -1497,7 +1578,9 @@
"com_ui_unarchive_conversation": "Unarchive conversation",
"com_ui_unarchive_error": "Failed to unarchive conversation",
"com_ui_unavailable": "Unavailable",
+ "com_ui_unfavorite": "Remove from favorites",
"com_ui_unknown": "Unknown",
+ "com_ui_unknown_file_type": "Unknown file type",
"com_ui_unpin": "Unpin",
"com_ui_unset": "Unset",
"com_ui_untitled": "Untitled",
@@ -1576,6 +1659,7 @@
"com_ui_x_selected": "{{0}} selected",
"com_ui_xhigh": "Extra High",
"com_ui_yes": "Yes",
+ "com_ui_you": "You",
"com_ui_your_api_key": "Your API Key",
"com_ui_zoom": "Zoom",
"com_ui_zoom_in": "Zoom in",
diff --git a/client/src/routes/index.tsx b/client/src/routes/index.tsx
index be447c70a9..b73aa47b1f 100644
--- a/client/src/routes/index.tsx
+++ b/client/src/routes/index.tsx
@@ -33,6 +33,11 @@ const loadInlinePromptsView = () =>
Component: m.default,
}));
+const loadSkillsView = () =>
+ import('~/components/Skills/layouts/SkillsView').then((m) => ({
+ Component: m.default,
+ }));
+
const baseEl = document.querySelector('base');
const baseHref = baseEl?.getAttribute('href') || '/';
@@ -128,6 +133,18 @@ export const router = createBrowserRouter(
path: 'prompts/:promptId',
lazy: loadInlinePromptsView,
},
+ {
+ path: 'skills',
+ lazy: loadSkillsView,
+ },
+ {
+ path: 'skills/:skillId',
+ lazy: loadSkillsView,
+ },
+ {
+ path: 'skills/:skillId/edit',
+ lazy: loadSkillsView,
+ },
{
path: 'agents',
element: (
diff --git a/client/src/utils/favoritesError.ts b/client/src/utils/favoritesError.ts
new file mode 100644
index 0000000000..b9dcb279d1
--- /dev/null
+++ b/client/src/utils/favoritesError.ts
@@ -0,0 +1,31 @@
+import type { TranslationKeys } from '~/hooks';
+
+type LocalizeFn = (key: TranslationKeys, options?: Record<string, string>) => string;
+
+interface ApiErrorShape {
+ response?: { data?: { code?: string; limit?: number } };
+}
+
+const isApiError = (error: unknown): error is ApiErrorShape =>
+ typeof error === 'object' && error !== null && 'response' in error;
+
+/**
+ * Builds a localized error message from an axios-shaped favorites/skill-favorites
+ * mutation rejection. Recognizes the `MAX_*_EXCEEDED` codes the backend emits and
+ * falls back to the generic error string otherwise.
+ */
+export function getFavoritesErrorMessage(
+ error: unknown,
+ localize: LocalizeFn,
+ defaultLimit: number,
+): string {
+ if (isApiError(error)) {
+ const { code, limit } = error.response?.data ?? {};
+ if (code === 'MAX_FAVORITES_EXCEEDED' || code === 'MAX_SKILL_FAVORITES_EXCEEDED') {
+ return localize('com_ui_max_favorites_reached', {
+ 0: String(limit ?? defaultLimit),
+ });
+ }
+ }
+ return localize('com_ui_error');
+}
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index bba6b5dc78..32f7a67c4a 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -30,6 +30,7 @@ export * from './localStorage';
export * from './promptGroups';
export * from './previewCache';
export * from './groupToolCalls';
+export * from './favoritesError';
export { default as cn } from './cn';
export { default as logger } from './logger';
export { default as getLoginError } from './getLoginError';
diff --git a/client/src/utils/resources.ts b/client/src/utils/resources.ts
index 7a1e2b86c1..a8bdfcb341 100644
--- a/client/src/utils/resources.ts
+++ b/client/src/utils/resources.ts
@@ -60,6 +60,17 @@ export const RESOURCE_CONFIGS: Record<ResourceType, ResourceConfig> = {
`Manage API access for ${name && name !== '' ? `"${name}"` : 'agent'}`,
getCopyUrlMessage: () => 'API endpoint copied',
},
+ [ResourceType.SKILL]: {
+ resourceType: ResourceType.SKILL,
+ defaultViewerRoleId: AccessRoleIds.SKILL_VIEWER,
+ defaultEditorRoleId: AccessRoleIds.SKILL_EDITOR,
+ defaultOwnerRoleId: AccessRoleIds.SKILL_OWNER,
+ getResourceName: (name?: string) => (name && name !== '' ? name : 'skill'),
+ getShareMessage: (name?: string) => (name && name !== '' ? name : 'skill'),
+ getManageMessage: (name?: string) =>
+ `Manage permissions for ${name && name !== '' ? name : 'skill'}`,
+ getCopyUrlMessage: () => 'Skill URL copied',
+ },
};
export const getResourceConfig = (resourceType: ResourceType): ResourceConfig | undefined => {
diff --git a/client/src/utils/roles.ts b/client/src/utils/roles.ts
index 1e8cb3d3b2..3720e91939 100644
--- a/client/src/utils/roles.ts
+++ b/client/src/utils/roles.ts
@@ -60,6 +60,19 @@ export const ROLE_LOCALIZATIONS = {
name: 'com_ui_remote_agent_role_owner' as const,
description: 'com_ui_remote_agent_role_owner_desc' as const,
} as const,
+ // Skill roles — reuse the generic role names; descriptions are skill-specific.
+ skill_viewer: {
+ name: 'com_ui_role_viewer' as const,
+ description: 'com_ui_skill_role_viewer_desc' as const,
+ } as const,
+ skill_editor: {
+ name: 'com_ui_role_editor' as const,
+ description: 'com_ui_skill_role_editor_desc' as const,
+ } as const,
+ skill_owner: {
+ name: 'com_ui_role_owner' as const,
+ description: 'com_ui_skill_role_owner_desc' as const,
+ } as const,
};
/**
diff --git a/client/vite.config.ts b/client/vite.config.ts
index 0422f8bd3d..3c0886ec18 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -157,6 +157,9 @@ export default defineConfig(({ command }) => ({
if (normalizedId.includes('@codesandbox/sandpack')) {
return 'sandpack';
}
+ if (normalizedId.includes('react-vtree')) {
+ return 'react-vtree';
+ }
if (normalizedId.includes('react-virtualized')) {
return 'virtualization';
}
diff --git a/package-lock.json b/package-lock.json
index 7f0724ef0c..482c3924a8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -467,6 +467,7 @@
"react-textarea-autosize": "^8.4.0",
"react-transition-group": "^4.4.5",
"react-virtualized": "^9.22.6",
+ "react-vtree": "^3.0.0",
"recoil": "^0.7.7",
"regenerator-runtime": "^0.14.1",
"rehype-highlight": "^6.0.0",
@@ -33256,6 +33257,13 @@
"cross-fetch": "^3.1.6"
}
},
+ "node_modules/memoize-one": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-5.2.1.tgz",
+ "integrity": "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==",
+ "license": "MIT",
+ "peer": true
+ },
"node_modules/memory-pager": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
@@ -38202,6 +38210,24 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/react-merge-refs": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/react-merge-refs/-/react-merge-refs-3.0.2.tgz",
+ "integrity": "sha512-MSZAfwFfdbEvwkKWP5EI5chuLYnNUxNS7vyS0i1Jp+wtd8J4Ga2ddzhaE68aMol2Z4vCnRM/oGOo1a3V75UPlw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/gregberge"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-refresh": {
"version": "0.18.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
@@ -38388,6 +38414,38 @@
"node": ">=6"
}
},
+ "node_modules/react-vtree": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/react-vtree/-/react-vtree-3.0.0.tgz",
+ "integrity": "sha512-YJoUVzDAJ0Xy0R8nv1JpzxFrrAaa4ZUBtkkis6nE2i7LnA+HI12rMI/mXVRUE8EZN1BTtmvG+l0xzTbCmwFYpQ==",
+ "license": "MIT",
+ "dependencies": {
+ "react-merge-refs": "3.0.2"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18",
+ "react-window": ">= 1.8.5"
+ }
+ },
+ "node_modules/react-window": {
+ "version": "1.8.11",
+ "resolved": "https://registry.npmjs.org/react-window/-/react-window-1.8.11.tgz",
+ "integrity": "sha512-+SRbUVT2scadgFSWx+R1P754xHPEqvcfSfVX10QYg6POOz+WNgkN48pS+BtZNIMGiL1HYrSEiCkwsMS15QogEQ==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/runtime": "^7.0.0",
+ "memoize-one": ">=3.1.1 <6"
+ },
+ "engines": {
+ "node": ">8.0.0"
+ },
+ "peerDependencies": {
+ "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/read-cache": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
diff --git a/packages/api/src/app/permissions.spec.ts b/packages/api/src/app/permissions.spec.ts
index 106ebbb50b..5bafe6148b 100644
--- a/packages/api/src/app/permissions.spec.ts
+++ b/packages/api/src/app/permissions.spec.ts
@@ -106,6 +106,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -153,6 +159,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -264,6 +276,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -311,6 +329,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -408,6 +432,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -455,6 +485,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -565,6 +601,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -612,6 +654,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -709,6 +757,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -756,6 +810,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -858,6 +918,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -893,6 +959,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@@ -1012,6 +1084,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: false,
[Permissions.SHARE_PUBLIC]: false,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: false,
+ [Permissions.SHARE_PUBLIC]: false,
+ },
};
const expectedPermissionsForAdmin = {
@@ -1051,6 +1129,12 @@ describe('updateInterfacePermissions - permissions', () => {
[Permissions.SHARE]: true,
[Permissions.SHARE_PUBLIC]: true,
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: true,
+ [Permissions.CREATE]: true,
+ [Permissions.SHARE]: true,
+ [Permissions.SHARE_PUBLIC]: true,
+ },
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
diff --git a/packages/api/src/app/permissions.ts b/packages/api/src/app/permissions.ts
index 92da1342ce..13005bad4a 100644
--- a/packages/api/src/app/permissions.ts
+++ b/packages/api/src/app/permissions.ts
@@ -45,6 +45,8 @@ function hasExplicitConfig(
return interfaceConfig?.mcpServers !== undefined;
case PermissionTypes.REMOTE_AGENTS:
return interfaceConfig?.remoteAgents !== undefined;
+ case PermissionTypes.SKILLS:
+ return interfaceConfig?.skills !== undefined;
default:
return false;
}
@@ -177,18 +179,26 @@ export async function updateInterfacePermissions({
typeof defaults.prompts === 'boolean' ? defaults.prompts : defaults.prompts?.use;
const agentsDefaultUse =
typeof defaults.agents === 'boolean' ? defaults.agents : defaults.agents?.use;
+ const skillsDefaultUse =
+ typeof defaults.skills === 'boolean' ? defaults.skills : defaults.skills?.use;
const promptsDefaultCreate =
typeof defaults.prompts === 'object' ? defaults.prompts?.create : undefined;
const agentsDefaultCreate =
typeof defaults.agents === 'object' ? defaults.agents?.create : undefined;
+ const skillsDefaultCreate =
+ typeof defaults.skills === 'object' ? defaults.skills?.create : undefined;
const promptsDefaultShare =
typeof defaults.prompts === 'object' ? defaults.prompts?.share : undefined;
const agentsDefaultShare =
typeof defaults.agents === 'object' ? defaults.agents?.share : undefined;
+ const skillsDefaultShare =
+ typeof defaults.skills === 'object' ? defaults.skills?.share : undefined;
const promptsDefaultPublic =
typeof defaults.prompts === 'object' ? defaults.prompts?.public : undefined;
const agentsDefaultPublic =
typeof defaults.agents === 'object' ? defaults.agents?.public : undefined;
+ const skillsDefaultPublic =
+ typeof defaults.skills === 'object' ? defaults.skills?.public : undefined;
const allPermissions: Partial<Record<PermissionTypes, Record<string, boolean | undefined>>> = {
[PermissionTypes.PROMPTS]: {
@@ -431,6 +441,39 @@ export async function updateInterfacePermissions({
}
: {}),
},
+ [PermissionTypes.SKILLS]: {
+ [Permissions.USE]: getPermissionValue(
+ getConfigUse(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.USE],
+ skillsDefaultUse,
+ ),
+ ...((typeof interfaceConfig?.skills === 'object' && 'create' in interfaceConfig.skills) ||
+ !existingPermissions?.[PermissionTypes.SKILLS]
+ ? {
+ [Permissions.CREATE]: getPermissionValue(
+ getConfigCreate(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.CREATE],
+ skillsDefaultCreate ?? true,
+ ),
+ }
+ : {}),
+ ...((typeof interfaceConfig?.skills === 'object' &&
+ ('share' in interfaceConfig.skills || 'public' in interfaceConfig.skills)) ||
+ !existingPermissions?.[PermissionTypes.SKILLS]
+ ? {
+ [Permissions.SHARE]: getPermissionValue(
+ getConfigShare(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.SHARE],
+ skillsDefaultShare,
+ ),
+ [Permissions.SHARE_PUBLIC]: getPermissionValue(
+ getConfigPublic(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.SHARE_PUBLIC],
+ skillsDefaultPublic,
+ ),
+ }
+ : {}),
+ },
};
// Check and add each permission type if needed
@@ -510,6 +553,21 @@ export async function updateInterfacePermissions({
),
},
],
+ [
+ PermissionTypes.SKILLS,
+ {
+ [Permissions.SHARE]: getPermissionValue(
+ getConfigShare(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.SHARE],
+ skillsDefaultShare,
+ ),
+ [Permissions.SHARE_PUBLIC]: getPermissionValue(
+ getConfigPublic(loadedInterface.skills),
+ defaultPerms[PermissionTypes.SKILLS]?.[Permissions.SHARE_PUBLIC],
+ skillsDefaultPublic,
+ ),
+ },
+ ],
];
for (const [permType, shareDefaults] of shareBackfill) {
diff --git a/packages/api/src/skills/binary.ts b/packages/api/src/skills/binary.ts
new file mode 100644
index 0000000000..f2a3a9f96b
--- /dev/null
+++ b/packages/api/src/skills/binary.ts
@@ -0,0 +1,24 @@
+const BINARY_CHECK_BYTES = 8192;
+const BINARY_THRESHOLD = 0.1;
+
+/**
+ * Determine whether a buffer contains binary (non-text) content.
+ * Scans the first 8 KB for null bytes and non-printable character ratio.
+ */
+export function isBinaryBuffer(buffer: Buffer): boolean {
+ const len = Math.min(buffer.length, BINARY_CHECK_BYTES);
+ if (len === 0) {
+ return false;
+ }
+ let nonPrintable = 0;
+ for (let i = 0; i < len; i++) {
+ const byte = buffer[i];
+ if (byte === 0) {
+ return true;
+ }
+ if (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
+ nonPrintable++;
+ }
+ }
+ return nonPrintable / len > BINARY_THRESHOLD;
+}
diff --git a/packages/api/src/skills/handlers.ts b/packages/api/src/skills/handlers.ts
index 3b044a8a9d..ef7c1356db 100644
--- a/packages/api/src/skills/handlers.ts
+++ b/packages/api/src/skills/handlers.ts
@@ -29,8 +29,10 @@ import type {
TDeleteSkillResponse,
TDeleteSkillFileResponse,
TSkillConflictResponse,
+ TSkillFileContentResponse,
} from 'librechat-data-provider';
import type { ServerRequest } from '~/types/http';
+import { isBinaryBuffer } from './binary';
/** Thin error shape the skill methods throw on validation failure. */
type SkillValidationError = Error & { code?: string; issues?: ValidationIssue[] };
@@ -79,6 +81,11 @@ export interface SkillsHandlersDeps {
resourceType: string;
requiredPermissions: number;
}) => Promise<Types.ObjectId[]>;
+ hasPublicPermission: (params: {
+ resourceType: string;
+ resourceId: string | Types.ObjectId;
+ requiredPermissions: number;
+ }) => Promise<boolean>;
grantPermission: (params: {
principalType: string;
principalId: string | Types.ObjectId;
@@ -88,6 +95,23 @@ export interface SkillsHandlersDeps {
grantedBy: string | Types.ObjectId;
}) => Promise<unknown>;
+ /** Single-file lookup + cache update for the download handler. */
+ getSkillFileByPath: (
+ skillId: string | Types.ObjectId,
+ relativePath: string,
+ ) => Promise<(ISkillFile & { _id: Types.ObjectId; content?: string; isBinary?: boolean }) | null>;
+ updateSkillFileContent: (
+ skillId: string | Types.ObjectId,
+ relativePath: string,
+ update: { content?: string; isBinary?: boolean },
+ ) => Promise<void>;
+
+ /** Storage strategy resolver — returns stream/URL helpers keyed by source. */
+ getStrategyFunctions: (source: string) => {
+ getDownloadStream?: (req: ServerRequest, filepath: string) => Promise<NodeJS.ReadableStream>;
+ [key: string]: unknown;
+ };
+
/** ObjectId validation helper from data-schemas. */
isValidObjectIdString: (value: unknown) => boolean;
}
@@ -116,7 +140,11 @@ function serializeSourceMetadata(
}
/** Converts a skill document to the wire format returned by the API. */
-function serializeSkill(skill: ISkill & { _id: Types.ObjectId }, publicSet: Set<string>): TSkill {
+function serializeSkill(
+ skill: ISkill & { _id: Types.ObjectId },
+ isPublic: boolean | Set<string>,
+): TSkill {
+ const pub = typeof isPublic === 'boolean' ? isPublic : isPublic.has(skill._id.toString());
return {
_id: skill._id.toString(),
name: skill.name,
@@ -131,7 +159,7 @@ function serializeSkill(skill: ISkill & { _id: Types.ObjectId }, publicSet: Set<
source: skill.source,
sourceMetadata: serializeSourceMetadata(skill.sourceMetadata),
fileCount: skill.fileCount,
- isPublic: publicSet.has(skill._id.toString()),
+ isPublic: pub,
tenantId: skill.tenantId,
createdAt: (skill.createdAt ?? new Date()).toISOString(),
updatedAt: (skill.updatedAt ?? new Date()).toISOString(),
@@ -140,8 +168,9 @@ function serializeSkill(skill: ISkill & { _id: Types.ObjectId }, publicSet: Set<
function serializeSkillSummary(
skill: ISkillSummary & { _id: Types.ObjectId },
- publicSet: Set<string>,
+ isPublic: boolean | Set<string>,
): TSkillSummary {
+ const pub = typeof isPublic === 'boolean' ? isPublic : isPublic.has(skill._id.toString());
return {
_id: skill._id.toString(),
name: skill.name,
@@ -154,7 +183,7 @@ function serializeSkillSummary(
source: skill.source,
sourceMetadata: serializeSourceMetadata(skill.sourceMetadata),
fileCount: skill.fileCount,
- isPublic: publicSet.has(skill._id.toString()),
+ isPublic: pub,
tenantId: skill.tenantId,
createdAt: (skill.createdAt ?? new Date()).toISOString(),
updatedAt: (skill.updatedAt ?? new Date()).toISOString(),
@@ -241,8 +270,12 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
deleteSkill,
listSkillFiles,
deleteSkillFile,
+ getSkillFileByPath,
+ updateSkillFileContent,
+ getStrategyFunctions,
findAccessibleResources,
findPubliclyAccessibleResources,
+ hasPublicPermission,
grantPermission,
isValidObjectIdString,
} = deps;
@@ -260,6 +293,19 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
}
}
+ /** O(1) public check for a single skill (avoids fetching all public IDs). */
+ async function isSkillPublic(skillId: string | Types.ObjectId): Promise<boolean> {
+ try {
+ return await hasPublicPermission({
+ resourceType: ResourceType.SKILL,
+ resourceId: skillId,
+ requiredPermissions: PermissionBits.VIEW,
+ });
+ } catch {
+ return false;
+ }
+ }
+
async function listHandler(req: ServerRequest, res: Response) {
try {
const user = req.user;
@@ -408,8 +454,8 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
if (!skill) {
return res.status(404).json({ error: 'Skill not found' });
}
- const publicSet = await getPublicSkillIdSet();
- return res.status(200).json(serializeSkill(skill, publicSet));
+ const pub = await isSkillPublic(skill._id);
+ return res.status(200).json(serializeSkill(skill, pub));
} catch (error) {
logger.error('[GET /skills/:id] Error fetching skill', error);
return res.status(500).json({ error: 'Error fetching skill' });
@@ -466,17 +512,17 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
if (result.status === 'not_found') {
return res.status(404).json({ error: 'Skill not found' });
}
- const publicSet = await getPublicSkillIdSet();
+ const pub = await isSkillPublic(id);
if (result.status === 'conflict') {
const conflict: TSkillConflictResponse = {
error: 'skill_version_conflict',
- current: serializeSkill(result.current, publicSet),
+ current: serializeSkill(result.current, pub),
};
return res.status(409).json(conflict);
}
return res
.status(200)
- .json(attachWarnings(serializeSkill(result.skill, publicSet), result.warnings));
+ .json(attachWarnings(serializeSkill(result.skill, pub), result.warnings));
} catch (error) {
logger.error('[PATCH /skills/:id] Error updating skill', error);
return res.status(500).json({ error: 'Error updating skill' });
@@ -489,10 +535,27 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
if (!isValidObjectIdString(id)) {
return res.status(400).json({ error: 'Invalid skill id' });
}
+
+ // Collect file records before deletion so we can clean up storage blobs
+ const files = await listSkillFiles(id);
+
const result = await deleteSkill(id);
if (!result.deleted) {
return res.status(404).json({ error: 'Skill not found' });
}
+
+ // Fire-and-forget blob cleanup for each file
+ for (const file of files) {
+ const { deleteFile: deleteBlob } = getStrategyFunctions(file.source) as {
+ deleteFile?: (r: ServerRequest, f: { filepath: string }) => Promise<void>;
+ };
+ if (deleteBlob) {
+ deleteBlob(req, { filepath: file.filepath }).catch((e) =>
+ logger.error(`[deleteSkill] Blob cleanup failed for ${file.relativePath}:`, e),
+ );
+ }
+ }
+
const response: TDeleteSkillResponse = { id, deleted: true };
return res.status(200).json(response);
} catch (error) {
@@ -513,22 +576,155 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
}
}
- function uploadFileStubHandler(_req: ServerRequest, res: Response) {
- return res.status(501).json({
- error: 'skill_file_upload_not_implemented',
- phase: 2,
- message:
- 'Skill file upload is not yet wired up. This endpoint is a stub reserved for phase 2.',
- });
- }
+ const SAFE_INLINE_MIMES = new Set([
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'image/avif',
+ 'image/bmp',
+ ]);
+ const MAX_TEXT_CACHE_BYTES = 512 * 1024;
+ const MAX_JSON_CONTENT_BYTES = 1024 * 1024;
+
+ async function downloadFileHandler(req: ServerRequest, res: Response) {
+ try {
+ const { id, relativePath } = req.params as { id: string; relativePath: string };
+ let decodedPath: string;
+ try {
+ decodedPath = decodeURIComponent(relativePath);
+ } catch {
+ return res.status(400).json({ error: 'Invalid file path encoding' });
+ }
+
+ // SKILL.md is the skill body itself, not a SkillFile document
+ if (decodedPath === 'SKILL.md') {
+ const skill = await getSkillById(id);
+ if (!skill) {
+ return res.status(404).json({ error: 'Skill not found' });
+ }
+ const response: TSkillFileContentResponse = {
+ content: skill.body,
+ mimeType: 'text/markdown',
+ isBinary: false,
+ relativePath: 'SKILL.md',
+ filename: 'SKILL.md',
+ bytes: Buffer.byteLength(skill.body, 'utf-8'),
+ };
+ return res.status(200).json(response);
+ }
+
+ const file = await getSkillFileByPath(id, decodedPath);
+ if (!file) {
+ return res.status(404).json({ error: 'Skill file not found' });
+ }
+
+ const strategy = getStrategyFunctions(file.source);
+ if (!strategy.getDownloadStream) {
+ return res.status(501).json({ error: 'Download not supported for this storage backend' });
+ }
+
+ // Raw mode: stream the file with its Content-Type (for images / downloads).
+ // Non-image files use Content-Disposition: attachment to prevent stored XSS
+ // (an uploaded .html served inline from this origin would execute scripts
+ // with access to the user's session). Images stay inline for <img> rendering.
+ if (req.query.raw === 'true') {
+ const isImageMime = SAFE_INLINE_MIMES.has(file.mimeType);
+ const safeName = file.filename.replace(/["\\\n\r]/g, '_');
+ res.setHeader('Content-Type', file.mimeType);
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader(
+ 'Content-Disposition',
+ `${isImageMime ? 'inline' : 'attachment'}; filename="${safeName}"`,
+ );
+ const stream = await strategy.getDownloadStream(req, file.filepath);
+ stream.on('error', (err: Error) => {
+ logger.error('[downloadFile] Stream error:', err);
+ if (!res.headersSent) {
+ res.status(500).json({ error: 'Error streaming file' });
+ } else {
+ res.destroy();
+ }
+ });
+ stream.pipe(res);
+ return;
+ }
- function downloadFileStubHandler(_req: ServerRequest, res: Response) {
- return res.status(501).json({
- error: 'skill_file_download_not_implemented',
- phase: 2,
- message:
- 'Skill file download is not yet wired up. This endpoint is a stub reserved for phase 2.',
- });
+ const base: Omit<TSkillFileContentResponse, 'content' | 'isBinary'> = {
+ mimeType: file.mimeType,
+ relativePath: file.relativePath,
+ filename: file.filename,
+ bytes: file.bytes,
+ };
+
+ // Already flagged binary — skip storage entirely
+ if (file.isBinary === true) {
+ return res.status(200).json({ ...base, isBinary: true });
+ }
+
+ // Text content already cached in DB
+ if (file.content != null) {
+ return res.status(200).json({ ...base, isBinary: false, content: file.content });
+ }
+
+ // Single-loop stream read: check binary after 8 KB, then either
+ // destroy (binary) or continue reading (text) in the same iteration.
+ // N.B. breaking out of `for await...of` destroys the stream via
+ // iterator.return(), so we must NOT use break + a second loop.
+ const stream = await strategy.getDownloadStream(req, file.filepath);
+ const chunks: Buffer[] = [];
+ let totalBytes = 0;
+ let binaryChecked = false;
+
+ for await (const raw of stream) {
+ const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
+ chunks.push(chunk);
+ totalBytes += chunk.length;
+
+ if (!binaryChecked && totalBytes >= 8192) {
+ binaryChecked = true;
+ if (isBinaryBuffer(Buffer.concat(chunks))) {
+ updateSkillFileContent(id, decodedPath, { isBinary: true }).catch((e) =>
+ logger.error('[downloadFile] Cache write failed:', e),
+ );
+ if ('destroy' in stream && typeof stream.destroy === 'function') {
+ stream.destroy();
+ }
+ return res.status(200).json({ ...base, isBinary: true });
+ }
+ }
+
+ // Cap JSON response size — files beyond this must use ?raw=true.
+ // No cache write here: { isBinary: false } without content provides
+ // no fast-path on subsequent reads, so we skip the DB round-trip.
+ if (totalBytes > MAX_JSON_CONTENT_BYTES) {
+ if ('destroy' in stream && typeof stream.destroy === 'function') {
+ stream.destroy();
+ }
+ return res.status(200).json({ ...base, isBinary: false });
+ }
+ }
+
+ // File was shorter than 8 KB — check what we have
+ if (!binaryChecked && isBinaryBuffer(Buffer.concat(chunks))) {
+ updateSkillFileContent(id, decodedPath, { isBinary: true }).catch((e) =>
+ logger.error('[downloadFile] Cache write failed:', e),
+ );
+ return res.status(200).json({ ...base, isBinary: true });
+ }
+
+ const buffer = Buffer.concat(chunks);
+ const text = buffer.toString('utf-8');
+ if (buffer.length <= MAX_TEXT_CACHE_BYTES) {
+ updateSkillFileContent(id, decodedPath, { content: text, isBinary: false }).catch((e) =>
+ logger.error('[downloadFile] Cache write failed:', e),
+ );
+ }
+ return res.status(200).json({ ...base, isBinary: false, content: text });
+ } catch (error) {
+ logger.error('[GET /skills/:id/files/:relativePath] Error', error);
+ return res.status(500).json({ error: 'Error downloading skill file' });
+ }
}
async function deleteFileHandler(req: ServerRequest, res: Response) {
@@ -540,10 +736,28 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
} catch {
return res.status(400).json({ error: 'Invalid file path encoding' });
}
+
+ // Look up the file record so we can clean up the storage blob
+ const file = await getSkillFileByPath(id, decodedPath);
+ if (!file) {
+ return res.status(404).json({ error: 'Skill file not found' });
+ }
+
const result = await deleteSkillFile(id, decodedPath);
if (!result.deleted) {
return res.status(404).json({ error: 'Skill file not found' });
}
+
+ // Clean up the stored blob — fire-and-forget so the response isn't delayed
+ const { deleteFile: deleteBlob } = getStrategyFunctions(file.source) as {
+ deleteFile?: (req: ServerRequest, file: { filepath: string }) => Promise<void>;
+ };
+ if (deleteBlob) {
+ deleteBlob(req, { filepath: file.filepath }).catch((e) =>
+ logger.error('[deleteFile] Storage cleanup failed:', e),
+ );
+ }
+
const response: TDeleteSkillFileResponse = {
skillId: id,
relativePath: decodedPath,
@@ -563,8 +777,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps) {
patch: patchHandler,
delete: deleteHandler,
listFiles: listFilesHandler,
- uploadFileStub: uploadFileStubHandler,
- downloadFileStub: downloadFileStubHandler,
+ downloadFile: downloadFileHandler,
deleteFile: deleteFileHandler,
};
}
diff --git a/packages/api/src/skills/import.ts b/packages/api/src/skills/import.ts
new file mode 100644
index 0000000000..ab8ba53420
--- /dev/null
+++ b/packages/api/src/skills/import.ts
@@ -0,0 +1,541 @@
+import crypto from 'crypto';
+import path from 'path';
+import JSZip from 'jszip';
+import { ResourceType, AccessRoleIds, PrincipalType } from 'librechat-data-provider';
+import { logger } from '@librechat/data-schemas';
+import type { Request, Response } from 'express';
+import type { Types } from 'mongoose';
+import type {
+ ISkill,
+ ISkillFile,
+ CreateSkillInput,
+ CreateSkillResult,
+ UpsertSkillFileInput,
+} from '@librechat/data-schemas';
+
+/** Security limits for zip processing. */
+const MAX_ZIP_BYTES = 50 * 1024 * 1024; // 50 MB compressed
+const MAX_DECOMPRESSED_BYTES = 500 * 1024 * 1024; // 500 MB total decompressed
+const MAX_ENTRIES = 500;
+const MAX_SINGLE_FILE_BYTES = 10 * 1024 * 1024; // 10 MB per file
+const SKILL_MD = 'SKILL.md';
+
+/** Strip surrounding YAML quotes (single or double) from a scalar value. */
+function unquoteYaml(value: string): string {
+ if (
+ value.length >= 2 &&
+ ((value[0] === '"' && value[value.length - 1] === '"') ||
+ (value[0] === "'" && value[value.length - 1] === "'"))
+ ) {
+ return value.slice(1, -1);
+ }
+ return value;
+}
+
+/** YAML frontmatter parser — extracts name + description from SKILL.md. */
+function parseFrontmatter(raw: string): { name: string; description: string } {
+ const trimmed = raw.trim();
+ if (!trimmed.startsWith('---')) {
+ return { name: '', description: '' };
+ }
+ const after = trimmed.slice(3);
+ const closingIdx = after.indexOf('\n---');
+ if (closingIdx === -1) {
+ return { name: '', description: '' };
+ }
+ const block = after.slice(0, closingIdx);
+ let name = '';
+ let description = '';
+ for (const line of block.split('\n')) {
+ const colon = line.indexOf(':');
+ if (colon === -1) {
+ continue;
+ }
+ const key = line.slice(0, colon).trim().toLowerCase();
+ const value = unquoteYaml(line.slice(colon + 1).trim());
+ if (key === 'name') {
+ name = value;
+ } else if (key === 'description') {
+ description = value;
+ }
+ }
+ return { name, description };
+}
+
+/** Validates a relative path is safe (no traversal, no absolute paths). */
+function isSafePath(p: string): boolean {
+ if (!p || p.startsWith('/') || p.startsWith('\\')) {
+ return false;
+ }
+ const segments = p.split('/');
+ for (const seg of segments) {
+ if (seg === '..' || seg === '.' || seg === '') {
+ return false;
+ }
+ }
+ return /^[a-zA-Z0-9._\-/]+$/.test(p);
+}
+
+/** Type guard for validation errors thrown by data-schemas. */
+function isValidationError(error: unknown): error is Error & { code: string; issues: unknown[] } {
+ return (
+ error instanceof Error &&
+ (error as Error & { code?: string }).code === 'SKILL_VALIDATION_FAILED'
+ );
+}
+
+/** Type guard for MongoDB duplicate key errors. */
+function isDuplicateKeyError(error: unknown): boolean {
+ return (
+ error != null &&
+ typeof error === 'object' &&
+ 'code' in error &&
+ (error as { code: unknown }).code === 11000
+ );
+}
+
+export interface ImportSkillDeps {
+ createSkill: (data: CreateSkillInput) => Promise<CreateSkillResult>;
+ getSkillById: (id: string | Types.ObjectId) => Promise<(ISkill & { _id: Types.ObjectId }) | null>;
+ deleteSkill: (id: string) => Promise<{ deleted: boolean }>;
+ upsertSkillFile: (row: UpsertSkillFileInput) => Promise<ISkillFile & { _id: Types.ObjectId }>;
+ saveBuffer: (
+ req: Request,
+ params: {
+ userId: string;
+ buffer: Buffer;
+ fileName: string;
+ basePath?: string;
+ isImage?: boolean;
+ },
+ ) => Promise<{ filepath: string; source: string }>;
+ deleteFile?: (
+ req: Request,
+ file: { filepath: string; source: string; [key: string]: unknown },
+ ) => Promise<void>;
+ grantPermission: (params: {
+ principalType: string;
+ principalId: string;
+ resourceType: string;
+ resourceId: Types.ObjectId;
+ accessRoleId: string;
+ grantedBy: string;
+ }) => Promise<unknown>;
+}
+
+interface ServerRequest extends Request {
+ user: {
+ id: string;
+ _id: Types.ObjectId;
+ name?: string;
+ username?: string;
+ tenantId?: string;
+ };
+ file?: Express.Multer.File;
+}
+
+/**
+ * `POST /api/skills/import`
+ *
+ * Accepts a single multipart file (.md, .zip, or .skill).
+ * Creates the skill, then processes additional files individually.
+ * Grants SKILL_OWNER to the uploader.
+ */
+export function createImportHandler(deps: ImportSkillDeps) {
+ return async function importSkillHandler(req: ServerRequest, res: Response) {
+ const { file } = req;
+ if (!file) {
+ return res.status(400).json({ error: 'No file provided' });
+ }
+
+ const ext = path.extname(file.originalname).toLowerCase();
+
+ try {
+ if (ext === '.md') {
+ return await handleMarkdown(req, res, deps, file);
+ }
+ if (ext === '.zip' || ext === '.skill') {
+ return await handleZip(req, res, deps, file);
+ }
+ return res.status(400).json({ error: `Unsupported file type: ${ext}` });
+ } catch (error) {
+ // Surface validation errors as 400 instead of generic 500
+ if (isValidationError(error)) {
+ return res.status(400).json({
+ error: 'Validation failed',
+ issues: error.issues,
+ message: (error.issues as Array<{ message?: string }>)?.map((i) => i.message).join('; '),
+ });
+ }
+ if (isDuplicateKeyError(error)) {
+ return res.status(409).json({ error: 'A skill with this name already exists' });
+ }
+ logger.error('[importSkill] Unhandled error:', error);
+ return res.status(500).json({ error: 'Failed to import skill' });
+ }
+ };
+}
+
+/** Resolve author metadata from the request user. */
+function getAuthorInfo(req: ServerRequest) {
+ const user = req.user;
+ const authorId = (user._id ?? user.id) as unknown as Types.ObjectId;
+ const authorName = user.name ?? user.username ?? 'Unknown';
+ const tenantId = user.tenantId;
+ return { authorId, authorName, tenantId };
+}
+
+/** Grant SKILL_OWNER permission to the uploader. Rolls back skill on failure. */
+async function grantOwnership(
+ deps: ImportSkillDeps,
+ userId: string,
+ skillId: Types.ObjectId,
+): Promise<{ ok: true } | { ok: false; error: string }> {
+ try {
+ await deps.grantPermission({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.SKILL,
+ resourceId: skillId,
+ accessRoleId: AccessRoleIds.SKILL_OWNER,
+ grantedBy: userId,
+ });
+ return { ok: true };
+ } catch (error) {
+ logger.error(`[importSkill] Failed to grant SKILL_OWNER for ${skillId}, rolling back:`, error);
+ try {
+ await deps.deleteSkill(skillId.toString());
+ } catch (rollbackError) {
+ logger.error(`[importSkill] Compensating delete failed for ${skillId}:`, rollbackError);
+ }
+ return { ok: false, error: 'Failed to initialize skill permissions' };
+ }
+}
+
+async function handleMarkdown(
+ req: ServerRequest,
+ res: Response,
+ deps: ImportSkillDeps,
+ file: Express.Multer.File,
+) {
+ const content = file.buffer.toString('utf-8');
+
+ const { name, description } = parseFrontmatter(content);
+ const inferredName =
+ name ||
+ file.originalname
+ .replace(/\.md$/i, '')
+ .replace(/[^a-z0-9-]/gi, '-')
+ .replace(/^-+/, '')
+ .toLowerCase();
+ if (!inferredName) {
+ return res
+ .status(400)
+ .json({ error: 'Could not determine skill name from file or frontmatter' });
+ }
+
+ const { authorId, authorName, tenantId } = getAuthorInfo(req);
+
+ const result = await deps.createSkill({
+ name: inferredName,
+ description: description || inferredName,
+ body: content,
+ author: authorId,
+ authorName,
+ tenantId,
+ });
+
+ const skill = result.skill as ISkill & { _id: Types.ObjectId };
+ const grant = await grantOwnership(deps, req.user.id, skill._id);
+ if (!grant.ok) {
+ return res.status(500).json({ error: grant.error });
+ }
+
+ return res.status(201).json(skill);
+}
+
+async function handleZip(
+ req: ServerRequest,
+ res: Response,
+ deps: ImportSkillDeps,
+ file: Express.Multer.File,
+) {
+ const userId = req.user.id;
+
+ const zipBuffer = file.buffer;
+
+ if (zipBuffer.length > MAX_ZIP_BYTES) {
+ return res.status(400).json({ error: `File too large (max ${MAX_ZIP_BYTES / 1024 / 1024}MB)` });
+ }
+
+ let zip: JSZip;
+ try {
+ zip = await JSZip.loadAsync(zipBuffer);
+ } catch {
+ return res.status(400).json({ error: 'Invalid or corrupt archive' });
+ }
+ const entries = Object.keys(zip.files);
+
+ if (entries.length > MAX_ENTRIES) {
+ return res.status(400).json({ error: `Too many files in archive (max ${MAX_ENTRIES})` });
+ }
+
+ // Find SKILL.md — at root or one level deep
+ let skillMdPath: string | null = null;
+ let prefix = '';
+ for (const p of entries) {
+ const normalized = p.replace(/\\/g, '/');
+ const segments = normalized.split('/').filter(Boolean);
+ const basename = segments[segments.length - 1];
+ if (basename?.toUpperCase() === SKILL_MD.toUpperCase() && segments.length <= 2) {
+ skillMdPath = p;
+ if (segments.length === 2) {
+ prefix = segments[0] + '/';
+ }
+ break;
+ }
+ }
+
+ if (!skillMdPath) {
+ return res.status(400).json({ error: 'Archive must contain a SKILL.md file' });
+ }
+
+ const skillMdEntry = zip.file(skillMdPath);
+ const declaredSize =
+ (skillMdEntry as unknown as { _data?: { uncompressedSize?: number } })?._data
+ ?.uncompressedSize ?? 0;
+ if (declaredSize > MAX_SINGLE_FILE_BYTES) {
+ return res
+ .status(400)
+ .json({ error: `SKILL.md too large (${Math.round(declaredSize / 1024 / 1024)}MB)` });
+ }
+ const skillMdContent = await skillMdEntry?.async('string');
+ if (!skillMdContent) {
+ return res.status(400).json({ error: 'Could not read SKILL.md from archive' });
+ }
+ if (Buffer.byteLength(skillMdContent, 'utf-8') > MAX_SINGLE_FILE_BYTES) {
+ return res.status(400).json({ error: 'SKILL.md exceeds maximum file size' });
+ }
+
+ const { name, description } = parseFrontmatter(skillMdContent);
+ const inferredName =
+ name ||
+ file.originalname
+ .replace(/\.(zip|skill)$/i, '')
+ .replace(/[^a-z0-9-]/gi, '-')
+ .replace(/^-+/, '')
+ .toLowerCase();
+
+ if (!inferredName) {
+ return res.status(400).json({ error: 'Could not determine skill name' });
+ }
+
+ const { authorId, authorName, tenantId } = getAuthorInfo(req);
+
+ // Create the skill (runs full validation: name pattern, description length, etc.)
+ const result = await deps.createSkill({
+ name: inferredName,
+ description: description || inferredName,
+ body: skillMdContent,
+ author: authorId,
+ authorName,
+ tenantId,
+ });
+
+ const skill = result.skill as ISkill & { _id: Types.ObjectId };
+
+ // Grant ownership — rolls back skill on failure
+ const grant = await grantOwnership(deps, userId, skill._id);
+ if (!grant.ok) {
+ return res.status(500).json({ error: grant.error });
+ }
+
+ // Process additional files (everything except SKILL.md)
+ const fileResults: Array<{ path: string; status: 'ok' | 'error'; error?: string }> = [];
+ let totalDecompressed = 0;
+
+ for (const [entryPath, zipEntry] of Object.entries(zip.files)) {
+ if (zipEntry.dir) {
+ continue;
+ }
+ const normalized = entryPath.replace(/\\/g, '/');
+
+ // Strip the prefix if SKILL.md was inside a folder
+ const relativePath =
+ prefix && normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized;
+
+ // Skip SKILL.md (already used as body)
+ if (relativePath.toUpperCase() === SKILL_MD.toUpperCase()) {
+ continue;
+ }
+
+ if (!relativePath || !isSafePath(relativePath)) {
+ fileResults.push({ path: normalized, status: 'error', error: 'Invalid path' });
+ continue;
+ }
+
+ try {
+ // Stream-decompress with hard byte cap. JSZip's nodeStream decompresses
+ // incrementally so we can abort mid-entry without buffering the full file.
+ const perFileLimit = MAX_SINGLE_FILE_BYTES;
+ const cumulativeLimit = MAX_DECOMPRESSED_BYTES - totalDecompressed;
+ const effectiveLimit = Math.min(perFileLimit, cumulativeLimit);
+
+ if (effectiveLimit <= 0) {
+ fileResults.push({
+ path: relativePath,
+ status: 'error',
+ error: 'Cumulative decompressed size exceeds limit',
+ });
+ break;
+ }
+
+ // Stream-decompress with enforced byte limit
+ const chunks: Buffer[] = [];
+ let entryBytes = 0;
+ let exceededLimit = false;
+ const entryStream = zipEntry.nodeStream('nodebuffer');
+
+ await new Promise<void>((resolve, reject) => {
+ entryStream.on('data', (chunk: Buffer) => {
+ entryBytes += chunk.length;
+ if (entryBytes > effectiveLimit) {
+ exceededLimit = true;
+ if ('destroy' in entryStream && typeof entryStream.destroy === 'function') {
+ entryStream.destroy();
+ }
+ resolve();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ entryStream.on('end', resolve);
+ entryStream.on('error', reject);
+ });
+
+ if (exceededLimit) {
+ const reason =
+ entryBytes > perFileLimit
+ ? `File too large (max ${perFileLimit / 1024 / 1024}MB)`
+ : 'Cumulative decompressed size exceeds limit';
+ fileResults.push({ path: relativePath, status: 'error', error: reason });
+ if (entryBytes > cumulativeLimit) {
+ break;
+ }
+ continue;
+ }
+
+ const fileBuffer = Buffer.concat(chunks);
+ totalDecompressed += fileBuffer.length;
+
+ const fileId = crypto.randomUUID();
+ const filename = path.basename(relativePath);
+ const storageFileName = `${fileId}__${filename}`;
+
+ const mimeType = guessMimeType(filename);
+
+ // Save to file storage (strategy-aware)
+ const { filepath, source } = await deps.saveBuffer(req, {
+ userId,
+ buffer: fileBuffer,
+ fileName: storageFileName,
+ basePath: 'uploads',
+ isImage: mimeType.startsWith('image/'),
+ });
+
+ // Upsert the SkillFile DB record (runs path validation internally).
+ // If the DB write fails, clean up the stored blob to prevent orphans.
+ try {
+ await deps.upsertSkillFile({
+ skillId: skill._id,
+ relativePath,
+ file_id: fileId,
+ filename,
+ filepath,
+ source,
+ mimeType,
+ bytes: fileBuffer.length,
+ isExecutable: false,
+ author: authorId,
+ tenantId,
+ });
+ } catch (dbError) {
+ if (deps.deleteFile) {
+ await deps
+ .deleteFile(req, { filepath, source })
+ .catch((e) =>
+ logger.error(`[importSkill] Orphan cleanup failed for ${relativePath}:`, e),
+ );
+ }
+ throw dbError;
+ }
+
+ fileResults.push({ path: relativePath, status: 'ok' });
+ } catch (error) {
+ logger.error(`[importSkill] Failed to process file ${relativePath}:`, error);
+ fileResults.push({
+ path: relativePath,
+ status: 'error',
+ error: (error as Error).message,
+ });
+ }
+ }
+
+ const errors: typeof fileResults = [];
+ let successCount = 0;
+ for (const r of fileResults) {
+ if (r.status === 'ok') {
+ successCount++;
+ } else {
+ errors.push(r);
+ }
+ }
+
+ logger.info(
+ `[importSkill] Imported skill "${inferredName}" with ${successCount} files (${errors.length} errors)`,
+ );
+
+ // Re-read the skill to get the current version/fileCount (bumped by each upsertSkillFile)
+ const refreshed = (await deps.getSkillById(skill._id)) ?? skill;
+
+ return res.status(201).json({
+ ...refreshed,
+ _importSummary: {
+ filesProcessed: fileResults.length,
+ filesSucceeded: successCount,
+ filesFailed: errors.length,
+ errors,
+ },
+ });
+}
+
+const MIME_MAP: Record<string, string> = {
+ '.md': 'text/markdown',
+ '.txt': 'text/plain',
+ '.js': 'application/javascript',
+ '.ts': 'text/typescript',
+ '.jsx': 'text/jsx',
+ '.tsx': 'text/tsx',
+ '.json': 'application/json',
+ '.yaml': 'text/yaml',
+ '.yml': 'text/yaml',
+ '.py': 'text/x-python',
+ '.sh': 'application/x-sh',
+ '.css': 'text/css',
+ '.html': 'text/html',
+ '.xml': 'application/xml',
+ '.csv': 'text/csv',
+ '.toml': 'text/toml',
+ '.ini': 'text/ini',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.svg': 'image/svg+xml',
+ '.webp': 'image/webp',
+ '.pdf': 'application/pdf',
+};
+
+function guessMimeType(filename: string): string {
+ return MIME_MAP[path.extname(filename).toLowerCase()] || 'application/octet-stream';
+}
diff --git a/packages/api/src/skills/index.ts b/packages/api/src/skills/index.ts
index 6c6f862d01..7c374e4c9d 100644
--- a/packages/api/src/skills/index.ts
+++ b/packages/api/src/skills/index.ts
@@ -1 +1,3 @@
+export * from './binary';
export * from './handlers';
+export * from './import';
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 69867a14ef..a0d7821131 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -361,6 +361,7 @@ export const getAllPromptGroups = () => `${prompts()}/all`;
/* Skills */
export const skills = () => `${BASE_URL}/api/skills`;
+export const importSkill = () => `${skills()}/import`;
export const getSkill = (id: string) => `${skills()}/${encodeURIComponent(id)}`;
@@ -386,6 +387,19 @@ export const skillFiles = (id: string) => `${getSkill(id)}/files`;
export const skillFile = (id: string, relativePath: string) =>
`${skillFiles(id)}/${encodeURIComponent(relativePath)}`;
+/**
+ * Skill filesystem tree (phase 2). URL shape mirrors the original UI PR so
+ * the tree hooks keep their call surface. `path` is pre-encoded by the
+ * caller (e.g. `${nodeId}/content`).
+ */
+export const skillTree = ({ skillId, path = '' }: { skillId: string; path?: string }) => {
+ let url = `${BASE_URL}/api/skills/${encodeURIComponent(skillId)}/tree`;
+ if (path) {
+ url += `/${path}`;
+ }
+ return url;
+};
+
/* Roles */
export const roles = () => `${BASE_URL}/api/roles`;
export const adminRoles = () => `${BASE_URL}/api/admin/roles`;
@@ -401,6 +415,7 @@ export const updateRemoteAgentsPermissions = (roleName: string) =>
export const updateMarketplacePermissions = (roleName: string) =>
`${getRole(roleName)}/marketplace`;
+export const updateSkillPermissions = (roleName: string) => `${getRole(roleName)}/skills`;
/* Conversation Tags */
export const conversationTags = (tag?: string) =>
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 7eb779ffc7..99a68de331 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -83,6 +83,7 @@ export const fileStrategiesSchema = z
avatar: fileStorageSchema.optional(),
image: fileStorageSchema.optional(),
document: fileStorageSchema.optional(),
+ skills: fileStorageSchema.optional(),
})
.optional();
@@ -744,6 +745,17 @@ export const interfaceSchema = z
public: z.boolean().optional(),
})
.optional(),
+ skills: z
+ .union([
+ z.boolean(),
+ z.object({
+ use: z.boolean().optional(),
+ create: z.boolean().optional(),
+ share: z.boolean().optional(),
+ public: z.boolean().optional(),
+ }),
+ ])
+ .optional(),
})
.default({
modelSelect: true,
@@ -789,6 +801,12 @@ export const interfaceSchema = z
share: false,
public: false,
},
+ skills: {
+ use: true,
+ create: true,
+ share: false,
+ public: false,
+ },
});
export type TInterfaceConfig = z.infer<typeof interfaceSchema>;
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index e67fbedbf2..17abcf8868 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -34,6 +34,19 @@ export function updateFavorites(favorites: q.TUserFavorite[]): Promise<q.TUserFa
return request.post(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`, { favorites });
}
+/**
+ * Skill favorites (star-a-skill). The backend route is phase 2 — see the
+ * original UI PR for the client surface. Until then, these resolve with
+ * an empty list so the UI hooks compile and the Star button is a no-op.
+ */
+export function getSkillFavorites(): Promise<string[]> {
+ return Promise.resolve([] as string[]);
+}
+
+export function updateSkillFavorites(skillFavorites: string[]): Promise<string[]> {
+ return Promise.resolve(skillFavorites);
+}
+
export function getSharedMessages(shareId: string): Promise<t.TSharedMessagesResponse> {
return request.get(endpoints.shareMessages(shareId));
}
@@ -893,6 +906,22 @@ export function uploadSkillFile(skillId: string, formData: FormData): Promise<sk
return request.postMultiPart(endpoints.skillFiles(skillId), formData);
}
+/**
+ * Import a skill from a .md, .zip, or .skill file. The backend extracts the
+ * archive, creates the skill from SKILL.md, and persists all additional files.
+ * Single HTTP request — no client-side zip processing needed.
+ */
+export function importSkill(formData: FormData): Promise<sk.TSkill> {
+ return request.postMultiPart(endpoints.importSkill(), formData);
+}
+
+export function getSkillFileContent(
+ skillId: string,
+ relativePath: string,
+): Promise<sk.TSkillFileContentResponse> {
+ return request.get(endpoints.skillFile(skillId, relativePath));
+}
+
export function deleteSkillFile(
skillId: string,
relativePath: string,
@@ -900,6 +929,87 @@ export function deleteSkillFile(
return request.delete(endpoints.skillFile(skillId, relativePath));
}
+/* -------------------------------------------------------------------------- */
+/* Skill Tree (nodes) — phase 2 backend */
+/* -------------------------------------------------------------------------- */
+/* These were introduced by the original UI PR and are shipped as stubs in */
+/* phase 1 so the tree UI compiles. Each resolves with empty/no-op data until */
+/* the backend persists a folder hierarchy. The call surface matches what the */
+/* tree hooks expect so wiring real endpoints later is a one-line swap. */
+
+export const getSkillTree = (_skillId: string): Promise<t.TSkillTreeResponse> => {
+ return Promise.resolve({ nodes: [] });
+};
+
+export const createSkillNode = (
+ skillId: string,
+ data: FormData | t.TCreateSkillNodeRequest,
+): Promise<t.TSkillNode> => {
+ const name = data instanceof FormData ? (data.get('name') as string) || 'untitled' : data.name;
+ const type = data instanceof FormData ? 'file' : data.type;
+ const now = new Date().toISOString();
+ return Promise.resolve({
+ _id: `pending-${now}`,
+ skillId,
+ parentId: null,
+ type,
+ name,
+ order: 0,
+ author: '',
+ createdAt: now,
+ updatedAt: now,
+ });
+};
+
+export const updateSkillNode = (variables: {
+ skillId: string;
+ nodeId: string;
+ data: t.TUpdateSkillNodeRequest;
+}): Promise<t.TSkillNode> => {
+ const now = new Date().toISOString();
+ return Promise.resolve({
+ _id: variables.nodeId,
+ skillId: variables.skillId,
+ parentId: variables.data.parentId ?? null,
+ type: 'file',
+ name: variables.data.name ?? '',
+ order: variables.data.order ?? 0,
+ author: '',
+ createdAt: now,
+ updatedAt: now,
+ });
+};
+
+export const deleteSkillNode = (_variables: { skillId: string; nodeId: string }): Promise<void> => {
+ return Promise.resolve();
+};
+
+export const getSkillNodeContent = (_variables: {
+ skillId: string;
+ nodeId: string;
+}): Promise<{ content: string; mimeType: string }> => {
+ return Promise.resolve({ content: '', mimeType: 'text/plain' });
+};
+
+export const updateSkillNodeContent = (variables: {
+ skillId: string;
+ nodeId: string;
+ content: string;
+}): Promise<t.TSkillNode> => {
+ const now = new Date().toISOString();
+ return Promise.resolve({
+ _id: variables.nodeId,
+ skillId: variables.skillId,
+ parentId: null,
+ type: 'file',
+ name: '',
+ order: 0,
+ author: '',
+ createdAt: now,
+ updatedAt: now,
+ });
+};
+
/* Roles */
export function listRoles(): Promise<q.ListRolesResponse> {
return request.get(`${endpoints.adminRoles()}?limit=200`);
@@ -957,6 +1067,12 @@ export function updateMarketplacePermissions(
return request.put(endpoints.updateMarketplacePermissions(variables.roleName), variables.updates);
}
+export function updateSkillPermissions(
+ variables: m.UpdateSkillPermVars,
+): Promise<m.UpdatePermResponse> {
+ return request.put(endpoints.updateSkillPermissions(variables.roleName), variables.updates);
+}
+
/* Tags */
export function getConversationTags(): Promise<t.TConversationTagsResponse> {
return request.get(endpoints.conversationTags());
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 28a568b87e..da923dfd4b 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -69,6 +69,14 @@ export enum QueryKeys {
skills = 'skills',
skill = 'skill',
skillFiles = 'skillFiles',
+ skillFileContent = 'skillFileContent',
+ /* Skill tree (phase 2 — filesystem-style node view) */
+ skillTree = 'skillTree',
+ skillNodeContent = 'skillNodeContent',
+ /* Skill favorites (star a skill in the sidebar) */
+ skillFavorites = 'skillFavorites',
+ /* General user favorites */
+ favorites = 'favorites',
}
// Dynamic query keys that require parameters
@@ -101,4 +109,10 @@ export enum MutationKeys {
enableTwoFactor = 'enableTwoFactor',
verifyTwoFactor = 'verifyTwoFactor',
updateMemoryPreferences = 'updateMemoryPreferences',
+ /* Skill mutations from the original UI PR — tree/node operations are
+ * phase 2 and currently stubbed in the data-service layer. */
+ createSkillNode = 'createSkillNode',
+ updateSkillNode = 'updateSkillNode',
+ deleteSkillNode = 'deleteSkillNode',
+ updateSkillNodeContent = 'updateSkillNodeContent',
}
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 13a824e2ef..a2b3e28d09 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -293,6 +293,7 @@ export const defaultAgentFormValues = {
name: '',
email: '',
},
+ skills: [],
};
export const ImageVisionTool: FunctionTool = {
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index 85ac417f6c..6afd7e36cf 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -677,3 +677,55 @@ export type TBalanceResponse = {
lastRefill?: Date;
refillAmount?: number;
};
+
+/* -------------------------------------------------------------------------- */
+/* Skill UI extensions (not yet persisted — phase 2 backend will fill these) */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * Trigger mode controlling whether an agent auto-invokes a skill, requires
+ * manual selection, or supports both. UI-only for phase 1 — the backend
+ * `TSkill` shape doesn't have `invocationMode` yet. Forms default to `auto`
+ * and the value is discarded on save until the backend lands support.
+ */
+export enum InvocationMode {
+ auto = 'auto',
+ manual = 'manual',
+ both = 'both',
+}
+
+/**
+ * Node in the filesystem-style skill tree view. Phase 1 derives these from
+ * the flat `TSkillFile[]` list; phase 2 will have the backend serve them
+ * directly from a persisted folder hierarchy. Kept in the shared types so
+ * tree UI helpers can be imported from both client and server.
+ */
+export type TSkillNode = {
+ _id: string;
+ skillId: string;
+ parentId: string | null;
+ type: 'file' | 'folder';
+ name: string;
+ fileId?: string;
+ order: number;
+ author: string;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TSkillTreeResponse = {
+ nodes: TSkillNode[];
+};
+
+export type TCreateSkillNodeRequest = {
+ type: 'file' | 'folder';
+ name: string;
+ parentId?: string | null;
+ order?: number;
+};
+
+export type TUpdateSkillNodeRequest = {
+ name?: string;
+ parentId?: string | null;
+ order?: number;
+};
diff --git a/packages/data-provider/src/types/assistants.ts b/packages/data-provider/src/types/assistants.ts
index 2ee30490c3..c3d0dd859c 100644
--- a/packages/data-provider/src/types/assistants.ts
+++ b/packages/data-provider/src/types/assistants.ts
@@ -272,6 +272,8 @@ export type Agent = {
support_contact?: SupportContact;
/** Per-tool configuration options (deferred loading, allowed callers, etc.) */
tool_options?: AgentToolOptions;
+ /** Skill ObjectIds the agent can invoke — phase 2 wiring in AgentConfig. */
+ skills?: string[];
};
export type TAgentsMap = Record<string, Agent | undefined>;
@@ -297,6 +299,7 @@ export type AgentCreateParams = {
| 'category'
| 'support_contact'
| 'tool_options'
+ | 'skills'
>;
export type AgentUpdateParams = {
@@ -321,6 +324,7 @@ export type AgentUpdateParams = {
| 'category'
| 'support_contact'
| 'tool_options'
+ | 'skills'
>;
export type AgentListParams = {
diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.ts
index 1eb8c200d6..69d2916d69 100644
--- a/packages/data-provider/src/types/files.ts
+++ b/packages/data-provider/src/types/files.ts
@@ -28,6 +28,7 @@ export enum FileContext {
image_generation = 'image_generation',
assistants_output = 'assistants_output',
message_attachment = 'message_attachment',
+ skill_file = 'skill_file',
filename = 'filename',
updatedAt = 'updatedAt',
source = 'source',
diff --git a/packages/data-provider/src/types/mutations.ts b/packages/data-provider/src/types/mutations.ts
index 4b2c470821..4f40794527 100644
--- a/packages/data-provider/src/types/mutations.ts
+++ b/packages/data-provider/src/types/mutations.ts
@@ -309,6 +309,8 @@ export type TUpdateSkillContext =
}
| undefined;
+export type ImportSkillOptions = MutationOptions<TSkill, FormData>;
+
export type CreateSkillOptions = MutationOptions<TSkill, TCreateSkill>;
export type UpdateSkillOptions = MutationOptions<
@@ -361,6 +363,13 @@ export type UpdateMCPServersPermOptions = MutationOptions<
types.TError | null | undefined
>;
+export type UpdateSkillPermOptions = MutationOptions<
+ UpdatePermResponse,
+ UpdateSkillPermVars,
+ unknown,
+ types.TError | null | undefined
+>;
+
export type UpdateRemoteAgentsPermVars = UpdatePermVars<p.TRemoteAgentsPermissions>;
export type UpdateRemoteAgentsPermOptions = MutationOptions<
@@ -379,6 +388,34 @@ export type UpdateMarketplacePermOptions = MutationOptions<
types.TError | null | undefined
>;
+/* Skill tree / node mutations (phase 2 — stubbed in data-service) */
+
+export type CreateSkillNodeBody = {
+ skillId: string;
+ data: FormData | types.TCreateSkillNodeRequest;
+};
+export type CreateSkillNodeOptions = MutationOptions<types.TSkillNode, CreateSkillNodeBody>;
+
+export type UpdateSkillNodeVariables = {
+ skillId: string;
+ nodeId: string;
+ data: types.TUpdateSkillNodeRequest;
+};
+export type UpdateSkillNodeOptions = MutationOptions<types.TSkillNode, UpdateSkillNodeVariables>;
+
+export type DeleteSkillNodeBody = { skillId: string; nodeId: string };
+export type DeleteSkillNodeOptions = MutationOptions<void, DeleteSkillNodeBody>;
+
+export type UpdateSkillNodeContentVariables = {
+ skillId: string;
+ nodeId: string;
+ content: string;
+};
+export type UpdateSkillNodeContentOptions = MutationOptions<
+ types.TSkillNode,
+ UpdateSkillNodeContentVariables
+>;
+
export type UpdateConversationTagOptions = MutationOptions<
types.TConversationTag,
types.TConversationTagRequest
diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.ts
index a12321720b..323090f250 100644
--- a/packages/data-provider/src/types/queries.ts
+++ b/packages/data-provider/src/types/queries.ts
@@ -212,6 +212,8 @@ export type TUserFavorite = {
model?: string;
endpoint?: string;
spec?: string;
+ /** Phase 2 — skill favoriting isn't persisted yet, but the shape is reserved. */
+ skillId?: string;
};
/* SharePoint Graph API Token */
diff --git a/packages/data-provider/src/types/skills.ts b/packages/data-provider/src/types/skills.ts
index 8e445d34b3..d7e7f9e4bf 100644
--- a/packages/data-provider/src/types/skills.ts
+++ b/packages/data-provider/src/types/skills.ts
@@ -1,5 +1,27 @@
import type { FileSources } from './files';
+/**
+ * Shared skill validation constants — the single source of truth for name,
+ * description, title, body, and file-path length limits. Mirrored by
+ * `packages/data-schemas/src/methods/skill.ts`; whenever those constants
+ * change, the DB-side validators MUST be updated to match.
+ *
+ * Exported from `librechat-data-provider` so both frontend form validators
+ * and backend Mongoose pre-save hooks use the same literals.
+ */
+export const SKILL_NAME_MAX_LENGTH = 64;
+export const SKILL_DESCRIPTION_MAX_LENGTH = 1024;
+export const SKILL_DESCRIPTION_SHORT_THRESHOLD = 20;
+export const SKILL_DISPLAY_TITLE_MAX_LENGTH = 128;
+export const SKILL_BODY_MAX_LENGTH = 100_000;
+
+/**
+ * Kebab-case identifier pattern: must start with a lowercase letter or digit,
+ * and contain only lowercase letters, digits, and hyphens. Mirrors the
+ * backend `SKILL_NAME_PATTERN` in `packages/data-schemas/src/methods/skill.ts`.
+ */
+export const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
+
/**
* Source of a skill — where its canonical definition came from.
* `inline` means the skill was authored directly in LibreChat.
@@ -81,6 +103,12 @@ export type TSkill = {
body: string;
frontmatter?: SkillFrontmatter;
category?: string;
+ /**
+ * UI-only phase 1. The backend doesn't persist `invocationMode` yet —
+ * forms default to `auto` and discard the value on save. Phase 2 will
+ * move this to a first-class column.
+ */
+ invocationMode?: import('../types').InvocationMode;
author: string;
authorName: string;
version: number;
@@ -124,6 +152,10 @@ export type TSkillFile = {
isExecutable: boolean;
author: string;
tenantId?: string;
+ /** Lazily cached text content (≤ 512 KB). Excluded from list responses. */
+ content?: string;
+ /** Set on first read. `true` prevents repeated storage reads for non-text files. */
+ isBinary?: boolean;
createdAt: string;
updatedAt: string;
};
@@ -206,6 +238,16 @@ export type TDeleteSkillFileResponse = {
deleted: true;
};
+/** Response from GET `/api/skills/:id/files/:relativePath` (JSON mode). */
+export type TSkillFileContentResponse = {
+ content?: string;
+ mimeType: string;
+ isBinary: boolean;
+ relativePath: string;
+ filename: string;
+ bytes: number;
+};
+
/** Variables passed into the skill file upload mutation. */
export type TUploadSkillFileVariables = {
skillId: string;
diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts
index 3cd71cfb20..6f08a09b76 100644
--- a/packages/data-schemas/src/app/interface.ts
+++ b/packages/data-schemas/src/app/interface.ts
@@ -53,6 +53,7 @@ export async function loadDefaultInterface({
peoplePicker: interfaceConfig?.peoplePicker,
marketplace: interfaceConfig?.marketplace,
remoteAgents: interfaceConfig?.remoteAgents,
+ skills: interfaceConfig?.skills,
});
return loadedInterface;
diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.ts
index 9a30ec5fc7..c271b7d4a8 100644
--- a/packages/data-schemas/src/methods/skill.ts
+++ b/packages/data-schemas/src/methods/skill.ts
@@ -1,4 +1,12 @@
-import { ResourceType } from 'librechat-data-provider';
+import {
+ ResourceType,
+ SKILL_NAME_MAX_LENGTH,
+ SKILL_DESCRIPTION_MAX_LENGTH,
+ SKILL_DESCRIPTION_SHORT_THRESHOLD as SKILL_DESCRIPTION_SHORT_THRESHOLD_SHARED,
+ SKILL_DISPLAY_TITLE_MAX_LENGTH,
+ SKILL_BODY_MAX_LENGTH,
+ SKILL_NAME_PATTERN as SKILL_NAME_PATTERN_SHARED,
+} from 'librechat-data-provider';
import type { Model, Types, FilterQuery } from 'mongoose';
import type {
ISkill,
@@ -48,13 +56,13 @@ export function partitionIssues(issues: ValidationIssue[]): {
return { errors, warnings };
}
-const SKILL_NAME_MAX = 64;
-const SKILL_DESCRIPTION_MAX = 1024;
-const SKILL_DESCRIPTION_SHORT_THRESHOLD = 20;
-const SKILL_DISPLAY_TITLE_MAX = 128;
-const SKILL_BODY_MAX = 100_000;
+const SKILL_NAME_MAX = SKILL_NAME_MAX_LENGTH;
+const SKILL_DESCRIPTION_MAX = SKILL_DESCRIPTION_MAX_LENGTH;
+const SKILL_DESCRIPTION_SHORT_THRESHOLD = SKILL_DESCRIPTION_SHORT_THRESHOLD_SHARED;
+const SKILL_DISPLAY_TITLE_MAX = SKILL_DISPLAY_TITLE_MAX_LENGTH;
+const SKILL_BODY_MAX = SKILL_BODY_MAX_LENGTH;
const SKILL_FILE_PATH_MAX = 500;
-const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
+const SKILL_NAME_PATTERN = SKILL_NAME_PATTERN_SHARED;
const RELATIVE_PATH_CHARS = /^[a-zA-Z0-9._\-/]+$/;
/**
@@ -793,7 +801,10 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Sk
skillId: Types.ObjectId | string,
): Promise<Array<ISkillFile & { _id: Types.ObjectId }>> {
const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;
- const rows = await SkillFile.find({ skillId }).sort({ relativePath: 1 }).lean();
+ const rows = await SkillFile.find({ skillId })
+ .select('-content')
+ .sort({ relativePath: 1 })
+ .lean();
return rows as unknown as Array<ISkillFile & { _id: Types.ObjectId }>;
}
@@ -831,6 +842,7 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Sk
author: row.author,
tenantId: row.tenantId,
},
+ $unset: { content: '', isBinary: '' },
},
{ new: false, upsert: true },
).lean();
@@ -865,6 +877,24 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Sk
}
// The public surface is scoped to methods that handlers and the user
+ async function getSkillFileByPath(
+ skillId: Types.ObjectId | string,
+ relativePath: string,
+ ): Promise<(ISkillFile & { _id: Types.ObjectId }) | null> {
+ const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;
+ const row = await SkillFile.findOne({ skillId, relativePath }).lean();
+ return row as unknown as (ISkillFile & { _id: Types.ObjectId }) | null;
+ }
+
+ async function updateSkillFileContent(
+ skillId: Types.ObjectId | string,
+ relativePath: string,
+ update: { content?: string; isBinary?: boolean },
+ ): Promise<void> {
+ const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;
+ await SkillFile.updateOne({ skillId, relativePath }, { $set: update });
+ }
+
// deletion controller actually call. The per-skill file cascade on
// `deleteSkill` is inlined; there's no need for a separate export.
return {
@@ -877,6 +907,8 @@ export function createSkillMethods(mongoose: typeof import('mongoose'), deps: Sk
listSkillFiles,
upsertSkillFile,
deleteSkillFile,
+ getSkillFileByPath,
+ updateSkillFileContent,
};
}
diff --git a/packages/data-schemas/src/schema/skillFile.ts b/packages/data-schemas/src/schema/skillFile.ts
index af2371894f..d8c11cbf09 100644
--- a/packages/data-schemas/src/schema/skillFile.ts
+++ b/packages/data-schemas/src/schema/skillFile.ts
@@ -90,6 +90,12 @@ const skillFileSchema: Schema<ISkillFileDocument> = new Schema(
type: String,
index: true,
},
+ content: {
+ type: String,
+ },
+ isBinary: {
+ type: Boolean,
+ },
},
{
timestamps: true,
diff --git a/packages/data-schemas/src/types/skill.ts b/packages/data-schemas/src/types/skill.ts
index afaa1b5c95..b1d120ff23 100644
--- a/packages/data-schemas/src/types/skill.ts
+++ b/packages/data-schemas/src/types/skill.ts
@@ -90,6 +90,10 @@ export interface ISkillFile {
isExecutable: boolean;
author: Types.ObjectId;
tenantId?: string;
+ /** Lazily cached text content (≤ 512 KB). Populated on first read; cleared on re-upload. */
+ content?: string;
+ /** Set on first read. `true` prevents repeated storage reads for non-text files. */
+ isBinary?: boolean;
createdAt?: Date;
updatedAt?: Date;
}