🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support agent skills (#12424)
Arvin Xue95f7419b9b2
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 9c7d5bcf2a9..ef3ba0b1ef2 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -170,6 +170,14 @@"builtins.lobe-page-agent.apiName.updateNode": "Update node","builtins.lobe-page-agent.apiName.wrapNodes": "Wrap nodes","builtins.lobe-page-agent.title": "Page",+ "builtins.lobe-skills.apiName.execScript": "Run Script",+ "builtins.lobe-skills.apiName.exportFile": "Export File",+ "builtins.lobe-skills.apiName.importFromMarket": "Import from Market",+ "builtins.lobe-skills.apiName.importSkill": "Import Skill",+ "builtins.lobe-skills.apiName.readReference": "Read Reference",+ "builtins.lobe-skills.apiName.runSkill": "Activate Skill",+ "builtins.lobe-skills.apiName.searchSkill": "Search Skills",+ "builtins.lobe-skills.title": "Skills","builtins.lobe-user-memory.apiName.addContextMemory": "Add context memory","builtins.lobe-user-memory.apiName.addExperienceMemory": "Add experience memory","builtins.lobe-user-memory.apiName.addIdentityMemory": "Add identity memory",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex aac2669140b..3d48a2b0a9a 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -129,6 +129,42 @@"agentInfoDescription.role.title": "Agent Profile","agentInfoDescription.value.unset": "Not Set","agentInfoDescription.value.untitled": "Untitled Agent",+ "agentSkillDetail.addedAt": "Added",+ "agentSkillDetail.publishedAt": "Published",+ "agentSkillDetail.repository": "GitHub Repository",+ "agentSkillDetail.skillContent": "Skill Content",+ "agentSkillDetail.sourceUrl": "Skill Import Source",+ "agentSkillDetail.updatedAt": "Updated",+ "agentSkillEdit.descriptionDesc": "A brief summary of what the skill does, helping the agent understand when to use it",+ "agentSkillEdit.fileReadonly": "This file is read-only. Only skill description and instructions can be edited.",+ "agentSkillEdit.instructions": "Instructions",+ "agentSkillEdit.instructionsDesc": "The core instructions in Markdown that define the skill behavior and workflow",+ "agentSkillEdit.instructionsPlaceholder": "Enter the skill instructions in Markdown format...",+ "agentSkillEdit.nameDesc": "The unique identifier for this skill, not editable after creation",+ "agentSkillEdit.saveSuccess": "Skill updated successfully",+ "agentSkillEdit.title": "Skill Settings",+ "agentSkillItem.deleteConfirm.desc": "Are you sure you want to delete the agent skill \"{{name}}\"? This action cannot be undone.",+ "agentSkillItem.deleteConfirm.title": "Delete Agent Skill",+ "agentSkillModal.content": "Skill Content",+ "agentSkillModal.contentPlaceholder": "Enter skill content in Markdown format...",+ "agentSkillModal.description": "Description",+ "agentSkillModal.descriptionPlaceholder": "Briefly describe this skill",+ "agentSkillModal.github.desc": "Import skills directly from a public GitHub repository.",+ "agentSkillModal.github.title": "Import from GitHub",+ "agentSkillModal.github.urlPlaceholder": "https://github.com/username/repo",+ "agentSkillModal.importError": "Import failed: {{error}}",+ "agentSkillModal.importSuccess": "Agent Skill imported successfully",+ "agentSkillModal.upload.desc": "Upload a local .zip or .skill file to install.",+ "agentSkillModal.upload.dragText": "Drag and drop or click to upload",+ "agentSkillModal.upload.requirementSkillMd": "SKILL.md contains skill name and description in YAML format",+ "agentSkillModal.upload.requirementZip": ".zip or .skill file with SKILL.md in root directory",+ "agentSkillModal.upload.requirements": "File Requirements",+ "agentSkillModal.upload.title": "Upload Skill",+ "agentSkillModal.upload.uploading": "Uploading...",+ "agentSkillModal.url.desc": "Import a skill by providing a direct link to a SKILL.md file.",+ "agentSkillModal.url.title": "Import from URL",+ "agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md",+ "agentSkillTag": "Agent Skill","agentTab.chat": "Chat Preferences","agentTab.meta": "Agent info","agentTab.modal": "Model Settings",@@ -643,7 +679,10 @@"systemAgent.translation.modelDesc": "Specify the model used for translation","systemAgent.translation.title": "Message Translation Agent","tab.about": "About",- "tab.addCustomSkill": "Add custom skill",+ "tab.addAgentSkill": "Add Agent Skill",+ "tab.addCustomMcp": "Add Custom MCP Skill",+ "tab.addCustomMcp.desc": "Manually configure a custom MCP server",+ "tab.addCustomSkill": "Add","tab.agent": "Agent Service","tab.all": "All","tab.apikey": "API Key Management",@@ -652,7 +691,13 @@"tab.experiment": "Experiment","tab.hotkey": "Hotkeys","tab.image": "Image Generation Service",+ "tab.importFromGithub": "Import from GitHub",+ "tab.importFromGithub.desc": "Import from a public GitHub repository",+ "tab.importFromUrl": "Import from URL",+ "tab.importFromUrl.desc": "Import via a direct link to SKILL.md","tab.llm": "Language Model",+ "tab.manualFill": "Manually Fill In",+ "tab.manualFill.desc": "Configure a custom MCP skill manually","tab.memory": "Memory","tab.profile": "My Account","tab.provider": "AI Service Provider",@@ -669,6 +714,8 @@"tab.sync": "Cloud Sync","tab.systemTools": "System Tools","tab.tts": "Text-to-Speech",+ "tab.uploadZip": "Upload Zip",+ "tab.uploadZip.desc": "Upload a local .zip or .skill file","tab.usage": "Usage Statistics","tools.add": "Add Skill","tools.builtins.groupName": "Built-ins",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 40e2780de0e..154c1edbac2 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -170,6 +170,14 @@"builtins.lobe-page-agent.apiName.updateNode": "更新节点","builtins.lobe-page-agent.apiName.wrapNodes": "包装节点","builtins.lobe-page-agent.title": "文档",+ "builtins.lobe-skills.apiName.execScript": "执行脚本",+ "builtins.lobe-skills.apiName.exportFile": "导出文件",+ "builtins.lobe-skills.apiName.importFromMarket": "从市场导入",+ "builtins.lobe-skills.apiName.importSkill": "导入技能",+ "builtins.lobe-skills.apiName.readReference": "读取参考资料",+ "builtins.lobe-skills.apiName.runSkill": "激活技能",+ "builtins.lobe-skills.apiName.searchSkill": "搜索技能",+ "builtins.lobe-skills.title": "技能","builtins.lobe-user-memory.apiName.addContextMemory": "添加情境记忆","builtins.lobe-user-memory.apiName.addExperienceMemory": "添加经验记忆","builtins.lobe-user-memory.apiName.addIdentityMemory": "添加身份记忆",@@ -321,8 +329,8 @@"dev.saveSuccess": "技能设置保存成功","dev.tabs.manifest": "功能描述清单 (Manifest)","dev.tabs.meta": "技能元信息",- "dev.title.create": "添加自定义技能",- "dev.title.edit": "编辑自定义技能",+ "dev.title.create": "添加自定义 MCP 技能",+ "dev.title.edit": "编辑自定义 MCP 技能","dev.title.editCommunity": "编辑社区技能","dev.title.skillDetails": "技能详情","dev.title.skillSettings": "技能设置",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 76a8330d441..fa8ac8b0527 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -129,6 +129,42 @@"agentInfoDescription.role.title": "助理档案","agentInfoDescription.value.unset": "未设置","agentInfoDescription.value.untitled": "未命名助理",+ "agentSkillDetail.addedAt": "添加于",+ "agentSkillDetail.publishedAt": "发布于",+ "agentSkillDetail.repository": "GitHub 仓库地址",+ "agentSkillDetail.skillContent": "技能内容",+ "agentSkillDetail.sourceUrl": "Skill 导入路径",+ "agentSkillDetail.updatedAt": "更新于",+ "agentSkillEdit.descriptionDesc": "简要说明该技能的功能,帮助智能体判断何时使用该技能",+ "agentSkillEdit.fileReadonly": "此文件仅供查看,只有技能描述和指令可以编辑。",+ "agentSkillEdit.instructions": "指令",+ "agentSkillEdit.instructionsDesc": "使用 Markdown 编写的核心指令,定义技能的行为和工作流程",+ "agentSkillEdit.instructionsPlaceholder": "以 Markdown 格式输入技能指令...",+ "agentSkillEdit.nameDesc": "该技能的唯一标识符,创建后不可修改",+ "agentSkillEdit.saveSuccess": "技能更新成功",+ "agentSkillEdit.title": "技能设置",+ "agentSkillItem.deleteConfirm.desc": "确定要删除 Agent 技能「{{name}}」吗?此操作无法撤销。",+ "agentSkillItem.deleteConfirm.title": "删除 Agent 技能",+ "agentSkillModal.content": "技能内容",+ "agentSkillModal.contentPlaceholder": "输入 Markdown 格式的技能内容...",+ "agentSkillModal.description": "描述",+ "agentSkillModal.descriptionPlaceholder": "简要描述该技能",+ "agentSkillModal.github.desc": "直接从公开的 GitHub 仓库中导入技能。",+ "agentSkillModal.github.title": "从 GitHub 导入",+ "agentSkillModal.github.urlPlaceholder": "https://github.com/username/repo",+ "agentSkillModal.importError": "导入失败:{{error}}",+ "agentSkillModal.importSuccess": "Agent 技能导入成功",+ "agentSkillModal.upload.desc": "上传本地 .zip 或 .skill 文件以安装技能。",+ "agentSkillModal.upload.dragText": "拖放或点击以上传",+ "agentSkillModal.upload.requirementSkillMd": "SKILL.md 包含以 YAML 格式编写的技能名称和描述",+ "agentSkillModal.upload.requirementZip": "根目录下包含 SKILL.md 文件的 .zip 或 .skill 文件",+ "agentSkillModal.upload.requirements": "文件要求",+ "agentSkillModal.upload.title": "上传技能",+ "agentSkillModal.upload.uploading": "上传中...",+ "agentSkillModal.url.desc": "通过提供 SKILL.md 文件的直接链接导入技能。",+ "agentSkillModal.url.title": "从 URL 导入",+ "agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md",+ "agentSkillTag": "Agent 技能","agentTab.chat": "对话偏好","agentTab.meta": "助理信息","agentTab.modal": "模型设置",@@ -643,7 +679,10 @@"systemAgent.translation.modelDesc": "指定用于翻译的模型","systemAgent.translation.title": "消息内容翻译助理","tab.about": "关于",- "tab.addCustomSkill": "添加自定义技能",+ "tab.addAgentSkill": "添加 Agent 技能",+ "tab.addCustomMcp": "添加自定义 MCP 技能",+ "tab.addCustomMcp.desc": "手动配置自定义 MCP 服务器",+ "tab.addCustomSkill": "添加","tab.agent": "助理服务","tab.all": "全部","tab.apikey": "API Key 管理",@@ -652,7 +691,13 @@"tab.experiment": "实验","tab.hotkey": "快捷键","tab.image": "绘画服务",+ "tab.importFromGithub": "从 GitHub 导入",+ "tab.importFromGithub.desc": "从公开的 GitHub 仓库导入",+ "tab.importFromUrl": "从 URL 导入",+ "tab.importFromUrl.desc": "通过 SKILL.md 的直接链接导入","tab.llm": "语言模型",+ "tab.manualFill": "自行填写内容",+ "tab.manualFill.desc": "手动配置自定义 MCP 技能","tab.memory": "记忆设置","tab.profile": "我的账号","tab.provider": "AI 服务商",@@ -669,6 +714,8 @@"tab.sync": "云端同步","tab.systemTools": "系统工具","tab.tts": "语音服务",+ "tab.uploadZip": "上传 Zip",+ "tab.uploadZip.desc": "上传本地 .zip 或 .skill 文件","tab.usage": "用量统计","tools.add": "集成技能","tools.builtins.groupName": "内置技能",diff --git a/package.json b/package.jsonindex 64fc8d64c3a..16428d225b5 100644--- a/package.json+++ b/package.json@@ -186,6 +186,7 @@"@langchain/community": "^0.3.59","@lobechat/agent-runtime": "workspace:*","@lobechat/builtin-agents": "workspace:*",+ "@lobechat/builtin-skills": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-cloud-sandbox": "workspace:*","@lobechat/builtin-tool-group-agent-builder": "workspace:*",@@ -196,6 +197,7 @@"@lobechat/builtin-tool-memory": "workspace:*","@lobechat/builtin-tool-notebook": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*",+ "@lobechat/builtin-tool-skills": "workspace:*","@lobechat/builtin-tool-web-browsing": "workspace:*","@lobechat/business-config": "workspace:*","@lobechat/business-const": "workspace:*",@@ -228,7 +230,7 @@"@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "^3.16.1","@lobehub/icons": "^4.1.0",- "@lobehub/market-sdk": "0.29.2",+ "@lobehub/market-sdk": "0.29.3","@lobehub/tts": "^4.0.2","@lobehub/ui": "^4.38.1","@modelcontextprotocol/sdk": "^1.25.3",@@ -489,4 +491,4 @@"drizzle-orm": "0.44.7"}}-}+}\ No newline at end of filediff --git a/packages/builtin-skills/package.json b/packages/builtin-skills/package.jsonnew file mode 100644index 00000000000..1c379d20168--- /dev/null+++ b/packages/builtin-skills/package.json@@ -0,0 +1,14 @@+{+ "name": "@lobechat/builtin-skills",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts",+ "dependencies": {},+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-skills/src/artifacts/content.ts b/packages/builtin-skills/src/artifacts/content.tsnew file mode 100644index 00000000000..9ee7e980350--- /dev/null+++ b/packages/builtin-skills/src/artifacts/content.ts@@ -0,0 +1,205 @@+export const systemPrompt = `<artifacts_guides>+The assistant possesses the capability to generate "Artifacts"—dedicated UI windows for presenting visual and interactive content. This feature segregates complex deliverables from the conversational stream, facilitating user ownership, modification, and reuse.++# 1. Evaluation Criteria++## When to Create an Artifact (Qualifying Content)+Target content that serves as a distinct visual or interactive "deliverable." Valid candidates are:+- **Interactive Components:** UI components, dashboards, data visualizations, or interactive widgets.+- **Visual Content:** SVG graphics, illustrations, icons, or diagrams.+- **Web Pages:** Landing pages, forms, or any HTML-based layouts.+- **Iterative Projects:** Content the user is likely to refine, modify, or maintain over time.++## When to Stay Inline (Disqualifying Content)+Do NOT generate artifacts for:+- **Code snippets:** Always present code inline using markdown code blocks, never as an artifact.+- **Documents or articles:** Use regular markdown text in conversation.+- **Trivial content:** Brief explanations, math equations, or short examples.+- **Meta-Commentary:** Feedback or suggestions about existing artifacts.+- **Context-Dependent Text:** Conversational explanations that lose meaning outside the thread.+- **One-off Answers:** Responses to transient questions unlikely to be revisited.++# 2. Operational Constraints+- **Frequency:** Limit to one artifact per response unless explicitly engaged in a multi-file task.+- **Preference:** Defaults to inline text for simplicity. Artifacts are reserved for when a separate visual window significantly enhances utility.+- **Capability Mapping:**+ - If asked for "images/SVG", provide an SVG artifact.+ - If asked for "websites" or "web pages", provide HTML or React artifacts.+ - If asked for "dashboards" or "interactive components", provide React artifacts.+ - If asked for "code", provide it inline as markdown code blocks, NOT as an artifact.+- **Safety:** Do NOT generate hazardous content. Apply the same safety standards as text responses.++# 3. Generation Workflow++When the intent matches the criteria, adhere strictly to this sequence:++## Step A: Artifact Construction+Wrap the content in \`<lobeArtifact>\` tags with the following attributes:++1. **\`identifier\`**: A consistent, kebab-case ID (e.g., \`dashboard-widget\`).+ - *Crucial:* Persist this ID across all future updates to this specific item. If updating an existing artifact, reuse the previous identifier.+2. **\`title\`**: A concise, descriptive string suitable for a header.+3. **\`type\`**: The MIME type defining the rendering logic.++## Step B: Content & Type Specifications++Select the appropriate type and follow its strict constraints:++### **HTML** (\`text/html\`)+- Single-file only (CSS/JS must be embedded)+- No external requests except scripts from \`cdnjs.cloudflare.com\`+- No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)++### **SVG** (\`image/svg+xml\`)+- Specify \`viewBox\` instead of fixed width/height++### **React** (\`application/lobe.artifacts.react\`)+- **Syntax:** Functional components (Hooks allowed: \`useState\`, \`useEffect\`)+- **Export:** Must use \`export default\`+- **Props:** No required props (provide defaults)+- **Styling:** Use Tailwind CSS. No arbitrary values (e.g., \`h-[50px]\`)+- **Pre-installed Libraries:**+ - \`lucide-react\` - Icons (e.g., \`import { Camera } from "lucide-react"\`)+ - \`recharts\` - Charts (e.g., \`import { LineChart, XAxis } from "recharts"\`)+ - \`shadcn/ui\` - UI components (e.g., \`import { Button, Card, Alert } from '@/components/ui/...'\`)+- **Images:** No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)+- **Note:** Import React hooks explicitly: \`import { useState } from "react"\`++## Step C: Integrity+- Output the **full, non-truncated** code/text.+- Do NOT use lazy placeholders like \`// ... rest of code\`.++Here are some examples of correct usage of artifacts:++<examples>+ <example_docstring>+ This example shows how to create an SVG artifact.+ </example_docstring>++ <example>+ <user_query>Can you draw a simple blue circle in SVG?</user_query>++ <assistant_response>+ I'll create a simple blue circle for you using SVG.++ <lobeArtifact identifier="blue-circle-svg" type="image/svg+xml" title="Simple blue circle SVG">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">+ <circle cx="50" cy="50" r="40" fill="blue" />+ </svg>+ </lobeArtifact>++ Here's a simple SVG image of a blue circle, as requested. The circle is centered at coordinates (50, 50) with a radius of 40 pixels, and it's filled with the color blue.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates creating an interactive React component.+ </example_docstring>++ <example>+ <user_query>Can you create a simple counter component?</user_query>++ <assistant_response>+ Here's an interactive counter component:++ <lobeArtifact identifier="counter-component" type="application/lobe.artifacts.react" title="Interactive Counter">+ import { useState } from "react";+ import { Button } from "@/components/ui/button";+ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+ import { Minus, Plus } from "lucide-react";++ export default function Counter() {+ const [count, setCount] = useState(0);++ return (+ <Card className="w-64 mx-auto mt-8">+ <CardHeader>+ <CardTitle className="text-center">Counter</CardTitle>+ </CardHeader>+ <CardContent className="flex items-center justify-center gap-4">+ <Button variant="outline" size="icon" onClick={() => setCount(c => c - 1)}>+ <Minus className="h-4 w-4" />+ </Button>+ <span className="text-4xl font-bold w-16 text-center">{count}</span>+ <Button variant="outline" size="icon" onClick={() => setCount(c => c + 1)}>+ <Plus className="h-4 w-4" />+ </Button>+ </CardContent>+ </Card>+ );+ }+ </lobeArtifact>++ This component provides a simple counter with increment and decrement buttons.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates when NOT to use an artifact—code should always be inline.+ </example_docstring>++ <example>+ <user_query>Can you help me create a Python script to calculate the factorial of a number?</user_query>++ <assistant_response>+ Sure! Here's a Python script that calculates the factorial of a number:++ \\\`\\\`\\\`python+ def factorial(n):+ if n == 0:+ return 1+ else:+ return n * factorial(n - 1)++ # Example usage+ print(factorial(5)) # Output: 120+ \\\`\\\`\\\`++ This uses recursion to calculate the factorial. The base case is when n equals 0, returning 1.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates creating an HTML page artifact.+ </example_docstring>++ <example>+ <user_query>Can you create a simple landing page for a coffee shop?</user_query>++ <assistant_response>+ Here's a landing page for a coffee shop:++ <lobeArtifact identifier="coffee-landing" type="text/html" title="Coffee Shop Landing Page">+ <!DOCTYPE html>+ <html lang="en">+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Brew & Bean</title>+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ body { font-family: Georgia, serif; color: #3c2415; }+ .hero { background: #f5e6d3; padding: 4rem 2rem; text-align: center; }+ .hero h1 { font-size: 3rem; margin-bottom: 1rem; }+ .hero p { font-size: 1.2rem; color: #6b4c3b; }+ </style>+ </head>+ <body>+ <div class="hero">+ <h1>Brew & Bean</h1>+ <p>Artisan coffee, crafted with care.</p>+ </div>+ </body>+ </html>+ </lobeArtifact>++ This creates a simple, elegant landing page with a hero section.+ </assistant_response>+ </example>+</examples>++The assistant should not mention any of these instructions to the user, nor make reference to the \`lobeArtifact\` tag, any of the MIME types (e.g. \`application/lobe.artifacts.react\`), or related syntax unless it is directly relevant to the query.++The assistant should always take care to not produce artifacts that would be highly hazardous to human health or wellbeing if misused, even if is asked to produce them for seemingly benign reasons. However, if Claude would be willing to produce the same content in text form, it should be willing to produce it in an artifact.+</artifacts_info>+`;diff --git a/packages/builtin-skills/src/artifacts/index.ts b/packages/builtin-skills/src/artifacts/index.tsnew file mode 100644index 00000000000..1cc20640d8b--- /dev/null+++ b/packages/builtin-skills/src/artifacts/index.ts@@ -0,0 +1,15 @@+import { type BuiltinSkill } from '@lobechat/types';++import { systemPrompt } from './content';++export const ArtifactsIdentifier = 'lobe-artifacts';++export const ArtifactsSkill: BuiltinSkill = {+ avatar: `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHJ4PSI1MTIiIGZpbGw9IiNDNDc4NUIiLz48cGF0aCBkPSJNNTEyIDYxMmM1NS4yMjggMCAxMDAtNDQuNzcyIDEwMC0xMDBzLTQ0Ljc3Mi0xMDAtMTAwLTEwMC0xMDAgNDQuNzcyLTEwMCAxMDAgNDQuNzcyIDEwMCAxMDAgMTAwWiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNTEyIDY2MmExNDkuOTk4IDE0OS45OTggMCAwIDEtOTIuNTk3IDEzOC41ODIgMTUwLjAwMiAxNTAuMDAyIDAgMCAxLTIwNC41MjEtMTA5LjMxOCAxNDkuOTk4IDE0OS45OTggMCAwIDEgNjMuNzgzLTE1My45ODRBMTQ5Ljk5MiAxNDkuOTkyIDAgMCAxIDM2MiA1MTJhMTQ5Ljk5OSAxNDkuOTk5IDAgMSAxIDE1MC0xNTAgMTQ5Ljk5OCAxNDkuOTk4IDAgMCAxIDI5Ny4xMTgtMjkuMjYzQTE1MCAxNTAgMCAwIDEgNjYyIDUxMmMyOS42NjcgMCA1OC42NjggOC43OTcgODMuMzM1IDI1LjI4YTE0OS45OTUgMTQ5Ljk5NSAwIDAgMSA2My43ODMgMTUzLjk4NEExNTAgMTUwIDAgMCAxIDUxMiA2NjJaTTUxMiAzNjJ2NTBNMzYyIDUxMmg1ME02NjIgNTEyaC01ME01MTIgNjYydi01ME0zNzguNjY3IDM3OC42NjdsNjIuNjY2IDYyLjY2Nk01ODIuNjY3IDQ0MS4zMzNsNjIuNjY2LTYyLjY2Nk0zNzguNjY3IDY0NS4zMzNsNjIuNjY2LTYyLjY2Nk01ODIuNjY3IDU4Mi42NjdsNjIuNjY2IDYyLjY2NiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4=`,+ content: systemPrompt,+ description:+ 'Generate visual and interactive artifacts like SVG graphics, HTML pages, and React components',+ identifier: ArtifactsIdentifier,+ name: 'Artifacts',+ source: 'builtin',+};diff --git a/packages/builtin-skills/src/find-skills/content.ts b/packages/builtin-skills/src/find-skills/content.tsnew file mode 100644index 00000000000..6caad233d04--- /dev/null+++ b/packages/builtin-skills/src/find-skills/content.ts@@ -0,0 +1,129 @@+export const systemPrompt = `# Find Skills++This skill helps you discover and install skills from the open agent skills ecosystem.++## When to Use This Skill++Use this skill when the user:++- Asks "how do I do X" where X might be a common task with an existing skill+- Says "find a skill for X" or "is there a skill for X"+- Asks "can you do X" where X is a specialized capability+- Expresses interest in extending agent capabilities+- Wants to search for tools, templates, or workflows+- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)++## What is the Skills CLI?++The Skills CLI (\`npx skills\`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.++**Key commands:**++- \`npx skills find [query]\` - Search for skills interactively or by keyword+- \`npx skills add <package>\` - Install a skill from GitHub or other sources+- \`npx skills check\` - Check for skill updates+- \`npx skills update\` - Update all installed skills++**Browse skills at:** https://skills.sh/++## How to Help Users Find Skills++### Step 1: Understand What They Need++When a user asks for help with something, identify:++1. The domain (e.g., React, testing, design, deployment)+2. The specific task (e.g., writing tests, creating animations, reviewing PRs)+3. Whether this is a common enough task that a skill likely exists++### Step 2: Search for Skills++Run the find command with a relevant query:++\`\`\`bash+npx skills find [query]+\`\`\`++For example:++- User asks "how do I make my React app faster?" → \`npx skills find react performance\`+- User asks "can you help me with PR reviews?" → \`npx skills find pr review\`+- User asks "I need to create a changelog" → \`npx skills find changelog\`++The command will return results like:++\`\`\`+Install with npx skills add <owner/repo@skill>++vercel-labs/agent-skills@vercel-react-best-practices+└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices+\`\`\`++### Step 3: Present Options to the User++When you find relevant skills, present them to the user with:++1. The skill name and what it does+2. The install command they can run+3. A link to learn more at skills.sh++Example response:++\`\`\`+I found a skill that might help! The "vercel-react-best-practices" skill provides+React and Next.js performance optimization guidelines from Vercel Engineering.++To install it:+npx skills add vercel-labs/agent-skills@vercel-react-best-practices++Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices+\`\`\`++### Step 4: Offer to Install++If the user wants to proceed, you can install the skill for them:++\`\`\`bash+npx skills add <owner/repo@skill> -g -y+\`\`\`++The \`-g\` flag installs globally (user-level) and \`-y\` skips confirmation prompts.++## Common Skill Categories++When searching, consider these common categories:++| Category | Example Queries |+| --------------- | ---------------------------------------- |+| Web Development | react, nextjs, typescript, css, tailwind |+| Testing | testing, jest, playwright, e2e |+| DevOps | deploy, docker, kubernetes, ci-cd |+| Documentation | docs, readme, changelog, api-docs |+| Code Quality | review, lint, refactor, best-practices |+| Design | ui, ux, design-system, accessibility |+| Productivity | workflow, automation, git |++## Tips for Effective Searches++1. **Use specific keywords**: "react testing" is better than just "testing"+2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"+3. **Check popular sources**: Many skills come from \`vercel-labs/agent-skills\` or \`ComposioHQ/awesome-claude-skills\`++## When No Skills Are Found++If no relevant skills exist:++1. Acknowledge that no existing skill was found+2. Offer to help with the task directly using your general capabilities+3. Suggest the user could create their own skill with \`npx skills init\`++Example:++\`\`\`+I searched for skills related to "xyz" but didn't find any matches.+I can still help you with this task directly! Would you like me to proceed?++If this is something you do often, you could create your own skill:+npx skills init my-xyz-skill+\`\`\`+`;diff --git a/packages/builtin-skills/src/find-skills/index.ts b/packages/builtin-skills/src/find-skills/index.tsnew file mode 100644index 00000000000..fb2056d1c8d--- /dev/null+++ b/packages/builtin-skills/src/find-skills/index.ts@@ -0,0 +1,14 @@+import { type BuiltinSkill } from '@lobechat/types';++import { systemPrompt } from './content';++export const FindSkillsIdentifier = 'find-skills';++export const FindSkillsSkill: BuiltinSkill = {+ content: systemPrompt,+ description:+ 'Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", or express interest in extending capabilities',+ identifier: FindSkillsIdentifier,+ name: 'Find Skills',+ source: 'builtin',+};diff --git a/packages/builtin-skills/src/index.ts b/packages/builtin-skills/src/index.tsnew file mode 100644index 00000000000..1ebb27eb9ea--- /dev/null+++ b/packages/builtin-skills/src/index.ts@@ -0,0 +1,8 @@+import type { BuiltinSkill } from '@lobechat/types';++import { ArtifactsSkill } from './artifacts';++export const builtinSkills: BuiltinSkill[] = [+ ArtifactsSkill,+ // FindSkillsSkill+];diff --git a/packages/builtin-tool-skills/package.json b/packages/builtin-tool-skills/package.jsonnew file mode 100644index 00000000000..b1187db7e9e--- /dev/null+++ b/packages/builtin-tool-skills/package.json@@ -0,0 +1,22 @@+{+ "name": "@lobechat/builtin-tool-skills",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executor": "./src/executor/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/prompts": "workspace:*",+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "*",+ "antd-style": "*",+ "react": "*",+ "react-i18next": "*"+ }+}diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..911efbef46a--- /dev/null+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts@@ -0,0 +1,387 @@+import { resourcesTreePrompt } from '@lobechat/prompts';+import {+ type BuiltinServerRuntimeOutput,+ type BuiltinSkill,+ type SkillItem,+ type SkillListItem,+ type SkillResourceContent,+} from '@lobechat/types';++import {+ type CommandResult,+ type ExecScriptParams,+ type ExportFileParams,+ type ImportFromMarketParams,+ type ImportSkillParams,+ type MarketSkillItem,+ type ReadReferenceParams,+ type RunCommandOptions,+ type RunSkillParams,+ type SearchSkillParams,+} from '../types';++/**+ * Unified skill service interface for dependency injection.+ * On client side, this is implemented by AgentSkillService.+ * On server side, this is composed from AgentSkillModel + SkillResourceService.+ */+export interface SkillImportServiceResult {+ skill: { id: string; name: string };+ status: 'created' | 'updated' | 'unchanged';+}++export interface ExportFileResult {+ fileId?: string;+ filename: string;+ mimeType?: string;+ size?: number;+ success: boolean;+ url?: string;+}++export interface SkillRuntimeService {+ execScript?: (+ command: string,+ options: {+ config?: { description?: string; id?: string; name?: string };+ description: string;+ runInClient?: boolean;+ },+ ) => Promise<CommandResult>;+ exportFile?: (path: string, filename: string) => Promise<ExportFileResult>;+ findAll: () => Promise<{ data: SkillListItem[]; total: number }>;+ findById: (id: string) => Promise<SkillItem | undefined>;+ findByName: (name: string) => Promise<SkillItem | undefined>;+ importFromGitHub: (gitUrl: string) => Promise<SkillImportServiceResult>;+ importFromMarket?: (identifier: string) => Promise<SkillImportServiceResult>;+ importFromUrl: (url: string) => Promise<SkillImportServiceResult>;+ importFromZipUrl: (url: string) => Promise<SkillImportServiceResult>;+ onSkillImported?: () => Promise<void>;+ readResource: (id: string, path: string) => Promise<SkillResourceContent>;+ runCommand?: (options: RunCommandOptions) => Promise<CommandResult>;+ searchSkill?: (+ params: SearchSkillParams,+ ) => Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }>;+}++export interface SkillsExecutionRuntimeOptions {+ builtinSkills?: BuiltinSkill[];+ service: SkillRuntimeService;+}++export class SkillsExecutionRuntime {+ private builtinSkills: BuiltinSkill[];+ private service: SkillRuntimeService;++ constructor(options: SkillsExecutionRuntimeOptions) {+ this.service = options.service;+ this.builtinSkills = options.builtinSkills || [];+ }++ async importSkill(args: ImportSkillParams): Promise<BuiltinServerRuntimeOutput> {+ const { url, type } = args;++ // Determine import method based on URL and type+ const isGitHub = url.includes('github.com');++ try {+ let result: SkillImportServiceResult;++ if (isGitHub && type === 'url') {+ result = await this.service.importFromGitHub(url);+ } else if (type === 'zip') {+ result = await this.service.importFromZipUrl(url);+ } else {+ result = await this.service.importFromUrl(url);+ }++ // Refresh skills list so the new skill becomes available+ await this.service.onSkillImported?.();++ return {+ content: `Skill "${result.skill.name}" ${result.status} successfully.`,+ state: {+ name: result.skill.name,+ skillId: result.skill.id,+ status: result.status,+ success: true,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to import skill: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ async execScript(args: ExecScriptParams): Promise<BuiltinServerRuntimeOutput> {+ const { command, runInClient, description, config } = args;++ // Try new execScript method first (with cloud sandbox support)+ if (this.service.execScript) {+ try {+ const result = await this.service.execScript(command, {+ config,+ description,+ runInClient,+ });++ const output = [result.output, result.stderr].filter(Boolean).join('\n');++ return {+ content: output || '(no output)',+ state: {+ command,+ exitCode: result.exitCode,+ success: result.success,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to execute command: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ // Fallback to legacy runCommand method+ if (!this.service.runCommand) {+ return {+ content: 'Command execution is not available in this environment.',+ success: false,+ };+ }++ try {+ const result = await this.service.runCommand({ command, runInClient });++ const output = [result.output, result.stderr].filter(Boolean).join('\n');++ return {+ content: output || '(no output)',+ state: {+ command,+ exitCode: result.exitCode,+ success: result.success,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to execute command: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ async exportFile(args: ExportFileParams): Promise<BuiltinServerRuntimeOutput> {+ const { path, filename } = args;++ if (!this.service.exportFile) {+ return {+ content: 'File export is not available in this environment.',+ success: false,+ };+ }++ try {+ const result = await this.service.exportFile(path, filename);++ if (!result.success) {+ return {+ content: `Failed to export file: ${filename}`,+ success: false,+ };+ }++ return {+ content: `File exported successfully: ${filename}\nDownload URL: ${result.url || 'N/A'}`,+ state: {+ fileId: result.fileId,+ filename: result.filename,+ mimeType: result.mimeType,+ size: result.size,+ url: result.url,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to export file: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ async readReference(args: ReadReferenceParams): Promise<BuiltinServerRuntimeOutput> {+ const { id, path } = args;++ // Validate path to prevent traversal attacks+ if (path.includes('..')) {+ return {+ content: 'Invalid path: path traversal is not allowed',+ success: false,+ };+ }++ try {+ // Resolve id: try findById first, fallback to findByName+ const skill = await this.service.findByName(id);+ if (!skill) {+ return {+ content: `Skill not found: "${id}"`,+ success: false,+ };+ }++ const resource = await this.service.readResource(skill.id, path);+ return {+ content: resource.content,+ state: {+ encoding: resource.encoding,+ fileType: resource.fileType,+ path: resource.path,+ size: resource.size,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to read resource: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ async runSkill(args: RunSkillParams): Promise<BuiltinServerRuntimeOutput> {+ const { name } = args;++ // Check builtin skills first — no DB query needed+ const builtinSkill = this.builtinSkills.find((s) => s.name === name);+ if (builtinSkill) {+ return {+ content: builtinSkill.content,+ state: {+ description: builtinSkill.description,+ hasResources: false,+ identifier: builtinSkill.identifier,+ name: builtinSkill.name,+ },+ success: true,+ };+ }++ // Fall back to DB query for user/market skills+ const skill = await this.service.findByName(name);++ if (!skill) {+ const { data: allSkills } = await this.service.findAll();+ const availableSkills = allSkills.map((s) => ({+ description: s.description,+ name: s.name,+ }));++ return {+ content: `Skill not found: "${name}". Available skills: ${JSON.stringify(availableSkills)}`,+ success: false,+ };+ }++ const hasResources = !!(skill.resources && Object.keys(skill.resources).length > 0);+ let content = skill.content || '';++ if (hasResources && skill.resources) {+ content += '\n\n' + resourcesTreePrompt(skill.name, skill.resources);+ }++ return {+ content,+ state: {+ description: skill.description || undefined,+ hasResources,+ id: skill.id,+ name: skill.name,+ },+ success: true,+ };+ }++ async searchSkill(args: SearchSkillParams): Promise<BuiltinServerRuntimeOutput> {+ if (!this.service.searchSkill) {+ return {+ content: 'Market skill search is not available in this environment.',+ success: false,+ };+ }++ try {+ const result = await this.service.searchSkill(args);++ if (result.items.length === 0) {+ return {+ content: args.search+ ? `No skills found matching "${args.search}"`+ : 'No skills found in the market',+ state: result,+ success: true,+ };+ }++ // Format results as a readable list+ const skillsList = result.items+ .map(+ (skill, index) =>+ `${index + 1}. **${skill.name}** (${skill.identifier})\n ${skill.description}${skill.summary ? `\n Summary: ${skill.summary}` : ''}${skill.repository ? `\n Repository: ${skill.repository}` : ''}${skill.downloadCount ? `\n Downloads: ${skill.downloadCount}` : ''}`,+ )+ .join('\n\n');++ return {+ content: `Found ${result.total} skills (page ${result.page}/${Math.ceil(result.total / result.pageSize)}):\n\n${skillsList}`,+ state: result,+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to search skills: ${(e as Error).message}`,+ success: false,+ };+ }+ }++ async importFromMarket(args: ImportFromMarketParams): Promise<BuiltinServerRuntimeOutput> {+ const { identifier } = args;++ if (!this.service.importFromMarket) {+ return {+ content: 'Market skill import is not available in this environment.',+ success: false,+ };+ }++ try {+ const result = await this.service.importFromMarket(identifier);++ // Refresh skills list so the new skill becomes available+ await this.service.onSkillImported?.();++ return {+ content: `Skill "${result.skill.name}" ${result.status} successfully from market.`,+ state: {+ name: result.skill.name,+ skillId: result.skill.id,+ status: result.status,+ success: true,+ },+ success: true,+ };+ } catch (e) {+ return {+ content: `Failed to import skill from market: ${(e as Error).message}`,+ success: false,+ };+ }+ }+}diff --git a/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsxnew file mode 100644index 00000000000..61128bad48e--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Inspector/ExecScript/index.tsx@@ -0,0 +1,63 @@+'use client';++import { type BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Check, X } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { ExecScriptParams, ExecScriptState } from '../../../types';++const styles = createStaticStyles(({ css }) => ({+ statusIcon: css`+ margin-block-end: -2px;+ margin-inline-start: 4px;+ `,+}));++export const ExecScriptInspector = memo<BuiltinInspectorProps<ExecScriptParams, ExecScriptState>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ // Show description if available, otherwise show command+ const description = args?.description || partialArgs?.description || args?.command || '';++ if (isArgumentsStreaming) {+ if (!description)+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.execScript')}</span>+ </div>+ );++ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.execScript')}: </span>+ <span className={highlightTextStyles.primary}>{description}</span>+ </div>+ );+ }++ const isSuccess = pluginState?.success;++ return (+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>+ <span style={{ marginInlineStart: 2 }}>+ <span>{t('builtins.lobe-skills.apiName.execScript')}: </span>+ {description && <span className={highlightTextStyles.primary}>{description}</span>}+ {isLoading ? null : pluginState?.success !== undefined ? (+ isSuccess ? (+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />+ ) : (+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />+ )+ ) : null}+ </span>+ </div>+ );+ },+);++ExecScriptInspector.displayName = 'ExecScriptInspector';diff --git a/packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsxnew file mode 100644index 00000000000..dd5f5d8198c--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsx@@ -0,0 +1,59 @@+'use client';++import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Check, X } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { ImportSkillParams, ImportSkillState } from '../../../types';++const styles = createStaticStyles(({ css }) => ({+ statusIcon: css`+ margin-block-end: -2px;+ margin-inline-start: 4px;+ `,+}));++export const ImportSkillInspector = memo<+ BuiltinInspectorProps<ImportSkillParams, ImportSkillState>+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const url = args?.url || partialArgs?.url;+ const displayName = pluginState?.name || url;++ if (isArgumentsStreaming && !url) {+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.importSkill')}</span>+ </div>+ );+ }++ const isSuccess = pluginState?.success;+ const hasResult = pluginState?.success !== undefined;++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>{t('builtins.lobe-skills.apiName.importSkill')}: </span>+ {displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}+ {!isLoading &&+ hasResult &&+ (isSuccess ? (+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />+ ) : (+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />+ ))}+ </div>+ );+});++ImportSkillInspector.displayName = 'ImportSkillInspector';diff --git a/packages/builtin-tool-skills/src/client/Inspector/ReadReference/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/ReadReference/index.tsxnew file mode 100644index 00000000000..a08feb95779--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Inspector/ReadReference/index.tsx@@ -0,0 +1,46 @@+'use client';++import { type BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { ReadReferenceParams, ReadReferenceState } from '../../../types';++export const ReadReferenceInspector = memo<+ BuiltinInspectorProps<ReadReferenceParams, ReadReferenceState>+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const path = args?.path || partialArgs?.path || '';+ const resolvedPath = pluginState?.path || path;++ if (isArgumentsStreaming) {+ if (!path)+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.readReference')}</span>+ </div>+ );++ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.readReference')}: </span>+ <span>{path}</span>+ </div>+ );+ }++ return (+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>+ <span>+ <span>{t('builtins.lobe-skills.apiName.readReference')}: </span>+ <span className={highlightTextStyles.primary}>{resolvedPath}</span>+ </span>+ </div>+ );+});++ReadReferenceInspector.displayName = 'ReadReferenceInspector';diff --git a/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsxnew file mode 100644index 00000000000..3f48cf58ac2--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Inspector/RunSkill/index.tsx@@ -0,0 +1,46 @@+'use client';++import { type BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { RunSkillParams, RunSkillState } from '../../../types';++export const RunSkillInspector = memo<BuiltinInspectorProps<RunSkillParams, RunSkillState>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const name = args?.name || partialArgs?.name || '';+ const activatedName = pluginState?.name;++ if (isArgumentsStreaming) {+ if (!name)+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.runSkill')}</span>+ </div>+ );++ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-skills.apiName.runSkill')}: </span>+ <span>{name}</span>+ </div>+ );+ }++ return (+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>+ <span>+ <span>{t('builtins.lobe-skills.apiName.runSkill')}: </span>+ <span className={highlightTextStyles.primary}>{activatedName || name}</span>+ </span>+ </div>+ );+ },+);++RunSkillInspector.displayName = 'RunSkillInspector';diff --git a/packages/builtin-tool-skills/src/client/Inspector/index.ts b/packages/builtin-tool-skills/src/client/Inspector/index.tsnew file mode 100644index 00000000000..dd2215bf741--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Inspector/index.ts@@ -0,0 +1,12 @@+import { SkillsApiName } from '../../types';+import { ExecScriptInspector } from './ExecScript';+import { ImportSkillInspector } from './ImportSkill';+import { ReadReferenceInspector } from './ReadReference';+import { RunSkillInspector } from './RunSkill';++export const SkillsInspectors = {+ [SkillsApiName.execScript]: ExecScriptInspector,+ [SkillsApiName.importSkill]: ImportSkillInspector,+ [SkillsApiName.readReference]: ReadReferenceInspector,+ [SkillsApiName.runSkill]: RunSkillInspector,+};diff --git a/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx b/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsxnew file mode 100644index 00000000000..461bdb3570d--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Render/ExecScript/index.tsx@@ -0,0 +1,44 @@+'use client';++import { type BuiltinRenderProps } from '@lobechat/types';+import { Block, Flexbox, Highlighter } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import type { ExecScriptParams, ExecScriptState } from '../../../types';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: hidden;+ padding-inline: 8px 0;+ `,+}));++const ExecScript = memo<BuiltinRenderProps<ExecScriptParams, ExecScriptState>>(+ ({ args, content, pluginState }) => {+ const { command } = pluginState || {};++ return (+ <Flexbox className={styles.container} gap={8}>+ <Block gap={8} padding={8} variant={'outlined'}>+ <Highlighter+ language={'sh'}+ showLanguage={false}+ style={{ paddingInline: 8 }}+ variant={'borderless'}+ wrap+ >+ {args?.command || command || ''}+ </Highlighter>+ {content && (+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>+ {content}+ </Highlighter>+ )}+ </Block>+ </Flexbox>+ );+ },+);++export default ExecScript;diff --git a/packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsx b/packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsxnew file mode 100644index 00000000000..f4ec014e345--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsx@@ -0,0 +1,68 @@+'use client';++import { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { CheckCircle, XCircle } from 'lucide-react';+import { memo } from 'react';++import type { ImportSkillParams, ImportSkillState } from '../../../types';++const ImportSkill = memo<BuiltinRenderProps<ImportSkillParams, ImportSkillState>>(+ ({ pluginState, content }) => {+ const { name, status, success } = pluginState || {};++ if (success === undefined) return null;++ if (!success) {+ return (+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>+ <XCircle size={14} style={{ color: 'var(--lobe-error-6)' }} />+ <span style={{ fontWeight: 500 }}>+ Failed to import skill+ {content && (+ <>+ :{' '}+ <code+ style={{+ background: 'var(--lobe-fill-tertiary)',+ borderRadius: 4,+ color: 'var(--lobe-text)',+ fontSize: 12,+ padding: '2px 6px',+ }}+ >+ {content}+ </code>+ </>+ )}+ </span>+ </Flexbox>+ );+ }++ const statusLabel =+ status === 'created' ? 'Imported' : status === 'updated' ? 'Updated' : 'Already up to date';++ return (+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>+ <CheckCircle size={14} style={{ color: 'var(--lobe-success-6)' }} />+ <span style={{ fontWeight: 500 }}>+ {statusLabel}:{' '}+ <code+ style={{+ background: 'var(--lobe-fill-tertiary)',+ borderRadius: 4,+ color: 'var(--lobe-text)',+ fontSize: 12,+ padding: '2px 6px',+ }}+ >+ {name}+ </code>+ </span>+ </Flexbox>+ );+ },+);++export default ImportSkill;diff --git a/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx b/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsxnew file mode 100644index 00000000000..5ef5901a260--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Render/ReadReference/index.tsx@@ -0,0 +1,110 @@+'use client';++import { type BuiltinRenderProps } from '@lobechat/types';+import { Block, Flexbox, Highlighter, Markdown, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import type { ReadReferenceParams, ReadReferenceState } from '../../../types';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: hidden;+ padding-inline: 8px 0;+ `,+}));++const getFileExtension = (path: string): string => {+ const parts = path.split('.');+ return parts.length > 1 ? parts.pop()?.toLowerCase() || 'text' : 'text';+};++const languageMap: Record<string, string> = {+ css: 'css',+ go: 'go',+ html: 'html',+ java: 'java',+ js: 'javascript',+ json: 'json',+ jsx: 'jsx',+ md: 'markdown',+ py: 'python',+ rs: 'rust',+ scss: 'scss',+ sh: 'bash',+ sql: 'sql',+ ts: 'typescript',+ tsx: 'tsx',+ xml: 'xml',+ xsd: 'xml',+ yaml: 'yaml',+ yml: 'yaml',+};++const getLanguage = (ext: string): string => languageMap[ext] || 'text';++const formatSize = (bytes: number): string => {+ if (bytes === 0) return '0 B';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++const ReadReference = memo<BuiltinRenderProps<ReadReferenceParams, ReadReferenceState>>(+ ({ content, pluginState }) => {+ const { encoding, path, size } = pluginState || {};++ if (!path || !content) return null;++ const ext = getFileExtension(path);+ const isMarkdown = ext === 'md' || ext === 'markdown';+ const isBinary = encoding === 'base64';++ const sizeText = size ? formatSize(size) : '';++ return (+ <Flexbox className={styles.container} gap={8}>+ <Flexbox align={'center'} horizontal justify={'space-between'}>+ <Text as={'span'} code ellipsis fontSize={12}>+ {path}+ </Text>+ {sizeText && (+ <Text as={'span'} code fontSize={12} type={'secondary'}>+ {sizeText}+ </Text>+ )}+ </Flexbox>++ {isBinary ? (+ <Block padding={12} variant={'outlined'}>+ <Text fontSize={12} type={'secondary'}>+ Binary file ({sizeText})+ </Text>+ </Block>+ ) : isMarkdown ? (+ <Block padding={12} variant={'outlined'}>+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>+ {content}+ </Markdown>+ </Block>+ ) : (+ <Block padding={0} variant={'outlined'}>+ <Highlighter+ language={getLanguage(ext)}+ showLanguage+ style={{ maxHeight: 400, overflow: 'auto' }}+ variant={'borderless'}+ wrap+ >+ {content}+ </Highlighter>+ </Block>+ )}+ </Flexbox>+ );+ },+);++ReadReference.displayName = 'ReadReference';++export default ReadReference;diff --git a/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsxnew file mode 100644index 00000000000..ba0b0789277--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Render/RunSkill/index.tsx@@ -0,0 +1,63 @@+'use client';++import { type BuiltinRenderProps } from '@lobechat/types';+import { Flexbox, Markdown, ScrollShadow } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import type { RunSkillParams, RunSkillState } from '../../../types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ container: css`+ overflow: hidden;++ width: 100%;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 12px;++ background: ${cssVar.colorBgContainer};+ `,+ content: css`+ padding-block: 8px;+ padding-inline: 16px;+ font-size: 14px;+ `,+ description: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ header: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ name: css`+ font-weight: 500;+ `,+}));++const RunSkill = memo<BuiltinRenderProps<RunSkillParams, RunSkillState>>(+ ({ content, pluginState }) => {+ const { description, name } = pluginState || {};++ if (!name) return null;++ return (+ <Flexbox className={styles.container}>+ <Flexbox className={styles.header} gap={4}>+ <span className={styles.name}>{name}</span>+ {description && <span className={styles.description}>{description}</span>}+ </Flexbox>+ {content && (+ <ScrollShadow className={styles.content} offset={12} size={12} style={{ maxHeight: 400 }}>+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>+ {content}+ </Markdown>+ </ScrollShadow>+ )}+ </Flexbox>+ );+ },+);++export default RunSkill;diff --git a/packages/builtin-tool-skills/src/client/Render/index.ts b/packages/builtin-tool-skills/src/client/Render/index.tsnew file mode 100644index 00000000000..69cf117d62a--- /dev/null+++ b/packages/builtin-tool-skills/src/client/Render/index.ts@@ -0,0 +1,12 @@+import { SkillsApiName } from '../../types';+import ExecScript from './ExecScript';+import ImportSkill from './ImportSkill';+import ReadReference from './ReadReference';+import RunSkill from './RunSkill';++export const SkillsRenders = {+ [SkillsApiName.execScript]: ExecScript,+ [SkillsApiName.importSkill]: ImportSkill,+ [SkillsApiName.readReference]: ReadReference,+ [SkillsApiName.runSkill]: RunSkill,+};diff --git a/packages/builtin-tool-skills/src/client/index.ts b/packages/builtin-tool-skills/src/client/index.tsnew file mode 100644index 00000000000..c14d306a91d--- /dev/null+++ b/packages/builtin-tool-skills/src/client/index.ts@@ -0,0 +1,4 @@+export { SkillsManifest } from '../manifest';+export * from '../types';+export { SkillsInspectors } from './Inspector';+export { SkillsRenders } from './Render';diff --git a/packages/builtin-tool-skills/src/const.ts b/packages/builtin-tool-skills/src/const.tsnew file mode 100644index 00000000000..7531177a7e9--- /dev/null+++ b/packages/builtin-tool-skills/src/const.ts@@ -0,0 +1 @@+export const isDesktop = process.env.NEXT_PUBLIC_IS_DESKTOP_APP === '1';diff --git a/packages/builtin-tool-skills/src/executor/index.ts b/packages/builtin-tool-skills/src/executor/index.tsnew file mode 100644index 00000000000..cd930ef7e91--- /dev/null+++ b/packages/builtin-tool-skills/src/executor/index.ts@@ -0,0 +1,231 @@+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';++import { SkillsExecutionRuntime } from '../ExecutionRuntime';+import {+ type ExecScriptParams,+ type ExportFileParams,+ type ImportFromMarketParams,+ type ImportSkillParams,+ type ReadReferenceParams,+ type RunSkillParams,+ type SearchSkillParams,+ SkillsApiName,+ SkillsIdentifier,+} from '../types';++class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {+ readonly identifier = SkillsIdentifier;+ protected readonly apiEnum = SkillsApiName;++ private runtime: SkillsExecutionRuntime;++ constructor(runtime: SkillsExecutionRuntime) {+ super();+ this.runtime = runtime;+ }++ importSkill = async (+ params: ImportSkillParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.importSkill(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ execScript = async (+ params: ExecScriptParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.execScript(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ runSkill = async (+ params: RunSkillParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.runSkill(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ readReference = async (+ params: ReadReferenceParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.readReference(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ exportFile = async (+ params: ExportFileParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.exportFile(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ searchSkill = async (+ params: SearchSkillParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.searchSkill(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };++ importFromMarket = async (+ params: ImportFromMarketParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await this.runtime.importFromMarket(params);++ if (result.success) {+ return { content: result.content, state: result.state, success: true };+ }++ return {+ content: result.content,+ error: { message: result.content, type: 'PluginServerError' },+ success: false,+ };+ } catch (e) {+ const err = e as Error;+ return {+ error: { body: e, message: err.message, type: 'PluginServerError' },+ success: false,+ };+ }+ };+}++export { SkillsExecutor };diff --git a/packages/builtin-tool-skills/src/index.ts b/packages/builtin-tool-skills/src/index.tsnew file mode 100644index 00000000000..27559503fd7--- /dev/null+++ b/packages/builtin-tool-skills/src/index.ts@@ -0,0 +1,11 @@+export { SkillsManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ type CommandResult,+ type MarketSkillItem,+ type ReadReferenceParams,+ type RunSkillParams,+ type SearchSkillParams,+ SkillsApiName,+ SkillsIdentifier,+} from './types';diff --git a/packages/builtin-tool-skills/src/manifest.ts b/packages/builtin-tool-skills/src/manifest.tsnew file mode 100644index 00000000000..7d65e46e2db--- /dev/null+++ b/packages/builtin-tool-skills/src/manifest.ts@@ -0,0 +1,199 @@+import { BuiltinToolManifest } from '@lobechat/types';++import { isDesktop } from './const';+import { systemPrompt } from './systemRole';+import { SkillsApiName, SkillsIdentifier } from './types';++export const SkillsManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Activate a skill by name to load its instructions. Skills are reusable instruction packages that extend your capabilities. Returns the skill content that you should follow to complete the task. If the skill is not found, returns a list of available skills.',+ name: SkillsApiName.runSkill,+ parameters: {+ properties: {+ name: {+ description: 'The exact name of the skill to activate.',+ type: 'string',+ },+ },+ required: ['name'],+ type: 'object',+ },+ },+ {+ description:+ "Read a reference file attached to a skill. Use this to load additional context files mentioned in a skill's content. Requires the id returned by runSkill and the file path.",+ name: SkillsApiName.readReference,+ parameters: {+ properties: {+ id: {+ description: 'The skill ID or name returned by runSkill.',+ type: 'string',+ },+ path: {+ description:+ 'The virtual path of the reference file to read. Must be a path mentioned in the skill content.',+ type: 'string',+ },+ },+ required: ['id', 'path'],+ type: 'object',+ },+ },+ {+ description:+ "Execute a shell command or script specified in a skill's instructions. Use this when a skill's content instructs you to run CLI commands (e.g., npx, npm, pip). IMPORTANT: Always include the 'config' parameter with the current skill's id and name (obtained from runSkill's state) so the system can locate skill resources. Returns the command output.",+ humanIntervention: 'required',+ name: SkillsApiName.execScript,+ parameters: {+ properties: {+ command: {+ description: 'The shell command to execute.',+ type: 'string',+ },+ config: {+ description:+ 'REQUIRED: Current skill context. Must include the id and name from the most recent runSkill call. The server uses this to locate skill resources (e.g., ZIP package for skill files). Example: { "id": "skill_xxx", "name": "skill-name", "description": "..." }',+ properties: {+ description: {+ description: "Current skill's description (optional)",+ type: 'string',+ },+ id: {+ description:+ "Current skill's ID from runSkill state (required for resource lookup)",+ type: 'string',+ },+ name: {+ description:+ "Current skill's name from runSkill state (required for resource lookup)",+ type: 'string',+ },+ },+ type: 'object',+ },+ description: {+ description:+ 'Clear description of what this command does (5-10 words, in active voice). Use the same language as the user input.',+ type: 'string',+ },+ ...(isDesktop && {+ runInClient: {+ description:+ 'Whether to run on the desktop client (for local shell access). MUST be true when command requires local-system tools. Default is false (cloud sandbox execution).',+ type: 'boolean',+ },+ }),+ },+ required: ['description', 'command'],+ type: 'object',+ },+ },+ {+ description:+ 'Export a file generated during skill execution to cloud storage. Use this to save outputs, results, or generated files for the user to download. The file will be uploaded and a permanent download URL will be returned.',+ name: SkillsApiName.exportFile,+ parameters: {+ properties: {+ filename: {+ description: 'The name for the exported file (e.g., "result.csv", "output.pdf")',+ type: 'string',+ },+ path: {+ description:+ 'The path of the file in the skill execution environment to export (e.g., "./output/result.csv")',+ type: 'string',+ },+ },+ required: ['path', 'filename'],+ type: 'object',+ },+ },+ {+ description:+ 'Import/install a skill from a URL. Supports SKILL.md URLs, GitHub repository URLs, and ZIP package URLs. Requires user confirmation before installation.',+ humanIntervention: 'required',+ name: SkillsApiName.importSkill,+ parameters: {+ properties: {+ type: {+ description:+ 'The type of the URL: "url" for SKILL.md or GitHub links, "zip" for ZIP package URLs.',+ enum: ['url', 'zip'],+ type: 'string',+ },+ url: {+ description: 'The URL of the skill resource to import.',+ type: 'string',+ },+ },+ required: ['url', 'type'],+ type: 'object',+ },+ },+ {+ description:+ 'Search for skills in the LobeHub Market. Use this to discover available skills that can extend Claude\'s capabilities. Search across skill names, descriptions, and summaries. Results can be filtered and sorted by various criteria (stars, downloads, etc).',+ name: SkillsApiName.searchSkill,+ parameters: {+ properties: {+ locale: {+ description: 'Locale for search results (e.g., "en-US", "zh-CN"). Optional.',+ type: 'string',+ },+ order: {+ description: 'Sort order: "asc" for ascending, "desc" for descending. Default: "desc".',+ enum: ['asc', 'desc'],+ type: 'string',+ },+ page: {+ description: 'Page number for pagination. Default: 1.',+ type: 'number',+ },+ pageSize: {+ description: 'Number of results per page. Default: 20.',+ type: 'number',+ },+ search: {+ description:+ 'Search query to filter skills. Searches across skill name, description, and summary. Optional.',+ type: 'string',+ },+ sort: {+ description:+ 'Field to sort by. Options: createdAt (creation date), downloadCount (downloads), forks (GitHub forks), name (alphabetical), stars (GitHub stars), updatedAt (last update), watchers (GitHub watchers). Default: "updatedAt".',+ enum: ['createdAt', 'downloadCount', 'forks', 'name', 'stars', 'updatedAt', 'watchers'],+ type: 'string',+ },+ },+ type: 'object',+ },+ },+ {+ description:+ 'Import/install a skill directly from the LobeHub Market using its identifier. This is the recommended way to install skills from the market after searching with searchSkill. The skill will be downloaded and installed automatically. Requires user confirmation before installation.',+ humanIntervention: 'required',+ name: SkillsApiName.importFromMarket,+ parameters: {+ properties: {+ identifier: {+ description:+ 'The unique identifier of the skill in the market (e.g., "github.anthropics.skills.skills.skill-creator"). You can get this from searchSkill results.',+ type: 'string',+ },+ },+ required: ['identifier'],+ type: 'object',+ },+ },+ ],+ identifier: SkillsIdentifier,+ meta: {+ avatar: '🛠️',+ description: 'Activate and use reusable skill packages',+ title: 'Skills',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.tsnew file mode 100644index 00000000000..e85bcf810dd--- /dev/null+++ b/packages/builtin-tool-skills/src/systemRole.ts@@ -0,0 +1,130 @@+import { isDesktop } from './const';++const runInClientSection = `+<run_in_client>+**IMPORTANT: When to use \`runInClient: true\` for execScript**++The \`runInClient\` parameter controls WHERE the command executes:+- \`runInClient: false\` (default): Command runs in the **cloud sandbox** - suitable for general CLI tools+- \`runInClient: true\`: Command runs on the **desktop client** - required for local file/shell access++**MUST set \`runInClient: true\` when the command involves:**+- Accessing local files or directories+- Installing packages globally on the user's machine+- Any operation that requires local system access++**Keep \`runInClient: false\` (or omit) when:**+- Running general CLI tools (e.g., npx, npm search)+- Command doesn't need local file system access+- Command can run in a sandboxed environment++**Note:** \`runInClient\` is only available on the **desktop app**. On web platform, commands always run in the cloud sandbox.+</run_in_client>+`;++export const systemPrompt = `You have access to a Skills tool that allows you to activate reusable instruction packages (skills) that extend your capabilities. Skills are pre-defined workflows, guidelines, or specialized knowledge that help you handle specific types of tasks.++<core_capabilities>+1. Activate a skill by name to load its instructions (runSkill)+2. Read reference files attached to a skill (readReference)+3. Execute shell commands specified in a skill's instructions (execScript)+4. Export files generated during skill execution to cloud storage (exportFile)+5. Import/install a skill from a URL, GitHub link, or ZIP package (importSkill)+6. Search for skills in the LobeHub Market (searchSkill)+7. Import/install a skill directly from the LobeHub Market (importFromMarket)+</core_capabilities>++<workflow>+1. When the user's request matches an available skill, call runSkill with the skill name+2. The skill content will be returned - follow those instructions to complete the task+3. If the skill content references additional files, use readReference to load them+4. If the skill content instructs you to run CLI commands, use execScript to execute them+5. If the skill execution generates output files, use exportFile to save them for the user+6. Apply the skill's instructions to fulfill the user's request+7. When the user wants to install/import a skill from a URL, call importSkill with the URL+8. When the user wants to find/discover skills, use searchSkill to search the LobeHub Market+9. When the user wants to install a skill from search results, use importFromMarket with the skill identifier+</workflow>++<tool_selection_guidelines>+- **runSkill**: Call this when the user's task matches one of the available skills+ - Provide the exact skill name+ - Returns the skill content (instructions, templates, guidelines) that you should follow+ - If the skill is not found, you'll receive a list of available skills++- **readReference**: Call this to read reference files mentioned in a skill's content+ - Requires the id (returned by runSkill) and the file path+ - Returns the file content for you to use as context+ - Only use paths that are referenced in the skill content++- **execScript**: Call this to execute shell commands mentioned in a skill's content+ - **IMPORTANT**: Always provide the \`config\` parameter with the current skill's id and name (from runSkill's state)+ - **USE CASE**: This is the preferred tool for executing commands from skill scripts+ - Automatically locates and provides skill resources (files, dependencies) to the execution environment+ - Provide the command to execute and a clear description of what it does+ - Returns the command output (stdout/stderr)+ - Only execute commands that are specified or suggested in the skill content+ - Requires user confirmation before execution+ - **If execScript fails or encounters issues, fall back to using the Cloud Sandbox's runCommand tool**++- **exportFile**: Call this to export files generated during skill execution+ - Use this when a skill generates output files that the user needs to download+ - Provide the file path in the execution environment and the desired filename+ - Returns a permanent download URL for the exported file+ - Best for: skill outputs, generated reports, processed data files, result artifacts++- **importSkill**: Call this to import/install a skill from a URL+ - Provide the URL and the type ("url" for SKILL.md or GitHub links, "zip" for ZIP packages)+ - For GitHub URLs (containing github.com), use type "url" — the system will auto-detect GitHub+ - Requires user confirmation before installation+ - Returns the skill name and import status (created/updated/unchanged)++- **searchSkill**: Call this to search for skills in the LobeHub Market+ - Provide a search query to find relevant skills+ - Returns a list of matching skills with name, description, author, and identifier+ - Use this when the user wants to discover or find new skills+ - After finding a skill, use importFromMarket to install it++- **importFromMarket**: Call this to install a skill directly from the LobeHub Market+ - Provide the skill identifier (obtained from searchSkill results)+ - Downloads and installs the skill from the market+ - Requires user confirmation before installation+ - Returns the skill name and import status (created/updated/unchanged)+ - Preferred over importSkill when the skill is available in the LobeHub Market+</tool_selection_guidelines>++<execscript_vs_runcommand>+**When to use execScript vs Cloud Sandbox runCommand:**++- **execScript (Preferred for skill scripts)**:+ - Use when executing commands that are part of a skill's workflow+ - Automatically provides skill resources (ZIP package with scripts, config files, dependencies)+ - Server locates the skill package and makes it available in the execution environment+ - Best for: skill-specific scripts, tool initialization, workflows defined in skills++- **Cloud Sandbox runCommand (Fallback or general commands)**:+ - Use for general shell commands that don't require skill resources+ - Use as fallback when execScript encounters errors or limitations+ - Use for ad-hoc commands not related to any specific skill+ - Best for: system commands, package installations, file operations++**Example workflow:**+1. User activates a skill with runSkill+2. Skill content instructs to run a script (e.g., "python scripts/init.py")+3. Use execScript with the skill's config to execute the script (skill resources automatically available)+4. If execScript fails, inform user and optionally try runCommand as fallback+</execscript_vs_runcommand>++${isDesktop ? runInClientSection : ''}+<best_practices>+- Only activate skills when the user's task clearly matches the skill's purpose+- Follow the skill's instructions carefully once loaded+- Use readReference only for files explicitly mentioned in the skill content+- Use execScript only for commands specified in the skill content, always including config parameter+- Use exportFile when the skill generates output files that need to be saved+- If runSkill returns an error with available skills, inform the user what skills are available+- If execScript fails, consider using Cloud Sandbox's runCommand as a fallback+- Use searchSkill to help users discover skills when they describe a task but don't know a specific skill+- Prefer importFromMarket over importSkill when the skill is available in the LobeHub Market+</best_practices>+`;diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.tsnew file mode 100644index 00000000000..c88a9d5c08b--- /dev/null+++ b/packages/builtin-tool-skills/src/types.ts@@ -0,0 +1,174 @@+export const SkillsIdentifier = 'lobe-skills';++export const SkillsApiName = {+ execScript: 'execScript',+ exportFile: 'exportFile',+ importSkill: 'importSkill',+ importFromMarket: 'importFromMarket',+ readReference: 'readReference',+ runSkill: 'runSkill',+ searchSkill: 'searchSkill',+};++export interface RunSkillParams {+ name: string;+}++export interface RunSkillState {+ description?: string;+ hasResources: boolean;+ id: string;+ name: string;+}++export interface ExecScriptParams {+ command: string;+ /**+ * Skill configuration context+ * Used by server to locate skill resources (zipUrl will be resolved server-side)+ */+ config?: {+ /**+ * Current skill's description+ */+ description?: string;+ /**+ * Current skill's ID+ */+ id?: string;+ /**+ * Current skill's name+ */+ name?: string;+ };+ description: string;+ /**+ * Whether to run on the desktop client (for local shell access).+ * Only available on desktop. When false or omitted, runs in cloud sandbox.+ */+ runInClient?: boolean;+}++export interface ExecScriptState {+ command: string;+ exitCode: number;+ success: boolean;+}++export interface RunCommandOptions {+ command: string;+ runInClient?: boolean;+ timeout?: number;+}++export interface CommandResult {+ exitCode: number;+ output: string;+ stderr?: string;+ success: boolean;+}++export interface ReadReferenceParams {+ id: string;+ path: string;+}++export interface ReadReferenceState {+ encoding: 'base64' | 'utf-8';+ fileType: string;+ path: string;+ size: number;+}++export interface ImportSkillParams {+ type: 'url' | 'zip';+ url: string;+}++export interface ImportSkillState {+ name?: string;+ skillId?: string;+ status: 'created' | 'updated' | 'unchanged';+ success: boolean;+}++export interface ExportFileParams {+ /**+ * The filename to use for the exported file+ */+ filename: string;+ /**+ * The path of the file in the skill execution environment to export+ */+ path: string;+}++export interface ExportFileState {+ fileId?: string;+ filename: string;+ mimeType?: string;+ size?: number;+ url?: string;+}++export interface SearchSkillParams {+ /**+ * Locale for search results (e.g., 'en-US', 'zh-CN')+ */+ locale?: string;+ /**+ * Sort order: 'asc' or 'desc'+ */+ order?: 'asc' | 'desc';+ /**+ * Page number (default: 1)+ */+ page?: number;+ /**+ * Page size (default: 20)+ */+ pageSize?: number;+ /**+ * Search query (searches name, description, summary)+ */+ search?: string;+ /**+ * Sort field: createdAt | downloadCount | forks | name | stars | updatedAt | watchers+ */+ sort?: 'createdAt' | 'downloadCount' | 'forks' | 'name' | 'stars' | 'updatedAt' | 'watchers';+}++export interface MarketSkillItem {+ category?: string;+ createdAt: string;+ description: string;+ downloadCount: number;+ identifier: string;+ name: string;+ repository?: string;+ sourceUrl?: string;+ summary?: string;+ updatedAt: string;+ version?: string;+}++export interface SearchSkillState {+ items: MarketSkillItem[];+ page: number;+ pageSize: number;+ total: number;+}++export interface ImportFromMarketParams {+ /**+ * The identifier of the skill to import from market+ */+ identifier: string;+}++export interface ImportFromMarketState {+ name?: string;+ skillId?: string;+ status: 'created' | 'updated' | 'unchanged';+ success: boolean;+}diff --git a/packages/context-engine/src/engine/index.ts b/packages/context-engine/src/engine/index.tsindex 740cf65fceb..1d2a11f4b3c 100644--- a/packages/context-engine/src/engine/index.ts+++ b/packages/context-engine/src/engine/index.ts@@ -1,3 +1,5 @@+// Skills Engine+export * from './skills';// Tools Engineexport * from './tools';// Messages Enginediff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex f927e206346..2e495fb95f8 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -32,6 +32,7 @@ import {KnowledgeInjector,PageEditorContextInjector,PageSelectionsInjector,+ SkillContextProvider,SystemRoleInjector,ToolSystemRoleProvider,UserMemoryInjector,@@ -120,6 +121,7 @@ export class MessagesEngine {historySummary,formatHistorySummary,knowledge,+ skillsConfig,toolsConfig,capabilities,variableGenerators,@@ -203,6 +205,15 @@ export class MessagesEngine {groupContext: groupAgentBuilderContext,}),+ // 7.5. Skill context injection (conditionally added)+ ...(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0+ ? [+ new SkillContextProvider({+ enabledSkills: skillsConfig.enabledSkills,+ }),+ ]+ : []),+// 8. Tool system role injection (conditionally added)...(toolsConfig?.manifests && toolsConfig.manifests.length > 0? [diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex bb8d917966b..5659384ebc4 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -11,6 +11,7 @@ import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderimport type { GroupMemberInfo } from '../../providers/GroupContextInjector';import type { GTDPlan } from '../../providers/GTDPlanInjector';import type { GTDTodoList } from '../../providers/GTDTodoInjector';+import type { SkillMeta } from '../../providers/SkillContextProvider';import type { LobeToolManifest } from '../tools/types';/**@@ -46,6 +47,13 @@ export interface ToolsConfig {tools?: string[];}+/**+ * Skills configuration+ */+export interface SkillsConfig {+ enabledSkills?: SkillMeta[];+}+/*** Variable generators for placeholder replacement* Used to replace {{variable}} placeholders in messages@@ -204,6 +212,10 @@ export interface MessagesEngineParams {/** Knowledge configuration */knowledge?: KnowledgeConfig;+ // ========== Skills ==========+ /** Skills configuration */+ skillsConfig?: SkillsConfig;+// ========== Tools ==========/** Tools configuration */toolsConfig?: ToolsConfig;@@ -275,5 +287,6 @@ export { type EvalContext } from '../../providers/EvalContextSystemInjector';export { type GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';export { type GTDPlan } from '../../providers/GTDPlanInjector';export { type GTDTodoItem, type GTDTodoList } from '../../providers/GTDTodoInjector';+export { type SkillMeta } from '../../providers/SkillContextProvider';export { type OpenAIChatMessage, type UIChatMessage } from '@/types/index';export { type FileContent, type KnowledgeBaseInfo } from '@lobechat/prompts';diff --git a/packages/context-engine/src/engine/skills/SkillEngine.ts b/packages/context-engine/src/engine/skills/SkillEngine.tsnew file mode 100644index 00000000000..d12f6b12ec6--- /dev/null+++ b/packages/context-engine/src/engine/skills/SkillEngine.ts@@ -0,0 +1,38 @@+import debug from 'debug';++import type { SkillMeta } from '../../providers/SkillContextProvider';++const log = debug('context-engine:skills-engine');++export interface SkillEngineOptions {+ skills: SkillMeta[];+}++/**+ * Skills Engine - Filters available skills by agent configuration+ *+ * Accepts a pre-merged array of SkillMeta from all sources (builtin, DB, etc.)+ * and provides filtering by agent's enabled plugin IDs.+ */+export class SkillEngine {+ private skills: Map<string, SkillMeta>;++ constructor(options: SkillEngineOptions) {+ this.skills = new Map(options.skills.map((s) => [s.identifier, s]));+ log('Initialized with %d skills: %o', this.skills.size, Array.from(this.skills.keys()));+ }++ /**+ * Filter skills by agent's enabled plugin IDs+ */+ getEnabledSkills(pluginIds: string[]): SkillMeta[] {+ return pluginIds.map((id) => this.skills.get(id)).filter((s): s is SkillMeta => !!s);+ }++ /**+ * Get all registered skills+ */+ getAllSkills(): SkillMeta[] {+ return Array.from(this.skills.values());+ }+}diff --git a/packages/context-engine/src/engine/skills/index.ts b/packages/context-engine/src/engine/skills/index.tsnew file mode 100644index 00000000000..c250ef8e8b8--- /dev/null+++ b/packages/context-engine/src/engine/skills/index.ts@@ -0,0 +1 @@+export { SkillEngine, type SkillEngineOptions } from './SkillEngine';diff --git a/packages/context-engine/src/providers/SkillContextProvider.ts b/packages/context-engine/src/providers/SkillContextProvider.tsnew file mode 100644index 00000000000..86351427f55--- /dev/null+++ b/packages/context-engine/src/providers/SkillContextProvider.ts@@ -0,0 +1,100 @@+import { type SkillItem, skillsPrompts } from '@lobechat/prompts';+import debug from 'debug';++import { BaseProvider } from '../base/BaseProvider';+import type { PipelineContext, ProcessorOptions } from '../types';++const log = debug('context-engine:provider:SkillContextProvider');++/**+ * Lightweight skill metadata for context injection+ * Compatible with the SkillMeta that will be added in @lobechat/types (Phase 3.2)+ */+export interface SkillMeta {+ description: string;+ identifier: string;+ location?: string;+ name: string;+}++/**+ * Skill Context Provider Configuration+ */+export interface SkillContextProviderConfig {+ enabledSkills: SkillMeta[];+}++/**+ * Skill Context Provider+ * Injects lightweight skill metadata into the system prompt so the LLM knows+ * which skills are available and can invoke them via `runSkill`.+ */+export class SkillContextProvider extends BaseProvider {+ readonly name = 'SkillContextProvider';++ constructor(+ private config: SkillContextProviderConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ const clonedContext = this.cloneContext(context);++ const { enabledSkills } = this.config;++ if (!enabledSkills || enabledSkills.length === 0) {+ log('No enabled skills, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ const skills: SkillItem[] = enabledSkills.map((skill) => ({+ description: skill.description,+ identifier: skill.identifier,+ location: skill.location,+ name: skill.name,+ }));++ const skillContent = skillsPrompts(skills);++ if (!skillContent) {+ log('No skill content generated, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ this.injectSkillContext(clonedContext, skillContent);++ clonedContext.metadata.skillContext = {+ injected: true,+ skillsCount: enabledSkills.length,+ };++ log(`Skill context injected, skills count: ${enabledSkills.length}`);+ return this.markAsExecuted(clonedContext);+ }++ /**+ * Inject skill context into the system message+ */+ private injectSkillContext(context: PipelineContext, skillContent: string): void {+ const existingSystemMessage = context.messages.find((msg) => msg.role === 'system');++ if (existingSystemMessage) {+ existingSystemMessage.content = [existingSystemMessage.content, skillContent]+ .filter(Boolean)+ .join('\n\n');++ log(+ `Skill context merged to existing system message, final length: ${existingSystemMessage.content.length}`,+ );+ } else {+ context.messages.unshift({+ content: skillContent,+ id: `skill-context-${Date.now()}`,+ role: 'system' as const,+ } as any);+ log(`New skill system message created, content length: ${skillContent.length}`);+ }+ }+}diff --git a/packages/context-engine/src/providers/__tests__/SkillContextProvider.test.ts b/packages/context-engine/src/providers/__tests__/SkillContextProvider.test.tsnew file mode 100644index 00000000000..4e964f825ed--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/SkillContextProvider.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { SkillContextProvider } from '../SkillContextProvider';+import type { SkillMeta } from '../SkillContextProvider';++const createContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] } as any,+ isAborted: false,+ messages,+ metadata: { maxTokens: 4096, model: 'gpt-4' },+});++const createSkills = (): SkillMeta[] => [+ {+ description: 'Generate interactive UI components',+ identifier: 'artifacts',+ location: '/path/to/skills/artifacts/SKILL.md',+ name: 'Artifacts',+ },+ {+ description: 'Custom skill description',+ identifier: 'my-skill',+ name: 'My Skill',+ },+];++describe('SkillContextProvider', () => {+ it('should inject skill metadata when skills are provided', async () => {+ const skills = createSkills();+ const provider = new SkillContextProvider({ enabledSkills: skills });++ const messages = [{ content: 'Hello', id: 'u1', role: 'user' }];+ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage).toBeDefined();+ expect(systemMessage!.content).toMatchSnapshot();++ expect(result.metadata.skillContext).toEqual({+ injected: true,+ skillsCount: 2,+ });+ });++ it('should merge with existing system message', async () => {+ const skills = createSkills();+ const provider = new SkillContextProvider({ enabledSkills: skills });++ const existingSystemContent = 'You are a helpful assistant.';+ const messages = [+ { content: existingSystemContent, id: 's1', role: 'system' },+ { content: 'Hello', id: 'u1', role: 'user' },+ ];++ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage!.content).toMatchSnapshot();+ });++ it('should skip injection when no skills are provided', async () => {+ const provider = new SkillContextProvider({ enabledSkills: [] });++ const messages = [{ content: 'Hello', id: 'u1', role: 'user' }];+ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage).toBeUndefined();+ expect(result.metadata.skillContext).toBeUndefined();+ });++ it('should render XML with location attribute', async () => {+ const skills: SkillMeta[] = [+ {+ description: 'Extracts text from PDF files',+ identifier: 'pdf-processing',+ location: '/path/to/skills/pdf-processing/SKILL.md',+ name: 'PDF Processing',+ },+ {+ description: 'Analyzes datasets and generates charts',+ identifier: 'data-analysis',+ location: '/path/to/skills/data-analysis/SKILL.md',+ name: 'Data Analysis',+ },+ ];+ const provider = new SkillContextProvider({ enabledSkills: skills });++ const messages = [{ content: 'Hello', id: 'u1', role: 'user' }];+ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage!.content).toMatchSnapshot();+ });++ it('should render XML without location when not provided', async () => {+ const skills: SkillMeta[] = [+ {+ description: 'Custom skill description',+ identifier: 'my-skill',+ name: 'My Skill',+ },+ ];+ const provider = new SkillContextProvider({ enabledSkills: skills });++ const messages = [{ content: 'Hello', id: 'u1', role: 'user' }];+ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage!.content).toMatchSnapshot();+ });++ it('should only inject lightweight metadata without content field', async () => {+ const skills: SkillMeta[] = [+ {+ description: 'Generate interactive UI components',+ identifier: 'artifacts',+ location: '/path/to/skills/artifacts/SKILL.md',+ name: 'Artifacts',+ },+ ];+ const provider = new SkillContextProvider({ enabledSkills: skills });++ const messages = [{ content: 'Hello', id: 'u1', role: 'user' }];+ const ctx = createContext(messages);+ const result = await provider.process(ctx);++ const systemMessage = result.messages.find((msg) => msg.role === 'system');+ expect(systemMessage!.content).not.toContain('<content>');+ expect(systemMessage!.content).toMatchSnapshot();+ });+});diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/SkillContextProvider.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/SkillContextProvider.test.ts.snapnew file mode 100644index 00000000000..a5d92ca18fa--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/SkillContextProvider.test.ts.snap@@ -0,0 +1,46 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`SkillContextProvider > should inject skill metadata when skills are provided 1`] = `+"<available_skills>+ <skill name="Artifacts" location="/path/to/skills/artifacts/SKILL.md">Generate interactive UI components</skill>+ <skill name="My Skill">Custom skill description</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed."+`;++exports[`SkillContextProvider > should merge with existing system message 1`] = `+"You are a helpful assistant.++<available_skills>+ <skill name="Artifacts" location="/path/to/skills/artifacts/SKILL.md">Generate interactive UI components</skill>+ <skill name="My Skill">Custom skill description</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed."+`;++exports[`SkillContextProvider > should only inject lightweight metadata without content field 1`] = `+"<available_skills>+ <skill name="Artifacts" location="/path/to/skills/artifacts/SKILL.md">Generate interactive UI components</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed."+`;++exports[`SkillContextProvider > should render XML with location attribute 1`] = `+"<available_skills>+ <skill name="PDF Processing" location="/path/to/skills/pdf-processing/SKILL.md">Extracts text from PDF files</skill>+ <skill name="Data Analysis" location="/path/to/skills/data-analysis/SKILL.md">Analyzes datasets and generates charts</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed."+`;++exports[`SkillContextProvider > should render XML without location when not provided 1`] = `+"<available_skills>+ <skill name="My Skill">Custom skill description</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed."+`;diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 21a7bd222d2..716bb054323 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -10,6 +10,7 @@ export { HistorySummaryProvider } from './HistorySummary';export { KnowledgeInjector } from './KnowledgeInjector';export { PageEditorContextInjector } from './PageEditorContextInjector';export { PageSelectionsInjector } from './PageSelectionsInjector';+export { SkillContextProvider } from './SkillContextProvider';export { SystemRoleInjector } from './SystemRoleInjector';export { ToolSystemRoleProvider } from './ToolSystemRole';export { UserMemoryInjector } from './UserMemoryInjector';@@ -38,6 +39,7 @@ export type { HistorySummaryConfig } from './HistorySummary';export type { KnowledgeInjectorConfig } from './KnowledgeInjector';export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';+export type { SkillContextProviderConfig, SkillMeta } from './SkillContextProvider';export type { SystemRoleInjectorConfig } from './SystemRoleInjector';export type { ToolSystemRoleConfig } from './ToolSystemRole';export type { MemoryContext, UserMemoryInjectorConfig } from './UserMemoryInjector';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 63f23a5693e..ee06d7c8db6 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -10,5 +10,6 @@ export * from './knowledgeBaseQA';export * from './messagesToText';export * from './plugin';export * from './search';+export * from './skills';export * from './systemRole';export * from './userMemory';diff --git a/packages/prompts/src/prompts/skills/index.test.ts b/packages/prompts/src/prompts/skills/index.test.tsnew file mode 100644index 00000000000..cc98e869732--- /dev/null+++ b/packages/prompts/src/prompts/skills/index.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';++import { type SkillItem, skillPrompt, skillsPrompts } from './index';++describe('skillPrompt', () => {+ it('should generate skill tag with location', () => {+ const skill: SkillItem = {+ description: 'Extracts text and tables from PDF files',+ identifier: 'pdf-processing',+ location: '/path/to/skills/pdf-processing/SKILL.md',+ name: 'PDF Processing',+ };++ expect(skillPrompt(skill)).toBe(+ ' <skill name="PDF Processing" location="/path/to/skills/pdf-processing/SKILL.md">Extracts text and tables from PDF files</skill>',+ );+ });++ it('should generate skill tag without location', () => {+ const skill: SkillItem = {+ description: 'Custom skill description',+ identifier: 'my-skill',+ name: 'My Skill',+ };++ expect(skillPrompt(skill)).toBe(' <skill name="My Skill">Custom skill description</skill>');+ });+});++describe('skillsPrompts', () => {+ it('should generate available_skills block with multiple skills', () => {+ const skills: SkillItem[] = [+ {+ description: 'Extracts text and tables from PDF files',+ identifier: 'pdf-processing',+ location: '/path/to/skills/pdf-processing/SKILL.md',+ name: 'PDF Processing',+ },+ {+ description: 'Analyzes datasets and generates charts',+ identifier: 'data-analysis',+ location: '/path/to/skills/data-analysis/SKILL.md',+ name: 'Data Analysis',+ },+ ];++ const expected = `<available_skills>+ <skill name="PDF Processing" location="/path/to/skills/pdf-processing/SKILL.md">Extracts text and tables from PDF files</skill>+ <skill name="Data Analysis" location="/path/to/skills/data-analysis/SKILL.md">Analyzes datasets and generates charts</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed.`;++ expect(skillsPrompts(skills)).toBe(expected);+ });++ it('should generate mixed skills with and without location', () => {+ const skills: SkillItem[] = [+ {+ description: 'Generate interactive UI components',+ identifier: 'artifacts',+ location: '/path/to/skills/artifacts/SKILL.md',+ name: 'Artifacts',+ },+ {+ description: 'Custom skill description',+ identifier: 'my-skill',+ name: 'My Skill',+ },+ ];++ const expected = `<available_skills>+ <skill name="Artifacts" location="/path/to/skills/artifacts/SKILL.md">Generate interactive UI components</skill>+ <skill name="My Skill">Custom skill description</skill>+</available_skills>++Use the runSkill tool to activate a skill when needed.`;++ expect(skillsPrompts(skills)).toBe(expected);+ });++ it('should return empty string for empty skills array', () => {+ expect(skillsPrompts([])).toBe('');+ });+});diff --git a/packages/prompts/src/prompts/skills/index.ts b/packages/prompts/src/prompts/skills/index.tsnew file mode 100644index 00000000000..4686bf8d44c--- /dev/null+++ b/packages/prompts/src/prompts/skills/index.ts@@ -0,0 +1,25 @@+export { buildResourcesTreeText, resourcesTreePrompt } from './resourcesTree';++export interface SkillItem {+ description: string;+ identifier: string;+ location?: string;+ name: string;+}++export const skillPrompt = (skill: SkillItem) =>+ skill.location+ ? ` <skill name="${skill.name}" location="${skill.location}">${skill.description}</skill>`+ : ` <skill name="${skill.name}">${skill.description}</skill>`;++export const skillsPrompts = (skills: SkillItem[]) => {+ if (skills.length === 0) return '';++ const skillTags = skills.map((skill) => skillPrompt(skill)).join('\n');++ return `<available_skills>+${skillTags}+</available_skills>++Use the runSkill tool to activate a skill when needed.`;+};diff --git a/packages/prompts/src/prompts/skills/resourcesTree.ts b/packages/prompts/src/prompts/skills/resourcesTree.tsnew file mode 100644index 00000000000..79568db6003--- /dev/null+++ b/packages/prompts/src/prompts/skills/resourcesTree.ts@@ -0,0 +1,90 @@+import type { SkillResourceMeta } from '@lobechat/types';++interface TreeNode {+ children: Map<string, TreeNode>;+ name: string;+ size?: number;+}++const formatSize = (bytes: number): string => {+ if (bytes === 0) return '0 B';+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++const buildTree = (resources: Record<string, SkillResourceMeta>): TreeNode => {+ const root: TreeNode = { children: new Map(), name: '' };++ for (const [path, meta] of Object.entries(resources)) {+ const parts = path.split('/');+ let current = root;++ for (let i = 0; i < parts.length; i++) {+ const part = parts[i];+ const isFile = i === parts.length - 1;++ if (!current.children.has(part)) {+ current.children.set(part, {+ children: new Map(),+ name: part,+ size: isFile ? meta.size : undefined,+ });+ }++ current = current.children.get(part)!;+ }+ }++ return root;+};++const renderTree = (node: TreeNode, prefix: string = ''): string[] => {+ const lines: string[] = [];+ const entries = [...node.children.entries()].sort(([a], [b]) => {+ // Directories first, then files+ const aIsDir = node.children.get(a)!.children.size > 0;+ const bIsDir = node.children.get(b)!.children.size > 0;+ if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;+ return a.localeCompare(b);+ });++ for (let i = 0; i < entries.length; i++) {+ const [, child] = entries[i];+ const isLast = i === entries.length - 1;+ const connector = isLast ? '└── ' : '├── ';+ const isDir = child.children.size > 0;++ if (isDir) {+ lines.push(`${prefix}${connector}${child.name}/`);+ const childPrefix = prefix + (isLast ? ' ' : '│ ');+ lines.push(...renderTree(child, childPrefix));+ } else {+ const sizeText = child.size !== undefined ? ` (${formatSize(child.size)})` : '';+ lines.push(`${prefix}${connector}${child.name}${sizeText}`);+ }+ }++ return lines;+};++export const buildResourcesTreeText = (resources: Record<string, SkillResourceMeta>): string => {+ const tree = buildTree(resources);+ const lines = renderTree(tree);+ return lines.join('\n');+};++export const resourcesTreePrompt = (+ skillName: string,+ resources: Record<string, SkillResourceMeta>,+): string => {+ const treeText = buildResourcesTreeText(resources);++ return `## Available Resources++Use \`readReference\` with skillName="${skillName}" and the file path to read these files.++\`\`\`+${treeText}+\`\`\``;+};diff --git a/packages/types/package.json b/packages/types/package.jsonindex 5a89ba33e44..2bcc27c3ab6 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -8,7 +8,7 @@"@lobechat/python-interpreter": "workspace:*","@lobechat/web-crawler": "workspace:*","@lobehub/chat-plugin-sdk": "^1.32.4",- "@lobehub/market-sdk": "0.29.1",+ "@lobehub/market-sdk": "0.29.3","@lobehub/market-types": "^1.12.3","model-bank": "workspace:*","type-fest": "^4.41.0",diff --git a/packages/types/src/skill/index.ts b/packages/types/src/skill/index.tsindex 9571a441169..8c5c8edf39b 100644--- a/packages/types/src/skill/index.ts+++ b/packages/types/src/skill/index.ts@@ -9,7 +9,8 @@ export const skillAuthorSchema = z.object({export const skillManifestSchema = z.object({- author: skillAuthorSchema.optional(),+ // Author can be either a string or an object (for compatibility with market skills)+ author: z.union([z.string(), skillAuthorSchema]).optional(),// Required: skill descriptiondescription: z.string().min(1, 'Skill description is required'),@@ -45,6 +46,7 @@ export interface BuiltinSkill {description: string;identifier: string;name: string;+ source: 'builtin';}// ===== Skill Source =====@@ -81,6 +83,7 @@ export interface SkillResourceMeta {export interface SkillResourceTreeNode {children?: SkillResourceTreeNode[];+ content?: string;name: string;path: string;type: 'file' | 'directory';diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 99d77a91530..2b45d29cdab 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -1,5 +1,5 @@export * from './base64';-export * from './chunkers'+export * from './chunkers';export * from './client/cookie';export * from './detectChinese';export * from './env';@@ -9,6 +9,7 @@ export * from './format';export * from './imageToBase64';export * from './keyboard';export * from './merge';+export * from './mimeType';export * from './multimodalContent';export * from './number';export * from './object';diff --git a/packages/utils/src/mimeType.ts b/packages/utils/src/mimeType.tsnew file mode 100644index 00000000000..c2f3998f7b5--- /dev/null+++ b/packages/utils/src/mimeType.ts@@ -0,0 +1,31 @@+import mime from 'mime';++// Custom mime types for common code files not recognized by mime package+const CUSTOM_MIME_TYPES: Record<string, string> = {+ '.clj': 'text/x-clojure',+ '.ex': 'text/x-elixir',+ '.exs': 'text/x-elixir',+ '.go': 'text/x-go',+ '.hs': 'text/x-haskell',+ '.kt': 'text/x-kotlin',+ '.lua': 'text/x-lua',+ '.pl': 'text/x-perl',+ '.py': 'text/x-python',+ '.r': 'text/x-r',+ '.rb': 'text/x-ruby',+ '.rs': 'text/x-rust',+ '.scala': 'text/x-scala',+ '.svelte': 'text/x-svelte',+ '.swift': 'text/x-swift',+ '.vue': 'text/x-vue',+};++/**+ * Get MIME type for a file path with fallback for code files+ * @param path - File path or filename+ * @returns MIME type string+ */+export const getMimeType = (path: string): string => {+ const ext = path.slice(path.lastIndexOf('.')).toLowerCase();+ return CUSTOM_MIME_TYPES[ext] || mime.getType(path) || 'application/octet-stream';+};diff --git a/src/app/[variants]/(main)/settings/skill/features/AgentSkillItem.tsx b/src/app/[variants]/(main)/settings/skill/features/AgentSkillItem.tsxnew file mode 100644index 00000000000..874e45599a7--- /dev/null+++ b/src/app/[variants]/(main)/settings/skill/features/AgentSkillItem.tsx@@ -0,0 +1,249 @@+'use client';++import { type BuiltinSkill, type SkillListItem } from '@lobechat/types';+import {+ Avatar,+ Button,+ DropdownMenu,+ Flexbox,+ Icon,+ Modal,+ stopPropagation,+ Tag,+} from '@lobehub/ui';+import { App, Space } from 'antd';+import { DownloadIcon, MoreHorizontalIcon, Plus, PuzzleIcon, Trash2 } from 'lucide-react';+import { lazy, memo, Suspense, useState } from 'react';+import { useTranslation } from 'react-i18next';++import SkillSourceTag from '@/components/SkillSourceTag';+import { createBuiltinAgentSkillDetailModal } from '@/features/SkillStore/SkillDetail';+import { agentSkillService } from '@/services/skill';+import { useToolStore } from '@/store/tool';+import { builtinToolSelectors } from '@/store/tool/selectors';+import { downloadFile } from '@/utils/client/downloadFile';++import { styles } from './style';++const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));+const AgentSkillEdit = lazy(() => import('@/features/AgentSkillEdit'));++const isBuiltinSkill = (skill: BuiltinSkill | SkillListItem): skill is BuiltinSkill =>+ !('id' in skill);++interface AgentSkillItemProps {+ skill: BuiltinSkill | SkillListItem;+}++const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {+ const { t } = useTranslation('setting');+ const { t: tc } = useTranslation('common');+ const { t: tp } = useTranslation('plugin');+ const { modal } = App.useApp();+ const [loading, setLoading] = useState(false);+ const [detailOpen, setDetailOpen] = useState(false);+ const [editOpen, setEditOpen] = useState(false);++ const isBuiltin = isBuiltinSkill(skill);++ const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);+ const [installBuiltinTool, uninstallBuiltinTool, isBuiltinInstalled] = useToolStore((s) => [+ s.installBuiltinTool,+ s.uninstallBuiltinTool,+ isBuiltin ? builtinToolSelectors.isBuiltinToolInstalled(skill.identifier)(s) : true,+ ]);++ const title = isBuiltin+ ? t(`tools.builtins.${skill.identifier}.title`, { defaultValue: skill.name })+ : skill.name;++ const avatar = isBuiltin ? skill.avatar : '🧩';++ // ===== Handlers =====++ const handleDownload = async () => {+ if (isBuiltin || !skill.zipFileHash) return;+ setLoading(true);+ try {+ const result = await agentSkillService.getZipUrl(skill.id);+ if (result.url) {+ await downloadFile(result.url, `${result.name || skill.name}.zip`);+ }+ } finally {+ setLoading(false);+ }+ };++ const handleUninstall = () => {+ modal.confirm({+ centered: true,+ okButtonProps: { danger: true },+ onOk: async () => {+ if (isBuiltin) {+ await uninstallBuiltinTool(skill.identifier);+ } else {+ setLoading(true);+ try {+ await deleteAgentSkill(skill.id);+ } finally {+ setLoading(false);+ }+ }+ },+ title: tp('store.actions.confirmUninstall'),+ type: 'error',+ });+ };++ // ===== Status & Actions =====++ const renderStatus = () => {+ if (!isBuiltin) return null;+ if (isBuiltinInstalled) {+ return <span className={styles.connected}>{t('tools.builtins.installed')}</span>;+ }+ return <span className={styles.disconnected}>{t('tools.builtins.uninstalled')}</span>;+ };++ const renderActions = () => {+ if (isBuiltin) {+ if (isBuiltinInstalled) {+ return (+ <DropdownMenu+ placement="bottomRight"+ items={[+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'uninstall',+ label: tp('store.actions.uninstall'),+ onClick: handleUninstall,+ },+ ]}+ >+ <Button icon={MoreHorizontalIcon} />+ </DropdownMenu>+ );+ }+ return (+ <Button icon={Plus} onClick={() => installBuiltinTool(skill.identifier)}>+ {tp('store.actions.install')}+ </Button>+ );+ }++ return (+ <Space.Compact>+ <Button onClick={() => setEditOpen(true)}>{tp('store.actions.configure')}</Button>+ <DropdownMenu+ placement="bottomRight"+ items={[+ ...(skill.zipFileHash+ ? [+ {+ icon: <DownloadIcon size={16} />,+ key: 'download',+ label: tc('download'),+ onClick: handleDownload,+ },+ { type: 'divider' as const },+ ]+ : []),+ {+ danger: true,+ icon: <Trash2 size={16} />,+ key: 'uninstall',+ label: tp('store.actions.uninstall'),+ onClick: handleUninstall,+ },+ ]}+ >+ <Button icon={MoreHorizontalIcon} loading={loading} />+ </DropdownMenu>+ </Space.Compact>+ );+ };++ // ===== Detail Modal =====++ const handleOpenDetail = () => {+ if (isBuiltin) {+ createBuiltinAgentSkillDetailModal({ identifier: skill.identifier });+ } else {+ setDetailOpen(true);+ }+ };++ const renderDetailModal = () => {+ if (isBuiltin) return null;+ return (+ <>+ <Modal+ destroyOnHidden+ footer={null}+ open={detailOpen}+ styles={{ body: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } }}+ title={tp('dev.title.skillDetails')}+ width={960}+ onCancel={() => setDetailOpen(false)}+ >+ <Suspense fallback={<div style={{ height: '100%' }} />}>+ <AgentSkillDetail skillId={skill.id} />+ </Suspense>+ </Modal>+ <Suspense>+ <AgentSkillEdit open={editOpen} skillId={skill.id} onClose={() => setEditOpen(false)} />+ </Suspense>+ </>+ );+ };++ const showDisconnected = isBuiltin && !isBuiltinInstalled;++ return (+ <>+ <Flexbox+ horizontal+ align="center"+ className={styles.container}+ gap={16}+ justify="space-between"+ >+ <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align="center"+ gap={16}+ style={{ cursor: 'pointer' }}+ onClick={handleOpenDetail}+ >+ <div className={`${styles.icon} ${showDisconnected ? styles.disconnectedIcon : ''}`}>+ <Avatar avatar={avatar} size={32} />+ </div>+ <Flexbox gap={4} style={{ overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8}>+ <span+ className={`${styles.title} ${showDisconnected ? styles.disconnectedTitle : ''}`}+ >+ {title}+ </span>+ {!isBuiltin && <Tag icon={<Icon icon={PuzzleIcon} />} size={'small'} />}+ <SkillSourceTag source={skill.source} />+ </Flexbox>+ {showDisconnected && renderStatus()}+ </Flexbox>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align="center" gap={12} onClick={stopPropagation}>+ {isBuiltin && isBuiltinInstalled && renderStatus()}+ {renderActions()}+ </Flexbox>+ </Flexbox>+ {renderDetailModal()}+ </>+ );+});++AgentSkillItem.displayName = 'AgentSkillItem';++export default AgentSkillItem;diff --git a/src/app/[variants]/(main)/settings/skill/features/BuiltinSkillItem.tsx b/src/app/[variants]/(main)/settings/skill/features/BuiltinSkillItem.tsxindex 51a0bfd1459..63fca947bce 100644--- a/src/app/[variants]/(main)/settings/skill/features/BuiltinSkillItem.tsx+++ b/src/app/[variants]/(main)/settings/skill/features/BuiltinSkillItem.tsx@@ -6,6 +6,7 @@ import { MoreHorizontalIcon, Plus, Trash2 } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import SkillSourceTag from '@/components/SkillSourceTag';import { createBuiltinSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { builtinToolSelectors } from '@/store/tool/selectors';@@ -104,9 +105,12 @@ const BuiltinSkillItem = memo<BuiltinSkillItemProps>(({ identifier, title, avata<Avatar avatar={avatar} size={32} /></div><Flexbox gap={4} style={{ overflow: 'hidden' }}>- <span className={`${styles.title} ${!isInstalled ? styles.disconnectedTitle : ''}`}>- {title}- </span>+ <Flexbox horizontal align="center" gap={8}>+ <span className={`${styles.title} ${!isInstalled ? styles.disconnectedTitle : ''}`}>+ {title}+ </span>+ <SkillSourceTag source="builtin" />+ </Flexbox>{!isInstalled && renderStatus()}</Flexbox></Flexbox>diff --git a/src/app/[variants]/(main)/settings/skill/features/KlavisSkillItem.tsx b/src/app/[variants]/(main)/settings/skill/features/KlavisSkillItem.tsxindex c79f0c5953a..062a2614596 100644--- a/src/app/[variants]/(main)/settings/skill/features/KlavisSkillItem.tsx+++ b/src/app/[variants]/(main)/settings/skill/features/KlavisSkillItem.tsx@@ -8,6 +8,7 @@ import { Loader2, MoreHorizontalIcon, SquareArrowOutUpRight, Unplug } from 'luciimport { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import SkillSourceTag from '@/components/SkillSourceTag';import { createKlavisSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { type KlavisServer } from '@/store/tool/slices/klavisStore';@@ -295,9 +296,12 @@ const KlavisSkillItem = memo<KlavisSkillItemProps>(({ serverType, server }) => {{renderIcon()}</div><Flexbox gap={4} style={{ overflow: 'hidden' }}>- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>- {serverType.label}- </span>+ <Flexbox horizontal align="center" gap={8}>+ <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>+ {serverType.label}+ </span>+ <SkillSourceTag source="builtin" />+ </Flexbox>{!isConnected && renderStatus()}</Flexbox></Flexbox>diff --git a/src/app/[variants]/(main)/settings/skill/features/LobehubSkillItem.tsx b/src/app/[variants]/(main)/settings/skill/features/LobehubSkillItem.tsxindex 8a48e419717..8b6d0094040 100644--- a/src/app/[variants]/(main)/settings/skill/features/LobehubSkillItem.tsx+++ b/src/app/[variants]/(main)/settings/skill/features/LobehubSkillItem.tsx@@ -8,6 +8,7 @@ import { Loader2, MoreHorizontalIcon, SquareArrowOutUpRight, Unplug } from 'luciimport { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import SkillSourceTag from '@/components/SkillSourceTag';import { createLobehubSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { type LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';@@ -274,9 +275,12 @@ const LobehubSkillItem = memo<LobehubSkillItemProps>(({ provider, server }) => {{renderIcon()}</div><Flexbox gap={4} style={{ overflow: 'hidden' }}>- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>- {provider.label}- </span>+ <Flexbox horizontal align="center" gap={8}>+ <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>+ {provider.label}+ </span>+ <SkillSourceTag source="builtin" />+ </Flexbox>{!isConnected && renderStatus()}</Flexbox></Flexbox>diff --git a/src/app/[variants]/(main)/settings/skill/features/McpSkillItem.tsx b/src/app/[variants]/(main)/settings/skill/features/McpSkillItem.tsxindex b5d88860603..bad01e4a0fe 100644--- a/src/app/[variants]/(main)/settings/skill/features/McpSkillItem.tsx+++ b/src/app/[variants]/(main)/settings/skill/features/McpSkillItem.tsx@@ -4,8 +4,10 @@ import { Flexbox, Modal } from '@lobehub/ui';import { memo, Suspense, useState } from 'react';import { useTranslation } from 'react-i18next';+import MCPTag from '@/components/Plugins/MCPTag';import PluginAvatar from '@/components/Plugins/PluginAvatar';import PluginTag from '@/components/Plugins/PluginTag';+import SkillSourceTag from '@/components/SkillSourceTag';import McpDetail from '@/features/MCP/MCPDetail';import McpDetailLoading from '@/features/MCP/MCPDetail/Loading';import PluginDetailModal from '@/features/PluginDetailModal';@@ -44,20 +46,21 @@ const McpSkillItem = memo<McpSkillItemProps>(gap={16}justify="space-between">- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>- <Flexbox- horizontal- align="center"- gap={16}- style={{ cursor: 'pointer' }}- onClick={() => setDetailOpen(true)}- >- <div className={styles.icon}>- <PluginAvatar avatar={avatar} size={32} />- </div>- <span className={styles.title}>{title}</span>+ <Flexbox horizontal align="center" gap={12} style={{ flex: 1, overflow: 'hidden' }}>+ <div className={styles.icon}>+ <PluginAvatar avatar={avatar} size={32} />+ </div>+ <Flexbox horizontal align="center" gap={8} style={{ overflow: 'hidden' }}>+ <span className={styles.title} onClick={() => setDetailOpen(true)}>+ {title}+ </span>+ {isCustomPlugin ? (+ <MCPTag showText={false} />+ ) : (+ <PluginTag author={author} isMCP={isMCP} type={type} />+ )}+ <SkillSourceTag source={isCustomPlugin ? 'user' : 'market'} /></Flexbox>- <PluginTag author={author} isMCP={isMCP} type={type} /></Flexbox><Actions identifier={identifier} isMCP={isMCP} type={type} /></Flexbox>diff --git a/src/app/[variants]/(main)/settings/skill/features/SkillList.tsx b/src/app/[variants]/(main)/settings/skill/features/SkillList.tsxindex b2f93c0c709..b5263665248 100644--- a/src/app/[variants]/(main)/settings/skill/features/SkillList.tsx+++ b/src/app/[variants]/(main)/settings/skill/features/SkillList.tsx@@ -1,15 +1,16 @@'use client';-import { type KlavisServerType, type LobehubSkillProviderType } from '@lobechat/const';import {getKlavisServerByServerIdentifier,getLobehubSkillProviderById,KLAVIS_SERVER_TYPES,+ type KlavisServerType,LOBEHUB_SKILL_PROVIDERS,+ type LobehubSkillProviderType,RECOMMENDED_SKILLS,RecommendedSkillType,} from '@lobechat/const';-import { type LobeBuiltinTool } from '@lobechat/types';+import { type BuiltinSkill, type LobeBuiltinTool } from '@lobechat/types';import { Center, Empty } from '@lobehub/ui';import { Divider } from 'antd';import { createStaticStyles } from 'antd-style';@@ -23,6 +24,7 @@ import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useToolStore } from '@/store/tool';import {+ agentSkillsSelectors,builtinToolSelectors,klavisStoreSelectors,lobehubSkillStoreSelectors,@@ -32,6 +34,7 @@ import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';import { type LobeToolType } from '@/types/tool/tool';+import AgentSkillItem from './AgentSkillItem';import BuiltinSkillItem from './BuiltinSkillItem';import KlavisSkillItem from './KlavisSkillItem';import LobehubSkillItem from './LobehubSkillItem';@@ -62,6 +65,9 @@ const SkillList = memo(() => {const allLobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);+ const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);const uninstalledBuiltinTools = useToolStore(builtinToolSelectors.uninstalledBuiltinTools,@@ -71,16 +77,19 @@ const SkillList = memo(() => {const [useFetchLobehubSkillConnections,useFetchUserKlavisServers,+ useFetchAgentSkills,useFetchUninstalledBuiltinTools,] = useToolStore((s) => [s.useFetchLobehubSkillConnections,s.useFetchUserKlavisServers,+ s.useFetchAgentSkills,s.useFetchUninstalledBuiltinTools,]);useFetchInstalledPlugins();useFetchLobehubSkillConnections(isLobehubSkillEnabled);useFetchUserKlavisServers(isKlavisEnabled);+ useFetchAgentSkills(true);useFetchUninstalledBuiltinTools(true);const getLobehubSkillServerByProvider = (providerId: string) => {@@ -105,11 +114,18 @@ const SkillList = memo(() => {// 3. Custom MCP Tools (type === 'customPlugin')const { integrations, communityMCPs, customMCPs } = useMemo(() => {type IntegrationItem =+ | { builtinAgentSkill: BuiltinSkill; type: 'builtinAgent' }| { builtinTool: LobeBuiltinTool; type: 'builtin' }| { provider: LobehubSkillProviderType; type: 'lobehub' }| { serverType: KlavisServerType; type: 'klavis' };let integrationItems: IntegrationItem[] = [];++ // Add builtin agent skills first so they appear early in the list+ for (const skill of builtinSkills) {+ integrationItems.push({ builtinAgentSkill: skill, type: 'builtinAgent' });+ }+const addedBuiltinIds = new Set<string>();const addedLobehubIds = new Set<string>();const addedKlavisIds = new Set<string>();@@ -202,7 +218,7 @@ const SkillList = memo(() => {// Filter integrations: show all builtin and lobehub skills, but only connected klavisintegrationItems = integrationItems.filter((item) => {- if (item.type === 'builtin' || item.type === 'lobehub') {+ if (item.type === 'builtinAgent' || item.type === 'builtin' || item.type === 'lobehub') {return true;}return (@@ -213,23 +229,31 @@ const SkillList = memo(() => {}// Sort integrations: installed/connected ones first+ const getIsConnected = (item: IntegrationItem) => {+ switch (item.type) {+ case 'builtinAgent': {+ return isBuiltinToolInstalled(item.builtinAgentSkill.identifier);+ }+ case 'builtin': {+ return isBuiltinToolInstalled(item.builtinTool.identifier);+ }+ case 'lobehub': {+ return (+ getLobehubSkillServerByProvider(item.provider.id)?.status ===+ LobehubSkillStatus.CONNECTED+ );+ }+ case 'klavis': {+ return (+ getKlavisServerByIdentifier(item.serverType.identifier)?.status ===+ KlavisServerStatus.CONNECTED+ );+ }+ }+ };const sortedIntegrations = integrationItems.sort((a, b) => {- const isConnectedA =- a.type === 'builtin'- ? isBuiltinToolInstalled(a.builtinTool.identifier)- : a.type === 'lobehub'- ? getLobehubSkillServerByProvider(a.provider.id)?.status ===- LobehubSkillStatus.CONNECTED- : getKlavisServerByIdentifier(a.serverType.identifier)?.status ===- KlavisServerStatus.CONNECTED;- const isConnectedB =- b.type === 'builtin'- ? isBuiltinToolInstalled(b.builtinTool.identifier)- : b.type === 'lobehub'- ? getLobehubSkillServerByProvider(b.provider.id)?.status ===- LobehubSkillStatus.CONNECTED- : getKlavisServerByIdentifier(b.serverType.identifier)?.status ===- KlavisServerStatus.CONNECTED;+ const isConnectedA = getIsConnected(a);+ const isConnectedB = getIsConnected(b);if (isConnectedA && !isConnectedB) return -1;if (!isConnectedA && isConnectedB) return 1;@@ -253,9 +277,16 @@ const SkillList = memo(() => {allKlavisServers,allBuiltinTools,uninstalledBuiltinTools,+ builtinSkills,]);- const hasAnySkills = integrations.length > 0 || communityMCPs.length > 0 || customMCPs.length > 0;+ const hasAnySkills =+ builtinSkills.length > 0 ||+ integrations.length > 0 ||+ marketAgentSkills.length > 0 ||+ userAgentSkills.length > 0 ||+ communityMCPs.length > 0 ||+ customMCPs.length > 0;if (!hasAnySkills) {return (@@ -268,6 +299,11 @@ const SkillList = memo(() => {const renderIntegrations = () =>integrations.map((item) => {+ if (item.type === 'builtinAgent') {+ return (+ <AgentSkillItem key={item.builtinAgentSkill.identifier} skill={item.builtinAgentSkill} />+ );+ }if (item.type === 'builtin') {const localizedTitle = t(`tools.builtins.${item.builtinTool.identifier}.title`, {defaultValue: item.builtinTool.manifest.meta?.title || item.builtinTool.identifier,@@ -299,6 +335,12 @@ const SkillList = memo(() => {);});+ const renderMarketAgentSkills = () =>+ marketAgentSkills.map((skill) => <AgentSkillItem key={skill.id} skill={skill} />);++ const renderUserAgentSkills = () =>+ userAgentSkills.map((skill) => <AgentSkillItem key={skill.id} skill={skill} />);+const renderCommunityMCPs = () =>communityMCPs.map((plugin) => (<McpSkillItem@@ -325,14 +367,20 @@ const SkillList = memo(() => {/>));+ const hasIntegrationsSection = integrations.length > 0;+ const hasCommunitySection = communityMCPs.length > 0 || marketAgentSkills.length > 0;+ const hasCustomSection = userAgentSkills.length > 0 || customMCPs.length > 0;+return (<div className={styles.container}>{integrations.length > 0 && renderIntegrations()}- {integrations.length > 0 && communityMCPs.length > 0 && <Divider style={{ margin: 0 }} />}+ {hasIntegrationsSection && hasCommunitySection && <Divider style={{ margin: 0 }} />}+ {marketAgentSkills.length > 0 && renderMarketAgentSkills()}{communityMCPs.length > 0 && renderCommunityMCPs()}- {(integrations.length > 0 || communityMCPs.length > 0) && customMCPs.length > 0 && (+ {(hasIntegrationsSection || hasCommunitySection) && hasCustomSection && (<Divider style={{ margin: 0 }} />)}+ {userAgentSkills.length > 0 && renderUserAgentSkills()}{customMCPs.length > 0 && renderCustomMCPs()}<div style={{ marginTop: 8 }}><AddSkillButton />diff --git a/src/components/SkillSourceTag/index.tsx b/src/components/SkillSourceTag/index.tsxnew file mode 100644index 00000000000..29b0f174a6b--- /dev/null+++ b/src/components/SkillSourceTag/index.tsx@@ -0,0 +1,41 @@+import { type SkillSource } from '@lobechat/types';+import { Icon, Tag } from '@lobehub/ui';+import { BadgeCheck, CircleUser, Package } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++interface SkillSourceTagProps {+ source: SkillSource;+}++const SkillSourceTag = memo<SkillSourceTagProps>(({ source }) => {+ const { t } = useTranslation('plugin');++ switch (source) {+ case 'builtin': {+ return (+ <Tag color={'success'} icon={<Icon icon={BadgeCheck} />} size={'small'}>+ LobeHub+ </Tag>+ );+ }+ case 'market': {+ return (+ <Tag color={'processing'} icon={<Icon icon={CircleUser} />} size={'small'}>+ {t('store.communityPlugin')}+ </Tag>+ );+ }+ case 'user': {+ return (+ <Tag color={'warning'} icon={<Icon icon={Package} />} size={'small'}>+ {t('store.customPlugin')}+ </Tag>+ );+ }+ }+});++SkillSourceTag.displayName = 'SkillSourceTag';++export default SkillSourceTag;diff --git a/src/features/AgentSkillDetail/ContentViewer.tsx b/src/features/AgentSkillDetail/ContentViewer.tsxnew file mode 100644index 00000000000..32efb791cf6--- /dev/null+++ b/src/features/AgentSkillDetail/ContentViewer.tsx@@ -0,0 +1,234 @@+'use client';++import { type SkillItem } from '@lobechat/types';+import { CopyButton, Highlighter, Markdown } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++const styles = createStaticStyles(({ css, cssVar }) => ({+ codeWrapper: css`+ position: relative;+ overflow-x: auto;+ margin-block-start: 16px;+ padding-block-end: calc(100cqb - 1lh);++ pre {+ margin: 0;+ }++ code {+ counter-reset: line;+ }++ .line {+ width: 100% !important;+ margin-inline: 0 !important;+ padding-inline: 0 !important;+ }++ .line::before {+ content: counter(line);+ counter-increment: line;+ user-select: none;++ display: inline-block;++ width: 4ch;+ margin-inline-end: 2ch;++ color: ${cssVar.colorTextQuaternary};+ text-align: end;+ }+ `,+ docWrapper: css`+ max-width: 798px;+ margin-inline: auto;+ padding-block: 8px;+ padding-inline: 24px;+ `,+}));++const getLanguage = (fileName: string): string => {+ const ext = fileName.toLowerCase().split('.').pop();+ switch (ext) {+ case 'js':+ case 'mjs':+ case 'cjs': {+ return 'javascript';+ }+ case 'ts': {+ return 'typescript';+ }+ case 'tsx': {+ return 'tsx';+ }+ case 'jsx': {+ return 'jsx';+ }+ case 'py':+ case 'pyw': {+ return 'python';+ }+ case 'java': {+ return 'java';+ }+ case 'go': {+ return 'go';+ }+ case 'rs': {+ return 'rust';+ }+ case 'rb': {+ return 'ruby';+ }+ case 'sh':+ case 'bash':+ case 'zsh': {+ return 'bash';+ }+ case 'html':+ case 'htm': {+ return 'html';+ }+ case 'css': {+ return 'css';+ }+ case 'scss': {+ return 'scss';+ }+ case 'json': {+ return 'json';+ }+ case 'xml': {+ return 'xml';+ }+ case 'yaml':+ case 'yml': {+ return 'yaml';+ }+ case 'toml': {+ return 'toml';+ }+ case 'md':+ case 'mdx': {+ return 'markdown';+ }+ case 'sql': {+ return 'sql';+ }+ case 'c':+ case 'h': {+ return 'c';+ }+ case 'cpp':+ case 'cxx':+ case 'cc':+ case 'hpp': {+ return 'cpp';+ }+ case 'cs': {+ return 'csharp';+ }+ case 'swift': {+ return 'swift';+ }+ case 'kt':+ case 'kts': {+ return 'kotlin';+ }+ case 'lua': {+ return 'lua';+ }+ case 'dart': {+ return 'dart';+ }+ case 'graphql':+ case 'gql': {+ return 'graphql';+ }+ default: {+ return 'txt';+ }+ }+};++const isMarkdownFile = (path: string) => {+ const ext = path.toLowerCase().split('.').pop();+ return ext === 'md' || ext === 'mdx';+};++const parseFrontmatter = (content: string): { body: string; frontmatter?: string } => {+ const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);+ if (!match) return { body: content };+ return { body: match[2], frontmatter: match[1] };+};++interface ContentViewerProps {+ contentMap: Record<string, string>;+ liveContent?: string;+ selectedFile: string;+ skillDetail?: SkillItem;+}++const ContentViewer = memo<ContentViewerProps>(+ ({ skillDetail, selectedFile, contentMap, liveContent }) => {+ if (selectedFile === 'SKILL.md') {+ const displayContent = liveContent ?? skillDetail?.content;+ if (!displayContent) {+ return (+ <div className={styles.docWrapper}>+ <p style={{ opacity: 0.45 }}>No content</p>+ </div>+ );+ }+ const { frontmatter, body } = parseFrontmatter(displayContent);+ return (+ <div className={styles.docWrapper}>+ {frontmatter && (+ <Highlighter fullFeatured language={'yaml'} variant={'outlined'}>+ {frontmatter}+ </Highlighter>+ )}+ <Markdown variant={'chat'}>{body}</Markdown>+ </div>+ );+ }++ const content = contentMap[selectedFile];++ if (isMarkdownFile(selectedFile)) {+ const { frontmatter, body } = parseFrontmatter(content);+ return (+ <div className={styles.docWrapper}>+ {frontmatter && (+ <Highlighter fullFeatured language={'yaml'} variant={'outlined'}>+ {frontmatter}+ </Highlighter>+ )}+ <Markdown variant={'chat'}>{body}</Markdown>+ </div>+ );+ }++ return (+ <div className={styles.codeWrapper}>+ <CopyButton+ content={content}+ style={{ position: 'absolute', right: 8, top: 0, zIndex: 1 }}+ />+ <Highlighter+ copyable={false}+ language={getLanguage(selectedFile)}+ showLanguage={false}+ variant={'borderless'}+ >+ {content}+ </Highlighter>+ </div>+ );+ },+);++ContentViewer.displayName = 'ContentViewer';++export default ContentViewer;diff --git a/src/features/AgentSkillDetail/FileTree.tsx b/src/features/AgentSkillDetail/FileTree.tsxnew file mode 100644index 00000000000..f8c137e6fe6--- /dev/null+++ b/src/features/AgentSkillDetail/FileTree.tsx@@ -0,0 +1,160 @@+'use client';++import { type SkillResourceTreeNode } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { ChevronDown, ChevronRight, File, FolderIcon, FolderOpenIcon } from 'lucide-react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';++const styles = createStaticStyles(({ css, cssVar }) => ({+ item: css`+ cursor: pointer;++ display: flex;+ gap: 6px;+ align-items: center;++ padding-block: 6px;+ padding-inline-end: 8px;+ border-radius: 6px;++ font-size: 13px;+ line-height: 1.4;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ itemSelected: css`+ color: ${cssVar.colorPrimary};+ background: ${cssVar.colorFillSecondary};+ `,+ label: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface FileTreeProps {+ onSelectFile: (path: string) => void;+ resourceTree: SkillResourceTreeNode[];+ selectedFile: string;+}++const TreeNode = memo<{+ depth: number;+ expandedFolders: Set<string>;+ node: SkillResourceTreeNode;+ onSelectFile: (_path: string) => void;+ onToggleFolder: (_path: string) => void;+ selectedFile: string;+}>(({ node, depth, selectedFile, onSelectFile, expandedFolders, onToggleFolder }) => {+ const isDir = node.type === 'directory';+ const isExpanded = expandedFolders.has(node.path);+ const isSelected = !isDir && selectedFile === node.path;++ const handleClick = () => {+ if (isDir) {+ onToggleFolder(node.path);+ } else {+ onSelectFile(node.path);+ }+ };++ return (+ <>+ <div+ className={`${styles.item} ${isSelected ? styles.itemSelected : ''}`}+ style={{ paddingInlineStart: 8 + depth * 16 }}+ title={node.path}+ onClick={handleClick}+ >+ {isDir && <Icon icon={isExpanded ? ChevronDown : ChevronRight} size={14} />}+ {!isDir && <span style={{ flexShrink: 0, width: 14 }} />}+ <Icon icon={isDir ? (isExpanded ? FolderOpenIcon : FolderIcon) : File} size={16} />+ <span className={styles.label}>{node.name}</span>+ </div>+ {isDir &&+ isExpanded &&+ node.children?.map((child) => (+ <TreeNode+ depth={depth + 1}+ expandedFolders={expandedFolders}+ key={child.path}+ node={child}+ selectedFile={selectedFile}+ onSelectFile={onSelectFile}+ onToggleFolder={onToggleFolder}+ />+ ))}+ </>+ );+});++TreeNode.displayName = 'TreeNode';++const FileTree = memo<FileTreeProps>(({ resourceTree, selectedFile, onSelectFile }) => {+ const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());++ useEffect(() => {+ // Expand all directories by default when tree is loaded+ const allDirs = new Set<string>();+ const collectDirs = (nodes: SkillResourceTreeNode[]) => {+ for (const node of nodes) {+ if (node.type === 'directory') {+ allDirs.add(node.path);+ if (node.children) collectDirs(node.children);+ }+ }+ };+ collectDirs(resourceTree);+ setExpandedFolders(allDirs);+ }, [resourceTree]);++ const handleToggleFolder = useCallback((path: string) => {+ setExpandedFolders((prev) => {+ const next = new Set(prev);+ if (next.has(path)) {+ next.delete(path);+ } else {+ next.add(path);+ }+ return next;+ });+ }, []);++ const isSkillMdSelected = selectedFile === 'SKILL.md';++ const hasResources = useMemo(() => resourceTree.length > 0, [resourceTree]);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>+ <div+ className={`${styles.item} ${isSkillMdSelected ? styles.itemSelected : ''}`}+ style={{ paddingInlineStart: 8 }}+ onClick={() => onSelectFile('SKILL.md')}+ >+ <span style={{ flexShrink: 0, width: 14 }} />+ <Icon icon={File} size={16} />+ <span className={styles.label}>SKILL.md</span>+ </div>+ {hasResources &&+ resourceTree.map((node) => (+ <TreeNode+ depth={0}+ expandedFolders={expandedFolders}+ key={node.path}+ node={node}+ selectedFile={selectedFile}+ onSelectFile={onSelectFile}+ onToggleFolder={handleToggleFolder}+ />+ ))}+ </div>+ );+});++FileTree.displayName = 'FileTree';++export default FileTree;diff --git a/src/features/AgentSkillDetail/index.tsx b/src/features/AgentSkillDetail/index.tsxnew file mode 100644index 00000000000..9b428690815--- /dev/null+++ b/src/features/AgentSkillDetail/index.tsx@@ -0,0 +1,167 @@+'use client';++import { type SkillResourceTreeNode } from '@lobechat/types';+import { Github } from '@lobehub/icons';+import { ActionIcon, Avatar, Flexbox, Icon } from '@lobehub/ui';+import { Skeleton } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { DotIcon, ExternalLinkIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import PublishedTime from '@/components/PublishedTime';+import { useToolStore } from '@/store/tool';++import ContentViewer from './ContentViewer';+import FileTree from './FileTree';++const styles = createStaticStyles(({ css, cssVar }) => ({+ description: css`+ overflow: hidden;++ margin: 0;++ font-size: 13px;+ line-height: 1.5;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ divider: css`+ flex-shrink: 0;+ width: 1px;+ background: ${cssVar.colorBorderSecondary};+ `,+ left: css`+ overflow-y: auto;+ flex-shrink: 0;+ width: 240px;+ padding: 8px;+ `,+ meta: css`+ flex-shrink: 0;+ padding: 16px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ name: css`+ font-size: 16px;+ font-weight: 500;+ line-height: 1.4;+ color: ${cssVar.colorText};+ `,+ right: css`+ container-type: size;+ overflow: auto;+ flex: 1;+ `,+}));++interface AgentSkillDetailProps {+ skillId: string;+}++const buildContentMap = (nodes: SkillResourceTreeNode[]): Record<string, string> => {+ const map: Record<string, string> = {};+ const walk = (items: SkillResourceTreeNode[]) => {+ for (const node of items) {+ if (node.type === 'file' && node.content !== undefined) {+ map[node.path] = node.content;+ } else if (node.children) {+ walk(node.children);+ }+ }+ };+ walk(nodes);+ return map;+};++const AgentSkillDetail = memo<AgentSkillDetailProps>(({ skillId }) => {+ const { t } = useTranslation('setting');+ const [selectedFile, setSelectedFile] = useState('SKILL.md');+ const { data, isLoading } = useToolStore((s) => s.useFetchAgentSkillDetail)(skillId);++ const skillDetail = data?.skillDetail;+ const resourceTree = data?.resourceTree ?? [];+ const contentMap = useMemo(() => buildContentMap(resourceTree), [resourceTree]);++ if (isLoading) return <Skeleton active paragraph={{ rows: 8 }} style={{ padding: 16 }} />;++ const version = skillDetail?.manifest?.version;+ const description = skillDetail?.description || skillDetail?.manifest?.description;+ const repository = skillDetail?.manifest?.repository;+ const sourceUrl = skillDetail?.manifest?.sourceUrl;++ return (+ <Flexbox style={{ height: '100%', overflow: 'hidden' }}>+ {skillDetail && (+ <div className={styles.meta}>+ <Flexbox horizontal align={'center'} gap={12}>+ <Avatar avatar={'🧩'} shape={'square'} size={40} />+ <Flexbox flex={1} gap={4} style={{ overflow: 'hidden' }}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} className={styles.description} gap={4}>+ <span className={styles.name}>{skillDetail.name}</span>+ {version && (+ <>+ <Icon icon={DotIcon} />+ <span>v{version}</span>+ </>+ )}+ <Icon icon={DotIcon} />+ {t('agentSkillDetail.updatedAt')}{' '}+ <PublishedTime+ date={new Date(skillDetail.updatedAt).toISOString()}+ template={'MMM DD, YYYY'}+ />+ </Flexbox>+ {(repository || sourceUrl) && (+ <Flexbox horizontal align={'center'} gap={2} style={{ flexShrink: 0 }}>+ {repository && (+ <a href={repository} rel="noreferrer" target={'_blank'}>+ <ActionIcon+ fill={cssVar.colorTextDescription}+ icon={Github}+ title={t('agentSkillDetail.repository')}+ />+ </a>+ )}+ {sourceUrl && (+ <a href={sourceUrl} rel="noreferrer" target={'_blank'}>+ <ActionIcon+ icon={ExternalLinkIcon}+ title={t('agentSkillDetail.sourceUrl')}+ />+ </a>+ )}+ </Flexbox>+ )}+ </Flexbox>+ {description && <p className={styles.description}>{description}</p>}+ </Flexbox>+ </Flexbox>+ </div>+ )}+ <Flexbox horizontal style={{ flex: 1, overflow: 'hidden' }}>+ <div className={styles.left}>+ <FileTree+ resourceTree={resourceTree}+ selectedFile={selectedFile}+ onSelectFile={setSelectedFile}+ />+ </div>+ <div className={styles.divider} />+ <div className={styles.right} key={selectedFile}>+ <ContentViewer+ contentMap={contentMap}+ selectedFile={selectedFile}+ skillDetail={skillDetail}+ />+ </div>+ </Flexbox>+ </Flexbox>+ );+});++AgentSkillDetail.displayName = 'AgentSkillDetail';++export default AgentSkillDetail;diff --git a/src/features/AgentSkillEdit/SkillEditForm.tsx b/src/features/AgentSkillEdit/SkillEditForm.tsxnew file mode 100644index 00000000000..d26929afb00--- /dev/null+++ b/src/features/AgentSkillEdit/SkillEditForm.tsx@@ -0,0 +1,156 @@+'use client';++import {+ ReactCodemirrorPlugin,+ ReactCodePlugin,+ ReactHRPlugin,+ ReactLinkPlugin,+ ReactListPlugin,+ ReactMathPlugin,+ ReactTablePlugin,+} from '@lobehub/editor';+import { Editor, useEditor } from '@lobehub/editor/react';+import { Form, type FormItemProps } from '@lobehub/ui';+import { Form as AForm, type FormInstance, Input } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo, useCallback, useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css }) => ({+ editorWrapper: css`+ min-height: 200px;+ padding-block: 8px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorder};+ border-radius: 8px;+ `,+ wrapper: css`+ max-width: 798px;+ margin-inline: auto;+ padding-block: 0;+ padding-inline: 24px;+ `,+}));++const PLUGINS = [+ ReactListPlugin,+ ReactCodePlugin,+ ReactCodemirrorPlugin,+ ReactHRPlugin,+ ReactLinkPlugin,+ ReactTablePlugin,+ ReactMathPlugin,+];++export interface SkillEditFormValues {+ content: string;+ description: string;+}++interface SkillEditFormProps {+ form: FormInstance;+ initialValues: SkillEditFormValues;+ name?: string;+ onSubmit: (values: SkillEditFormValues) => void;+}++const SkillEditForm = memo<SkillEditFormProps>(({ name, form, initialValues, onSubmit }) => {+ const { t } = useTranslation('setting');+ const editor = useEditor();+ const currentValueRef = useRef(initialValues.content);++ useEffect(() => {+ form.setFieldsValue(initialValues);+ }, [initialValues]);++ useEffect(() => {+ currentValueRef.current = initialValues.content;+ }, [initialValues.content]);++ useEffect(() => {+ if (!editor) return;+ try {+ setTimeout(() => {+ if (initialValues.content) {+ editor.setDocument('markdown', initialValues.content);+ }+ }, 100);+ } catch {+ setTimeout(() => {+ editor.setDocument('markdown', initialValues.content);+ }, 100);+ }+ }, [editor, initialValues.content]);++ const handleContentChange = useCallback(+ (e: any) => {+ const nextContent = (e.getDocument('markdown') as unknown as string) || '';+ if (nextContent !== currentValueRef.current) {+ currentValueRef.current = nextContent;+ form.setFieldValue('content', nextContent);+ }+ },+ [form],+ );++ const items: FormItemProps[] = [+ {+ children: <Input disabled readOnly value={name} />,+ desc: t('agentSkillEdit.nameDesc'),+ label: t('settingAgent.name.title'),+ },+ {+ children: (+ <Input.TextArea+ autoSize={{ maxRows: 4, minRows: 2 }}+ placeholder={t('agentSkillModal.descriptionPlaceholder')}+ />+ ),+ desc: t('agentSkillEdit.descriptionDesc'),+ label: t('agentSkillModal.description'),+ name: 'description',+ },+ {+ children: (+ <div className={styles.editorWrapper}>+ <Editor+ content={''}+ editor={editor}+ lineEmptyPlaceholder={t('agentSkillEdit.instructionsPlaceholder')}+ placeholder={t('agentSkillEdit.instructionsPlaceholder')}+ plugins={PLUGINS}+ style={{ paddingBottom: 48 }}+ type={'text'}+ variant={'chat'}+ onTextChange={handleContentChange}+ />+ </div>+ ),+ desc: t('agentSkillEdit.instructionsDesc'),+ label: t('agentSkillEdit.instructions'),+ },+ ];++ return (+ <div className={styles.wrapper}>+ <Form+ form={form}+ gap={0}+ initialValues={initialValues}+ items={items}+ itemsType={'flat'}+ layout={'vertical'}+ variant={'borderless'}+ onFinish={onSubmit}+ >+ <AForm.Item hidden name="content">+ <Input type="hidden" />+ </AForm.Item>+ </Form>+ </div>+ );+});++SkillEditForm.displayName = 'SkillEditForm';++export default SkillEditForm;diff --git a/src/features/AgentSkillEdit/index.tsx b/src/features/AgentSkillEdit/index.tsxnew file mode 100644index 00000000000..ad0aef08113--- /dev/null+++ b/src/features/AgentSkillEdit/index.tsx@@ -0,0 +1,210 @@+'use client';++import { isDesktop } from '@lobechat/const';+import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';+import { type SkillResourceTreeNode } from '@lobechat/types';+import { Button, Drawer, Flexbox } from '@lobehub/ui';+import { Alert, App, Form as AForm, Popconfirm, Skeleton } from 'antd';+import { createStaticStyles } from 'antd-style';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';+import FileTree from '@/features/AgentSkillDetail/FileTree';+import { useToolStore } from '@/store/tool';++import SkillEditForm, { type SkillEditFormValues } from './SkillEditForm';++const styles = createStaticStyles(({ css, cssVar }) => ({+ divider: css`+ flex-shrink: 0;+ width: 1px;+ background: ${cssVar.colorBorderSecondary};+ `,+ left: css`+ overflow-y: auto;+ flex-shrink: 0;+ width: 240px;+ padding: 8px;+ `,+ right: css`+ container-type: size;+ overflow: auto;+ flex: 1;+ `,+}));++const buildContentMap = (nodes: SkillResourceTreeNode[]): Record<string, string> => {+ const map: Record<string, string> = {};+ const walk = (items: SkillResourceTreeNode[]) => {+ for (const node of items) {+ if (node.type === 'file' && node.content !== undefined) {+ map[node.path] = node.content;+ } else if (node.children) {+ walk(node.children);+ }+ }+ };+ walk(nodes);+ return map;+};++interface AgentSkillEditProps {+ onClose: () => void;+ open: boolean;+ skillId: string;+}++const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) => {+ const { t } = useTranslation('setting');+ const { t: tp } = useTranslation('plugin');+ const { t: tc } = useTranslation('common');+ const { message } = App.useApp();++ const [selectedFile, setSelectedFile] = useState('SKILL.md');+ const [saving, setSaving] = useState(false);+ const [form] = AForm.useForm();++ const { data, isLoading } = useToolStore((s) => s.useFetchAgentSkillDetail)(+ open ? skillId : undefined,+ );+ const updateAgentSkill = useToolStore((s) => s.updateAgentSkill);+ const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);++ const skillDetail = data?.skillDetail;+ const resourceTree = data?.resourceTree ?? [];+ const contentMap = useMemo(() => buildContentMap(resourceTree), [resourceTree]);++ const initialValues: SkillEditFormValues = useMemo(+ () => ({+ content: skillDetail?.content || '',+ description: skillDetail?.description || skillDetail?.manifest?.description || '',+ }),+ [skillDetail],+ );++ const handleSubmit = async (values: SkillEditFormValues) => {+ setSaving(true);+ try {+ await updateAgentSkill({+ content: values.content,+ id: skillId,+ manifest: { description: values.description },+ });+ message.success(t('agentSkillEdit.saveSuccess'));+ onClose();+ } finally {+ setSaving(false);+ }+ };++ const handleDelete = async () => {+ await deleteAgentSkill(skillId);+ message.success(tp('dev.deleteSuccess'));+ onClose();+ };++ const footer = (+ <Flexbox horizontal flex={1} gap={12} justify={'space-between'}>+ <Popconfirm+ arrow={false}+ cancelText={tc('cancel')}+ okText={tc('ok')}+ placement={'topLeft'}+ title={tp('dev.confirmDeleteDevPlugin')}+ okButtonProps={{+ danger: true,+ type: 'primary',+ }}+ onConfirm={handleDelete}+ >+ <Button danger>{tc('delete')}</Button>+ </Popconfirm>+ <Flexbox horizontal gap={12}>+ <Button onClick={onClose}>{tc('cancel')}</Button>+ <Button+ loading={saving}+ type={'primary'}+ onClick={() => {+ form.submit();+ }}+ >+ {tp('dev.update')}+ </Button>+ </Flexbox>+ </Flexbox>+ );++ return (+ <Drawer+ destroyOnHidden+ containerMaxWidth={'auto'}+ footer={footer}+ height={isDesktop ? `calc(100vh - ${TITLE_BAR_HEIGHT}px)` : '100vh'}+ open={open}+ placement={'bottom'}+ push={false}+ title={t('agentSkillEdit.title')}+ styles={{+ body: { padding: 0 },+ bodyContent: { height: '100%' },+ }}+ onClose={(e) => {+ e.stopPropagation();+ onClose();+ }}+ >+ {isLoading ? (+ <Skeleton active paragraph={{ rows: 8 }} style={{ padding: 16 }} />+ ) : (+ <Flexbox+ horizontal+ height={'100%'}+ onClick={(e) => {+ e.stopPropagation();+ }}+ >+ <div className={styles.left}>+ <FileTree+ resourceTree={resourceTree}+ selectedFile={selectedFile}+ onSelectFile={setSelectedFile}+ />+ </div>+ <div className={styles.divider} />+ <div className={styles.right}>+ <div+ style={{+ display: selectedFile === 'SKILL.md' ? undefined : 'none',+ height: '100%',+ overflow: 'auto',+ }}+ >+ <SkillEditForm+ form={form}+ initialValues={initialValues}+ name={skillDetail?.name}+ onSubmit={handleSubmit}+ />+ </div>+ {selectedFile !== 'SKILL.md' && (+ <>+ <Alert banner showIcon message={t('agentSkillEdit.fileReadonly')} type="info" />+ <ContentViewer+ contentMap={contentMap}+ key={selectedFile}+ selectedFile={selectedFile}+ skillDetail={skillDetail}+ />+ </>+ )}+ </div>+ </Flexbox>+ )}+ </Drawer>+ );+});++AgentSkillEdit.displayName = 'AgentSkillEdit';++export default AgentSkillEdit;diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsxindex 14980796e21..80c6ab0d269 100644--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx@@ -19,6 +19,7 @@ import { agentByIdSelectors } from '@/store/agent/selectors';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useToolStore } from '@/store/tool';import {+ agentSkillsSelectors,builtinToolSelectors,klavisStoreSelectors,lobehubSkillStoreSelectors,@@ -53,21 +54,29 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)const allLobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);const isLobehubSkillEnabled = useServerConfigStore(serverConfigSelectors.enableLobehubSkill);+ // Agent Skills 相关状态+ const installedBuiltinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);+const [useFetchPluginStore,useFetchUserKlavisServers,useFetchLobehubSkillConnections,useFetchUninstalledBuiltinTools,+ useFetchAgentSkills,] = useToolStore((s) => [s.useFetchPluginStore,s.useFetchUserKlavisServers,s.useFetchLobehubSkillConnections,s.useFetchUninstalledBuiltinTools,+ s.useFetchAgentSkills,]);useFetchPluginStore();useFetchInstalledPlugins();useFetchUninstalledBuiltinTools(true);+ useFetchAgentSkills(true);useCheckPluginsIsInstalled(plugins);// 使用 SWR 加载用户的 Klavis 集成(从数据库)@@ -87,14 +96,23 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)() => new Set(KLAVIS_SERVER_TYPES.map((type) => type.identifier)),[],);- // 过滤掉 builtinList 中的 klavis 工具(它们会单独显示在 Klavis 区域)- const filteredBuiltinList = useMemo(- () =>- isKlavisEnabledInEnv- ? builtinList.filter((item) => !allKlavisTypeIdentifiers.has(item.identifier))- : builtinList,- [builtinList, allKlavisTypeIdentifiers, isKlavisEnabledInEnv],- );+ // 获取所有 skill 的 identifier 集合(用于过滤 builtinList)+ const allSkillIdentifiers = useMemo(() => {+ const ids = new Set<string>();+ for (const s of installedBuiltinSkills) ids.add(s.identifier);+ for (const s of marketAgentSkills) ids.add(s.identifier);+ for (const s of userAgentSkills) ids.add(s.identifier);+ return ids;+ }, [installedBuiltinSkills, marketAgentSkills, userAgentSkills]);++ // 过滤掉 builtinList 中的 klavis 工具和 skill(它们会单独显示)+ const filteredBuiltinList = useMemo(() => {+ let list = builtinList;+ if (isKlavisEnabledInEnv) {+ list = list.filter((item) => !allKlavisTypeIdentifiers.has(item.identifier));+ }+ return list.filter((item) => !allSkillIdentifiers.has(item.identifier));+ }, [builtinList, allKlavisTypeIdentifiers, isKlavisEnabledInEnv, allSkillIdentifiers]);// 获取推荐的 Klavis skill IDsconst recommendedKlavisIds = useMemo(@@ -213,6 +231,83 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)[filteredBuiltinList, checked, togglePlugin, setUpdating],);+ // Builtin Agent Skills 列表项(归入 LobeHub 分组)+ const builtinAgentSkillItems = useMemo(+ () =>+ installedBuiltinSkills.map((skill) => ({+ icon: (+ <Avatar+ avatar={skill.avatar || '🧩'}+ shape={'square'}+ size={SKILL_ICON_SIZE}+ style={{ flex: 'none' }}+ />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={checked.includes(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [installedBuiltinSkills, checked, togglePlugin, setUpdating],+ );++ // Market Agent Skills 列表项(归入 Community 分组)+ const marketAgentSkillItems = useMemo(+ () =>+ marketAgentSkills.map((skill) => ({+ icon: (+ <Avatar avatar={'🧩'} shape={'square'} size={SKILL_ICON_SIZE} style={{ flex: 'none' }} />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={checked.includes(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [marketAgentSkills, checked, togglePlugin, setUpdating],+ );++ // User Agent Skills 列表项(归入 Custom 分组)+ const userAgentSkillItems = useMemo(+ () =>+ userAgentSkills.map((skill) => ({+ icon: (+ <Avatar avatar={'🧩'} shape={'square'} size={SKILL_ICON_SIZE} style={{ flex: 'none' }} />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={checked.includes(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [userAgentSkills, checked, togglePlugin, setUpdating],+ );+// Skills 列表项(包含 LobeHub Skill 和 Klavis)// 已连接的排在前面const skillItems = useMemo(() => {@@ -256,19 +351,27 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)),});- // 构建 LobeHub 分组的 children(包含内置工具和 LobeHub Skill/Klavis)+ // 构建 LobeHub 分组的 children(包含 Builtin Agent Skills、内置工具和 LobeHub Skill/Klavis)const lobehubGroupChildren: ItemType[] = [- // 1. 内置工具+ // 1. Builtin Agent Skills+ ...builtinAgentSkillItems,+ // 2. 内置工具...builtinItems,- // 2. LobeHub Skill 和 Klavis(作为内置技能)+ // 3. LobeHub Skill 和 Klavis(作为内置技能)...skillItems,];- // 构建 Community 分组的 children(只包含社区插件)- const communityGroupChildren: ItemType[] = communityPlugins.map(mapPluginToItem);+ // 构建 Community 分组的 children(Market Agent Skills + 社区插件)+ const communityGroupChildren: ItemType[] = [+ ...marketAgentSkillItems,+ ...communityPlugins.map(mapPluginToItem),+ ];- // 构建 Custom 分组的 children(只包含自定义插件)- const customGroupChildren: ItemType[] = customPlugins.map(mapPluginToItem);+ // 构建 Custom 分组的 children(User Agent Skills + 自定义插件)+ const customGroupChildren: ItemType[] = [+ ...userAgentSkillItems,+ ...customPlugins.map(mapPluginToItem),+ ];// 市场 tab 的 itemsconst marketItems: ItemType[] = [@@ -351,15 +454,44 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)// 合并已启用的 LobeHub Skill 和 Klavis(作为内置技能)const enabledSkillItems = [...connectedLobehubSkillItems, ...connectedKlavisItems];- // 构建内置工具分组的 children(包含内置工具和 LobeHub Skill/Klavis)+ // 已启用的 Builtin Agent Skills+ const enabledBuiltinAgentSkillItems = installedBuiltinSkills+ .filter((skill) => checked.includes(skill.identifier))+ .map((skill) => ({+ icon: (+ <Avatar+ avatar={skill.avatar || '🧩'}+ shape={'square'}+ size={SKILL_ICON_SIZE}+ style={{ flex: 'none' }}+ />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // 构建内置工具分组的 children(包含 Builtin Agent Skills、内置工具和 LobeHub Skill/Klavis)const allBuiltinItems: ItemType[] = [- // 1. 内置工具+ // 1. Builtin Agent Skills+ ...enabledBuiltinAgentSkillItems,+ // 2. 内置工具...enabledBuiltinItems,- // 2. divider (如果有内置工具且有 skill items)+ // 3. divider (如果有内置工具且有 skill items)...(enabledBuiltinItems.length > 0 && enabledSkillItems.length > 0? [{ key: 'installed-divider-builtin-skill', type: 'divider' as const }]: []),- // 3. LobeHub Skill 和 Klavis+ // 4. LobeHub Skill 和 Klavis...enabledSkillItems,];@@ -420,20 +552,66 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)),}));- // Community 分组(只包含社区插件)- if (enabledCommunityPlugins.length > 0) {+ // 已启用的 Market Agent Skills+ const enabledMarketAgentSkillItems = marketAgentSkills+ .filter((skill) => checked.includes(skill.identifier))+ .map((skill) => ({+ icon: (+ <Avatar avatar={'🧩'} shape={'square'} size={SKILL_ICON_SIZE} style={{ flex: 'none' }} />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // Community 分组(Market Agent Skills + 社区插件)+ const allCommunityItems = [...enabledMarketAgentSkillItems, ...enabledCommunityPlugins];+ if (allCommunityItems.length > 0) {installedItems.push({- children: enabledCommunityPlugins,+ children: allCommunityItems,key: 'installed-community',label: t('skillStore.tabs.community'),type: 'group',});}- // Custom 分组(只包含自定义插件)- if (enabledCustomPlugins.length > 0) {+ // 已启用的 User Agent Skills+ const enabledUserAgentSkillItems = userAgentSkills+ .filter((skill) => checked.includes(skill.identifier))+ .map((skill) => ({+ icon: (+ <Avatar avatar={'🧩'} shape={'square'} size={SKILL_ICON_SIZE} style={{ flex: 'none' }} />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await togglePlugin(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // Custom 分组(User Agent Skills + 自定义插件)+ const allCustomItems = [...enabledUserAgentSkillItems, ...enabledCustomPlugins];+ if (allCustomItems.length > 0) {installedItems.push({- children: enabledCustomPlugins,+ children: allCustomItems,key: 'installed-custom',label: t('skillStore.tabs.custom'),type: 'group',@@ -443,6 +621,9 @@ export const useControls = ({ setUpdating }: { setUpdating: (updating: boolean)return installedItems;}, [filteredBuiltinList,+ installedBuiltinSkills,+ marketAgentSkills,+ userAgentSkills,communityPlugins,customPlugins,klavisServerItems,diff --git a/src/features/Conversation/Messages/Assistant/useMarkdown.tsx b/src/features/Conversation/Messages/Assistant/useMarkdown.tsxindex 325162b6d40..b80c7d307fe 100644--- a/src/features/Conversation/Messages/Assistant/useMarkdown.tsx+++ b/src/features/Conversation/Messages/Assistant/useMarkdown.tsx@@ -24,7 +24,7 @@ const isHtmlCode = (content: string, language: string) => {export const useMarkdown = (id: string): Partial<MarkdownProps> => {const item = useConversationStore(dataSelectors.getDbMessageById(id), isEqual)!;- const { role, search } = item;+ const { role, search } = item || {};const { transitionMode } = useUserStore(userGeneralSettingsSelectors.config);const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));const animated = transitionMode === 'fadeIn' && generating;diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 5ae6b2cd2ab..571be3f1a0b 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -464,7 +464,7 @@ describe('Generation Actions', () => {});it('should delete message BEFORE regeneration to prevent message not found issue (LOBE-2533)', async () => {- // This test verifies the fix for LOBE-2533:+ // This test verifies the fix:// When "delete and regenerate" is called, if regeneration happens first,// it switches to a new branch, causing the original message to no longer// appear in displayMessages. Then deleteMessage cannot find the messagediff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex f07b252102f..ba727cd2116 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -223,7 +223,7 @@ export const generationSlice: StateCreator<type: 'regenerate',});- // IMPORTANT: Delete first, then regenerate (LOBE-2533)+ // IMPORTANT: Delete first, then regenerate// If we regenerate first, it switches to a new branch, causing the original// message to no longer appear in displayMessages. Then deleteMessage cannot// find the message and fails silently.diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsxindex 06202d0076e..40d9ebf9891 100644--- a/src/features/PluginDevModal/index.tsx+++ b/src/features/PluginDevModal/index.tsx@@ -1,13 +1,12 @@+import { isDesktop } from '@lobechat/const';import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';-import { Button, Drawer, Flexbox, Segmented, Tag } from '@lobehub/ui';+import { type LobeToolCustomPlugin } from '@lobechat/types';+import { Button, Drawer, Flexbox } from '@lobehub/ui';import { App, Form, Popconfirm } from 'antd';import { useResponsive } from 'antd-style';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { isDesktop } from '@/const/version';-import { type LobeToolCustomPlugin } from '@/types/tool/plugin';-import MCPManifestForm from './MCPManifestForm';import PluginPreview from './PluginPreview';@@ -24,7 +23,6 @@ interface DevModalProps {const DevModal = memo<DevModalProps>(({ open, mode = 'create', value, onValueChange, onSave, onOpenChange, onDelete }) => {const isEditMode = mode === 'edit';- const [configMode, setConfigMode] = useState<'mcp' | 'claude'>('mcp');const { t } = useTranslation('plugin');const { message } = App.useApp();@@ -138,34 +136,6 @@ const DevModal = memo<DevModalProps>(}}><Flexbox flex={3} gap={16} padding={24} style={{ overflowY: 'auto' }}>- <Segmented- block- value={configMode}- variant={'filled'}- options={[- {- label: t('dev.manifest.mode.mcp'),- value: 'mcp',- },- {- disabled: true,- label: (- <Flexbox horizontal align={'center'} gap={4} justify={'center'}>- {t('dev.manifest.mode.claude')}- <div>- <Tag variant={'filled'}>{t('dev.manifest.mode.claudeWip')}</Tag>- </div>- </Flexbox>- ),- value: 'claude',- },- ]}- onChange={(e) => {- if (e === 'claude') return; // Claude Skill is disabled- setConfigMode(e as 'mcp' | 'claude');- }}- />-<MCPManifestForm form={form} isEditMode={isEditMode} /></Flexbox><PluginPreview form={form} />diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex 40761192bba..6e0b7844dc0 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -26,6 +26,7 @@ import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectorsimport { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { useToolStore } from '@/store/tool';import {+ agentSkillsSelectors,builtinToolSelectors,klavisStoreSelectors,lobehubSkillStoreSelectors,@@ -98,6 +99,14 @@ const AgentTool = memo<AgentToolProps>(const allLobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);const isLobehubSkillEnabled = useServerConfigStore(serverConfigSelectors.enableLobehubSkill);+ // Agent Skills 相关状态+ const installedBuiltinSkills = useToolStore(+ builtinToolSelectors.installedBuiltinSkills,+ isEqual,+ );+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);+const [updating, setUpdating] = useState(false);const [dropdownOpen, setDropdownOpen] = useState(false);@@ -106,14 +115,23 @@ const AgentTool = memo<AgentToolProps>(const isInitializedRef = useRef(false);// Fetch plugins- const [useFetchPluginStore, useFetchUserKlavisServers, useFetchLobehubSkillConnections] =- useToolStore((s) => [- s.useFetchPluginStore,- s.useFetchUserKlavisServers,- s.useFetchLobehubSkillConnections,- ]);+ const [+ useFetchPluginStore,+ useFetchUserKlavisServers,+ useFetchLobehubSkillConnections,+ useFetchUninstalledBuiltinTools,+ useFetchAgentSkills,+ ] = useToolStore((s) => [+ s.useFetchPluginStore,+ s.useFetchUserKlavisServers,+ s.useFetchLobehubSkillConnections,+ s.useFetchUninstalledBuiltinTools,+ s.useFetchAgentSkills,+ ]);useFetchPluginStore();useFetchInstalledPlugins();+ useFetchUninstalledBuiltinTools(true);+ useFetchAgentSkills(true);useCheckPluginsIsInstalled(plugins);// 使用 SWR 加载用户的 Klavis 集成(从数据库)@@ -194,7 +212,16 @@ const AgentTool = memo<AgentToolProps>([],);- // 过滤掉 builtinList 中的 klavis 工具(它们会单独显示在 Klavis 区域)+ // 获取所有 skill 的 identifier 集合(用于过滤 builtinList)+ const allSkillIdentifiers = useMemo(() => {+ const ids = new Set<string>();+ for (const s of installedBuiltinSkills) ids.add(s.identifier);+ for (const s of marketAgentSkills) ids.add(s.identifier);+ for (const s of userAgentSkills) ids.add(s.identifier);+ return ids;+ }, [installedBuiltinSkills, marketAgentSkills, userAgentSkills]);++ // 过滤掉 builtinList 中的 klavis 工具和 skill(它们会单独显示)// 根据配置,可选地过滤掉 availableInWeb: false 的工具(如 LocalSystem 仅桌面版可用)const filteredBuiltinList = useMemo(() => {// Cast to LobeToolMetaWithAvailability for type safety when filterAvailableInWeb is used@@ -213,6 +240,9 @@ const AgentTool = memo<AgentToolProps>(list = list.filter((item) => !allKlavisTypeIdentifiers.has(item.identifier));}+ // Filter out skills (they are shown separately)+ list = list.filter((item) => !allSkillIdentifiers.has(item.identifier));+return list;}, [builtinList,@@ -220,6 +250,7 @@ const AgentTool = memo<AgentToolProps>(isKlavisEnabledInEnv,filterAvailableInWeb,useAllMetaList,+ allSkillIdentifiers,]);// Klavis 服务器列表项@@ -285,10 +316,84 @@ const AgentTool = memo<AgentToolProps>(}};- // 合并 builtin 工具、LobeHub Skill Providers 和 Klavis 服务器+ // Builtin Agent Skills 列表项(归入 LobeHub 分组)+ const builtinAgentSkillItems = useMemo(+ () =>+ installedBuiltinSkills.map((skill) => ({+ icon: (+ <Avatar+ avatar={skill.avatar || '🧩'}+ size={SKILL_ICON_SIZE}+ style={{ marginInlineEnd: 0 }}+ />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={isToolEnabled(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [installedBuiltinSkills, isToolEnabled, handleToggleTool],+ );++ // Market Agent Skills 列表项(归入 Community 分组)+ const marketAgentSkillItems = useMemo(+ () =>+ marketAgentSkills.map((skill) => ({+ icon: <Avatar avatar={'🧩'} size={SKILL_ICON_SIZE} style={{ marginInlineEnd: 0 }} />,+ key: skill.identifier,+ label: (+ <ToolItem+ checked={isToolEnabled(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [marketAgentSkills, isToolEnabled, handleToggleTool],+ );++ // User Agent Skills 列表项(归入 Custom 分组)+ const userAgentSkillItems = useMemo(+ () =>+ userAgentSkills.map((skill) => ({+ icon: <Avatar avatar={'🧩'} size={SKILL_ICON_SIZE} style={{ marginInlineEnd: 0 }} />,+ key: skill.identifier,+ label: (+ <ToolItem+ checked={isToolEnabled(skill.identifier)}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ })),+ [userAgentSkills, isToolEnabled, handleToggleTool],+ );++ // 合并 Builtin Agent Skills、builtin 工具、LobeHub Skill Providers 和 Klavis 服务器const builtinItems = useMemo(() => [- // 原有的 builtin 工具+ // 1. Builtin Agent Skills+ ...builtinAgentSkillItems,+ // 2. 原有的 builtin 工具...filteredBuiltinList.map((item) => ({icon: (<Avatar@@ -311,12 +416,19 @@ const AgentTool = memo<AgentToolProps>(/>),})),- // LobeHub Skill Providers+ // 3. LobeHub Skill Providers...lobehubSkillItems,- // Klavis 服务器+ // 4. Klavis 服务器...klavisServerItems,],- [filteredBuiltinList, klavisServerItems, lobehubSkillItems, isToolEnabled, handleToggleTool],+ [+ builtinAgentSkillItems,+ filteredBuiltinList,+ klavisServerItems,+ lobehubSkillItems,+ isToolEnabled,+ handleToggleTool,+ ],);// 区分社区插件和自定义插件@@ -364,6 +476,18 @@ const AgentTool = memo<AgentToolProps>([customPlugins, mapPluginToItem],);+ // Community 分组 children(Market Agent Skills + 社区插件)+ const communityGroupChildren = useMemo(+ () => [...marketAgentSkillItems, ...communityPluginItems],+ [marketAgentSkillItems, communityPluginItems],+ );++ // Custom 分组 children(User Agent Skills + 自定义插件)+ const customGroupChildren = useMemo(+ () => [...userAgentSkillItems, ...customPluginItems],+ [userAgentSkillItems, customPluginItems],+ );+// All tab items (市场 tab)const allTabItems: ItemType[] = useMemo(() => [@@ -378,22 +502,22 @@ const AgentTool = memo<AgentToolProps>(},]: []),- // Community 分组- ...(communityPluginItems.length > 0+ // Community 分组(Market Agent Skills + 社区插件)+ ...(communityGroupChildren.length > 0? [{- children: communityPluginItems,+ children: communityGroupChildren,key: 'community',label: t('skillStore.tabs.community'),type: 'group' as const,},]: []),- // Custom 分组- ...(customPluginItems.length > 0+ // Custom 分组(User Agent Skills + 自定义插件)+ ...(customGroupChildren.length > 0? [{- children: customPluginItems,+ children: customGroupChildren,key: 'custom',label: t('skillStore.tabs.custom'),type: 'group' as const,@@ -401,7 +525,7 @@ const AgentTool = memo<AgentToolProps>(]: []),],- [builtinItems, communityPluginItems, customPluginItems, t],+ [builtinItems, communityGroupChildren, customGroupChildren, t],);// Installed tab items - 只显示已启用的@@ -444,8 +568,35 @@ const AgentTool = memo<AgentToolProps>(plugins.includes(item.key as string),);- // LobeHub 分组(builtin + LobeHub Skill + Klavis)+ // 已启用的 Builtin Agent Skills+ const enabledBuiltinAgentSkillItems = installedBuiltinSkills+ .filter((skill) => isToolEnabled(skill.identifier))+ .map((skill) => ({+ icon: (+ <Avatar+ avatar={skill.avatar || '🧩'}+ size={SKILL_ICON_SIZE}+ style={{ marginInlineEnd: 0 }}+ />+ ),+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // LobeHub 分组(Builtin Agent Skills + builtin + LobeHub Skill + Klavis)const lobehubGroupItems = [+ ...enabledBuiltinAgentSkillItems,...enabledBuiltinItems,...connectedLobehubSkillItems,...connectedKlavisItems,@@ -484,9 +635,31 @@ const AgentTool = memo<AgentToolProps>(),}));- if (enabledCommunityPlugins.length > 0) {+ // 已启用的 Market Agent Skills+ const enabledMarketAgentSkillItems = marketAgentSkills+ .filter((skill) => isToolEnabled(skill.identifier))+ .map((skill) => ({+ icon: <Avatar avatar={'🧩'} size={SKILL_ICON_SIZE} style={{ marginInlineEnd: 0 }} />,+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // Community 分组(Market Agent Skills + 社区插件)+ const allCommunityItems = [...enabledMarketAgentSkillItems, ...enabledCommunityPlugins];+ if (allCommunityItems.length > 0) {items.push({- children: enabledCommunityPlugins,+ children: allCommunityItems,key: 'installed-community',label: t('skillStore.tabs.community'),type: 'group',@@ -517,9 +690,31 @@ const AgentTool = memo<AgentToolProps>(),}));- if (enabledCustomPlugins.length > 0) {+ // 已启用的 User Agent Skills+ const enabledUserAgentSkillItems = userAgentSkills+ .filter((skill) => isToolEnabled(skill.identifier))+ .map((skill) => ({+ icon: <Avatar avatar={'🧩'} size={SKILL_ICON_SIZE} style={{ marginInlineEnd: 0 }} />,+ key: skill.identifier,+ label: (+ <ToolItem+ checked={true}+ id={skill.identifier}+ label={skill.name}+ onUpdate={async () => {+ setUpdating(true);+ await handleToggleTool(skill.identifier);+ setUpdating(false);+ }}+ />+ ),+ }));++ // Custom 分组(User Agent Skills + 自定义插件)+ const allCustomItems = [...enabledUserAgentSkillItems, ...enabledCustomPlugins];+ if (allCustomItems.length > 0) {items.push({- children: enabledCustomPlugins,+ children: allCustomItems,key: 'installed-custom',label: t('skillStore.tabs.custom'),type: 'group',@@ -529,6 +724,9 @@ const AgentTool = memo<AgentToolProps>(return items;}, [filteredBuiltinList,+ installedBuiltinSkills,+ marketAgentSkills,+ userAgentSkills,klavisServerItems,lobehubSkillItems,communityPlugins,diff --git a/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailContent.tsx b/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailContent.tsxnew file mode 100644index 00000000000..22b3257f01d--- /dev/null+++ b/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailContent.tsx@@ -0,0 +1,18 @@+'use client';++import { BuiltinAgentSkillDetailProvider } from './BuiltinAgentSkillDetailProvider';+import SkillDetailInner from './SkillDetailInner';++export interface BuiltinAgentSkillDetailContentProps {+ identifier: string;+}++export const BuiltinAgentSkillDetailContent = ({+ identifier,+}: BuiltinAgentSkillDetailContentProps) => {+ return (+ <BuiltinAgentSkillDetailProvider identifier={identifier}>+ <SkillDetailInner type="builtin" />+ </BuiltinAgentSkillDetailProvider>+ );+};diff --git a/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailProvider.tsx b/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailProvider.tsxnew file mode 100644index 00000000000..8563c20e345--- /dev/null+++ b/src/features/SkillStore/SkillDetail/BuiltinAgentSkillDetailProvider.tsx@@ -0,0 +1,59 @@+'use client';++import isEqual from 'fast-deep-equal';+import { type ReactNode, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';++import { DetailContext, type DetailContextValue } from './DetailContext';++interface BuiltinAgentSkillDetailProviderProps {+ children: ReactNode;+ identifier: string;+}++export const BuiltinAgentSkillDetailProvider = ({+ children,+ identifier,+}: BuiltinAgentSkillDetailProviderProps) => {+ const { t } = useTranslation(['setting']);++ const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);++ const skill = useMemo(+ () => builtinSkills.find((s) => s.identifier === identifier),+ [identifier, builtinSkills],+ );++ if (!skill) return null;++ const localizedTitle = t(`tools.builtins.${identifier}.title`, {+ defaultValue: skill.name,+ });+ const localizedDescription = t(`tools.builtins.${identifier}.description`, {+ defaultValue: skill.description,+ });+ const localizedReadme = t(`tools.builtins.${identifier}.readme`, {+ defaultValue: '',+ });++ const value: DetailContextValue = {+ author: 'LobeHub',+ authorUrl: 'https://lobehub.com',+ config: null as any,+ description: skill.description,+ icon: skill.avatar || '',+ identifier,+ isConnected: true,+ label: localizedTitle,+ localizedDescription,+ localizedReadme,+ readme: '',+ skillContent: skill.content,+ tools: [],+ toolsLoading: false,+ };++ return <DetailContext value={value}>{children}</DetailContext>;+};diff --git a/src/features/SkillStore/SkillDetail/DetailContext.tsx b/src/features/SkillStore/SkillDetail/DetailContext.tsxindex 57802452a67..7f44e92f8c9 100644--- a/src/features/SkillStore/SkillDetail/DetailContext.tsx+++ b/src/features/SkillStore/SkillDetail/DetailContext.tsx@@ -18,6 +18,7 @@ export interface DetailContextValue {localizedReadme: string;readme: string;serverName?: Klavis.McpServerName;+ skillContent?: string;tools: Array<{ description?: string; inputSchema?: any; name: string }>;toolsLoading: boolean;}diff --git a/src/features/SkillStore/SkillDetail/Schema.tsx b/src/features/SkillStore/SkillDetail/Schema.tsxindex 3e7def9d027..abaa0d1db37 100644--- a/src/features/SkillStore/SkillDetail/Schema.tsx+++ b/src/features/SkillStore/SkillDetail/Schema.tsx@@ -1,23 +1,53 @@'use client';+import { type SkillItem } from '@lobechat/types';import { Flexbox, Segmented, Skeleton, Tag } from '@lobehub/ui';-import { memo, useState } from 'react';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import Title from '@/app/[variants]/(main)/community/features/Title';+import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';+import FileTree from '@/features/AgentSkillDetail/FileTree';import { DetailProvider } from '@/features/MCPPluginDetail/DetailProvider';import Tools from '@/features/MCPPluginDetail/Schema/Tools';import { ModeType } from '@/features/MCPPluginDetail/Schema/types';import { useDetailContext } from './DetailContext';+const styles = createStaticStyles(({ css }) => ({+ divider: css`+ flex-shrink: 0;+ width: 1px;+ background: ${cssVar.colorBorderSecondary};+ `,+ left: css`+ overflow-y: auto;+ flex-shrink: 0;+ width: 240px;+ padding: 8px;+ `,+ right: css`+ container-type: size;+ overflow: auto;+ flex: 1;+ `,+}));+const Schema = memo(() => {const { t } = useTranslation('discover');- const { tools, toolsLoading } = useDetailContext();+ const { t: ts } = useTranslation('setting');+ const { tools, toolsLoading, skillContent } = useDetailContext();const [activeKey, setActiveKey] = useState<string[]>([]);const [mode, setMode] = useState<ModeType>(ModeType.Docs);+ const [selectedFile, setSelectedFile] = useState('SKILL.md');const toolsCount = tools.length;+ const skillDetail = useMemo(+ () => (skillContent ? ({ content: skillContent, name: '' } as SkillItem) : undefined),+ [skillContent],+ );+if (toolsLoading) {return (<Flexbox gap={16}>@@ -28,25 +58,56 @@ const Schema = memo(() => {return (<DetailProvider config={{ tools, toolsCount }}>- <Flexbox gap={8}>- <Flexbox horizontal align="center" gap={12} justify="space-between">- <Title level={3} tag={<Tag>{toolsCount}</Tag>}>- {t('mcp.details.schema.tools.title')}- </Title>- <Segmented- shape="round"- value={mode}- variant="outlined"- options={[- { label: t('mcp.details.schema.mode.docs'), value: ModeType.Docs },- { label: 'JSON', value: ModeType.JSON },- ]}- onChange={(v) => setMode(v as ModeType)}- />+ {toolsCount > 0 && (+ <Flexbox gap={8}>+ <Flexbox horizontal align="center" gap={12} justify="space-between">+ <Title level={3} tag={<Tag>{toolsCount}</Tag>}>+ {t('mcp.details.schema.tools.title')}+ </Title>+ <Segmented+ shape="round"+ value={mode}+ variant="outlined"+ options={[+ { label: t('mcp.details.schema.mode.docs'), value: ModeType.Docs },+ { label: 'JSON', value: ModeType.JSON },+ ]}+ onChange={(v) => setMode(v as ModeType)}+ />+ </Flexbox>+ <p style={{ marginBottom: 24 }}>{t('mcp.details.schema.tools.desc')}</p>+ <Tools activeKey={activeKey} mode={mode} setActiveKey={setActiveKey} /></Flexbox>- <p style={{ marginBottom: 24 }}>{t('mcp.details.schema.tools.desc')}</p>- <Tools activeKey={activeKey} mode={mode} setActiveKey={setActiveKey} />- </Flexbox>+ )}+ {skillContent && (+ <Flexbox gap={8}>+ <Flexbox+ horizontal+ style={{+ border: `1px solid ${cssVar.colorBorderSecondary}`,+ borderRadius: 8,+ height: 400,+ overflow: 'hidden',+ }}+ >+ <div className={styles.left}>+ <FileTree+ resourceTree={[]}+ selectedFile={selectedFile}+ onSelectFile={setSelectedFile}+ />+ </div>+ <div className={styles.divider} />+ <div className={styles.right} key={selectedFile}>+ <ContentViewer+ contentMap={{}}+ selectedFile={selectedFile}+ skillDetail={skillDetail}+ />+ </div>+ </Flexbox>+ </Flexbox>+ )}</DetailProvider>);});diff --git a/src/features/SkillStore/SkillDetail/index.tsx b/src/features/SkillStore/SkillDetail/index.tsxindex 78c13b6ad68..405443896b6 100644--- a/src/features/SkillStore/SkillDetail/index.tsx+++ b/src/features/SkillStore/SkillDetail/index.tsx@@ -4,10 +4,26 @@ import { createModal } from '@lobehub/ui';import { t } from 'i18next';import { type Klavis } from 'klavis';+import { BuiltinAgentSkillDetailContent } from './BuiltinAgentSkillDetailContent';import { BuiltinSkillDetailContent } from './BuiltinSkillDetailContent';import { KlavisSkillDetailContent } from './KlavisSkillDetailContent';import { LobehubSkillDetailContent } from './LobehubSkillDetailContent';+export interface CreateBuiltinAgentSkillDetailModalOptions {+ identifier: string;+}++export const createBuiltinAgentSkillDetailModal = ({+ identifier,+}: CreateBuiltinAgentSkillDetailModalOptions) =>+ createModal({+ children: <BuiltinAgentSkillDetailContent identifier={identifier} />,+ destroyOnHidden: true,+ footer: null,+ title: t('dev.title.skillDetails', { ns: 'plugin' }),+ width: 800,+ });+export interface CreateBuiltinSkillDetailModalOptions {identifier: string;}diff --git a/src/features/SkillStore/SkillList/AddSkillButton.tsx b/src/features/SkillStore/SkillList/AddSkillButton.tsxindex 6008b6cd4f5..e62c7eafdc2 100644--- a/src/features/SkillStore/SkillList/AddSkillButton.tsx+++ b/src/features/SkillStore/SkillList/AddSkillButton.tsx@@ -1,17 +1,31 @@-import { type ButtonProps } from '@lobehub/ui';-import { Button } from '@lobehub/ui';-import { Grid2x2Plus } from 'lucide-react';-import { type Ref } from 'react';-import { useState } from 'react';+import { Button, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';+import { ChevronDown, FileArchive, Github, Grid2x2Plus, Link, PenLine } from 'lucide-react';+import { type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import DevModal from '@/features/PluginDevModal';import { useAgentStore } from '@/store/agent';import { useToolStore } from '@/store/tool';-const AddSkillButton = ({ ref, ...props }: ButtonProps & { ref?: Ref<HTMLButtonElement> }) => {+import ImportFromGithubModal from './ImportFromGithubModal';+import ImportFromUrlModal from './ImportFromUrlModal';+import UploadSkillModal from './UploadSkillModal';++const MenuLabel = ({ desc, title }: { desc: string; title: ReactNode }) => (+ <Flexbox gap={2}>+ <span>{title}</span>+ <Text style={{ fontSize: 12 }} type="secondary">+ {desc}+ </Text>+ </Flexbox>+);++const AddSkillButton = () => {const { t } = useTranslation('setting');- const [showModal, setModal] = useState(false);+ const [showMcpModal, setMcpModal] = useState(false);+ const [showUrlModal, setUrlModal] = useState(false);+ const [showGithubModal, setGithubModal] = useState(false);+ const [showUploadModal, setUploadModal] = useState(false);const [installCustomPlugin, updateNewDevPlugin] = useToolStore((s) => [s.installCustomPlugin,@@ -26,23 +40,55 @@ const AddSkillButton = ({ ref, ...props }: ButtonProps & { ref?: Ref<HTMLButtonE}}><DevModal- open={showModal}- onOpenChange={setModal}+ open={showMcpModal}+ onOpenChange={setMcpModal}onValueChange={updateNewDevPlugin}onSave={async (devPlugin) => {await installCustomPlugin(devPlugin);await togglePlugin(devPlugin.identifier);}}/>- <Button- icon={Grid2x2Plus}- ref={ref}- onClick={() => {- setModal(true);- }}+ <ImportFromUrlModal open={showUrlModal} onOpenChange={setUrlModal} />+ <ImportFromGithubModal open={showGithubModal} onOpenChange={setGithubModal} />+ <UploadSkillModal open={showUploadModal} onOpenChange={setUploadModal} />+ <DropdownMenu+ nativeButton={false}+ placement="bottomRight"+ items={[+ {+ icon: <Icon icon={Link} />,+ key: 'importUrl',+ label: <MenuLabel desc={t('tab.importFromUrl.desc')} title={t('tab.importFromUrl')} />,+ onClick: () => setUrlModal(true),+ },+ {+ icon: <Icon icon={Github} />,+ key: 'importGithub',+ label: (+ <MenuLabel desc={t('tab.importFromGithub.desc')} title={t('tab.importFromGithub')} />+ ),+ onClick: () => setGithubModal(true),+ },+ {+ icon: <Icon icon={FileArchive} />,+ key: 'uploadZip',+ label: <MenuLabel desc={t('tab.uploadZip.desc')} title={t('tab.uploadZip')} />,+ onClick: () => setUploadModal(true),+ },+ { type: 'divider' as const },+ {+ icon: <Icon icon={PenLine} />,+ key: 'customMcp',+ label: <MenuLabel desc={t('tab.addCustomMcp.desc')} title={t('tab.addCustomMcp')} />,+ onClick: () => setMcpModal(true),+ },+ ]}>- {t('tab.addCustomSkill')}- </Button>+ <Button icon={Grid2x2Plus}>+ {t('tab.addCustomSkill')}+ <Icon icon={ChevronDown} size={14} />+ </Button>+ </DropdownMenu></div>);};diff --git a/src/features/SkillStore/SkillList/AgentSkillItem.tsx b/src/features/SkillStore/SkillList/AgentSkillItem.tsxnew file mode 100644index 00000000000..d450fb58c45--- /dev/null+++ b/src/features/SkillStore/SkillList/AgentSkillItem.tsx@@ -0,0 +1,161 @@+'use client';++import { ActionIcon, Avatar, Block, DropdownMenu, Flexbox, Icon, Modal, Tag } from '@lobehub/ui';+import { App } from 'antd';+import { createStaticStyles, cssVar } from 'antd-style';+import { DownloadIcon, MoreVerticalIcon, PackageSearch, PuzzleIcon, Trash2 } from 'lucide-react';+import { lazy, memo, Suspense, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { agentSkillService } from '@/services/skill';+import { useToolStore } from '@/store/tool';+import { type SkillListItem } from '@/types/index';+import { downloadFile } from '@/utils/client/downloadFile';++import { itemStyles } from './style';++const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));+const AgentSkillEdit = lazy(() => import('@/features/AgentSkillEdit'));++const styles = createStaticStyles(({ css }) => ({+ title: css`+ cursor: pointer;++ overflow: hidden;++ font-size: 14px;+ font-weight: 500;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ &:hover {+ color: ${cssVar.colorPrimary};+ }+ `,+}));++interface AgentSkillItemProps {+ skill: SkillListItem;+}++const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {+ const { t } = useTranslation('plugin');+ const { t: tc } = useTranslation('common');+ const { modal } = App.useApp();+ const [detailOpen, setDetailOpen] = useState(false);+ const [editOpen, setEditOpen] = useState(false);+ const [loading, setLoading] = useState(false);+ const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);++ const handleDownload = async () => {+ if (!skill.zipFileHash) return;++ setLoading(true);+ try {+ const result = await agentSkillService.getZipUrl(skill.id);+ if (result.url) {+ await downloadFile(result.url, `${result.name || skill.name}.zip`);+ }+ } finally {+ setLoading(false);+ }+ };++ const handleDelete = () => {+ modal.confirm({+ centered: true,+ okButtonProps: { danger: true },+ onOk: async () => {+ await deleteAgentSkill(skill.id);+ },+ title: t('store.actions.confirmUninstall'),+ type: 'error',+ });+ };++ return (+ <>+ <Flexbox className={itemStyles.container} gap={0}>+ <Block+ horizontal+ align={'center'}+ gap={12}+ paddingBlock={12}+ paddingInline={12}+ variant={'outlined'}+ >+ <Avatar avatar={'🧩'} shape={'square'} size={40} />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8}>+ <span className={styles.title} onClick={() => setDetailOpen(true)}>+ {skill.name}+ </span>+ <Tag icon={<Icon icon={PuzzleIcon} />} size={'small'} />+ </Flexbox>+ {skill.description && (+ <span className={itemStyles.description}>{skill.description}</span>+ )}+ </Flexbox>+ <Flexbox horizontal>+ {skill.source === 'user' && (+ <ActionIcon+ icon={PackageSearch}+ title={t('store.actions.manifest')}+ onClick={() => setEditOpen(true)}+ />+ )}+ <DropdownMenu+ nativeButton={false}+ placement="bottomRight"+ items={[+ ...(skill.zipFileHash+ ? [+ {+ icon: <Icon icon={DownloadIcon} />,+ key: 'download',+ label: tc('download'),+ onClick: handleDownload,+ },+ { type: 'divider' as const },+ ]+ : []),+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'uninstall',+ label: t('store.actions.uninstall'),+ onClick: handleDelete,+ },+ ]}+ >+ <ActionIcon icon={MoreVerticalIcon} loading={loading} />+ </DropdownMenu>+ </Flexbox>+ </Block>+ </Flexbox>+ <Modal+ destroyOnHidden+ footer={null}+ open={detailOpen}+ styles={{ body: { height: 'calc(100dvh - 200px)', overflow: 'hidden', padding: 0 } }}+ title={t('dev.title.skillDetails')}+ width={960}+ onCancel={() => setDetailOpen(false)}+ >+ <Suspense fallback={<div style={{ height: '100%' }} />}>+ <AgentSkillDetail skillId={skill.id} />+ </Suspense>+ </Modal>+ {skill.source === 'user' && (+ <Suspense>+ <AgentSkillEdit open={editOpen} skillId={skill.id} onClose={() => setEditOpen(false)} />+ </Suspense>+ )}+ </>+ );+});++AgentSkillItem.displayName = 'AgentSkillStoreItem';++export default AgentSkillItem;diff --git a/src/features/SkillStore/SkillList/Community/Item.tsx b/src/features/SkillStore/SkillList/Community/Item.tsxindex c102fb6791c..25ca7412e4e 100644--- a/src/features/SkillStore/SkillList/Community/Item.tsx+++ b/src/features/SkillStore/SkillList/Community/Item.tsx@@ -15,6 +15,7 @@ import { MoreVerticalIcon, Plus, Trash2 } from 'lucide-react';import React, { memo, Suspense, useState } from 'react';import { useTranslation } from 'react-i18next';+import MCPTag from '@/components/Plugins/MCPTag';import PluginAvatar from '@/components/Plugins/PluginAvatar';import McpDetail from '@/features/MCP/MCPDetail';import McpDetailLoading from '@/features/MCP/MCPDetail/Loading';@@ -138,7 +139,10 @@ const Item = memo<DiscoverMcpItem>(({ name, description, icon, identifier }) =>><PluginAvatar avatar={icon} size={40} /><Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>- <span className={styles.title}>{name}</span>+ <Flexbox align="center" gap={8} horizontal>+ <span className={styles.title}>{name}</span>+ <MCPTag showText={false} />+ </Flexbox>{description && <span className={styles.description}>{description}</span>}</Flexbox><div onClick={stopPropagation}>{renderAction()}</div>diff --git a/src/features/SkillStore/SkillList/Community/index.tsx b/src/features/SkillStore/SkillList/Community/index.tsxindex 023e6d77571..0a4bec074be 100644--- a/src/features/SkillStore/SkillList/Community/index.tsx+++ b/src/features/SkillStore/SkillList/Community/index.tsx@@ -1,13 +1,18 @@'use client';+import { type SkillListItem } from '@lobechat/types';import { Center, Icon, Text } from '@lobehub/ui';+import isEqual from 'fast-deep-equal';import { ServerCrash } from 'lucide-react';-import { memo, useEffect, useRef } from 'react';+import { memo, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { VirtuosoGrid } from 'react-virtuoso';import { useToolStore } from '@/store/tool';+import { agentSkillsSelectors } from '@/store/tool/selectors';+import { type DiscoverMcpItem } from '@/types/discover';+import AgentSkillItem from '../AgentSkillItem';import Empty from '../Empty';import Loading from '../Loading';import { virtuosoGridStyles } from '../style';@@ -15,6 +20,10 @@ import VirtuosoLoading from '../VirtuosoLoading';import WantMoreSkills from '../WantMoreSkills';import Item from './Item';+type CommunityListItem =+ | { itemType: 'agentSkill'; skill: SkillListItem }+ | { data: DiscoverMcpItem; itemType: 'mcp' };+export const CommunityList = memo(() => {const { t } = useTranslation('setting');@@ -28,6 +37,7 @@ export const CommunityList = memo(() => {useFetchMCPPluginList,loadMoreMCPPlugins,resetMCPPluginList,+ useFetchAgentSkills,] = useToolStore((s) => [s.mcpSearchKeywords,s.isMcpListInit,@@ -38,8 +48,35 @@ export const CommunityList = memo(() => {s.useFetchMCPPluginList,s.loadMoreMCPPlugins,s.resetMCPPluginList,+ s.useFetchAgentSkills,]);+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ useFetchAgentSkills(true);++ const filteredMarketAgentSkills = useMemo(() => {+ const lowerKeywords = (keywords || '').toLowerCase().trim();+ if (!lowerKeywords) return marketAgentSkills;++ return marketAgentSkills.filter((skill) => {+ const name = skill.name?.toLowerCase() || '';+ const identifier = skill.identifier?.toLowerCase() || '';+ return name.includes(lowerKeywords) || identifier.includes(lowerKeywords);+ });+ }, [marketAgentSkills, keywords]);++ const combinedItems = useMemo<CommunityListItem[]>(() => {+ const agentSkillItems: CommunityListItem[] = filteredMarketAgentSkills.map((skill) => ({+ itemType: 'agentSkill' as const,+ skill,+ }));+ const mcpItems: CommunityListItem[] = allItems.map((data) => ({+ data,+ itemType: 'mcp' as const,+ }));+ return [...agentSkillItems, ...mcpItems];+ }, [filteredMarketAgentSkills, allItems]);+const prevKeywordsRef = useRef(keywords);useEffect(() => {@@ -71,7 +108,7 @@ export const CommunityList = memo(() => {);}- if (allItems.length === 0) return <Empty search={hasSearchKeywords} />;+ if (combinedItems.length === 0) return <Empty search={hasSearchKeywords} />;// Check if we've reached the end of the listconst hasReachedEnd = totalPages !== undefined && currentPage >= totalPages;@@ -84,17 +121,23 @@ export const CommunityList = memo(() => {return (<VirtuosoGrid- data={allItems}+ data={combinedItems}endReached={loadMoreMCPPlugins}increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}itemClassName={virtuosoGridStyles.item}- itemContent={(_, item) => <Item {...item} />}listClassName={virtuosoGridStyles.list}overscan={24}style={{ height: '60vh', width: '100%' }}components={{Footer: renderFooter,}}+ itemContent={(_, item) =>+ item.itemType === 'agentSkill' ? (+ <AgentSkillItem skill={item.skill} />+ ) : (+ <Item {...item.data} />+ )+ }/>);};diff --git a/src/features/SkillStore/SkillList/Custom/Item.tsx b/src/features/SkillStore/SkillList/Custom/Item.tsxindex d73ceda2325..32e478903d3 100644--- a/src/features/SkillStore/SkillList/Custom/Item.tsx+++ b/src/features/SkillStore/SkillList/Custom/Item.tsx@@ -7,6 +7,7 @@ import { MoreVerticalIcon, PackageSearch, Trash2 } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';+import MCPTag from '@/components/Plugins/MCPTag';import PluginAvatar from '@/components/Plugins/PluginAvatar';import PluginDetailModal from '@/features/PluginDetailModal';import DevModal from '@/features/PluginDevModal';@@ -88,9 +89,12 @@ const Item = memo<ItemProps>(({ identifier, title, description, avatar }) => {><PluginAvatar avatar={avatar} size={40} /><Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>- <span className={styles.title} onClick={() => setDetailOpen(true)}>- {title || identifier}- </span>+ <Flexbox align="center" gap={8} horizontal>+ <span className={styles.title} onClick={() => setDetailOpen(true)}>+ {title || identifier}+ </span>+ <MCPTag showText={false} />+ </Flexbox>{description && <span className={itemStyles.description}>{description}</span>}</Flexbox><Flexbox horizontal>diff --git a/src/features/SkillStore/SkillList/Custom/index.tsx b/src/features/SkillStore/SkillList/Custom/index.tsxindex 2dbf3e6488c..823782604aa 100644--- a/src/features/SkillStore/SkillList/Custom/index.tsx+++ b/src/features/SkillStore/SkillList/Custom/index.tsx@@ -4,17 +4,21 @@ import isEqual from 'fast-deep-equal';import { memo, useMemo } from 'react';import { useToolStore } from '@/store/tool';-import { pluginSelectors } from '@/store/tool/selectors';+import { agentSkillsSelectors, pluginSelectors } from '@/store/tool/selectors';+import AgentSkillItem from '../AgentSkillItem';import Empty from '../Empty';import { gridStyles } from '../style';import Item from './Item';export const CustomList = memo(() => {const customPlugins = useToolStore(pluginSelectors.installedCustomPluginMetaList, isEqual);+ const agentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);const searchKeywords = useToolStore((s) => s.customPluginSearchKeywords || '');+ const useFetchAgentSkills = useToolStore((s) => s.useFetchAgentSkills);+ useFetchAgentSkills(true);- const filteredItems = useMemo(() => {+ const filteredPlugins = useMemo(() => {const lowerKeywords = searchKeywords.toLowerCase().trim();if (!lowerKeywords) return customPlugins;@@ -25,15 +29,29 @@ export const CustomList = memo(() => {});}, [customPlugins, searchKeywords]);+ const filteredAgentSkills = useMemo(() => {+ const lowerKeywords = searchKeywords.toLowerCase().trim();+ if (!lowerKeywords) return agentSkills;++ return agentSkills.filter((skill) => {+ const name = skill.name?.toLowerCase() || '';+ const identifier = skill.identifier?.toLowerCase() || '';+ return name.includes(lowerKeywords) || identifier.includes(lowerKeywords);+ });+ }, [agentSkills, searchKeywords]);+const hasSearchKeywords = Boolean(searchKeywords && searchKeywords.trim());- if (filteredItems.length === 0) {+ if (filteredAgentSkills.length === 0 && filteredPlugins.length === 0) {return <Empty search={hasSearchKeywords} />;}return (<div className={gridStyles.grid}>- {filteredItems.map((plugin) => (+ {filteredAgentSkills.map((skill) => (+ <AgentSkillItem key={skill.id} skill={skill} />+ ))}+ {filteredPlugins.map((plugin) => (<Itemavatar={plugin.avatar}description={plugin.description}diff --git a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsxnew file mode 100644index 00000000000..8d71bfcd259--- /dev/null+++ b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx@@ -0,0 +1,97 @@+'use client';++import { Alert, Flexbox, Icon, Input } from '@lobehub/ui';+import { App, Button, Modal, Typography } from 'antd';+import { ArrowLeftRight, Github, Sparkles } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';++interface ImportFromGithubModalProps {+ onOpenChange: (open: boolean) => void;+ open: boolean;+}++const ImportFromGithubModal = memo<ImportFromGithubModalProps>(({ open, onOpenChange }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { message } = App.useApp();+ const importAgentSkillFromGitHub = useToolStore((s) => s.importAgentSkillFromGitHub);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [url, setUrl] = useState('');++ const handleClose = () => {+ onOpenChange(false);+ setError(null);+ setUrl('');+ };++ const handleImport = async () => {+ const trimmed = url.trim();+ if (!trimmed) return;++ setLoading(true);+ setError(null);++ try {+ await importAgentSkillFromGitHub({ gitUrl: trimmed });+ message.success(t('agentSkillModal.importSuccess'));+ handleClose();+ } catch (err: any) {+ setError(err?.message || String(err));+ } finally {+ setLoading(false);+ }+ };++ return (+ <Modal destroyOnClose footer={null} open={open} title={null} width={480} onCancel={handleClose}>+ <Flexbox align="center" gap={16} padding={'16px 0'}>+ <Flexbox horizontal align="center" gap={8}>+ <Icon icon={Github} size={28} />+ <Icon+ icon={ArrowLeftRight}+ size={16}+ style={{ color: 'var(--ant-color-text-tertiary)' }}+ />+ <Icon icon={Sparkles} size={28} />+ </Flexbox>++ <Flexbox align="center" gap={4}>+ <Typography.Title level={4} style={{ margin: 0 }}>+ {t('agentSkillModal.github.title')}+ </Typography.Title>+ <Typography.Text type="secondary">{t('agentSkillModal.github.desc')}</Typography.Text>+ </Flexbox>+ </Flexbox>++ <Flexbox gap={16}>+ {error && (+ <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />+ )}++ <Flexbox gap={8}>+ <Typography.Text strong>URL</Typography.Text>+ <Input+ placeholder={t('agentSkillModal.github.urlPlaceholder')}+ value={url}+ onPressEnter={handleImport}+ onChange={(e) => {+ setUrl(e.target.value);+ if (error) setError(null);+ }}+ />+ </Flexbox>++ <Button block loading={loading} type="primary" onClick={handleImport}>+ {t('common:import')}+ </Button>+ </Flexbox>+ </Modal>+ );+});++ImportFromGithubModal.displayName = 'ImportFromGithubModal';++export default ImportFromGithubModal;diff --git a/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsxnew file mode 100644index 00000000000..02812e07956--- /dev/null+++ b/src/features/SkillStore/SkillList/ImportFromUrlModal.tsx@@ -0,0 +1,97 @@+'use client';++import { Alert, Flexbox, Icon, Input } from '@lobehub/ui';+import { App, Button, Modal, Typography } from 'antd';+import { ArrowLeftRight, Link, Sparkles } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';++interface ImportFromUrlModalProps {+ onOpenChange: (open: boolean) => void;+ open: boolean;+}++const ImportFromUrlModal = memo<ImportFromUrlModalProps>(({ open, onOpenChange }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { message } = App.useApp();+ const importAgentSkillFromUrl = useToolStore((s) => s.importAgentSkillFromUrl);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [url, setUrl] = useState('');++ const handleClose = () => {+ onOpenChange(false);+ setError(null);+ setUrl('');+ };++ const handleImport = async () => {+ const trimmed = url.trim();+ if (!trimmed) return;++ setLoading(true);+ setError(null);++ try {+ await importAgentSkillFromUrl({ url: trimmed });+ message.success(t('agentSkillModal.importSuccess'));+ handleClose();+ } catch (err: any) {+ setError(err?.message || String(err));+ } finally {+ setLoading(false);+ }+ };++ return (+ <Modal destroyOnClose footer={null} open={open} title={null} width={480} onCancel={handleClose}>+ <Flexbox align="center" gap={16} padding={'16px 0'}>+ <Flexbox horizontal align="center" gap={8}>+ <Icon icon={Link} size={28} />+ <Icon+ icon={ArrowLeftRight}+ size={16}+ style={{ color: 'var(--ant-color-text-tertiary)' }}+ />+ <Icon icon={Sparkles} size={28} />+ </Flexbox>++ <Flexbox align="center" gap={4}>+ <Typography.Title level={4} style={{ margin: 0 }}>+ {t('agentSkillModal.url.title')}+ </Typography.Title>+ <Typography.Text type="secondary">{t('agentSkillModal.url.desc')}</Typography.Text>+ </Flexbox>+ </Flexbox>++ <Flexbox gap={16}>+ {error && (+ <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />+ )}++ <Flexbox gap={8}>+ <Typography.Text strong>URL</Typography.Text>+ <Input+ placeholder={t('agentSkillModal.url.urlPlaceholder')}+ value={url}+ onPressEnter={handleImport}+ onChange={(e) => {+ setUrl(e.target.value);+ if (error) setError(null);+ }}+ />+ </Flexbox>++ <Button block loading={loading} type="primary" onClick={handleImport}>+ {t('common:import')}+ </Button>+ </Flexbox>+ </Modal>+ );+});++ImportFromUrlModal.displayName = 'ImportFromUrlModal';++export default ImportFromUrlModal;diff --git a/src/features/SkillStore/SkillList/LobeHub/index.tsx b/src/features/SkillStore/SkillList/LobeHub/index.tsxindex 91e61706923..dbcad45d57e 100644--- a/src/features/SkillStore/SkillList/LobeHub/index.tsx+++ b/src/features/SkillStore/SkillList/LobeHub/index.tsx@@ -1,12 +1,13 @@'use client';import { KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';-import { type LobeToolMeta } from '@lobechat/types';+import { type BuiltinSkill, type LobeToolMeta } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import {+ createBuiltinAgentSkillDetailModal,createBuiltinSkillDetailModal,createKlavisSkillDetailModal,createLobehubSkillDetailModal,@@ -48,6 +49,7 @@ export const LobeHubList = memo<LobeHubListProps>(({ keywords }) => {const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);// Use custom selector to get only actual builtin tools (not Klavis)const builtinTools = useToolStore(getBuiltinToolsOnly, isEqual);+ const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);const [useFetchLobehubSkillConnections, useFetchUserKlavisServers] = useToolStore((s) => [s.useFetchLobehubSkillConnections,@@ -75,10 +77,16 @@ export const LobeHubList = memo<LobeHubListProps>(({ keywords }) => {const items: Array<| { provider: (typeof LOBEHUB_SKILL_PROVIDERS)[number]; type: 'lobehub' }| { serverType: (typeof KLAVIS_SERVER_TYPES)[number]; type: 'klavis' }+ | { skill: BuiltinSkill; type: 'builtinAgentSkill' }| { tool: LobeToolMeta; type: 'builtin' }> = [];- // Add builtin tools first+ // Add builtin agent skills first+ for (const skill of builtinSkills) {+ items.push({ skill, type: 'builtinAgentSkill' });+ }++ // Add builtin toolsfor (const tool of builtinTools) {items.push({ tool, type: 'builtin' });}@@ -102,6 +110,11 @@ export const LobeHubList = memo<LobeHubListProps>(({ keywords }) => {if (!lowerKeywords) return items;return items.filter((item) => {+ if (item.type === 'builtinAgentSkill') {+ const name = item.skill.name.toLowerCase();+ const identifier = item.skill.identifier.toLowerCase();+ return name.includes(lowerKeywords) || identifier.includes(lowerKeywords);+ }if (item.type === 'builtin') {const title = item.tool.meta?.title?.toLowerCase() || '';const identifier = item.tool.identifier?.toLowerCase() || '';@@ -110,7 +123,7 @@ export const LobeHubList = memo<LobeHubListProps>(({ keywords }) => {const label = item.type === 'lobehub' ? item.provider.label : item.serverType.label;return label.toLowerCase().includes(lowerKeywords);});- }, [keywords, isLobehubSkillEnabled, isKlavisEnabled, builtinTools]);+ }, [keywords, isLobehubSkillEnabled, isKlavisEnabled, builtinTools, builtinSkills]);const hasSearchKeywords = Boolean(keywords && keywords.trim());@@ -120,6 +133,26 @@ export const LobeHubList = memo<LobeHubListProps>(({ keywords }) => {<><div className={gridStyles.grid}>{filteredItems.map((item) => {+ if (item.type === 'builtinAgentSkill') {+ const localizedTitle = t(`tools.builtins.${item.skill.identifier}.title`, {+ defaultValue: item.skill.name,+ });+ const localizedDescription = t(`tools.builtins.${item.skill.identifier}.description`, {+ defaultValue: item.skill.description,+ });+ return (+ <BuiltinItem+ avatar={item.skill.avatar}+ description={localizedDescription}+ identifier={item.skill.identifier}+ key={item.skill.identifier}+ title={localizedTitle}+ onOpenDetail={() =>+ createBuiltinAgentSkillDetailModal({ identifier: item.skill.identifier })+ }+ />+ );+ }if (item.type === 'builtin') {const localizedTitle = t(`tools.builtins.${item.tool.identifier}.title`, {defaultValue: item.tool.meta?.title || item.tool.identifier,diff --git a/src/features/SkillStore/SkillList/UploadSkillModal.tsx b/src/features/SkillStore/SkillList/UploadSkillModal.tsxnew file mode 100644index 00000000000..86d4e54cee3--- /dev/null+++ b/src/features/SkillStore/SkillList/UploadSkillModal.tsx@@ -0,0 +1,151 @@+'use client';++import { LoadingOutlined } from '@ant-design/icons';+import { Alert, Flexbox, Icon } from '@lobehub/ui';+import { App, Modal, Spin, Typography, Upload } from 'antd';+import { sha256 } from 'js-sha256';+import { ArrowLeftRight, InboxIcon, Sparkles, Upload as UploadIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaClient } from '@/libs/trpc/client/lambda';+import { uploadService } from '@/services/upload';+import { useToolStore } from '@/store/tool';++interface UploadSkillModalProps {+ onOpenChange: (open: boolean) => void;+ open: boolean;+}++const UploadSkillModal = memo<UploadSkillModalProps>(({ open, onOpenChange }) => {+ const { t } = useTranslation(['setting', 'common']);+ const { message } = App.useApp();+ const importAgentSkillFromZip = useToolStore((s) => s.importAgentSkillFromZip);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const handleClose = () => {+ onOpenChange(false);+ setError(null);+ };++ const handleUploadFile = async (file: File) => {+ setLoading(true);+ setError(null);++ try {+ const { data: metadata } = await uploadService.uploadFileToS3(file, {+ directory: 'skills',+ });++ const hash = sha256(await file.arrayBuffer());++ const result = await lambdaClient.file.createFile.mutate({+ fileType: file.type || 'application/zip',+ hash,+ metadata: {},+ name: file.name,+ size: file.size,+ url: metadata.path,+ });++ await importAgentSkillFromZip({ zipFileId: result.id });+ message.success(t('agentSkillModal.importSuccess'));+ handleClose();+ } catch (err: any) {+ setError(err?.message || String(err));+ } finally {+ setLoading(false);+ }+ };++ return (+ <Modal+ destroyOnClose+ closable={!loading}+ footer={null}+ maskClosable={!loading}+ open={open}+ title={null}+ width={480}+ onCancel={handleClose}+ >+ <Flexbox align="center" gap={16} padding={'16px 0'}>+ <Flexbox horizontal align="center" gap={8}>+ <Icon icon={UploadIcon} size={28} />+ <Icon+ icon={ArrowLeftRight}+ size={16}+ style={{ color: 'var(--ant-color-text-tertiary)' }}+ />+ <Icon icon={Sparkles} size={28} />+ </Flexbox>++ <Flexbox align="center" gap={4}>+ <Typography.Title level={4} style={{ margin: 0 }}>+ {t('agentSkillModal.upload.title')}+ </Typography.Title>+ <Typography.Text type="secondary">{t('agentSkillModal.upload.desc')}</Typography.Text>+ </Flexbox>+ </Flexbox>++ <Flexbox gap={16}>+ {error && (+ <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />+ )}++ <Upload.Dragger+ accept=".zip,.skill"+ disabled={loading}+ showUploadList={false}+ beforeUpload={(file) => {+ handleUploadFile(file);+ return false;+ }}+ >+ <Flexbox align="center" gap={8} padding={24}>+ {loading ? (+ <>+ <Spin indicator={<LoadingOutlined spin />} />+ <Typography.Text type="secondary">+ {t('agentSkillModal.upload.uploading')}+ </Typography.Text>+ </>+ ) : (+ <>+ <Icon+ icon={InboxIcon}+ size={48}+ style={{ color: 'var(--ant-color-text-quaternary)' }}+ />+ <Typography.Text type="secondary">+ {t('agentSkillModal.upload.dragText')}+ </Typography.Text>+ </>+ )}+ </Flexbox>+ </Upload.Dragger>++ <Flexbox gap={8}>+ <Typography.Text strong>{t('agentSkillModal.upload.requirements')}</Typography.Text>+ <ul style={{ margin: 0, paddingLeft: 20 }}>+ <li>+ <Typography.Text type="secondary">+ {t('agentSkillModal.upload.requirementZip')}+ </Typography.Text>+ </li>+ <li>+ <Typography.Text type="secondary">+ {t('agentSkillModal.upload.requirementSkillMd')}+ </Typography.Text>+ </li>+ </ul>+ </Flexbox>+ </Flexbox>+ </Modal>+ );+});++UploadSkillModal.displayName = 'UploadSkillModal';++export default UploadSkillModal;diff --git a/src/features/SkillStore/index.tsx b/src/features/SkillStore/index.tsxindex 3e6ab6903d8..8e3f15dc4d8 100644--- a/src/features/SkillStore/index.tsx+++ b/src/features/SkillStore/index.tsx@@ -1,6 +1,6 @@'use client';-import { createModal } from '@lobehub/ui';+import { createModal, LOBE_THEME_APP_ID } from '@lobehub/ui';import { t } from 'i18next';import { MemoryRouter } from 'react-router-dom';@@ -21,6 +21,9 @@ export const createSkillStoreModal = () =>),destroyOnHidden: false,footer: null,+ // Render the antd Modal inside appElement instead of document.body,+ // so the modal and DropdownMenu portals share the same stacking context+ getContainer: () => document.getElementById(LOBE_THEME_APP_ID) || document.body,styles: {body: { overflow: 'hidden', padding: 0 },},diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex 6a8ae5c448c..bfe270e75bf 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -17,6 +17,7 @@ import {lobehubSkillStoreSelectors,pluginSelectors,} from '@/store/tool/selectors';+import { defaultToolIds } from '@/tools';import { getSearchConfig } from '../getSearchConfig';import { isCanUseFC } from '../isCanUseFC';@@ -82,7 +83,7 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =export const createAgentToolsEngine = (workingModel: WorkingModel) =>createToolsEngine({// Add default tools based on configuration- defaultToolIds: [WebBrowsingManifest.identifier, KnowledgeBaseManifest.identifier],+ defaultToolIds,// Create search-aware enableChecker for this requestenableChecker: ({ pluginId }) => {// Check platform-specific constraints (e.g., LocalSystem desktop-only)diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 565dd70ca08..b46bbab6a8d 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -171,6 +171,14 @@ export default {'builtins.lobe-page-agent.apiName.updateNode': 'Update node','builtins.lobe-page-agent.apiName.wrapNodes': 'Wrap nodes','builtins.lobe-page-agent.title': 'Page',+ 'builtins.lobe-skills.apiName.execScript': 'Run Script',+ 'builtins.lobe-skills.apiName.exportFile': 'Export File',+ 'builtins.lobe-skills.apiName.importFromMarket': 'Import from Market',+ 'builtins.lobe-skills.apiName.importSkill': 'Import Skill',+ 'builtins.lobe-skills.apiName.readReference': 'Read Reference',+ 'builtins.lobe-skills.apiName.runSkill': 'Activate Skill',+ 'builtins.lobe-skills.apiName.searchSkill': 'Search Skills',+ 'builtins.lobe-skills.title': 'Skills','builtins.lobe-user-memory.apiName.addContextMemory': 'Add context memory','builtins.lobe-user-memory.apiName.addExperienceMemory': 'Add experience memory','builtins.lobe-user-memory.apiName.addIdentityMemory': 'Add identity memory',@@ -325,8 +333,8 @@ export default {'dev.saveSuccess': 'Settings saved','dev.tabs.manifest': 'Manifest','dev.tabs.meta': 'Meta info',- 'dev.title.create': 'Add Custom Skill',- 'dev.title.edit': 'Edit Custom Skill',+ 'dev.title.create': 'Add Custom MCP Skill',+ 'dev.title.edit': 'Edit Custom MCP Skill','dev.title.editCommunity': 'Edit Community Skill','dev.title.skillDetails': 'Skill Details','dev.title.skillSettings': 'Skill Settings',diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex 6df94288329..aa9e49d8e5c 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -114,7 +114,6 @@ export default {'agentInfoDescription.basic.name': 'Name','agentInfoDescription.basic.tags': 'Tags','agentInfoDescription.basic.title': 'Agent info',-'agentInfoDescription.chat.enableHistoryCount': 'Enable Message History Count','agentInfoDescription.chat.historyCount': 'Message History Count','agentInfoDescription.chat.no': 'No',@@ -133,7 +132,49 @@ export default {'agentInfoDescription.role.systemRole': 'Agent Profile','agentInfoDescription.role.title': 'Agent Profile','agentInfoDescription.value.unset': 'Not Set',+'agentInfoDescription.value.untitled': 'Untitled Agent',+ 'agentSkillDetail.addedAt': 'Added',+ 'agentSkillDetail.publishedAt': 'Published',+ 'agentSkillDetail.repository': 'GitHub Repository',+ 'agentSkillDetail.skillContent': 'Skill Content',+ 'agentSkillDetail.sourceUrl': 'Skill Import Source',+ 'agentSkillDetail.updatedAt': 'Updated',+ 'agentSkillEdit.descriptionDesc':+ 'A brief summary of what the skill does, helping the agent understand when to use it',+ 'agentSkillEdit.fileReadonly':+ 'This file is read-only. Only skill description and instructions can be edited.',+ 'agentSkillEdit.instructions': 'Instructions',+ 'agentSkillEdit.instructionsDesc':+ 'The core instructions in Markdown that define the skill behavior and workflow',+ 'agentSkillEdit.instructionsPlaceholder': 'Enter the skill instructions in Markdown format...',+ 'agentSkillEdit.nameDesc': 'The unique identifier for this skill, not editable after creation',+ 'agentSkillEdit.saveSuccess': 'Skill updated successfully',+ 'agentSkillEdit.title': 'Skill Settings',+ 'agentSkillItem.deleteConfirm.desc':+ 'Are you sure you want to delete the agent skill "{{name}}"? This action cannot be undone.',+ 'agentSkillItem.deleteConfirm.title': 'Delete Agent Skill',+ 'agentSkillModal.content': 'Skill Content',+ 'agentSkillModal.contentPlaceholder': 'Enter skill content in Markdown format...',+ 'agentSkillModal.description': 'Description',+ 'agentSkillModal.descriptionPlaceholder': 'Briefly describe this skill',+ 'agentSkillModal.github.desc': 'Import skills directly from a public GitHub repository.',+ 'agentSkillModal.github.title': 'Import from GitHub',+ 'agentSkillModal.github.urlPlaceholder': 'https://github.com/username/repo',+ 'agentSkillModal.importError': 'Import failed: {{error}}',+ 'agentSkillModal.importSuccess': 'Agent Skill imported successfully',+ 'agentSkillModal.upload.desc': 'Upload a local .zip or .skill file to install.',+ 'agentSkillModal.upload.dragText': 'Drag and drop or click to upload',+ 'agentSkillModal.upload.requirementSkillMd':+ 'SKILL.md contains skill name and description in YAML format',+ 'agentSkillModal.upload.requirementZip': '.zip or .skill file with SKILL.md in root directory',+ 'agentSkillModal.upload.requirements': 'File Requirements',+ 'agentSkillModal.upload.title': 'Upload Skill',+ 'agentSkillModal.upload.uploading': 'Uploading...',+ 'agentSkillModal.url.desc': 'Import a skill by providing a direct link to a SKILL.md file.',+ 'agentSkillModal.url.title': 'Import from URL',+ 'agentSkillModal.url.urlPlaceholder': 'https://example.com/path/to/SKILL.md',+ 'agentSkillTag': 'Agent Skill','agentTab.chat': 'Chat Preferences','agentTab.meta': 'Agent info','agentTab.modal': 'Model Settings',@@ -744,7 +785,10 @@ When I am ___, I need ___'systemAgent.translation.modelDesc': 'Specify the model used for translation','systemAgent.translation.title': 'Message Translation Agent','tab.about': 'About',- 'tab.addCustomSkill': 'Add custom skill',+ 'tab.addAgentSkill': 'Add Agent Skill',+ 'tab.addCustomMcp': 'Add Custom MCP Skill',+ 'tab.addCustomMcp.desc': 'Manually configure a custom MCP server',+ 'tab.addCustomSkill': 'Add','tab.agent': 'Agent Service','tab.all': 'All','tab.apikey': 'API Key Management',@@ -753,7 +797,13 @@ When I am ___, I need ___'tab.experiment': 'Experiment','tab.hotkey': 'Hotkeys','tab.image': 'Image Generation Service',+ 'tab.importFromGithub': 'Import from GitHub',+ 'tab.importFromGithub.desc': 'Import from a public GitHub repository',+ 'tab.importFromUrl': 'Import from URL',+ 'tab.importFromUrl.desc': 'Import via a direct link to SKILL.md','tab.llm': 'Language Model',+ 'tab.manualFill': 'Manually Fill In',+ 'tab.manualFill.desc': 'Configure a custom MCP skill manually','tab.memory': 'Memory','tab.profile': 'My Account','tab.provider': 'AI Service Provider',@@ -770,6 +820,8 @@ When I am ___, I need ___'tab.sync': 'Cloud Sync','tab.systemTools': 'System Tools','tab.tts': 'Text-to-Speech',+ 'tab.uploadZip': 'Upload Zip',+ 'tab.uploadZip.desc': 'Upload a local .zip or .skill file','tab.usage': 'Usage Statistics','tools.add': 'Add Skill','tools.builtins.groupName': 'Built-ins',@@ -794,8 +846,7 @@ When I am ___, I need ___'tools.builtins.lobe-local-system.readme':'Access your local filesystem on desktop. Read, write, search, and organize files. Execute shell commands with background task support and grep content with regex patterns.','tools.builtins.lobe-local-system.title': 'Local System',- 'tools.builtins.lobe-notebook.description':- 'Create and manage documents in the topic notebook',+ 'tools.builtins.lobe-notebook.description': 'Create and manage documents in the topic notebook','tools.builtins.lobe-notebook.readme':'Create and manage persistent documents within conversation topics. Save notes, reports, articles, and markdown content that stays accessible across sessions.','tools.builtins.lobe-notebook.title': 'Notebook',diff --git a/src/server/modules/GitHub/index.test.ts b/src/server/modules/GitHub/index.test.tsnew file mode 100644index 00000000000..90f7ef23634--- /dev/null+++ b/src/server/modules/GitHub/index.test.ts@@ -0,0 +1,364 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ GitHub,+ GitHubDownloadError,+ GitHubNotFoundError,+ GitHubParseError,+ github,+} from './index';++describe('GitHub', () => {+ describe('parseRepoUrl', () => {+ const gh = new GitHub();++ it('should parse standard GitHub URL', () => {+ const result = gh.parseRepoUrl('https://github.com/lobehub/lobe-chat');+ expect(result).toEqual({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should parse GitHub URL with tree/branch', () => {+ const result = gh.parseRepoUrl('https://github.com/lobehub/lobe-chat/tree/develop');+ expect(result).toEqual({+ branch: 'develop',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should parse GitHub URL with tree/branch and path', () => {+ const result = gh.parseRepoUrl(+ 'https://github.com/lobehub/lobe-chat/tree/feature/new-ui/src/components',+ );+ expect(result).toEqual({+ branch: 'feature',+ owner: 'lobehub',+ path: 'new-ui/src/components',+ repo: 'lobe-chat',+ });+ });++ // When URL contains subdirectory path like /tree/main/skills/skill-creator,+ // the path should be captured and returned+ it('should capture subdirectory path from GitHub URL', () => {+ const result = gh.parseRepoUrl(+ 'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',+ );+ expect(result).toEqual({+ branch: 'main',+ owner: 'openclaw',+ path: 'skills/skill-creator',+ repo: 'openclaw',+ });+ });++ it('should capture nested subdirectory path from GitHub URL', () => {+ const result = gh.parseRepoUrl(+ 'https://github.com/lobehub/skills/tree/develop/agents/coding/python-expert',+ );+ expect(result).toEqual({+ branch: 'develop',+ owner: 'lobehub',+ path: 'agents/coding/python-expert',+ repo: 'skills',+ });+ });++ it('should not have path when URL has no subdirectory', () => {+ const result = gh.parseRepoUrl('https://github.com/lobehub/lobe-chat/tree/main');+ expect(result).toEqual({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ expect(result.path).toBeUndefined();+ });++ it('should parse GitHub URL without protocol', () => {+ const result = gh.parseRepoUrl('github.com/lobehub/lobe-chat');+ expect(result).toEqual({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should parse GitHub URL with .git suffix', () => {+ const result = gh.parseRepoUrl('https://github.com/lobehub/lobe-chat.git');+ expect(result).toEqual({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should parse shorthand format (owner/repo)', () => {+ const result = gh.parseRepoUrl('lobehub/lobe-chat');+ expect(result).toEqual({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should use custom default branch', () => {+ const result = gh.parseRepoUrl('https://github.com/lobehub/lobe-chat', 'dev');+ expect(result).toEqual({+ branch: 'dev',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ });++ it('should handle repo names with dots and hyphens', () => {+ const result = gh.parseRepoUrl('https://github.com/owner-name/repo.name-v2');+ expect(result).toEqual({+ branch: 'main',+ owner: 'owner-name',+ repo: 'repo.name-v2',+ });+ });++ it('should throw GitHubParseError for invalid URL', () => {+ expect(() => gh.parseRepoUrl('https://gitlab.com/owner/repo')).toThrow(GitHubParseError);+ expect(() => gh.parseRepoUrl('invalid-url')).toThrow(GitHubParseError);+ expect(() => gh.parseRepoUrl('https://github.com/')).toThrow(GitHubParseError);+ });+ });++ describe('buildRepoZipUrl', () => {+ const gh = new GitHub();++ it('should build correct ZIP URL', () => {+ const url = gh.buildRepoZipUrl({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ expect(url).toBe('https://github.com/lobehub/lobe-chat/archive/refs/heads/main.zip');+ });++ it('should handle different branches', () => {+ const url = gh.buildRepoZipUrl({+ branch: 'feature/new-ui',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ expect(url).toBe(+ 'https://github.com/lobehub/lobe-chat/archive/refs/heads/feature/new-ui.zip',+ );+ });+ });++ describe('buildRawFileUrl', () => {+ const gh = new GitHub();++ it('should build correct raw file URL', () => {+ const url = gh.buildRawFileUrl({+ branch: 'main',+ filePath: 'README.md',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ expect(url).toBe('https://raw.githubusercontent.com/lobehub/lobe-chat/main/README.md');+ });++ it('should handle nested file paths', () => {+ const url = gh.buildRawFileUrl({+ branch: 'develop',+ filePath: 'src/components/Button/index.tsx',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });+ expect(url).toBe(+ 'https://raw.githubusercontent.com/lobehub/lobe-chat/develop/src/components/Button/index.tsx',+ );+ });+ });++ describe('downloadRepoZip', () => {+ const gh = new GitHub();+ const mockFetch = vi.fn();++ beforeEach(() => {+ vi.stubGlobal('fetch', mockFetch);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should download repository ZIP successfully', async () => {+ const mockBuffer = new ArrayBuffer(100);+ mockFetch.mockResolvedValueOnce({+ arrayBuffer: () => Promise.resolve(mockBuffer),+ ok: true,+ });++ const result = await gh.downloadRepoZip({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });++ expect(result).toBeInstanceOf(Buffer);+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://github.com/lobehub/lobe-chat/archive/refs/heads/main.zip',+ {+ headers: {+ 'User-Agent': 'LobeHub',+ },+ },+ );+ });++ it('should throw GitHubNotFoundError for 404', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ await expect(+ gh.downloadRepoZip({+ branch: 'main',+ owner: 'lobehub',+ repo: 'non-existent',+ }),+ ).rejects.toThrow(GitHubNotFoundError);+ });++ it('should throw GitHubDownloadError for other errors', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 500,+ statusText: 'Internal Server Error',+ });++ await expect(+ gh.downloadRepoZip({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ }),+ ).rejects.toThrow(GitHubDownloadError);+ });++ it('should use custom user agent', async () => {+ const customGh = new GitHub({ userAgent: 'CustomAgent/1.0' });+ const mockBuffer = new ArrayBuffer(100);+ mockFetch.mockResolvedValueOnce({+ arrayBuffer: () => Promise.resolve(mockBuffer),+ ok: true,+ });++ await customGh.downloadRepoZip({+ branch: 'main',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });++ expect(mockFetch).toHaveBeenCalledWith(expect.any(String), {+ headers: {+ 'User-Agent': 'CustomAgent/1.0',+ },+ });+ });+ });++ describe('downloadRawFile', () => {+ const gh = new GitHub();+ const mockFetch = vi.fn();++ beforeEach(() => {+ vi.stubGlobal('fetch', mockFetch);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should download raw file successfully', async () => {+ const mockContent = '# README\n\nThis is a test.';+ mockFetch.mockResolvedValueOnce({+ ok: true,+ text: () => Promise.resolve(mockContent),+ });++ const result = await gh.downloadRawFile({+ branch: 'main',+ filePath: 'README.md',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });++ expect(result).toBe(mockContent);+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://raw.githubusercontent.com/lobehub/lobe-chat/main/README.md',+ {+ headers: {+ 'User-Agent': 'LobeHub',+ },+ },+ );+ });++ it('should throw GitHubNotFoundError for 404', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ await expect(+ gh.downloadRawFile({+ branch: 'main',+ filePath: 'non-existent.md',+ owner: 'lobehub',+ repo: 'lobe-chat',+ }),+ ).rejects.toThrow(GitHubNotFoundError);+ });+ });++ describe('downloadRawFileBuffer', () => {+ const gh = new GitHub();+ const mockFetch = vi.fn();++ beforeEach(() => {+ vi.stubGlobal('fetch', mockFetch);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should download raw file as buffer successfully', async () => {+ const mockBuffer = new ArrayBuffer(50);+ mockFetch.mockResolvedValueOnce({+ arrayBuffer: () => Promise.resolve(mockBuffer),+ ok: true,+ });++ const result = await gh.downloadRawFileBuffer({+ branch: 'main',+ filePath: 'image.png',+ owner: 'lobehub',+ repo: 'lobe-chat',+ });++ expect(result).toBeInstanceOf(Buffer);+ });+ });++ describe('github singleton', () => {+ it('should be an instance of GitHub', () => {+ expect(github).toBeInstanceOf(GitHub);+ });+ });+});diff --git a/src/server/modules/GitHub/index.ts b/src/server/modules/GitHub/index.tsnew file mode 100644index 00000000000..2d8f4e2b9d2--- /dev/null+++ b/src/server/modules/GitHub/index.ts@@ -0,0 +1,243 @@+import debug from 'debug';++const log = debug('lobe-chat:module:github');++export interface GitHubRepoInfo {+ branch: string;+ owner: string;+ /**+ * Subdirectory path within the repository (e.g., 'skills/skill-creator')+ * Extracted from URLs like: https://github.com/owner/repo/tree/branch/path/to/dir+ */+ path?: string;+ repo: string;+}++export interface GitHubRawFileInfo extends GitHubRepoInfo {+ filePath: string;+}++export class GitHub {+ private readonly userAgent: string;++ constructor(options?: { userAgent?: string }) {+ this.userAgent = options?.userAgent || 'LobeHub';+ }++ /**+ * Parse GitHub URL to extract owner, repo, branch, and optional path+ * Supports multiple formats:+ * - https://github.com/owner/repo+ * - https://github.com/owner/repo/tree/branch+ * - https://github.com/owner/repo/tree/branch/path/to/dir+ * - github.com/owner/repo+ * - owner/repo (shorthand)+ * - https://github.com/owner/repo.git+ */+ parseRepoUrl(url: string, defaultBranch = 'main'): GitHubRepoInfo {+ log('parseRepoUrl: input url=%s, defaultBranch=%s', url, defaultBranch);++ // Handle shorthand format: owner/repo+ if (/^[\w.-]+\/[\w.-]+$/.test(url)) {+ const [owner, repo] = url.split('/');+ const result = { branch: defaultBranch, owner, repo };+ log('parseRepoUrl: matched shorthand format, result=%o', result);+ return result;+ }++ // Handle full URL formats+ // Capture: owner, repo, branch, and optional path after branch+ const match = url.match(+ /(?:https?:\/\/)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+)(?:\/(.+))?)?$/,+ );++ if (!match) {+ log('parseRepoUrl: failed to parse url=%s', url);+ throw new GitHubParseError(`Invalid GitHub URL format: ${url}`);+ }++ const [, owner, repo, branch, path] = match;+ const result: GitHubRepoInfo = {+ branch: branch || defaultBranch,+ owner,+ repo: repo.replace(/\.git$/, ''),+ };++ // Add path if it exists (subdirectory within the repo)+ if (path) {+ result.path = path;+ }++ log('parseRepoUrl: matched full URL format, result=%o', result);+ return result;+ }++ /**+ * Generate skill identifier from repo info+ *+ * Format: {owner}-{repo}-{skillName}+ * The skill name is the last segment of the path (directory name).+ * All parts are lowercased and joined with hyphens.+ *+ * @param info - Repository information+ * @returns Skill identifier string+ */+ generateIdentifier(info: GitHubRepoInfo): string {+ const parts = [+ this.normalizeIdentifierPart(info.owner),+ this.normalizeIdentifierPart(info.repo),+ ];++ if (info.path) {+ const lastSegment = info.path.split('/').findLast(Boolean);+ if (lastSegment) {+ parts.push(this.normalizeIdentifierPart(lastSegment));+ }+ }++ return parts.join('-').toLowerCase();+ }++ /**+ * Normalize a string for use as part of a skill identifier.+ * Replaces non-alphanumeric characters (except hyphens) with hyphens,+ * collapses consecutive hyphens, and trims leading/trailing hyphens.+ */+ private normalizeIdentifierPart(part: string): string {+ return part+ .replaceAll(/[^\w-]/g, '-')+ .replaceAll(/-+/g, '-')+ .replaceAll(/^-|-$/g, '');+ }++ /**+ * Build the ZIP download URL for a GitHub repository+ */+ buildRepoZipUrl(info: GitHubRepoInfo): string {+ return `https://github.com/${info.owner}/${info.repo}/archive/refs/heads/${info.branch}.zip`;+ }++ /**+ * Build the raw file URL for a GitHub repository+ */+ buildRawFileUrl(info: GitHubRawFileInfo): string {+ return `https://raw.githubusercontent.com/${info.owner}/${info.repo}/${info.branch}/${info.filePath}`;+ }++ /**+ * Download repository as ZIP buffer+ */+ async downloadRepoZip(info: GitHubRepoInfo): Promise<Buffer> {+ const zipUrl = this.buildRepoZipUrl(info);+ log('downloadRepoZip: fetching url=%s', zipUrl);++ const response = await fetch(zipUrl, {+ headers: {+ 'User-Agent': this.userAgent,+ },+ });++ log('downloadRepoZip: response status=%d, ok=%s', response.status, response.ok);++ if (!response.ok) {+ if (response.status === 404) {+ log('downloadRepoZip: repository not found');+ throw new GitHubNotFoundError(+ `Repository not found: ${info.owner}/${info.repo}@${info.branch}`,+ );+ }+ log('downloadRepoZip: download failed with status=%d', response.status);+ throw new GitHubDownloadError(+ `Failed to download repository: ${response.status} ${response.statusText}`,+ );+ }++ const arrayBuffer = await response.arrayBuffer();+ const buffer = Buffer.from(arrayBuffer);+ log('downloadRepoZip: downloaded %d bytes', buffer.length);+ return buffer;+ }++ /**+ * Download a single raw file from GitHub+ */+ async downloadRawFile(info: GitHubRawFileInfo): Promise<string> {+ const rawUrl = this.buildRawFileUrl(info);++ const response = await fetch(rawUrl, {+ headers: {+ 'User-Agent': this.userAgent,+ },+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new GitHubNotFoundError(+ `File not found: ${info.owner}/${info.repo}@${info.branch}/${info.filePath}`,+ );+ }+ throw new GitHubDownloadError(+ `Failed to download file: ${response.status} ${response.statusText}`,+ );+ }++ return response.text();+ }++ /**+ * Download a single raw file as buffer from GitHub+ */+ async downloadRawFileBuffer(info: GitHubRawFileInfo): Promise<Buffer> {+ const rawUrl = this.buildRawFileUrl(info);++ const response = await fetch(rawUrl, {+ headers: {+ 'User-Agent': this.userAgent,+ },+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new GitHubNotFoundError(+ `File not found: ${info.owner}/${info.repo}@${info.branch}/${info.filePath}`,+ );+ }+ throw new GitHubDownloadError(+ `Failed to download file: ${response.status} ${response.statusText}`,+ );+ }++ const arrayBuffer = await response.arrayBuffer();+ return Buffer.from(arrayBuffer);+ }+}++export class GitHubError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubError';+ }+}++export class GitHubParseError extends GitHubError {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubParseError';+ }+}++export class GitHubNotFoundError extends GitHubError {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubNotFoundError';+ }+}++export class GitHubDownloadError extends GitHubError {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubDownloadError';+ }+}++export const github = new GitHub();diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.tsindex 29125bf2caf..4181083d62d 100644--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts@@ -16,7 +16,7 @@ import { type LobeToolManifest } from '@lobechat/context-engine';import { ToolsEngine } from '@lobechat/context-engine';import debug from 'debug';-import { builtinTools } from '@/tools';+import { builtinTools, defaultToolIds } from '@/tools';import {type ServerAgentToolsContext,@@ -109,7 +109,7 @@ export const createServerAgentToolsEngine = (// Pass additional manifests (e.g., LobeHub Skills)additionalManifests,// Add default tools based on configuration- defaultToolIds: [WebBrowsingManifest.identifier, KnowledgeBaseManifest.identifier],+ defaultToolIds,// Create search-aware enableChecker for this requestenableChecker: ({ pluginId }) => {// Filter LocalSystem tool on server (it's desktop-only)diff --git a/src/server/modules/S3/index.ts b/src/server/modules/S3/index.tsindex 4dfb0c7e3d6..887a2cc5234 100644--- a/src/server/modules/S3/index.ts+++ b/src/server/modules/S3/index.ts@@ -154,12 +154,20 @@ export class S3 {});}- // Add a new method for uploading binary content- public async uploadBuffer(path: string, buffer: Buffer, contentType?: string) {+ /**+ * Upload buffer with specified content type+ */+ public async uploadBuffer(+ path: string,+ buffer: Buffer,+ contentType?: string,+ cacheControl?: string,+ ) {const command = new PutObjectCommand({ACL: this.setAcl ? 'public-read' : undefined,Body: buffer,Bucket: this.bucket,+ CacheControl: cacheControl,ContentType: contentType,Key: path,});@@ -178,6 +186,9 @@ export class S3 {return this.client.send(command);}+ /**+ * Upload media file (images only) with long-term cache+ */public async uploadMedia(key: string, buffer: Buffer) {const contentType = mime.getType(key) || 'application/octet-stream';const command = new PutObjectCommand({diff --git a/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.tsnew file mode 100644index 00000000000..a58ae535112--- /dev/null+++ b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts@@ -0,0 +1,711 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import { agentSkills } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentSkillsRouter } from '../../agentSkills';+import { cleanupTestUser, createTestContext, createTestUser } from './setup';++// Mock getServerDB to return our test database instance+let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++// Mock FileService to avoid S3 dependency+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ createFileRecord: vi.fn().mockResolvedValue({ fileId: 'mock-file-id', url: '/f/mock-file-id' }),+ downloadFileToLocal: vi.fn(),+ getFileContent: vi.fn(),+ uploadBuffer: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ uploadMedia: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ })),+}));++// Mock SkillResourceService to avoid S3 dependency+vi.mock('@/server/services/skill/resource', () => ({+ SkillResourceService: vi.fn().mockImplementation(() => ({+ storeResources: vi.fn().mockResolvedValue({}),+ readResource: vi.fn().mockRejectedValue(new Error('Resource not found')),+ listResources: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock GitHub module+const normalizeIdentifierPart = (part: string) =>+ part+ .replaceAll(/[^\w-]/g, '-')+ .replaceAll(/-+/g, '-')+ .replaceAll(/^-|-$/g, '');++const mockGitHubInstance = {+ downloadRepoZip: vi.fn(),+ generateIdentifier: vi+ .fn()+ .mockImplementation((info: { owner: string; path?: string; repo: string }) => {+ const parts = [normalizeIdentifierPart(info.owner), normalizeIdentifierPart(info.repo)];+ if (info.path) {+ const lastSegment = info.path.split('/').findLast(Boolean);+ if (lastSegment) parts.push(normalizeIdentifierPart(lastSegment));+ }+ return parts.join('-').toLowerCase();+ }),+ parseRepoUrl: vi.fn(),+};+vi.mock('@/server/modules/GitHub', () => ({+ GitHub: vi.fn().mockImplementation(() => mockGitHubInstance),+ GitHubNotFoundError: class extends Error {},+ GitHubParseError: class extends Error {},+}));++// Mock SkillParser+const mockParserInstance = {+ parseSkillMd: vi.fn(),+ parseZipPackage: vi.fn(),+};+vi.mock('@/server/services/skill/parser', () => ({+ SkillParser: vi.fn().mockImplementation(() => mockParserInstance),+}));++// Mock global fetch for URL imports+const mockFetch = vi.fn();+vi.stubGlobal('fetch', mockFetch);++describe('Skill Router Integration Tests', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ });++ describe('create', () => {+ it('should create a new skill', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.create({+ name: 'Test Skill',+ content: '# Test Skill\n\nThis is a test skill.',+ description: 'A skill for testing',+ });++ expect(result).toBeDefined();+ expect(result!.name).toBe('Test Skill');+ expect(result!.content).toBe('# Test Skill\n\nThis is a test skill.');+ expect(result!.description).toBe('A skill for testing');+ expect(result!.source).toBe('user');+ expect(result!.identifier).toMatch(/^user\./);+ });++ it('should create skill with custom identifier', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.create({+ name: 'Custom ID Skill',+ content: '# Custom',+ description: 'Custom identifier skill',+ identifier: 'custom.skill.id',+ });++ expect(result!.identifier).toBe('custom.skill.id');+ });++ it('should throw error for duplicate identifier', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ await caller.create({+ name: 'First Skill',+ content: '# First',+ description: 'First skill',+ identifier: 'duplicate.id',+ });++ await expect(+ caller.create({+ name: 'Second Skill',+ content: '# Second',+ description: 'Second skill',+ identifier: 'duplicate.id',+ }),+ ).rejects.toThrow();+ });+ });++ describe('list', () => {+ it('should list all skills for user', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ await caller.create({ name: 'Skill 1', content: '# Skill 1', description: 'Skill 1 desc' });+ await caller.create({ name: 'Skill 2', content: '# Skill 2', description: 'Skill 2 desc' });++ const result = await caller.list();++ expect(result.data).toHaveLength(2);+ expect(result.total).toBe(2);+ });++ it('should filter skills by source', async () => {+ // Insert skills with different sources directly+ await serverDB.insert(agentSkills).values([+ {+ name: 'User Skill',+ description: 'User skill description',+ identifier: 'user.skill',+ source: 'user',+ manifest: { name: 'User Skill', description: 'User skill description' },+ userId,+ },+ {+ name: 'Market Skill',+ description: 'Market skill description',+ identifier: 'market.skill',+ source: 'market',+ manifest: { name: 'Market Skill', description: 'Market skill description' },+ userId,+ },+ ]);++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const userSkills = await caller.list({ source: 'user' });+ expect(userSkills.data).toHaveLength(1);+ expect(userSkills.data[0].source).toBe('user');++ const marketSkills = await caller.list({ source: 'market' });+ expect(marketSkills.data).toHaveLength(1);+ expect(marketSkills.data[0].source).toBe('market');+ });+ });++ describe('getById', () => {+ it('should get skill by id', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'Get By ID Skill',+ content: '# Get By ID',+ description: 'Get by ID skill',+ });++ const result = await caller.getById({ id: created!.id });++ expect(result).toBeDefined();+ expect(result?.id).toBe(created!.id);+ expect(result?.name).toBe('Get By ID Skill');+ });++ it('should return undefined for non-existent id', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.getById({ id: 'non-existent-id' });++ expect(result).toBeUndefined();+ });+ });++ describe('getByIdentifier', () => {+ it('should get skill by identifier', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ await caller.create({+ name: 'By Identifier',+ content: '# By Identifier',+ description: 'By identifier skill',+ identifier: 'test.by.identifier',+ });++ const result = await caller.getByIdentifier({ identifier: 'test.by.identifier' });++ expect(result).toBeDefined();+ expect(result?.identifier).toBe('test.by.identifier');+ });+ });++ describe('getByName', () => {+ it('should get skill by name', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ await caller.create({+ name: 'Unique Skill Name',+ content: '# By Name',+ description: 'By name skill',+ });++ const result = await caller.getByName({ name: 'Unique Skill Name' });++ expect(result).toBeDefined();+ expect(result?.name).toBe('Unique Skill Name');+ });++ it('should return undefined for non-existent name', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.getByName({ name: 'non-existent-name' });++ expect(result).toBeUndefined();+ });+ });++ describe('search', () => {+ it('should search skills by name', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ await caller.create({ name: 'TypeScript Expert', content: '# TS', description: 'TS expert' });+ await caller.create({ name: 'Python Master', content: '# Py', description: 'Py master' });++ const result = await caller.search({ query: 'TypeScript' });++ expect(result.data).toHaveLength(1);+ expect(result.data[0].name).toBe('TypeScript Expert');+ });++ it('should search skills by description', async () => {+ await serverDB.insert(agentSkills).values([+ {+ name: 'Skill A',+ description: 'Helps with coding tasks',+ identifier: 'search.a',+ source: 'user',+ manifest: { name: 'Skill A', description: 'Helps with coding tasks' },+ userId,+ },+ {+ name: 'Skill B',+ description: 'Helps with writing',+ identifier: 'search.b',+ source: 'user',+ manifest: { name: 'Skill B', description: 'Helps with writing' },+ userId,+ },+ ]);++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.search({ query: 'coding' });++ expect(result.data).toHaveLength(1);+ expect(result.data[0].name).toBe('Skill A');+ });+ });++ describe('update', () => {+ it('should update skill content', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'Original Name',+ content: '# Original',+ description: 'Original description',+ });++ await caller.update({+ id: created!.id,+ content: '# Updated Content',+ });++ const updated = await caller.getById({ id: created!.id });++ expect(updated?.content).toBe('# Updated Content');+ // Name should remain unchanged+ expect(updated?.name).toBe('Original Name');+ });++ it('should update skill via manifest and sync to top-level fields', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'Original Name',+ content: '# Test',+ description: 'Original description',+ });++ await caller.update({+ id: created!.id,+ manifest: {+ name: 'Updated Name',+ description: 'Updated description',+ version: '2.0.0',+ },+ });++ const updated = await caller.getById({ id: created!.id });++ // Top-level fields should be synced from manifest+ expect(updated?.name).toBe('Updated Name');+ expect(updated?.description).toBe('Updated description');+ // Manifest should contain all fields+ expect(updated?.manifest).toMatchObject({+ name: 'Updated Name',+ description: 'Updated description',+ version: '2.0.0',+ });+ });++ it('should merge manifest instead of replacing', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'Merge Test',+ content: '# Test',+ description: 'Merge test skill',+ });++ // First update: add version+ await caller.update({+ id: created!.id,+ manifest: {+ version: '1.0.0',+ },+ });++ // Second update: add license (should keep version)+ await caller.update({+ id: created!.id,+ manifest: {+ license: 'MIT',+ },+ });++ const updated = await caller.getById({ id: created!.id });++ // Both version and license should exist+ expect(updated?.manifest).toMatchObject({+ name: 'Merge Test',+ description: 'Merge test skill',+ version: '1.0.0',+ license: 'MIT',+ });+ });+ });++ describe('delete', () => {+ it('should delete skill', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'To Delete',+ content: '# Delete Me',+ description: 'To delete skill',+ });++ await caller.delete({ id: created!.id });++ const deleted = await caller.getById({ id: created!.id });++ expect(deleted).toBeUndefined();+ });++ it('should not affect other skills when deleting', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const skill1 = await caller.create({+ name: 'Skill 1',+ content: '# 1',+ description: 'Skill 1',+ });+ const skill2 = await caller.create({+ name: 'Skill 2',+ content: '# 2',+ description: 'Skill 2',+ });++ await caller.delete({ id: skill1!.id });++ const remaining = await caller.list();++ expect(remaining.data).toHaveLength(1);+ expect(remaining.data[0].id).toBe(skill2!.id);+ });+ });++ describe('listResources', () => {+ it('should return empty array for skill without resources', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'No Resources',+ content: '# No Resources',+ description: 'Skill without resources',+ });++ const result = await caller.listResources({ id: created!.id });++ // Mock returns empty array+ expect(result).toEqual([]);+ });++ it('should throw for non-existent skill', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ // getById returns undefined, which triggers NOT_FOUND TRPCError+ await expect(caller.listResources({ id: 'non-existent' })).rejects.toThrow();+ });+ });++ describe('readResource', () => {+ it('should throw for non-existent skill', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ // getById returns undefined, which triggers NOT_FOUND TRPCError+ await expect(+ caller.readResource({ id: 'non-existent', path: 'readme.md' }),+ ).rejects.toThrow();+ });++ it('should throw for skill without resources', async () => {+ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const created = await caller.create({+ name: 'No Resources',+ content: '# No Resources',+ description: 'Skill without resources',+ });++ // Skill exists but has no resources, triggers BAD_REQUEST with message+ await expect(caller.readResource({ id: created!.id, path: 'readme.md' })).rejects.toThrow(+ 'Skill has no resources',+ );+ });+ });++ describe('importFromGitHub', () => {+ it('should import skill from GitHub with subdirectory path', async () => {+ // Setup mocks+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'openclaw',+ path: 'skills/skill-creator',+ repo: 'openclaw',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip-content'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill Creator\n\nCreate skills easily.',+ manifest: { name: 'skill-creator', description: 'Create skills' },+ resources: new Map(),+ // zipHash undefined to skip globalFiles foreign key (FileService is mocked)+ zipHash: undefined,+ });++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.importFromGitHub({+ gitUrl: 'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',+ });++ expect(result).toBeDefined();+ expect(result!.skill.name).toBe('skill-creator');+ expect(result!.skill.identifier).toBe('openclaw-openclaw-skill-creator');+ expect(result!.skill.source).toBe('market');+ expect(result!.skill.manifest).toMatchObject({+ repository: 'https://github.com/openclaw/openclaw',+ sourceUrl: 'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',+ });++ // Verify parseRepoUrl was called with correct URL+ expect(mockGitHubInstance.parseRepoUrl).toHaveBeenCalledWith(+ 'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',+ undefined,+ );++ // Verify parseZipPackage was called with basePath and repackSkillZip+ expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(expect.any(Buffer), {+ basePath: 'skills/skill-creator',+ repackSkillZip: true,+ });+ });++ it('should update existing skill when re-importing from same GitHub path', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ path: 'skills/demo',+ repo: 'skills',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));++ let callCount = 0;+ mockParserInstance.parseZipPackage.mockImplementation(() => {+ callCount++;+ return {+ content: callCount === 1 ? '# Original' : '# Updated Content',+ manifest: {+ name: callCount === 1 ? 'Original Name' : 'Updated Name',+ description: callCount === 1 ? 'Original desc' : 'Updated desc',+ },+ resources: new Map(),+ // zipHash undefined to skip globalFiles foreign key+ zipHash: undefined,+ };+ });++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ // First import+ const first = await caller.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skills/tree/main/skills/demo',+ });+ expect(first!.skill.name).toBe('Original Name');+ expect(first!.skill.content).toBe('# Original');++ // Re-import (should update)+ const second = await caller.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skills/tree/main/skills/demo',+ });+ expect(second!.skill.id).toBe(first!.skill.id); // Same skill updated+ expect(second!.skill.name).toBe('Updated Name');+ expect(second!.skill.content).toBe('# Updated Content');+ });+ });++ describe('importFromUrl', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ });++ it('should import skill from URL', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => `---+name: URL Skill+description: A skill from URL+---+# URL Skill Content`,+ });++ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# URL Skill Content',+ manifest: { name: 'URL Skill', description: 'A skill from URL' },+ raw: 'raw',+ });++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ const result = await caller.importFromUrl({+ url: 'https://example.com/skill.md',+ });++ expect(result).toBeDefined();+ expect(result!.status).toBe('created');+ expect(result!.skill.name).toBe('URL Skill');+ expect(result!.skill.identifier).toBe('url.example.com.skill');+ expect(result!.skill.source).toBe('market');+ expect(result!.skill.manifest).toMatchObject({+ sourceUrl: 'https://example.com/skill.md',+ });+ });++ it('should update existing skill when re-importing from same URL', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => 'content',+ });++ let callCount = 0;+ mockParserInstance.parseSkillMd.mockImplementation(() => {+ callCount++;+ return {+ content: callCount === 1 ? '# Original' : '# Updated',+ manifest: {+ name: callCount === 1 ? 'Original Name' : 'Updated Name',+ description: callCount === 1 ? 'Original desc' : 'Updated desc',+ },+ raw: 'raw',+ };+ });++ const caller = agentSkillsRouter.createCaller(createTestContext(userId));++ // First import+ const first = await caller.importFromUrl({+ url: 'https://example.com/update-test.md',+ });+ expect(first!.status).toBe('created');+ expect(first!.skill.content).toBe('# Original');++ // Re-import (should update)+ const second = await caller.importFromUrl({+ url: 'https://example.com/update-test.md',+ });+ expect(second!.skill.id).toBe(first!.skill.id); // Same skill updated+ expect(second!.skill.name).toBe('Updated Name');+ expect(second!.skill.content).toBe('# Updated');+ });+ });++ describe('user isolation', () => {+ it('should not access skills from other users', async () => {+ // Create skill for original user+ const caller1 = agentSkillsRouter.createCaller(createTestContext(userId));+ await caller1.create({+ name: 'User 1 Skill',+ content: '# User 1',+ description: 'User 1 skill',+ });++ // Create another user+ const otherUserId = await createTestUser(serverDB);+ const caller2 = agentSkillsRouter.createCaller(createTestContext(otherUserId));++ // Other user should not see original user's skills+ const otherUserSkills = await caller2.list();+ expect(otherUserSkills.data).toHaveLength(0);++ // Cleanup other user+ await cleanupTestUser(serverDB, otherUserId);+ });++ it('should not update skills from other users', async () => {+ const caller1 = agentSkillsRouter.createCaller(createTestContext(userId));+ const created = await caller1.create({+ name: 'Original',+ content: '# Original',+ description: 'Original skill',+ });++ // Create another user+ const otherUserId = await createTestUser(serverDB);+ const caller2 = agentSkillsRouter.createCaller(createTestContext(otherUserId));++ // Try to update (should not affect the skill due to userId filter)+ await caller2.update({ id: created!.id, manifest: { name: 'Hacked' } });++ // Original skill should be unchanged+ const unchanged = await caller1.getById({ id: created!.id });+ expect(unchanged?.name).toBe('Original');++ await cleanupTestUser(serverDB, otherUserId);+ });++ it('should not delete skills from other users', async () => {+ const caller1 = agentSkillsRouter.createCaller(createTestContext(userId));+ const created = await caller1.create({+ name: 'Protected',+ content: '# Protected',+ description: 'Protected skill',+ });++ // Create another user+ const otherUserId = await createTestUser(serverDB);+ const caller2 = agentSkillsRouter.createCaller(createTestContext(otherUserId));++ // Try to delete (should not affect the skill due to userId filter)+ await caller2.delete({ id: created!.id });++ // Original skill should still exist+ const stillExists = await caller1.getById({ id: created!.id });+ expect(stillExists).toBeDefined();++ await cleanupTestUser(serverDB, otherUserId);+ });+ });+});diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.tsindex 53fd872bd0f..f77821d2c52 100644--- a/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/execGroupAgent.integration.test.ts@@ -305,7 +305,6 @@ describe('execGroupAgent', () => {});describe('Stream Events', () => {- // TODO: LOBE-1748 - Fix missing agent_runtime_end event// This test documents the current bug where agent_runtime_end is not sent// When fixed, remove .todo and the test should passit.todo('should emit agent_runtime_end event when agent completes', async () => {@@ -334,7 +333,6 @@ describe('execGroupAgent', () => {// IMPORTANT: This test verifies that agent_runtime_end event is sent// If this test fails, it means the SSE stream won't close properly- // See LOBE-1748 for detailsexpect(eventTypes).toContain('agent_runtime_end');// Also verify the event has correct data structurediff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.tsindex b81a5003df7..b5819d3d0e8 100644--- a/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts@@ -1,7 +1,7 @@// @vitest-environment node/*** Integration tests for multi-round tool execution- * Tests for LOBE-1657 fix: tool messages should not be duplicated across rounds+ * Tests fix: tool messages should not be duplicated across rounds** Note: AgentStateManager and StreamEventManager will automatically use* InMemory implementations when Redis is not available (test environment).@@ -242,7 +242,7 @@ afterEach(async () => {describe('Multi-Round Tool Execution', () => {/**- * This test verifies the fix for LOBE-1657:+ * This test verifies the fix:* When executing multiple rounds of batch tool calls, tool messages should not be duplicated.** Scenario: LLM returns multiple tool calls in each rounddiff --git a/src/server/routers/lambda/agentSkills.ts b/src/server/routers/lambda/agentSkills.tsnew file mode 100644index 00000000000..36516640b0b--- /dev/null+++ b/src/server/routers/lambda/agentSkills.ts@@ -0,0 +1,267 @@+import { SkillManifest, skillManifestSchema } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { AgentSkillModel } from '@/database/models/agentSkill';+import { FileModel } from '@/database/models/file';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { FileService } from '@/server/services/file';+import { MarketService } from '@/server/services/market';+import {+ SkillImportError,+ SkillImporter,+ SkillResourceError,+ SkillResourceService,+} from '@/server/services/skill';++// ===== Error Handling =====++const skillImportErrorToTRPCCode = (+ code: SkillImportError['code'],+): 'CONFLICT' | 'BAD_REQUEST' | 'NOT_FOUND' | 'BAD_GATEWAY' => {+ switch (code) {+ case 'CONFLICT': {+ return 'CONFLICT';+ }++ case 'NOT_FOUND':+ case 'FILE_NOT_FOUND': {+ return 'NOT_FOUND';+ }++ case 'DOWNLOAD_FAILED': {+ return 'BAD_GATEWAY';+ }++ default: {+ return 'BAD_REQUEST';+ }+ }+};++const handleSkillImportError = (error: unknown): never => {+ if (error instanceof SkillImportError) {+ throw new TRPCError({+ code: skillImportErrorToTRPCCode(error.code),+ message: error.message,+ });+ }+ throw error;+};++// ===== Procedure with Context =====++const skillProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ fileModel: new FileModel(ctx.serverDB, ctx.userId),+ fileService: new FileService(ctx.serverDB, ctx.userId),+ marketService: new MarketService({ userInfo: { userId: ctx.userId } }),+ skillImporter: new SkillImporter(ctx.serverDB, ctx.userId),+ skillModel: new AgentSkillModel(ctx.serverDB, ctx.userId),+ skillResourceService: new SkillResourceService(ctx.serverDB, ctx.userId),+ },+ });+});++// ===== Input Schemas =====++const createSkillSchema = z.object({+ content: z.string(),+ description: z.string().min(1),+ identifier: z.string().optional(),+ name: z.string().min(1),+});++const updateSkillSchema = z.object({+ content: z.string().optional(),+ id: z.string(),+ // All metadata should be passed through manifest+ manifest: skillManifestSchema.partial().optional(),+});++// ===== Router =====++export const agentSkillsRouter = router({+ // ===== Create =====++ create: skillProcedure.input(createSkillSchema).mutation(async ({ ctx, input }) => {+ try {+ return await ctx.skillImporter.createUserSkill(input);+ } catch (error) {+ handleSkillImportError(error);+ }+ }),++ // ===== Delete =====++ delete: skillProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {+ return ctx.skillModel.delete(input.id);+ }),++ // ===== Query =====++ getById: skillProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {+ return ctx.skillModel.findById(input.id);+ }),++ getByIdWithZipUrl: skillProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ ctx, input }) => {+ const skill = await ctx.skillModel.findById(input.id);+ if (!skill) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Skill not found' });+ }++ if (!skill.zipFileHash) {+ return { name: skill.name, url: null };+ }++ const fileInfo = await ctx.fileModel.checkHash(skill.zipFileHash);+ if (!fileInfo.isExist || !fileInfo.url) {+ return { name: skill.name, url: null };+ }++ const fullUrl = await ctx.fileService.getFullFileUrl(fileInfo.url);+ return { name: skill.name, url: fullUrl || null };+ }),++ getByIdentifier: skillProcedure+ .input(z.object({ identifier: z.string() }))+ .query(async ({ ctx, input }) => {+ return ctx.skillModel.findByIdentifier(input.identifier);+ }),++ getByName: skillProcedure.input(z.object({ name: z.string() })).query(async ({ ctx, input }) => {+ return ctx.skillModel.findByName(input.name);+ }),++ importFromGitHub: skillProcedure+ .input(+ z.object({+ branch: z.string().optional(),+ gitUrl: z.string().url(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.skillImporter.importFromGitHub(input);+ } catch (error) {+ handleSkillImportError(error);+ }+ }),++ importFromUrl: skillProcedure+ .input(z.object({ url: z.string().url() }))+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.skillImporter.importFromUrl(input);+ } catch (error) {+ handleSkillImportError(error);+ }+ }),++ importFromZip: skillProcedure+ .input(z.object({ zipFileId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.skillImporter.importFromZip(input);+ } catch (error) {+ handleSkillImportError(error);+ }+ }),++ importFromMarket: skillProcedure+ .input(z.object({ identifier: z.string() }))+ .mutation(async ({ ctx, input }) => {+ try {+ // Get download URL from market service+ const downloadUrl = ctx.marketService.getSkillDownloadUrl(input.identifier);+ // Import using the download URL+ return await ctx.skillImporter.importFromUrl({ url: downloadUrl });+ } catch (error) {+ handleSkillImportError(error);+ }+ }),++ list: skillProcedure+ .input(+ z+ .object({+ source: z.enum(['builtin', 'market', 'user']).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ if (input?.source) {+ return ctx.skillModel.listBySource(input.source);+ }++ return ctx.skillModel.findAll();+ }),++ listResources: skillProcedure+ .input(z.object({ id: z.string(), includeContent: z.boolean().optional() }))+ .query(async ({ ctx, input }) => {+ const skill = await ctx.skillModel.findById(input.id);+ if (!skill) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Skill not found' });+ }++ if (!skill.resources) {+ return [];+ }++ return ctx.skillResourceService.listResources(skill.resources, input.includeContent);+ }),++ readResource: skillProcedure+ .input(+ z.object({+ id: z.string(),+ path: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const skill = await ctx.skillModel.findById(input.id);+ if (!skill) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Skill not found' });+ }++ if (!skill.resources || Object.keys(skill.resources).length === 0) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Skill has no resources' });+ }++ try {+ return await ctx.skillResourceService.readResource(skill.resources, input.path);+ } catch (error) {+ if (error instanceof SkillResourceError) {+ throw new TRPCError({ code: 'NOT_FOUND', message: error.message });+ }++ throw error;+ }+ }),++ search: skillProcedure.input(z.object({ query: z.string() })).query(async ({ ctx, input }) => {+ return ctx.skillModel.search(input.query);+ }),++ // ===== Update =====++ update: skillProcedure.input(updateSkillSchema).mutation(async ({ ctx, input }) => {+ const { id, content, manifest } = input;+ return ctx.skillModel.update(id, {+ content,+ // Sync name/description from manifest to top-level fields+ description: manifest?.description,+ manifest: manifest as SkillManifest | undefined,+ name: manifest?.name,+ });+ }),+});++export type AgentSkillsRouter = typeof agentSkillsRouter;diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex 08f08242d46..2e39a99a5fb 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -12,6 +12,7 @@ import { agentRouter } from './agent';import { agentCronJobRouter } from './agentCronJob';import { agentEvalRouter } from './agentEval';import { agentGroupRouter } from './agentGroup';+import { agentSkillsRouter } from './agentSkills';import { aiAgentRouter } from './aiAgent';import { aiChatRouter } from './aiChat';import { aiModelRouter } from './aiModel';@@ -54,6 +55,7 @@ export const lambdaRouter = router({agent: agentRouter,agentCronJob: agentCronJobRouter,agentEval: agentEvalRouter,+ agentSkills: agentSkillsRouter,aiAgent: aiAgentRouter,aiChat: aiChatRouter,aiModel: aiModelRouter,diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.tsindex 4f2c77ddf99..bd72e260fe4 100644--- a/src/server/routers/lambda/market/index.ts+++ b/src/server/routers/lambda/market/index.ts@@ -20,6 +20,7 @@ import {import { agentRouter } from './agent';import { agentGroupRouter } from './agentGroup';import { oidcRouter } from './oidc';+import { skillRouter } from './skill';import { socialRouter } from './social';import { userRouter } from './user';@@ -53,7 +54,10 @@ export const marketRouter = router({// ============================== Agent Group Management (authenticated) ==============================agentGroup: agentGroupRouter,-+ // ============================== Skill Management ==============================+ skill: skillRouter,++getAgentsByPlugin: marketProcedure.input(z.object({diff --git a/src/server/routers/lambda/market/skill.ts b/src/server/routers/lambda/market/skill.tsnew file mode 100644index 00000000000..2f712f27ad2--- /dev/null+++ b/src/server/routers/lambda/market/skill.ts@@ -0,0 +1,53 @@+import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { publicProcedure, router } from '@/libs/trpc/lambda';+import { marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/middleware';+import { MarketService } from '@/server/services/market';++const log = debug('lambda-router:market:skill');++// Public procedure with optional user info for trusted client token+const marketProcedure = publicProcedure+ .use(serverDatabase)+ .use(marketUserInfo)+ .use(async ({ ctx, next }) => {+ return next({+ ctx: {+ marketService: new MarketService({+ accessToken: ctx.marketAccessToken,+ userInfo: ctx.marketUserInfo,+ }),+ },+ });+ });++export const skillRouter = router({+ searchSkill: marketProcedure+ .input(+ z.object({+ locale: z.string().optional(),+ order: z.enum(['asc', 'desc']).optional(),+ page: z.number().optional(),+ pageSize: z.number().optional(),+ search: z.string().optional(),+ sort: z+ .enum(['createdAt', 'downloadCount', 'forks', 'name', 'stars', 'updatedAt', 'watchers'])+ .optional(),+ }),+ )+ .query(async ({ input, ctx }) => {+ log('searchSkill input: %O', input);++ try {+ return await ctx.marketService.searchSkill(input);+ } catch (error) {+ log('Error searching skills: %O', error);+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to search skills',+ });+ }+ }),+});diff --git a/src/server/routers/tools/market.ts b/src/server/routers/tools/market.tsindex 74d5fae238a..d9fb0e36069 100644--- a/src/server/routers/tools/market.ts+++ b/src/server/routers/tools/market.ts@@ -4,6 +4,8 @@ import debug from 'debug';import { sha256 } from 'js-sha256';import { z } from 'zod';+import { AgentSkillModel } from '@/database/models/agentSkill';+import { FileModel } from '@/database/models/file';import { type ToolCallContent } from '@/libs/mcp';import { authedProcedure, router } from '@/libs/trpc/lambda';import { marketUserInfo, serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';@@ -87,7 +89,7 @@ const callCodeInterpreterToolSchema = z.object({params: z.record(z.any()),toolName: z.string(),topicId: z.string(),- userId: z.string(),+ userId: z.string().optional(), // Optional: fallback to ctx.userId if not provided});// Schema for export and upload file (combined operation)@@ -228,7 +230,9 @@ export const marketRouter = router({callCodeInterpreterTool: marketToolProcedure.input(callCodeInterpreterToolSchema).mutation(async ({ input, ctx }) => {- const { toolName, params, userId, topicId } = input;+ const { toolName, params, topicId } = input;+ // Use client-provided userId if available, otherwise fallback to authenticated userId+ const userId = input?.userId || ctx.userId;log('Calling cloud code interpreter tool: %s with params: %O', toolName, {params,@@ -237,13 +241,68 @@ export const marketRouter = router({});try {+ // For execScript tool, look up skill zipUrl if config is provided+ let enhancedParams = params;+ if (toolName === 'execScript' && params.config) {+ const agentSkillModel = new AgentSkillModel(ctx.serverDB, userId);++ // Look up skill by name+ let skill;+ if (params.config.name) {+ skill = await agentSkillModel.findByName(params.config.name);++ // If skill not found, return error with available skills+ if (!skill) {+ const allSkills = await agentSkillModel.findAll();+ const availableSkills = allSkills.data.map((s) => s.name).join(', ');++ const errorMessage = availableSkills+ ? `Skill "${params.config.name}" not found. Available skills: ${availableSkills}`+ : `Skill "${params.config.name}" not found. No skills available. Please import a skill first.`;++ log('Skill not found: %s. Available skills: %s', params.config.name, availableSkills);++ return {+ error: {+ message: errorMessage,+ name: 'SkillNotFound',+ },+ result: null,+ sessionExpiredAndRecreated: false,+ success: false,+ } as CallToolResult;+ }+ }++ // If skill exists and has zipFileHash, get the full URL+ if (skill?.zipFileHash) {+ const fileService = ctx.fileService;+ // Get S3 key from globalFiles+ const fileModel = new FileModel(ctx.serverDB, userId);+ const fileInfo = await fileModel.checkHash(skill.zipFileHash);++ if (fileInfo.isExist && fileInfo.url) {+ // Convert S3 key to full URL+ const fullUrl = await fileService.getFullFileUrl(fileInfo.url);+ if (fullUrl) {+ // Add zipUrl to params+ enhancedParams = {+ ...params,+ zipUrl: fullUrl,+ };+ log('Added zipUrl to execScript params for skill %s: %s', skill.name, fullUrl);+ }+ }+ }+ }+// Use marketService from ctxconst market = ctx.marketService.market;// Call market-sdk's runBuildInToolconst response = await market.plugins.runBuildInTool(toolName as CodeInterpreterToolName,- params as any,+ enhancedParams as any,{ topicId, userId },);diff --git a/src/server/services/file/__tests__/index.test.ts b/src/server/services/file/__tests__/index.test.tsindex 4f40fda60b7..a3d36c4481e 100644--- a/src/server/services/file/__tests__/index.test.ts+++ b/src/server/services/file/__tests__/index.test.ts@@ -337,4 +337,77 @@ describe('FileService', () => {);});});++ describe('createGlobalFile', () => {+ beforeEach(() => {+ mockFileModel.checkHash = vi.fn();+ mockFileModel.createGlobalFile = vi.fn();+ });++ it('should create global file with metadata when hash does not exist', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: false });+ mockFileModel.createGlobalFile.mockResolvedValue([{ hashId: 'test-hash' }]);++ const result = await service.createGlobalFile({+ fileHash: 'test-hash',+ fileType: 'text/markdown',+ metadata: {+ dirname: 'skills/source_files/abc123',+ filename: 'README.md',+ path: 'skills/source_files/abc123/README.md',+ },+ size: 1024,+ url: 'skills/source_files/abc123/README.md',+ });++ expect(result).toEqual({ fileHash: 'test-hash' });+ expect(mockFileModel.createGlobalFile).toHaveBeenCalledWith({+ creator: mockUserId,+ fileType: 'text/markdown',+ hashId: 'test-hash',+ metadata: {+ dirname: 'skills/source_files/abc123',+ filename: 'README.md',+ path: 'skills/source_files/abc123/README.md',+ },+ size: 1024,+ url: 'skills/source_files/abc123/README.md',+ });+ });++ it('should not create global file when hash already exists', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: true });++ const result = await service.createGlobalFile({+ fileHash: 'existing-hash',+ fileType: 'text/plain',+ size: 100,+ url: 'some/path.txt',+ });++ expect(result).toEqual({ fileHash: 'existing-hash' });+ expect(mockFileModel.createGlobalFile).not.toHaveBeenCalled();+ });++ it('should work without metadata', async () => {+ mockFileModel.checkHash.mockResolvedValue({ isExist: false });+ mockFileModel.createGlobalFile.mockResolvedValue([{ hashId: 'test-hash' }]);++ await service.createGlobalFile({+ fileHash: 'test-hash',+ fileType: 'text/plain',+ size: 100,+ url: 'some/path.txt',+ });++ expect(mockFileModel.createGlobalFile).toHaveBeenCalledWith({+ creator: mockUserId,+ fileType: 'text/plain',+ hashId: 'test-hash',+ metadata: undefined,+ size: 100,+ url: 'some/path.txt',+ });+ });+ });});diff --git a/src/server/services/file/impls/s3.ts b/src/server/services/file/impls/s3.tsindex 535b74eaf49..787ab7520c3 100644--- a/src/server/services/file/impls/s3.ts+++ b/src/server/services/file/impls/s3.ts@@ -113,4 +113,9 @@ export class S3StaticFileImpl implements FileServiceImpl {await this.s3.uploadMedia(key, buffer);return { key };}++ async uploadBuffer(key: string, buffer: Buffer, contentType: string): Promise<{ key: string }> {+ await this.s3.uploadBuffer(key, buffer, contentType);+ return { key };+ }}diff --git a/src/server/services/file/impls/type.ts b/src/server/services/file/impls/type.tsindex c486058451b..b0f94bfb8c4 100644--- a/src/server/services/file/impls/type.ts+++ b/src/server/services/file/impls/type.ts@@ -47,13 +47,18 @@ export interface FileServiceImpl {*/getKeyFromFullUrl: (url: string) => Promise<string | null>;+ /**+ * Upload buffer with specified content type (for any file type)+ */+ uploadBuffer(key: string, buffer: Buffer, contentType: string): Promise<{ key: string }>;+/*** Upload content*/uploadContent: (path: string, content: string) => Promise<any>;/**- * Upload media file+ * Upload media file (images only)*/uploadMedia: (key: string, buffer: Buffer) => Promise<{ key: string }>;}diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.tsindex a2209fd39ed..753942a6790 100644--- a/src/server/services/file/index.ts+++ b/src/server/services/file/index.ts@@ -102,12 +102,23 @@ export class FileService {}/**- * Upload media file+ * Upload media file (images only)*/public async uploadMedia(key: string, buffer: Buffer): Promise<{ key: string }> {return this.impl.uploadMedia(key, buffer);}+ /**+ * Upload buffer with specified content type (for any file type)+ */+ public async uploadBuffer(+ key: string,+ buffer: Buffer,+ contentType: string,+ ): Promise<{ key: string }> {+ return this.impl.uploadBuffer(key, buffer, contentType);+ }+/*** Create file record (common method)* Automatically handles globalFiles deduplication logic@@ -148,6 +159,71 @@ export class FileService {};}+ /**+ * Delete user file record but keep globalFiles record+ * Used for GitHub skill imports where we only need globalFiles for foreign key+ *+ * @param fileId - File ID to delete from user's files table+ */+ public async deleteUserFileRecord(fileId: string): Promise<void> {+ await this.fileModel.delete(fileId, false); // false = don't remove globalFiles+ }++ /**+ * Create global file record only (no user file record)+ * Used for skill resources that should not appear in user's file list+ *+ * @param params - File parameters+ * @returns fileHash for reference+ */+ public async createGlobalFile(params: {+ fileHash: string;+ fileType: string;+ metadata?: { dirname: string; filename: string; path: string };+ size: number;+ url: string;+ }): Promise<{ fileHash: string }> {+ // Check if hash already exists+ const { isExist } = await this.fileModel.checkHash(params.fileHash);++ // Only create if not exists+ if (!isExist) {+ await this.fileModel.createGlobalFile({+ creator: this.userId,+ fileType: params.fileType,+ hashId: params.fileHash,+ metadata: params.metadata,+ size: params.size,+ url: params.url,+ });+ }++ return { fileHash: params.fileHash };+ }++ /**+ * Get file content by hash from globalFiles+ * Used for reading skill resources stored in globalFiles only+ *+ * @param fileHash - File hash (globalFiles.hashId)+ * @returns File content as string+ */+ public async getFileContentByHash(fileHash: string): Promise<string> {+ const result = await this.fileModel.checkHash(fileHash);+ if (!result.isExist || !result.url) {+ throw new TRPCError({ code: 'NOT_FOUND', message: `Global file not found: ${fileHash}` });+ }+ return this.getFileContent(result.url);+ }++ public async getFileByteArrayByHash(fileHash: string): Promise<Uint8Array> {+ const result = await this.fileModel.checkHash(fileHash);+ if (!result.isExist || !result.url) {+ throw new TRPCError({ code: 'NOT_FOUND', message: `Global file not found: ${fileHash}` });+ }+ return this.getFileByteArray(result.url);+ }+/*** Upload base64 data and create database record* @param base64Data - Base64 data (supports data URI format or pure base64)diff --git a/src/server/services/market/index.ts b/src/server/services/market/index.tsindex 2464f26add7..1411a83b833 100644--- a/src/server/services/market/index.ts+++ b/src/server/services/market/index.ts@@ -385,7 +385,71 @@ export class MarketService {await this.market.user.register(params);}- // ============================== Skills Methods ==============================+ // ============================== Skills Methods (using SDK) ==============================++ /**+ * Search for skills in the LobeHub Market+ */+ async searchSkill(params: {+ category?: string;+ locale?: string;+ order?: 'asc' | 'desc';+ page?: number;+ pageSize?: number;+ search?: string;+ sort?: 'createdAt' | 'downloadCount' | 'forks' | 'name' | 'stars' | 'updatedAt' | 'watchers';+ }) {+ log('searchSkill: %O', params);++ const result = await this.market.marketSkills.getSkillList(params);++ log('searchSkill response: %O', result);++ return {+ items: result.items,+ page: result.currentPage,+ pageSize: result.pageSize,+ total: result.totalCount,+ };+ }++ /**+ * Get skill detail from market+ */+ async getSkillDetail(identifier: string, options?: { locale?: string; version?: string }) {+ log('getSkillDetail: %s, options: %O', identifier, options);++ const result = await this.market.marketSkills.getSkillDetail(identifier, options);++ log('getSkillDetail response: %O', result);++ return result;+ }++ /**+ * Get skill download URL from market+ */+ getSkillDownloadUrl(identifier: string, version?: string): string {+ return this.market.marketSkills.getDownloadUrl(identifier, version);+ }++ /**+ * Download skill ZIP directly+ */+ async downloadSkill(identifier: string, version?: string) {+ log('downloadSkill: %s, version: %s', identifier, version);++ return this.market.marketSkills.downloadSkill(identifier, version);+ }++ /**+ * Get skill categories+ */+ async getSkillCategories() {+ log('getSkillCategories');++ return this.market.marketSkills.getCategories();+ }/*** Execute a LobeHub Skill tooldiff --git a/src/server/services/skill/errors.ts b/src/server/services/skill/errors.tsnew file mode 100644index 00000000000..11e7080a0a2--- /dev/null+++ b/src/server/services/skill/errors.ts@@ -0,0 +1,41 @@+import { z } from 'zod';++export class SkillParseError extends Error {+ cause?: Error;++ constructor(message: string, cause?: Error) {+ super(message);+ this.name = 'SkillParseError';+ this.cause = cause;+ }+}++export class SkillManifestError extends Error {+ zodError?: z.ZodError;++ constructor(message: string, zodError?: z.ZodError) {+ super(message);+ this.name = 'SkillManifestError';+ this.zodError = zodError;+ }+}++export class SkillResourceError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'SkillResourceError';+ }+}++export class SkillImportError extends Error {+ code: 'CONFLICT' | 'INVALID_URL' | 'NOT_FOUND' | 'DOWNLOAD_FAILED' | 'FILE_NOT_FOUND';++ constructor(+ message: string,+ code: 'CONFLICT' | 'INVALID_URL' | 'NOT_FOUND' | 'DOWNLOAD_FAILED' | 'FILE_NOT_FOUND',+ ) {+ super(message);+ this.name = 'SkillImportError';+ this.code = code;+ }+}diff --git a/src/server/services/skill/importer.test.ts b/src/server/services/skill/importer.test.tsnew file mode 100644index 00000000000..3dbd45409f0--- /dev/null+++ b/src/server/services/skill/importer.test.ts@@ -0,0 +1,1108 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import { agentSkills, files, globalFiles, users } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { SkillImportError } from './errors';+import { SkillImporter } from './importer';++// Mock external dependencies only (GitHub, S3, parser)+const normalizeIdentifierPart = (part: string) =>+ part+ .replaceAll(/[^\w-]/g, '-')+ .replaceAll(/-+/g, '-')+ .replaceAll(/^-|-$/g, '');++const mockGitHubInstance = {+ downloadRepoZip: vi.fn(),+ generateIdentifier: vi+ .fn()+ .mockImplementation((info: { owner: string; path?: string; repo: string }) => {+ const parts = [normalizeIdentifierPart(info.owner), normalizeIdentifierPart(info.repo)];+ if (info.path) {+ const lastSegment = info.path.split('/').findLast(Boolean);+ if (lastSegment) parts.push(normalizeIdentifierPart(lastSegment));+ }+ return parts.join('-').toLowerCase();+ }),+ parseRepoUrl: vi.fn(),+};+vi.mock('@/server/modules/GitHub', () => ({+ GitHub: vi.fn().mockImplementation(() => mockGitHubInstance),+ GitHubNotFoundError: class GitHubNotFoundError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubNotFoundError';+ }+ },+ GitHubParseError: class GitHubParseError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'GitHubParseError';+ }+ },+}));++const mockParserInstance = {+ parseSkillMd: vi.fn(),+ parseZipPackage: vi.fn(),+};+vi.mock('./parser', () => ({+ SkillParser: vi.fn().mockImplementation(() => mockParserInstance),+}));++// Mock global fetch for URL imports+const mockFetch = vi.fn();+vi.stubGlobal('fetch', mockFetch);++// Mock S3 operations in FileService implementation+vi.mock('@/server/services/file/impls', () => ({+ createFileServiceModule: vi.fn().mockImplementation(() => ({+ createPreSignedUrl: vi.fn().mockResolvedValue('mock-presigned-url'),+ createPreSignedUrlForPreview: vi.fn().mockResolvedValue('mock-preview-url'),+ deleteFile: vi.fn().mockResolvedValue(undefined),+ deleteFiles: vi.fn().mockResolvedValue(undefined),+ getFileByteArray: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])), // Non-empty content+ getFileContent: vi.fn().mockResolvedValue('mock-content'),+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 100 }),+ getFullFileUrl: vi.fn().mockResolvedValue('mock-full-url'),+ getKeyFromFullUrl: vi.fn().mockResolvedValue(null),+ uploadBuffer: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ uploadContent: vi.fn().mockResolvedValue(undefined),+ uploadMedia: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ })),+}));++// Mock fs/promises readFile+vi.mock('node:fs/promises', () => ({+ readFile: vi.fn().mockResolvedValue(Buffer.from('mock-zip-content')),+}));++describe('SkillImporter', () => {+ let db: LobeChatDatabase;+ let userId: string;+ let importer: SkillImporter;++ beforeEach(async () => {+ vi.clearAllMocks();++ db = await getTestDB();+ userId = `test-user-${Date.now()}`;++ // Create test user+ await db.insert(users).values({ id: userId });++ importer = new SkillImporter(db, userId);+ });++ afterEach(async () => {+ // Cleanup: delete user (cascade deletes agentSkills and files)+ await db.delete(users).where(eq(users.id, userId));+ // Clean up orphaned globalFiles+ await db.delete(globalFiles);+ });++ describe('createUserSkill', () => {+ it('should create a user skill with generated identifier', async () => {+ const result = await importer.createUserSkill({+ content: '# Test content',+ name: 'Test Skill',+ description: 'A test skill',+ });++ expect(result).toBeDefined();+ expect(result.name).toBe('Test Skill');+ expect(result.identifier).toMatch(/^user\./);+ expect(result.source).toBe('user');++ // Verify in database+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.id),+ });+ expect(dbSkill).toBeDefined();+ expect(dbSkill?.name).toBe('Test Skill');+ expect(dbSkill?.content).toBe('# Test content');+ expect(dbSkill?.description).toBe('A test skill');+ });++ it('should create a user skill with custom identifier', async () => {+ const result = await importer.createUserSkill({+ content: '# Test content',+ description: 'A test skill',+ identifier: 'custom-identifier',+ name: 'Test Skill',+ });++ expect(result.identifier).toBe('custom-identifier');++ // Verify in database+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.identifier, 'custom-identifier'),+ });+ expect(dbSkill).toBeDefined();+ expect(dbSkill?.identifier).toBe('custom-identifier');+ });++ it('should throw CONFLICT error when identifier exists', async () => {+ // Create first skill+ await importer.createUserSkill({+ content: '# First',+ description: 'First skill',+ identifier: 'duplicate-id',+ name: 'First Skill',+ });++ // Try to create second skill with same identifier+ await expect(+ importer.createUserSkill({+ content: '# Second',+ description: 'Second skill',+ identifier: 'duplicate-id',+ name: 'Second Skill',+ }),+ ).rejects.toThrow(SkillImportError);++ try {+ await importer.createUserSkill({+ content: '# Third',+ description: 'Third skill',+ identifier: 'duplicate-id',+ name: 'Third Skill',+ });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('CONFLICT');+ }+ });++ it('should store manifest with description', async () => {+ const result = await importer.createUserSkill({+ content: '# Content',+ description: 'This is a description',+ name: 'Skill with Description',+ });++ // Verify manifest in database+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.id),+ });+ expect(dbSkill?.manifest).toMatchObject({+ description: 'This is a description',+ name: 'Skill with Description',+ });+ });+ });++ describe('importFromZip', () => {+ it('should import skill from ZIP file', async () => {+ // Create a mock file record for the ZIP file+ const zipFileId = `zip-file-${Date.now()}`;+ const zipHash = `zip-hash-${Date.now()}`;++ // Insert mock file record+ await db.insert(globalFiles).values({+ creator: userId,+ fileType: 'application/zip',+ hashId: zipHash,+ size: 1000,+ url: 'mock/path/skill.zip',+ });++ await db.insert(files).values({+ fileHash: zipHash,+ fileType: 'application/zip',+ id: zipFileId,+ name: 'skill.zip',+ size: 1000,+ url: 'mock/path/skill.zip',+ userId,+ });++ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# ZIP Skill content',+ manifest: { name: 'ZIP Skill', description: 'A ZIP skill' },+ resources: new Map(),+ // zipHash undefined to skip globalFiles foreign key (file already exists from user upload)+ zipHash: undefined,+ });++ const result = await importer.importFromZip({ zipFileId });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.name).toBe('ZIP Skill');+ expect(result.skill.source).toBe('user');+ expect(result.skill.identifier).toMatch(/^user\./);++ // Verify in database+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill).toBeDefined();+ expect(dbSkill?.content).toBe('# ZIP Skill content');+ expect(dbSkill?.description).toBe('A ZIP skill');+ });++ it('should store resources from ZIP file', async () => {+ const zipFileId = `zip-file-res-${Date.now()}`;+ const zipHash = `zip-hash-res-${Date.now()}`;+ const parsedZipHash = `parsed-hash-${Date.now()}`;++ await db.insert(globalFiles).values({+ creator: userId,+ fileType: 'application/zip',+ hashId: zipHash,+ size: 1000,+ url: 'mock/path/skill.zip',+ });++ await db.insert(files).values({+ fileHash: zipHash,+ fileType: 'application/zip',+ id: zipFileId,+ name: 'skill.zip',+ size: 1000,+ url: 'mock/path/skill.zip',+ userId,+ });++ // Also create globalFiles for the parsed hash (for foreign key reference)+ await db.insert(globalFiles).values({+ creator: userId,+ fileType: 'application/zip',+ hashId: parsedZipHash,+ size: 1000,+ url: 'mock/path/parsed-skill.zip',+ });++ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill with resources',+ manifest: { name: 'Resource Skill', description: 'Has resources' },+ resources: new Map([+ ['readme.md', Buffer.from('# README')],+ ['docs/guide.md', Buffer.from('# Guide')],+ ]),+ zipHash: parsedZipHash,+ });++ const result = await importer.importFromZip({ zipFileId });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.resources).toBeDefined();++ // Verify resources mapping was stored+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill?.resources).toBeDefined();+ expect(Object.keys(dbSkill?.resources || {})).toHaveLength(2);+ });++ it('should throw CONFLICT error when skill name already exists', async () => {+ const zipFileId = `zip-file-conflict-${Date.now()}`;+ const zipHash = `zip-hash-conflict-${Date.now()}`;++ await db.insert(globalFiles).values({+ creator: userId,+ fileType: 'application/zip',+ hashId: zipHash,+ size: 1000,+ url: 'mock/path/skill.zip',+ });++ await db.insert(files).values({+ fileHash: zipHash,+ fileType: 'application/zip',+ id: zipFileId,+ name: 'skill.zip',+ size: 1000,+ url: 'mock/path/skill.zip',+ userId,+ });++ // First, create a skill with the same name+ await importer.createUserSkill({+ content: '# Existing Skill',+ description: 'Already exists',+ name: 'Duplicate Name',+ });++ // Now try to import a ZIP with the same name+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# New Skill from ZIP',+ manifest: { name: 'Duplicate Name', description: 'From ZIP' },+ resources: new Map(),+ zipHash: undefined,+ });++ await expect(importer.importFromZip({ zipFileId })).rejects.toThrow(SkillImportError);++ try {+ await importer.importFromZip({ zipFileId });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('CONFLICT');+ expect((e as SkillImportError).message).toContain('Duplicate Name');+ }+ });+ });++ describe('importFromGitHub', () => {+ it('should import skill from GitHub repository', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-demo',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# GitHub Skill content',+ manifest: { name: 'GitHub Skill', description: 'A GitHub skill' },+ resources: new Map(),+ zipHash: `github-hash-${Date.now()}`,+ });++ const result = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-demo',+ });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.name).toBe('GitHub Skill');+ expect(result.skill.identifier).toBe('lobehub-skill-demo');+ expect(result.skill.source).toBe('market');++ // Verify manifest contains repository info+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill?.manifest).toMatchObject({+ repository: 'https://github.com/lobehub/skill-demo',+ sourceUrl: 'https://github.com/lobehub/skill-demo',+ });+ });++ it('should import skill from GitHub subdirectory', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'openclaw',+ path: 'skills/skill-creator',+ repo: 'openclaw',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill Creator content',+ manifest: { name: 'skill-creator', description: 'Create skills' },+ resources: new Map(),+ zipHash: `subdirectory-hash-${Date.now()}`,+ });++ const result = await importer.importFromGitHub({+ gitUrl: 'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',+ });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.identifier).toBe('openclaw-openclaw-skill-creator');++ // Verify parseZipPackage was called with basePath and repackSkillZip+ expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(expect.any(Buffer), {+ basePath: 'skills/skill-creator',+ repackSkillZip: true,+ });+ });++ it('should update existing skill when re-importing from same repo', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-update',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));++ // First import+ mockParserInstance.parseZipPackage.mockResolvedValueOnce({+ content: '# Original content',+ manifest: { name: 'Original Name', description: 'Original desc' },+ resources: new Map(),+ zipHash: `update-hash-1-${Date.now()}`,+ });++ const first = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-update',+ });++ expect(first.status).toBe('created');+ expect(first.skill.name).toBe('Original Name');+ expect(first.skill.content).toBe('# Original content');++ // Second import (should update)+ mockParserInstance.parseZipPackage.mockResolvedValueOnce({+ content: '# Updated content',+ manifest: { name: 'Updated Name', description: 'Updated desc' },+ resources: new Map(),+ zipHash: `update-hash-2-${Date.now()}`,+ });++ const second = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-update',+ });++ expect(second.status).toBe('updated');+ expect(second.skill.id).toBe(first.skill.id); // Same skill updated+ expect(second.skill.name).toBe('Updated Name');+ expect(second.skill.content).toBe('# Updated content');++ // Verify only one skill exists in database+ const dbSkills = await db+ .select()+ .from(agentSkills)+ .where(+ and(eq(agentSkills.userId, userId), eq(agentSkills.identifier, 'lobehub-skill-update')),+ );+ expect(dbSkills).toHaveLength(1);+ });++ it('should throw INVALID_URL error for invalid GitHub URL', async () => {+ const { GitHubParseError } = await import('@/server/modules/GitHub');+ mockGitHubInstance.parseRepoUrl.mockImplementation(() => {+ throw new GitHubParseError('Invalid GitHub URL');+ });++ await expect(+ importer.importFromGitHub({ gitUrl: 'https://invalid-url.com/repo' }),+ ).rejects.toThrow(SkillImportError);++ try {+ await importer.importFromGitHub({ gitUrl: 'https://invalid-url.com/repo' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('INVALID_URL');+ }+ });++ it('should throw NOT_FOUND error when repository does not exist', async () => {+ const { GitHubNotFoundError } = await import('@/server/modules/GitHub');+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'non-existent',+ });+ mockGitHubInstance.downloadRepoZip.mockImplementation(() => {+ throw new GitHubNotFoundError('Repository not found');+ });++ await expect(+ importer.importFromGitHub({ gitUrl: 'https://github.com/lobehub/non-existent' }),+ ).rejects.toThrow(SkillImportError);++ try {+ await importer.importFromGitHub({ gitUrl: 'https://github.com/lobehub/non-existent' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('NOT_FOUND');+ }+ });++ it('should use custom branch when provided', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'develop',+ owner: 'lobehub',+ repo: 'skill-branch',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Branch Skill',+ manifest: { name: 'Branch Skill', description: 'From develop branch' },+ resources: new Map(),+ zipHash: `branch-hash-${Date.now()}`,+ });++ await importer.importFromGitHub({+ branch: 'develop',+ gitUrl: 'https://github.com/lobehub/skill-branch',+ });++ expect(mockGitHubInstance.parseRepoUrl).toHaveBeenCalledWith(+ 'https://github.com/lobehub/skill-branch',+ 'develop',+ );+ });++ it('should only keep globalFiles record, not user files record for ZIP', async () => {+ const zipHash = `only-global-${Date.now()}`;++ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-global-only',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill Content',+ manifest: { name: 'Global Only Skill', description: 'Test global files' },+ resources: new Map(),+ zipHash,+ });++ const result = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-global-only',+ });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.zipFileHash).toBe(zipHash);++ // Verify: globalFiles should have the record+ const globalFileRecord = await db.query.globalFiles.findFirst({+ where: eq(globalFiles.hashId, zipHash),+ });+ expect(globalFileRecord).toBeDefined();+ expect(globalFileRecord?.hashId).toBe(zipHash);++ // Verify: user's files table should NOT have the ZIP record (deleted)+ const userFileRecords = await db+ .select()+ .from(files)+ .where(and(eq(files.userId, userId), eq(files.fileHash, zipHash)));+ expect(userFileRecords).toHaveLength(0);+ });++ it('should store ZIP file at correct path', async () => {+ const zipHash = `path-test-${Date.now()}`;+ const { createFileServiceModule } = await import('@/server/services/file/impls');+ const mockUploadBuffer = vi.fn().mockResolvedValue({ key: 'mock-key' });+ (createFileServiceModule as any).mockReturnValue({+ createPreSignedUrl: vi.fn(),+ createPreSignedUrlForPreview: vi.fn(),+ deleteFile: vi.fn(),+ deleteFiles: vi.fn(),+ getFileByteArray: vi.fn(),+ getFileContent: vi.fn(),+ getFileMetadata: vi.fn(),+ getFullFileUrl: vi.fn(),+ getKeyFromFullUrl: vi.fn(),+ uploadBuffer: mockUploadBuffer,+ uploadContent: vi.fn(),+ uploadMedia: vi.fn(),+ });++ // Create new importer to pick up the mock+ const freshImporter = new SkillImporter(db, userId);++ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-path-test',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Content',+ manifest: { name: 'Path Test Skill', description: 'Test path' },+ resources: new Map(),+ zipHash,+ });++ await freshImporter.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-path-test',+ });++ // Verify uploadBuffer was called with correct path+ expect(mockUploadBuffer).toHaveBeenCalledWith(+ `skills/zip/${zipHash}.zip`,+ expect.any(Buffer),+ 'application/zip',+ );+ });++ it('should call parseZipPackage with repackSkillZip: true', async () => {+ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'repack-test',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('large-repo-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill',+ manifest: { name: 'Test', description: 'Test' },+ resources: new Map(),+ skillZipBuffer: Buffer.from('small-skill-zip'),+ zipHash: 'skill-hash',+ });++ await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/repack-test',+ });++ // Verify parseZipPackage was called with repackSkillZip: true+ expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(+ expect.any(Buffer),+ expect.objectContaining({ repackSkillZip: true }),+ );+ });++ it('should upload skillZipBuffer instead of full repo ZIP', async () => {+ const { createFileServiceModule } = await import('@/server/services/file/impls');+ const mockUploadBuffer = vi.fn().mockResolvedValue({ key: 'mock-key' });+ (createFileServiceModule as any).mockReturnValue({+ createPreSignedUrl: vi.fn(),+ createPreSignedUrlForPreview: vi.fn(),+ deleteFile: vi.fn(),+ deleteFiles: vi.fn(),+ getFileByteArray: vi.fn(),+ getFileContent: vi.fn(),+ getFileMetadata: vi.fn(),+ getFullFileUrl: vi.fn(),+ getKeyFromFullUrl: vi.fn(),+ uploadBuffer: mockUploadBuffer,+ uploadContent: vi.fn(),+ uploadMedia: vi.fn(),+ });++ const freshImporter = new SkillImporter(db, userId);+ const largeRepoZip = Buffer.alloc(10_000_000); // 10MB repo ZIP+ const smallSkillZip = Buffer.from('small-repacked-skill-zip');++ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'large-repo',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(largeRepoZip);+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill',+ manifest: { name: 'Test', description: 'Test' },+ resources: new Map(),+ skillZipBuffer: smallSkillZip,+ zipHash: 'skill-content-hash',+ });++ await freshImporter.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/large-repo',+ });++ // Verify uploadBuffer was called with skillZipBuffer, not the large repo ZIP+ expect(mockUploadBuffer).toHaveBeenCalledWith(+ expect.stringContaining('skills/zip/'),+ smallSkillZip, // Should be the small repacked ZIP+ 'application/zip',+ );+ });++ it('should skip import when skill exists with same zipHash (deduplication)', async () => {+ const zipHash = `dedup-hash-${Date.now()}`;++ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-dedup',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));+ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# Skill Content',+ manifest: { name: 'Dedup Skill', description: 'Test deduplication' },+ resources: new Map([+ ['readme.md', Buffer.from('# README')],+ ['docs/guide.md', Buffer.from('# Guide')],+ ]),+ zipHash,+ });++ // First import+ const first = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-dedup',+ });++ expect(first).toBeDefined();+ expect(first.status).toBe('created');+ expect(first.skill.zipFileHash).toBe(zipHash);++ // Record how many times parseZipPackage was called+ const parseCallCountAfterFirst = mockParserInstance.parseZipPackage.mock.calls.length;++ // Second import with same zipHash should skip+ const second = await importer.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-dedup',+ });++ // Should return the existing skill with 'unchanged' status+ expect(second.status).toBe('unchanged');+ expect(second.skill.id).toBe(first.skill.id);+ expect(second.skill.zipFileHash).toBe(zipHash);++ // parseZipPackage should be called again (to get the new hash)+ // but we should verify no resource storage happened+ expect(mockParserInstance.parseZipPackage.mock.calls.length).toBe(+ parseCallCountAfterFirst + 1,+ );++ // Verify only one skill exists in database+ const dbSkills = await db+ .select()+ .from(agentSkills)+ .where(eq(agentSkills.identifier, 'lobehub-skill-dedup'));+ expect(dbSkills).toHaveLength(1);+ });++ it('should update skill when content changes (different zipHash)', async () => {+ const { createFileServiceModule } = await import('@/server/services/file/impls');+ const mockUploadBuffer = vi.fn().mockResolvedValue({ key: 'mock-key' });+ (createFileServiceModule as any).mockReturnValue({+ createPreSignedUrl: vi.fn(),+ createPreSignedUrlForPreview: vi.fn(),+ deleteFile: vi.fn(),+ deleteFiles: vi.fn(),+ getFileByteArray: vi.fn(),+ getFileContent: vi.fn(),+ getFileMetadata: vi.fn(),+ getFullFileUrl: vi.fn(),+ getKeyFromFullUrl: vi.fn(),+ uploadBuffer: mockUploadBuffer,+ uploadContent: vi.fn(),+ uploadMedia: vi.fn(),+ });++ const freshImporter = new SkillImporter(db, userId);++ mockGitHubInstance.parseRepoUrl.mockReturnValue({+ branch: 'main',+ owner: 'lobehub',+ repo: 'skill-update-content',+ });+ mockGitHubInstance.downloadRepoZip.mockResolvedValue(Buffer.from('mock-zip'));++ // First import+ mockParserInstance.parseZipPackage.mockResolvedValueOnce({+ content: '# Original Content',+ manifest: { name: 'Update Skill', description: 'Version 1' },+ resources: new Map(),+ zipHash: 'hash-v1',+ });++ const first = await freshImporter.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-update-content',+ });++ expect(first.status).toBe('created');+ expect(first.skill.content).toBe('# Original Content');+ expect(first.skill.zipFileHash).toBe('hash-v1');+ const uploadCountAfterFirst = mockUploadBuffer.mock.calls.length;++ // Second import with different zipHash (content changed)+ mockParserInstance.parseZipPackage.mockResolvedValueOnce({+ content: '# Updated Content',+ manifest: { name: 'Update Skill', description: 'Version 2' },+ resources: new Map(),+ zipHash: 'hash-v2',+ });++ const second = await freshImporter.importFromGitHub({+ gitUrl: 'https://github.com/lobehub/skill-update-content',+ });++ // Should update the existing skill+ expect(second.status).toBe('updated');+ expect(second.skill.id).toBe(first.skill.id);+ expect(second.skill.content).toBe('# Updated Content');+ expect(second.skill.zipFileHash).toBe('hash-v2');++ // uploadBuffer should be called again for the new ZIP+ expect(mockUploadBuffer.mock.calls.length).toBe(uploadCountAfterFirst + 1);+ });+ });++ describe('importFromUrl', () => {+ beforeEach(() => {+ mockFetch.mockReset();+ });++ it('should import skill from URL', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => `---+name: URL Skill+description: A skill from URL+---+# URL Skill Content++This is the skill content.`,+ });++ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# URL Skill Content\n\nThis is the skill content.',+ manifest: { name: 'URL Skill', description: 'A skill from URL' },+ raw: 'raw content',+ });++ const result = await importer.importFromUrl({+ url: 'https://example.com/skill.md',+ });++ expect(result).toBeDefined();+ expect(result.status).toBe('created');+ expect(result.skill.name).toBe('URL Skill');+ expect(result.skill.identifier).toBe('url.example.com.skill');+ expect(result.skill.source).toBe('market');+ expect(result.skill.content).toBe('# URL Skill Content\n\nThis is the skill content.');++ // Verify manifest contains source URL+ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill?.manifest).toMatchObject({+ sourceUrl: 'https://example.com/skill.md',+ });+ });++ it('should handle URL with path', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => `---+name: Nested Skill+description: A nested skill+---+# Content`,+ });++ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# Content',+ manifest: { name: 'Nested Skill', description: 'A nested skill' },+ raw: 'raw',+ });++ const result = await importer.importFromUrl({+ url: 'https://pinchwork.dev/skills/my-skill/SKILL.md',+ });++ expect(result.skill.identifier).toBe('url.pinchwork.dev.skills.my-skill.SKILL');+ });++ it('should update existing skill when re-importing from same URL', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => 'content',+ });++ // First import+ mockParserInstance.parseSkillMd.mockReturnValueOnce({+ content: '# Original',+ manifest: { name: 'Original Name', description: 'Original desc' },+ raw: 'raw',+ });++ const first = await importer.importFromUrl({+ url: 'https://example.com/update-test.md',+ });++ expect(first.status).toBe('created');+ expect(first.skill.content).toBe('# Original');++ // Second import with updated content+ mockParserInstance.parseSkillMd.mockReturnValueOnce({+ content: '# Updated',+ manifest: { name: 'Updated Name', description: 'Updated desc' },+ raw: 'raw',+ });++ const second = await importer.importFromUrl({+ url: 'https://example.com/update-test.md',+ });++ expect(second.status).toBe('updated');+ expect(second.skill.id).toBe(first.skill.id);+ expect(second.skill.content).toBe('# Updated');+ expect(second.skill.name).toBe('Updated Name');+ });++ it('should return unchanged when content is the same', async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => 'content',+ });++ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# Same Content',+ manifest: { name: 'Same Skill', description: 'Same desc' },+ raw: 'raw',+ });++ const first = await importer.importFromUrl({+ url: 'https://example.com/same-content.md',+ });++ expect(first.status).toBe('created');++ // Second import with same content+ const second = await importer.importFromUrl({+ url: 'https://example.com/same-content.md',+ });++ expect(second.status).toBe('unchanged');+ expect(second.skill.id).toBe(first.skill.id);+ });++ it('should throw INVALID_URL error for invalid URL', async () => {+ await expect(importer.importFromUrl({ url: 'not-a-valid-url' })).rejects.toThrow(+ SkillImportError,+ );++ try {+ await importer.importFromUrl({ url: 'not-a-valid-url' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('INVALID_URL');+ }+ });++ it('should throw NOT_FOUND error when URL returns 404', async () => {+ mockFetch.mockResolvedValue({+ ok: false,+ status: 404,+ statusText: 'Not Found',+ });++ await expect(+ importer.importFromUrl({ url: 'https://example.com/not-found.md' }),+ ).rejects.toThrow(SkillImportError);++ try {+ await importer.importFromUrl({ url: 'https://example.com/not-found.md' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('NOT_FOUND');+ }+ });++ it('should throw DOWNLOAD_FAILED error when fetch fails', async () => {+ mockFetch.mockResolvedValue({+ ok: false,+ status: 500,+ statusText: 'Internal Server Error',+ });++ await expect(importer.importFromUrl({ url: 'https://example.com/error.md' })).rejects.toThrow(+ SkillImportError,+ );++ try {+ await importer.importFromUrl({ url: 'https://example.com/error.md' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('DOWNLOAD_FAILED');+ }+ });++ it('should throw DOWNLOAD_FAILED error when network error occurs', async () => {+ mockFetch.mockRejectedValue(new Error('Network error'));++ await expect(+ importer.importFromUrl({ url: 'https://example.com/network-error.md' }),+ ).rejects.toThrow(SkillImportError);++ try {+ await importer.importFromUrl({ url: 'https://example.com/network-error.md' });+ } catch (e) {+ expect((e as SkillImportError).code).toBe('DOWNLOAD_FAILED');+ }+ });+ });++ describe('importFromZip without repacking', () => {+ it('should NOT pass repackSkillZip option for user uploaded ZIP', async () => {+ // Reset the mock to ensure it returns non-empty content (previous tests may have overwritten it)+ const { createFileServiceModule } = await import('@/server/services/file/impls');+ (createFileServiceModule as any).mockReturnValue({+ createPreSignedUrl: vi.fn().mockResolvedValue('mock-presigned-url'),+ createPreSignedUrlForPreview: vi.fn().mockResolvedValue('mock-preview-url'),+ deleteFile: vi.fn().mockResolvedValue(undefined),+ deleteFiles: vi.fn().mockResolvedValue(undefined),+ getFileByteArray: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])),+ getFileContent: vi.fn().mockResolvedValue('mock-content'),+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 100 }),+ getFullFileUrl: vi.fn().mockResolvedValue('mock-full-url'),+ getKeyFromFullUrl: vi.fn().mockResolvedValue(null),+ uploadBuffer: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ uploadContent: vi.fn().mockResolvedValue(undefined),+ uploadMedia: vi.fn().mockResolvedValue({ key: 'mock-key' }),+ });++ // Create a fresh importer instance to pick up the reset mock+ const freshImporter = new SkillImporter(db, userId);++ const zipFileId = `zip-no-repack-${Date.now()}`;+ const zipHash = `hash-no-repack-${Date.now()}`;++ await db.insert(globalFiles).values({+ creator: userId,+ fileType: 'application/zip',+ hashId: zipHash,+ size: 1000,+ url: 'mock/path/skill.zip',+ });++ await db.insert(files).values({+ fileHash: zipHash,+ fileType: 'application/zip',+ id: zipFileId,+ name: 'skill.zip',+ size: 1000,+ url: 'mock/path/skill.zip',+ userId,+ });++ mockParserInstance.parseZipPackage.mockResolvedValue({+ content: '# User Skill',+ manifest: { name: 'User Skill', description: 'User uploaded' },+ resources: new Map(),+ zipHash: undefined, // User uploaded ZIP doesn't need to track hash for foreign key+ });++ await freshImporter.importFromZip({ zipFileId });++ // Verify parseZipPackage was called WITHOUT repackSkillZip option+ expect(mockParserInstance.parseZipPackage).toHaveBeenCalledTimes(1);+ const callArgs = mockParserInstance.parseZipPackage.mock.calls[0];+ expect(callArgs[0]).toBeInstanceOf(Buffer);+ // Second argument should be undefined (no options passed)+ expect(callArgs[1]).toBeUndefined();+ });+ });++ describe('user isolation', () => {+ it('should not find skills from other users', async () => {+ // Create skill for first user+ await importer.createUserSkill({+ content: '# User 1 Skill',+ description: 'User 1 skill',+ identifier: 'isolation-test-skill',+ name: 'User 1 Skill',+ });++ // Create second user+ const otherUserId = `other-user-${Date.now()}`;+ await db.insert(users).values({ id: otherUserId });++ // Create importer for second user+ const otherImporter = new SkillImporter(db, otherUserId);++ // Second user should not be able to create skill with same identifier+ // because findByIdentifier filters by userId+ const otherResult = await otherImporter.createUserSkill({+ content: '# User 2 Skill',+ description: 'User 2 skill',+ identifier: 'isolation-test-skill', // Same identifier, different user+ name: 'User 2 Skill',+ });++ // Both skills should exist (different users)+ const allSkills = await db+ .select()+ .from(agentSkills)+ .where(eq(agentSkills.identifier, 'isolation-test-skill'));+ expect(allSkills).toHaveLength(2);++ // Clean up other user+ await db.delete(users).where(eq(users.id, otherUserId));+ });+ });+});diff --git a/src/server/services/skill/importer.ts b/src/server/services/skill/importer.tsnew file mode 100644index 00000000000..4ce8553d6b8--- /dev/null+++ b/src/server/services/skill/importer.ts@@ -0,0 +1,455 @@+import { readFile } from 'node:fs/promises';++import { type LobeChatDatabase } from '@lobechat/database';+import {+ type CreateSkillInput,+ type ImportGitHubInput,+ type ImportUrlInput,+ type ImportZipInput,+ type SkillImportResult,+ type SkillManifest,+} from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import debug from 'debug';++import { AgentSkillModel } from '@/database/models/agentSkill';+import { GitHub, GitHubNotFoundError, GitHubParseError } from '@/server/modules/GitHub';+import { FileService } from '@/server/services/file';++import { SkillImportError, SkillManifestError } from './errors';+import { SkillParser } from './parser';+import { SkillResourceService } from './resource';++const log = debug('lobe-chat:service:skill-importer');++export class SkillImporter {+ private skillModel: AgentSkillModel;+ private parser: SkillParser;+ private resourceService: SkillResourceService;+ private fileService: FileService;+ private github: GitHub;+ private userId: string;++ constructor(db: LobeChatDatabase, userId: string) {+ this.skillModel = new AgentSkillModel(db, userId);+ this.parser = new SkillParser();+ this.resourceService = new SkillResourceService(db, userId);+ this.fileService = new FileService(db, userId);+ this.github = new GitHub({ userAgent: 'LobeHub-Skill-Importer' });+ this.userId = userId;+ }++ /**+ * Create a skill manually by user+ */+ async createUserSkill(input: CreateSkillInput) {+ // Check if name already exists for this user+ const existingByName = await this.skillModel.findByName(input.name);+ if (existingByName) {+ throw new SkillImportError(`Skill with name "${input.name}" already exists`, 'CONFLICT');+ }++ const identifier = input.identifier || `user.${nanoid(12)}`;++ // Check if identifier already exists+ const existingByIdentifier = await this.skillModel.findByIdentifier(identifier);+ if (existingByIdentifier) {+ throw new SkillImportError(+ `Skill with identifier "${identifier}" already exists`,+ 'CONFLICT',+ );+ }++ const manifest: SkillManifest = {+ description: input.description || '',+ name: input.name,+ };++ return this.skillModel.create({+ content: input.content,+ description: input.description,+ identifier,+ manifest,+ name: input.name,+ source: 'user',+ });+ }++ /**+ * Import skill from ZIP file+ * @param input - Contains zipFileId from files table+ * @returns SkillImportResult with status: 'created'+ */+ async importFromZip(input: ImportZipInput): Promise<SkillImportResult> {+ log('importFromZip: starting with zipFileId=%s', input.zipFileId);++ // 1. Download ZIP file to local+ const { filePath, cleanup } = await this.fileService.downloadFileToLocal(input.zipFileId);+ log('importFromZip: downloaded to filePath=%s', filePath);++ try {+ const buffer = await readFile(filePath);+ log('importFromZip: read buffer size=%d bytes', buffer.length);++ // 2. Parse ZIP package+ const { manifest, content, resources, zipHash } = await this.parser.parseZipPackage(buffer);+ log(+ 'importFromZip: parsed manifest=%o, resources count=%d, zipHash=%s',+ manifest,+ resources.size,+ zipHash,+ );++ // 3. Check if name already exists for this user+ const existingByName = await this.skillModel.findByName(manifest.name);+ if (existingByName) {+ throw new SkillImportError(`Skill with name "${manifest.name}" already exists`, 'CONFLICT');+ }++ // 4. Store resource files+ const resourceIds = zipHash+ ? await this.resourceService.storeResources(zipHash, resources)+ : {};+ log('importFromZip: stored resources=%o', resourceIds);++ // 5. Generate identifier+ const identifier = `user.${nanoid(12)}`;+ log('importFromZip: generated identifier=%s', identifier);++ // 6. Create skill record+ const skill = await this.skillModel.create({+ content,+ description: manifest.description,+ identifier,+ manifest,+ name: manifest.name,+ resources: resourceIds,+ source: 'user',+ zipFileHash: zipHash,+ });+ log('importFromZip: created skill id=%s', skill.id);+ return { skill, status: 'created' };+ } finally {+ cleanup();+ log('importFromZip: cleaned up temp file');+ }+ }++ /**+ * Import skill from GitHub repository+ * @param input - GitHub repository info+ * @returns SkillImportResult with status: 'created' | 'updated' | 'unchanged'+ */+ async importFromGitHub(input: ImportGitHubInput): Promise<SkillImportResult> {+ log('importFromGitHub: starting with gitUrl=%s, branch=%s', input.gitUrl, input.branch);++ // 1. Parse GitHub URL+ let repoInfo;+ try {+ repoInfo = this.github.parseRepoUrl(input.gitUrl, input.branch);+ log('importFromGitHub: parsed repoInfo=%o', repoInfo);+ } catch (error) {+ log('importFromGitHub: failed to parse URL, error=%s', (error as Error).message);+ if (error instanceof GitHubParseError) {+ throw new SkillImportError(error.message, 'INVALID_URL');+ }+ throw error;+ }++ // 2. Download repository ZIP+ let zipBuffer;+ try {+ log('importFromGitHub: downloading repository ZIP...');+ zipBuffer = await this.github.downloadRepoZip(repoInfo);+ log('importFromGitHub: downloaded ZIP size=%d bytes', zipBuffer.length);+ } catch (error) {+ log('importFromGitHub: download failed, error=%s', (error as Error).message);+ if (error instanceof GitHubNotFoundError) {+ throw new SkillImportError(error.message, 'NOT_FOUND');+ }+ throw new SkillImportError(+ `Failed to download GitHub repository: ${(error as Error).message}`,+ 'DOWNLOAD_FAILED',+ );+ }++ // 3. Parse ZIP package (pass basePath for subdirectory imports, repack to save only skill files)+ log('importFromGitHub: parsing ZIP package with basePath=%s', repoInfo.path);+ const { manifest, content, resources, zipHash, skillZipBuffer } =+ await this.parser.parseZipPackage(zipBuffer, {+ basePath: repoInfo.path,+ repackSkillZip: true,+ });+ log(+ 'importFromGitHub: parsed manifest=%o, resources count=%d, zipHash=%s, skillZipSize=%d',+ manifest,+ resources.size,+ zipHash,+ skillZipBuffer?.length ?? 0,+ );++ // 4. Generate identifier (use GitHub info for uniqueness, include path for subdirectory imports)+ const identifier = this.github.generateIdentifier(repoInfo);+ log('importFromGitHub: identifier=%s', identifier);++ // 5. Check for existing skill with same zipHash (deduplication)+ const existing = await this.skillModel.findByIdentifier(identifier);+ if (existing && existing.zipFileHash === zipHash) {+ log(+ 'importFromGitHub: skill unchanged (same zipHash=%s), skipping update id=%s',+ zipHash,+ existing.id,+ );+ return { skill: existing, status: 'unchanged' };+ }++ // 6. Store resource files (only if skill is new or changed)+ log('importFromGitHub: storing %d resources...', resources.size);+ const resourceIds = zipHash+ ? await this.resourceService.storeResources(zipHash, resources)+ : {};+ log('importFromGitHub: stored resources=%o', resourceIds);++ // 7. Build manifest with repository info+ const fullManifest: SkillManifest = {+ ...manifest,+ repository: `https://github.com/${repoInfo.owner}/${repoInfo.repo}`,+ sourceUrl: input.gitUrl,+ };++ // 8. Upload ZIP file to S3 and create globalFiles record (for zipFileHash foreign key)+ // Use skillZipBuffer (repacked skill-only ZIP) instead of full repo zipBuffer+ let zipFileHash: string | undefined;+ const zipToUpload = skillZipBuffer ?? zipBuffer;+ if (zipHash && zipToUpload) {+ const zipKey = `skills/zip/${zipHash}.zip`;+ await this.fileService.uploadBuffer(zipKey, zipToUpload, 'application/zip');+ // Use createGlobalFile directly - no need to create then delete user file record+ await this.fileService.createGlobalFile({+ fileHash: zipHash,+ fileType: 'application/zip',+ metadata: {+ dirname: 'skills/zip',+ filename: `${zipHash}.zip`,+ path: zipKey,+ },+ size: zipToUpload.length,+ url: zipKey,+ });+ zipFileHash = zipHash;+ log(+ 'importFromGitHub: uploaded ZIP file, hash=%s, size=%d bytes',+ zipFileHash,+ zipToUpload.length,+ );+ }++ // 9. Update existing skill or create new+ if (existing) {+ log('importFromGitHub: skill exists but content changed, updating id=%s', existing.id);+ const skill = await this.skillModel.update(existing.id, {+ content,+ description: manifest.description,+ manifest: fullManifest,+ name: manifest.name,+ resources: resourceIds,+ zipFileHash,+ });+ log('importFromGitHub: updated skill id=%s', skill.id);+ return { skill, status: 'updated' };+ }++ // 10. Create new skill record+ log('importFromGitHub: creating new skill...');+ const skill = await this.skillModel.create({+ content,+ description: (manifest as any).description,+ identifier,+ manifest: fullManifest,+ name: manifest.name,+ resources: resourceIds,+ source: 'market', // GitHub source marked as market+ zipFileHash,+ });+ log('importFromGitHub: created skill id=%s', skill.id);+ return { skill, status: 'created' };+ }++ /**+ * Import skill from a direct URL pointing to SKILL.md+ * @param input - URL to SKILL.md file+ * @returns SkillImportResult with status: 'created' | 'updated' | 'unchanged'+ */+ async importFromUrl(input: ImportUrlInput): Promise<SkillImportResult> {+ log('importFromUrl: starting with url=%s', input.url);++ // 1. Validate URL+ let url: URL;+ try {+ url = new URL(input.url);+ } catch {+ throw new SkillImportError('Invalid URL format', 'INVALID_URL');+ }++ // 2. Fetch content (auto-detect SKILL.md or ZIP)+ let manifest: SkillManifest;+ let skillContent: string;+ let zipHash: string | undefined;+ let resources: Map<string, Buffer> | undefined;+ let zipBuffer: Buffer | undefined;++ try {+ log('importFromUrl: fetching URL...');+ // Create abort controller for timeout+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout++ let response: Response;+ try {+ response = await fetch(input.url, { signal: controller.signal });+ } finally {+ clearTimeout(timeoutId);+ }++ if (!response.ok) {+ if (response.status === 404) {+ throw new SkillImportError(`Resource not found at ${input.url}`, 'NOT_FOUND');+ }+ throw new SkillImportError(+ `Failed to fetch URL: ${response.status} ${response.statusText}`,+ 'DOWNLOAD_FAILED',+ );+ }++ // Detect if it's a ZIP file based on URL or content-type+ // Use optional chaining for headers to handle mock responses in tests+ const contentType = response.headers?.get?.('content-type') || '';+ const isZip =+ url.pathname.endsWith('.zip') ||+ url.pathname.includes('/download') ||+ contentType.includes('application/zip') ||+ contentType.includes('application/octet-stream');++ if (isZip) {+ // Handle ZIP file+ log('importFromUrl: detected ZIP file, parsing as package...');+ zipBuffer = Buffer.from(await response.arrayBuffer());+ const parsed = await this.parser.parseZipPackage(zipBuffer);+ manifest = parsed.manifest;+ skillContent = parsed.content;+ zipHash = parsed.zipHash;+ resources = parsed.resources;+ log('importFromUrl: parsed ZIP, manifest=%o, resources count=%d', manifest, resources.size);+ } else {+ // Handle plain SKILL.md+ log('importFromUrl: detected SKILL.md, parsing as markdown...');+ const content = await response.text();+ const parsed = this.parser.parseSkillMd(content);+ manifest = parsed.manifest;+ skillContent = parsed.content;+ log('importFromUrl: parsed SKILL.md, manifest=%o', manifest);+ }+ } catch (error) {+ if (error instanceof SkillImportError || error instanceof SkillManifestError) throw error;+ log('importFromUrl: fetch error: %O', error);+ log('importFromUrl: error type: %s', error?.constructor?.name);+ log('importFromUrl: error message: %s', (error as Error).message);+ log('importFromUrl: error stack: %s', (error as Error).stack);+ throw new SkillImportError(+ `Failed to process URL: ${(error as Error).message}`,+ 'DOWNLOAD_FAILED',+ );+ }++ log('importFromUrl: parsed manifest=%o', manifest);++ // 4. Generate identifier based on URL host and path+ const pathPart = url.pathname+ .replace(/^\//, '') // Remove leading slash+ .replace(/\.md$/i, '') // Remove .md extension+ .replaceAll('/', '.'); // Replace slashes with dots+ const identifier = `url.${url.host}.${pathPart || 'skill'}`;+ log('importFromUrl: identifier=%s', identifier);++ // 5. Check for existing skill+ const existing = await this.skillModel.findByIdentifier(identifier);++ // 6. Build manifest with source URL+ const fullManifest: SkillManifest = {+ ...manifest,+ sourceUrl: input.url,+ };++ // 7. Handle ZIP resources if present+ let resourceMap: Record<string, { fileHash: string; size: number }> | undefined;+ if (resources && resources.size > 0 && zipHash) {+ log('importFromUrl: storing %d resource files...', resources.size);+ resourceMap = await this.resourceService.storeResources(zipHash, resources);+ log('importFromUrl: stored resource files');+ }++ // 8. Upload ZIP file to S3 and create globalFiles record (for zipFileHash foreign key)+ let zipFileHash: string | undefined;+ if (zipHash && zipBuffer) {+ const zipKey = `skills/zip/${zipHash}.zip`;+ await this.fileService.uploadBuffer(zipKey, zipBuffer, 'application/zip');+ // Use createGlobalFile directly - no need to create then delete user file record+ await this.fileService.createGlobalFile({+ fileHash: zipHash,+ fileType: 'application/zip',+ metadata: {+ dirname: 'skills/zip',+ filename: `${zipHash}.zip`,+ path: zipKey,+ },+ size: zipBuffer.length,+ url: zipKey,+ });+ zipFileHash = zipHash;+ log(+ 'importFromUrl: uploaded ZIP file, hash=%s, size=%d bytes',+ zipFileHash,+ zipBuffer.length,+ );+ }++ // 9. Update existing skill or create new+ if (existing) {+ // Check if content is the same (simple deduplication based on content and zipHash)+ // Use nullish coalescing to handle null/undefined comparison correctly+ const existingHash = existing.zipFileHash ?? undefined;+ const isSameContent = existing.content === skillContent && existingHash === zipFileHash;+ if (isSameContent) {+ log('importFromUrl: skill unchanged, skipping update id=%s', existing.id);+ return { skill: existing, status: 'unchanged' };+ }++ log('importFromUrl: skill exists but content changed, updating id=%s', existing.id);+ const skill = await this.skillModel.update(existing.id, {+ content: skillContent,+ description: manifest.description,+ manifest: fullManifest,+ name: manifest.name,+ ...(resourceMap && { resources: resourceMap }),+ ...(zipFileHash && { zipFileHash }),+ });+ log('importFromUrl: updated skill id=%s', skill.id);+ return { skill, status: 'updated' };+ }++ // 10. Create new skill record+ log('importFromUrl: creating new skill...');+ const skill = await this.skillModel.create({+ content: skillContent,+ description: manifest.description,+ identifier,+ manifest: fullManifest,+ name: manifest.name,+ ...(resourceMap && { resources: resourceMap }),+ source: 'market', // URL source marked as market+ ...(zipFileHash && { zipFileHash }),+ });+ log('importFromUrl: created skill id=%s', skill.id);+ return { skill, status: 'created' };+ }+}diff --git a/src/server/services/skill/index.ts b/src/server/services/skill/index.tsnew file mode 100644index 00000000000..9d495a90847--- /dev/null+++ b/src/server/services/skill/index.ts@@ -0,0 +1,4 @@+export * from './errors';+export * from './importer';+export * from './parser';+export * from './resource';diff --git a/src/server/services/skill/parser.test.ts b/src/server/services/skill/parser.test.tsnew file mode 100644index 00000000000..6ae17230970--- /dev/null+++ b/src/server/services/skill/parser.test.ts@@ -0,0 +1,725 @@+import { unzip, zip } from 'fflate';+import { sha256 } from 'js-sha256';+import { mkdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { SkillManifestError, SkillParseError } from './errors';+import { SkillParser } from './parser';++const createZip = (files: Record<string, Uint8Array>): Promise<Uint8Array> => {+ return new Promise((resolve, reject) => {+ zip(files, (error, data) => {+ if (error) reject(error);+ else resolve(data);+ });+ });+};++const extractZip = (data: Uint8Array): Promise<Record<string, Uint8Array>> => {+ return new Promise((resolve, reject) => {+ unzip(data, (error, unzipped) => {+ if (error) reject(error);+ else resolve(unzipped);+ });+ });+};++describe('SkillParser', () => {+ const parser = new SkillParser();++ describe('parseSkillMd', () => {+ it('should parse valid SKILL.md with frontmatter', () => {+ const content = `---+name: test-skill+description: A test skill+version: 1.0.0+---+# Test Skill++This is a test skill.`;++ const result = parser.parseSkillMd(content);++ expect(result.manifest.name).toBe('test-skill');+ expect(result.manifest.description).toBe('A test skill');+ expect(result.manifest.version).toBe('1.0.0');+ expect(result.content).toContain('# Test Skill');+ expect(result.raw).toBe(content);+ });++ it('should parse SKILL.md with optional author field', () => {+ const content = `---+name: test-skill+description: A test skill+author:+ name: John Doe+ url: https://example.com+---+Content`;++ const result = parser.parseSkillMd(content);++ expect(result.manifest.author).toEqual({+ name: 'John Doe',+ url: 'https://example.com',+ });+ });++ it('should parse SKILL.md with permissions', () => {+ const content = `---+name: test-skill+description: A test skill+permissions:+ - read_files+ - execute_code+---+Content`;++ const result = parser.parseSkillMd(content);++ expect(result.manifest.permissions).toEqual(['read_files', 'execute_code']);+ });++ it('should allow custom fields via passthrough', () => {+ const content = `---+name: test-skill+description: A test skill+customField: customValue+---+Content`;++ const result = parser.parseSkillMd(content);++ expect((result.manifest as any).customField).toBe('customValue');+ });++ it('should throw SkillManifestError for missing required name', () => {+ const content = `---+description: A test skill+---+Content`;++ expect(() => parser.parseSkillMd(content)).toThrow(SkillManifestError);+ });++ it('should throw SkillManifestError for missing required description', () => {+ const content = `---+name: test-skill+---+Content`;++ expect(() => parser.parseSkillMd(content)).toThrow(SkillManifestError);+ });++ it('should throw SkillManifestError for empty name', () => {+ const content = `---+name: ""+description: A test skill+---+Content`;++ expect(() => parser.parseSkillMd(content)).toThrow(SkillManifestError);+ });++ it('should trim content', () => {+ const content = `---+name: test+description: test+---++ Content with whitespace++`;++ const result = parser.parseSkillMd(content);++ expect(result.content).toBe('Content with whitespace');+ });+ });++ describe('validateManifest', () => {+ it('should validate valid manifest', () => {+ const data = {+ description: 'A test skill',+ name: 'test-skill',+ version: '1.0.0',+ };++ const result = parser.validateManifest(data);++ expect(result.name).toBe('test-skill');+ expect(result.description).toBe('A test skill');+ });++ it('should validate manifest with repository URL', () => {+ const data = {+ description: 'A test skill',+ name: 'test-skill',+ repository: 'https://github.com/lobehub/skills',+ };++ const result = parser.validateManifest(data);++ expect(result.repository).toBe('https://github.com/lobehub/skills');+ });++ it('should throw for invalid author URL', () => {+ const data = {+ author: {+ name: 'John',+ url: 'not-a-url',+ },+ description: 'A test skill',+ name: 'test-skill',+ };++ expect(() => parser.validateManifest(data)).toThrow(SkillManifestError);+ });+ });++ describe('parseZipPackage', () => {+ it('should parse ZIP with SKILL.md in root', async () => {+ const skillMd = `---+name: test-skill+description: A test skill+---+# Test Content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ 'resource.txt': new TextEncoder().encode('Resource content'),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.manifest.name).toBe('test-skill');+ expect(result.content).toBe('# Test Content');+ expect(result.resources.has('resource.txt')).toBe(true);+ expect(result.resources.get('resource.txt')?.toString()).toBe('Resource content');+ expect(result.zipHash).toBeDefined();+ expect(result.zipHash).toHaveLength(64); // SHA-256 hex length+ });++ it('should parse ZIP with SKILL.md in subdirectory', async () => {+ const skillMd = `---+name: nested-skill+description: A nested skill+---+Nested content`;++ const testFiles = {+ 'my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'my-skill/assets/image.png': new TextEncoder().encode('PNG data'),+ 'my-skill/lib/helper.js': new TextEncoder().encode('helper code'),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.manifest.name).toBe('nested-skill');+ expect(result.resources.has('assets/image.png')).toBe(true);+ expect(result.resources.has('lib/helper.js')).toBe(true);+ // SKILL.md should not be in resources+ expect(result.resources.has('SKILL.md')).toBe(false);+ });++ it('should skip __MACOSX files', async () => {+ const skillMd = `---+name: test+description: test+---+Content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ '__MACOSX/._SKILL.md': new TextEncoder().encode('Mac metadata'),+ '__MACOSX/._resource.txt': new TextEncoder().encode('More metadata'),+ 'resource.txt': new TextEncoder().encode('Real content'),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.resources.has('resource.txt')).toBe(true);+ expect(result.resources.has('__MACOSX/._SKILL.md')).toBe(false);+ expect(result.resources.has('__MACOSX/._resource.txt')).toBe(false);+ });++ it('should skip hidden files', async () => {+ const skillMd = `---+name: test+description: test+---+Content`;++ const testFiles = {+ '.hidden': new TextEncoder().encode('Hidden file'),+ '.gitignore': new TextEncoder().encode('*.log'),+ 'SKILL.md': new TextEncoder().encode(skillMd),+ 'visible.txt': new TextEncoder().encode('Visible'),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.resources.has('visible.txt')).toBe(true);+ expect(result.resources.has('.hidden')).toBe(false);+ expect(result.resources.has('.gitignore')).toBe(false);+ });++ it('should skip files outside skill directory when SKILL.md is in subdirectory', async () => {+ const skillMd = `---+name: test+description: test+---+Content`;++ const testFiles = {+ 'README.md': new TextEncoder().encode('Root readme'),+ 'my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'my-skill/resource.txt': new TextEncoder().encode('Skill resource'),+ 'other-folder/file.txt': new TextEncoder().encode('Other file'),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.resources.has('resource.txt')).toBe(true);+ expect(result.resources.has('README.md')).toBe(false);+ expect(result.resources.has('other-folder/file.txt')).toBe(false);+ });++ it('should throw SkillParseError when SKILL.md is not found', async () => {+ const testFiles = {+ 'README.md': new TextEncoder().encode('No skill here'),+ 'some-file.txt': new TextEncoder().encode('Just a file'),+ };++ const zipped = await createZip(testFiles);++ await expect(parser.parseZipPackage(Buffer.from(zipped))).rejects.toThrow(SkillParseError);+ await expect(parser.parseZipPackage(Buffer.from(zipped))).rejects.toThrow(+ 'SKILL.md not found',+ );+ });++ it('should throw SkillParseError for invalid ZIP', async () => {+ const invalidBuffer = Buffer.from([1, 2, 3, 4]);++ await expect(parser.parseZipPackage(invalidBuffer)).rejects.toThrow(SkillParseError);+ });++ it('should throw SkillManifestError for invalid manifest in ZIP', async () => {+ const skillMd = `---+invalid: true+---+Content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ };++ const zipped = await createZip(testFiles);++ await expect(parser.parseZipPackage(Buffer.from(zipped))).rejects.toThrow(SkillManifestError);+ });++ it('should calculate consistent zipHash', async () => {+ const skillMd = `---+name: test+description: test+---+Content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ };++ const zipped = await createZip(testFiles);+ const buffer = Buffer.from(zipped);++ const result1 = await parser.parseZipPackage(buffer);+ const result2 = await parser.parseZipPackage(buffer);++ expect(result1.zipHash).toBe(result2.zipHash);+ });++ it('should handle empty resource set', async () => {+ const skillMd = `---+name: test+description: test+---+Only SKILL.md`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.resources.size).toBe(0);+ });++ it('should prefer root SKILL.md over subdirectory SKILL.md', async () => {+ const rootSkillMd = `---+name: root-skill+description: Root skill+---+Root content`;++ const nestedSkillMd = `---+name: nested-skill+description: Nested skill+---+Nested content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(rootSkillMd),+ 'nested/SKILL.md': new TextEncoder().encode(nestedSkillMd),+ };++ const zipped = await createZip(testFiles);+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.manifest.name).toBe('root-skill');+ });++ // When importing from GitHub URL like https://github.com/openclaw/openclaw/tree/main/skills/skill-creator,+ // the downloaded ZIP has structure: openclaw-main/skills/skill-creator/SKILL.md+ // parseZipPackage should accept a basePath parameter to look in the correct subdirectory+ it('should find SKILL.md in deep subdirectory when basePath is provided (GitHub subdirectory import)', async () => {+ const skillMd = `---+name: skill-creator+description: A skill in deep subdirectory+---+Deep nested content`;++ // Simulate GitHub ZIP structure: repo-branch/path/to/skill/SKILL.md+ const testFiles = {+ 'openclaw-main/README.md': new TextEncoder().encode('# OpenClaw'),+ 'openclaw-main/skills/other-skill/SKILL.md': new TextEncoder().encode(+ '---\nname: other\ndescription: other\n---\nOther',+ ),+ 'openclaw-main/skills/skill-creator/SKILL.md': new TextEncoder().encode(skillMd),+ 'openclaw-main/skills/skill-creator/resources/template.md': new TextEncoder().encode(+ 'Template',+ ),+ };++ const zipped = await createZip(testFiles);++ // parseZipPackage should accept a basePath parameter to specify which subdirectory to look in+ const result = await parser.parseZipPackage(Buffer.from(zipped), {+ basePath: 'skills/skill-creator',+ });++ expect(result.manifest.name).toBe('skill-creator');+ expect(result.content).toBe('Deep nested content');+ expect(result.resources.has('resources/template.md')).toBe(true);+ });++ it('should work with basePath having leading/trailing slashes', async () => {+ const skillMd = `---+name: test-skill+description: Test skill+---+Content`;++ const testFiles = {+ 'repo-main/path/to/skill/SKILL.md': new TextEncoder().encode(skillMd),+ };++ const zipped = await createZip(testFiles);++ // Test with leading slash+ const result1 = await parser.parseZipPackage(Buffer.from(zipped), {+ basePath: '/path/to/skill/',+ });+ expect(result1.manifest.name).toBe('test-skill');++ // Test with trailing slash+ const result2 = await parser.parseZipPackage(Buffer.from(zipped), {+ basePath: 'path/to/skill/',+ });+ expect(result2.manifest.name).toBe('test-skill');+ });++ it('should fallback to default behavior when basePath is not provided', async () => {+ const skillMd = `---+name: root-skill+description: Root skill+---+Root content`;++ const testFiles = {+ 'repo-main/SKILL.md': new TextEncoder().encode(skillMd),+ 'repo-main/nested/SKILL.md': new TextEncoder().encode(+ '---\nname: nested\ndescription: nested\n---\nNested',+ ),+ };++ const zipped = await createZip(testFiles);++ // Without basePath, should find the first-level SKILL.md+ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.manifest.name).toBe('root-skill');+ });+ });++ describe('parseZipPackage with repackSkillZip', () => {+ it('should not return skillZipBuffer when repackSkillZip is false/undefined', async () => {+ const skillMd = `---+name: user-skill+description: User uploaded skill+---+User skill content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ 'resource.txt': new TextEncoder().encode('Resource content'),+ };++ const zipped = await createZip(testFiles);+ const buffer = Buffer.from(zipped);++ const result = await parser.parseZipPackage(buffer);++ expect(result.skillZipBuffer).toBeUndefined();+ // zipHash should be the hash of the original ZIP+ expect(result.zipHash).toBe(sha256(buffer));+ });++ it('should return repacked skillZipBuffer when repackSkillZip is true', async () => {+ const skillMd = `---+name: github-skill+description: GitHub imported skill+---+GitHub skill content`;++ // Simulate large GitHub repo ZIP with skill in subdirectory+ const testFiles = {+ 'repo-main/LICENSE': new TextEncoder().encode('MIT License text...'),+ 'repo-main/README.md': new TextEncoder().encode('# Large Repository\n'.repeat(1000)),+ 'repo-main/other-folder/large-file.txt': new TextEncoder().encode('x'.repeat(10000)),+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'repo-main/skills/my-skill/resources/template.md': new TextEncoder().encode('Template'),+ };++ const zipped = await createZip(testFiles);+ const buffer = Buffer.from(zipped);++ const result = await parser.parseZipPackage(buffer, {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });++ expect(result.skillZipBuffer).toBeDefined();+ // zipHash should be the hash of the repacked ZIP, not the original+ expect(result.zipHash).toBe(sha256(result.skillZipBuffer!));+ expect(result.zipHash).not.toBe(sha256(buffer));+ // skillZipBuffer should be much smaller than original ZIP+ expect(result.skillZipBuffer!.length).toBeLessThan(buffer.length);+ });++ it('should produce consistent hash for same skill content even when repo changes', async () => {+ const skillMd = `---+name: stable-skill+description: Skill with stable content+---+Stable content`;++ // V1: Original repo+ const testFilesV1 = {+ 'repo-main/README.md': new TextEncoder().encode('# Version 1'),+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'repo-main/skills/my-skill/resource.txt': new TextEncoder().encode('Resource'),+ };++ // V2: Repo changed (README updated), but skill directory unchanged+ const testFilesV2 = {+ 'repo-main/CHANGELOG.md': new TextEncoder().encode('# Changelog\n- Added feature'),+ 'repo-main/README.md': new TextEncoder().encode('# Version 2 - Updated!'),+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'repo-main/skills/my-skill/resource.txt': new TextEncoder().encode('Resource'),+ };++ const zippedV1 = await createZip(testFilesV1);+ const zippedV2 = await createZip(testFilesV2);++ const result1 = await parser.parseZipPackage(Buffer.from(zippedV1), {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });+ const result2 = await parser.parseZipPackage(Buffer.from(zippedV2), {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });++ // Same skill content should produce same hash+ expect(result1.zipHash).toBe(result2.zipHash);+ });++ it('should produce different hash when skill content changes', async () => {+ const skillMdV1 = `---+name: changing-skill+description: Version 1+---+Content V1`;++ const skillMdV2 = `---+name: changing-skill+description: Version 2+---+Content V2 with updates`;++ const testFilesV1 = {+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMdV1),+ };++ const testFilesV2 = {+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMdV2),+ };++ const zippedV1 = await createZip(testFilesV1);+ const zippedV2 = await createZip(testFilesV2);++ const result1 = await parser.parseZipPackage(Buffer.from(zippedV1), {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });+ const result2 = await parser.parseZipPackage(Buffer.from(zippedV2), {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });++ // Different skill content should produce different hash+ expect(result1.zipHash).not.toBe(result2.zipHash);+ });++ it('repacked ZIP should contain only skill files', async () => {+ const skillMd = `---+name: isolated-skill+description: Isolated skill+---+Skill content`;++ const testFiles = {+ 'repo-main/LICENSE': new TextEncoder().encode('MIT'),+ 'repo-main/README.md': new TextEncoder().encode('# Repo README'),+ 'repo-main/other-skill/SKILL.md': new TextEncoder().encode(+ '---\nname: other\ndescription: other\n---\nOther',+ ),+ 'repo-main/skills/my-skill/SKILL.md': new TextEncoder().encode(skillMd),+ 'repo-main/skills/my-skill/docs/guide.md': new TextEncoder().encode('Guide'),+ 'repo-main/skills/my-skill/examples/example.md': new TextEncoder().encode('Example'),+ };++ const zipped = await createZip(testFiles);++ const result = await parser.parseZipPackage(Buffer.from(zipped), {+ basePath: 'skills/my-skill',+ repackSkillZip: true,+ });++ // Extract the repacked ZIP and verify contents+ const unzipped = await extractZip(result.skillZipBuffer!);+ const files = Object.keys(unzipped);++ // Should contain SKILL.md and skill resources+ expect(files).toContain('SKILL.md');+ expect(files).toContain('docs/guide.md');+ expect(files).toContain('examples/example.md');++ // Should NOT contain repo root files or other skills+ expect(files).not.toContain('LICENSE');+ expect(files).not.toContain('README.md');+ expect(files).not.toContain('repo-main/LICENSE');+ expect(files).not.toContain('other-skill/SKILL.md');+ });++ it('should work with root SKILL.md when repackSkillZip is true', async () => {+ const skillMd = `---+name: root-skill+description: Root skill+---+Root content`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ 'resource.txt': new TextEncoder().encode('Resource'),+ };++ const zipped = await createZip(testFiles);+ const buffer = Buffer.from(zipped);++ const result = await parser.parseZipPackage(buffer, {+ repackSkillZip: true,+ });++ expect(result.skillZipBuffer).toBeDefined();+ expect(result.zipHash).toBe(sha256(result.skillZipBuffer!));++ // Verify repacked content+ const unzipped = await extractZip(result.skillZipBuffer!);+ expect(Object.keys(unzipped)).toContain('SKILL.md');+ expect(Object.keys(unzipped)).toContain('resource.txt');+ });+ });++ describe('parseZipFile', () => {+ const testDir = join(tmpdir(), 'skill-parser-test');+ let testZipPath: string;++ beforeAll(async () => {+ await mkdir(testDir, { recursive: true });++ const skillMd = `---+name: file-test-skill+description: A skill from file+---+Content from file`;++ const testFiles = {+ 'SKILL.md': new TextEncoder().encode(skillMd),+ 'resource.txt': new TextEncoder().encode('Resource content'),+ };++ const zipped = await createZip(testFiles);+ testZipPath = join(testDir, 'test-skill.zip');+ await writeFile(testZipPath, zipped);+ });++ afterAll(async () => {+ await rm(testDir, { force: true, recursive: true });+ });++ it('should parse ZIP file from path', async () => {+ const result = await parser.parseZipFile(testZipPath);++ expect(result.manifest.name).toBe('file-test-skill');+ expect(result.manifest.description).toBe('A skill from file');+ expect(result.content).toBe('Content from file');+ expect(result.resources.has('resource.txt')).toBe(true);+ expect(result.zipHash).toBeDefined();+ });++ it('should throw SkillParseError for non-existent file', async () => {+ const nonExistentPath = join(testDir, 'non-existent.zip');++ await expect(parser.parseZipFile(nonExistentPath)).rejects.toThrow(SkillParseError);+ await expect(parser.parseZipFile(nonExistentPath)).rejects.toThrow('Failed to read ZIP file');+ });++ it('should throw SkillParseError for invalid ZIP file', async () => {+ const invalidZipPath = join(testDir, 'invalid.zip');+ await writeFile(invalidZipPath, Buffer.from([1, 2, 3, 4]));++ await expect(parser.parseZipFile(invalidZipPath)).rejects.toThrow(SkillParseError);+ });+ });+});diff --git a/src/server/services/skill/parser.ts b/src/server/services/skill/parser.tsnew file mode 100644index 00000000000..894606d6292--- /dev/null+++ b/src/server/services/skill/parser.ts@@ -0,0 +1,293 @@+import {+ type ParsedSkill,+ type ParsedZipSkill,+ type SkillManifest,+ skillManifestSchema,+} from '@lobechat/types';+import { unzip as fflateUnzip, zip as fflateZip } from 'fflate';+import matter from 'gray-matter';+import { sha256 } from 'js-sha256';+import { readFile } from 'node:fs/promises';++import { SkillManifestError, SkillParseError } from './errors';++export interface ParseZipOptions {+ /**+ * Base path within the ZIP to look for SKILL.md+ * Used when importing from GitHub subdirectory URLs like:+ * https://github.com/owner/repo/tree/main/skills/skill-name+ */+ basePath?: string;+ /**+ * Whether to repack only the skill directory into a new ZIP+ * Used for GitHub imports to avoid storing the entire repo ZIP+ * When true:+ * - skillZipBuffer will contain the repacked skill directory+ * - zipHash will be the hash of the repacked ZIP (not the original)+ */+ repackSkillZip?: boolean;+}++export class SkillParser {+ /**+ * Parse SKILL.md file content+ * @param fileContent - Raw content of SKILL.md file+ * @returns Parsed manifest, content and raw content+ */+ parseSkillMd(fileContent: string): ParsedSkill {+ try {+ const { data, content } = matter(fileContent);+ const manifest = this.validateManifest(data);++ return {+ content: content.trim(),+ manifest,+ raw: fileContent,+ };+ } catch (error) {+ if (error instanceof SkillManifestError) throw error;+ throw new SkillParseError('Failed to parse SKILL.md', error as Error);+ }+ }++ /**+ * Parse ZIP file from path+ * @param filePath - Path to ZIP file+ * @returns Parsed manifest, content, resource file mapping and ZIP hash+ */+ async parseZipFile(filePath: string): Promise<ParsedZipSkill> {+ try {+ const buffer = await readFile(filePath);+ return this.parseZipPackage(buffer);+ } catch (error) {+ if (error instanceof SkillParseError || error instanceof SkillManifestError) {+ throw error;+ }+ throw new SkillParseError(`Failed to read ZIP file: ${filePath}`, error as Error);+ }+ }++ /**+ * Parse ZIP package+ * @param buffer - ZIP file Buffer+ * @param options - Optional parsing options including basePath for subdirectory imports+ * @returns Parsed manifest, content, resource file mapping and ZIP hash+ */+ async parseZipPackage(buffer: Buffer, options?: ParseZipOptions): Promise<ParsedZipSkill> {+ try {+ const unzipped = await this.unzipBuffer(buffer);++ // Find SKILL.md (support root directory, first-level subdirectory, or specified basePath)+ const { skillMdContent, skillMdPath } = this.findSkillMd(unzipped, options?.basePath);+ if (!skillMdPath) {+ throw new SkillParseError('SKILL.md not found in zip package');+ }++ // Parse SKILL.md+ const { content, manifest } = this.parseSkillMd(skillMdContent);++ // Extract resource files+ const resources = this.extractResources(unzipped, skillMdPath);++ // If repackSkillZip is true, create a new ZIP with only the skill files+ if (options?.repackSkillZip) {+ const skillZipBuffer = await this.repackSkillZip(skillMdContent, resources);+ const zipHash = sha256(skillZipBuffer);+ return { content, manifest, resources, skillZipBuffer, zipHash };+ }++ // Calculate ZIP hash from original buffer+ const zipHash = sha256(buffer);++ return { content, manifest, resources, zipHash };+ } catch (error) {+ if (error instanceof SkillParseError || error instanceof SkillManifestError) {+ throw error;+ }+ throw new SkillParseError('Failed to parse ZIP package', error as Error);+ }+ }++ /**+ * Validate manifest data+ */+ validateManifest(data: unknown): SkillManifest {+ const result = skillManifestSchema.safeParse(data);+ if (!result.success) {+ throw new SkillManifestError(+ 'Invalid skill manifest: ' + result.error.issues.map((i) => i.message).join(', '),+ result.error,+ );+ }+ return result.data;+ }++ /**+ * Unzip Buffer using fflate+ */+ private unzipBuffer(buffer: Buffer): Promise<Record<string, Uint8Array>> {+ return new Promise((resolve, reject) => {+ fflateUnzip(new Uint8Array(buffer), (error, unzipped) => {+ if (error) reject(new SkillParseError('Failed to unzip buffer', error));+ else resolve(unzipped);+ });+ });+ }++ /**+ * Repack skill directory into a new ZIP+ * Creates a ZIP containing only SKILL.md and resources with normalized paths+ * Uses fixed mtime to ensure deterministic output (same content = same hash)+ */+ private repackSkillZip(skillMdContent: string, resources: Map<string, Buffer>): Promise<Buffer> {+ return new Promise((resolve, reject) => {+ // Use fixed timestamp (1980-01-01) for deterministic output+ // ZIP format requires dates in 1980-2099 range+ const fixedMtime = new Date('1980-01-01T00:00:00Z');++ // Use Zippable format with fixed mtime for deterministic output+ const files: Record<string, [Uint8Array, { mtime: Date }]> = {+ 'SKILL.md': [new TextEncoder().encode(skillMdContent), { mtime: fixedMtime }],+ };++ // Add all resources with their relative paths (sorted for determinism)+ const sortedPaths = [...resources.keys()].sort();+ for (const path of sortedPaths) {+ files[path] = [new Uint8Array(resources.get(path)!), { mtime: fixedMtime }];+ }++ fflateZip(files, { level: 6 }, (error, data) => {+ if (error) reject(new SkillParseError('Failed to repack skill ZIP', error));+ else resolve(Buffer.from(data));+ });+ });+ }++ /**+ * Find SKILL.md file+ * Supports:+ * - Root directory: SKILL.md+ * - First-level subdirectory: skill-name/SKILL.md+ * - GitHub subdirectory with basePath: repo-branch/basePath/SKILL.md+ */+ private findSkillMd(+ unzipped: Record<string, Uint8Array>,+ basePath?: string,+ ): {+ skillMdContent: string;+ skillMdPath: string | null;+ } {+ const decoder = new TextDecoder();++ // If basePath is provided (GitHub subdirectory import), look in that specific path+ if (basePath) {+ // GitHub ZIP structure: {repo}-{branch}/path/to/SKILL.md+ // We need to find the root directory prefix first (e.g., "openclaw-main/")+ const allPaths = Object.keys(unzipped);+ const rootPrefix = this.findGitHubRootPrefix(allPaths);++ if (rootPrefix) {+ // Construct the full path: rootPrefix + basePath + /SKILL.md+ const normalizedBasePath = basePath.replaceAll(/^\/|\/$/g, ''); // Remove leading/trailing slashes+ const targetPath = `${rootPrefix}${normalizedBasePath}/SKILL.md`;++ if (unzipped[targetPath]) {+ return {+ skillMdContent: decoder.decode(unzipped[targetPath]),+ skillMdPath: targetPath,+ };+ }+ }++ // Fallback: try to find SKILL.md that contains the basePath+ const basePathPattern = new RegExp(+ `^[^/]+/${basePath.replaceAll(/^\/|\/$/g, '')}/SKILL\\.md$`,+ );+ const matchWithBasePath = allPaths.find((path) => basePathPattern.test(path));++ if (matchWithBasePath) {+ return {+ skillMdContent: decoder.decode(unzipped[matchWithBasePath]),+ skillMdPath: matchWithBasePath,+ };+ }+ }++ // Check root directory first+ if (unzipped['SKILL.md']) {+ return {+ skillMdContent: decoder.decode(unzipped['SKILL.md']),+ skillMdPath: 'SKILL.md',+ };+ }++ // Check first-level subdirectory+ const skillMdPattern = /^[^/]+\/SKILL\.md$/;+ const match = Object.keys(unzipped).find((path) => skillMdPattern.test(path));++ if (match) {+ return {+ skillMdContent: decoder.decode(unzipped[match]),+ skillMdPath: match,+ };+ }++ return { skillMdContent: '', skillMdPath: null };+ }++ /**+ * Find the GitHub ZIP root prefix (e.g., "repo-branch/")+ * GitHub ZIPs have structure: {repo}-{branch}/...+ */+ private findGitHubRootPrefix(paths: string[]): string | null {+ // Find first directory-like path+ for (const path of paths) {+ const firstSlash = path.indexOf('/');+ if (firstSlash > 0) {+ return path.slice(0, firstSlash + 1);+ }+ }+ return null;+ }++ /**+ * Extract resource files+ * Excludes SKILL.md itself, directories, hidden files and __MACOSX+ */+ private extractResources(+ unzipped: Record<string, Uint8Array>,+ skillMdPath: string,+ ): Map<string, Buffer> {+ const resources = new Map<string, Buffer>();++ // Determine base path (if SKILL.md is in subdirectory)+ const basePath = skillMdPath.includes('/')+ ? skillMdPath.slice(0, skillMdPath.lastIndexOf('/') + 1)+ : '';++ for (const [path, data] of Object.entries(unzipped)) {+ // Skip directories, hidden files, __MACOSX and SKILL.md+ if (+ path.endsWith('/') ||+ path.startsWith('.') ||+ path.includes('__MACOSX') ||+ path === skillMdPath+ ) {+ continue;+ }++ // Skip files outside base path+ if (basePath && !path.startsWith(basePath)) continue;++ // Calculate relative path+ const relativePath = basePath ? path.slice(basePath.length) : path;++ // Skip empty paths+ if (!relativePath) continue;++ resources.set(relativePath, Buffer.from(data));+ }++ return resources;+ }+}diff --git a/src/server/services/skill/resource.test.ts b/src/server/services/skill/resource.test.tsnew file mode 100644index 00000000000..1f1facb9b0c--- /dev/null+++ b/src/server/services/skill/resource.test.ts@@ -0,0 +1,255 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { SkillResourceService } from './resource';++// Create mock functions that can be inspected+const mockCreateGlobalFile = vi.fn().mockResolvedValue({ fileHash: 'mock-file-hash' });+const mockGetFileContentByHash = vi.fn().mockResolvedValue('file content');+const mockGetFileByteArrayByHash = vi+ .fn()+ .mockResolvedValue(new Uint8Array([0x89, 0x50, 0x4e, 0x47]));+const mockUploadBuffer = vi.fn().mockResolvedValue({ key: 'mock-key' });++// Mock FileService only (no longer need FileModel)+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ createGlobalFile: mockCreateGlobalFile,+ getFileByteArrayByHash: mockGetFileByteArrayByHash,+ getFileContentByHash: mockGetFileContentByHash,+ uploadBuffer: mockUploadBuffer,+ })),+}));++describe('SkillResourceService', () => {+ describe('listResources (buildTree)', () => {+ it('should build flat file list', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = {+ 'README.md': { fileHash: 'hash1', size: 100 },+ 'config.json': { fileHash: 'hash2', size: 200 },+ };++ const tree = await service.listResources(resources);++ expect(tree).toHaveLength(2);+ expect(tree[0]).toEqual({+ children: undefined,+ name: 'README.md',+ path: 'README.md',+ type: 'file',+ });+ expect(tree[1]).toEqual({+ children: undefined,+ name: 'config.json',+ path: 'config.json',+ type: 'file',+ });+ });++ it('should build nested directory structure', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = {+ 'lib/utils.ts': { fileHash: 'hash1', size: 100 },+ 'lib/helpers.ts': { fileHash: 'hash2', size: 200 },+ 'src/index.ts': { fileHash: 'hash3', size: 300 },+ };++ const tree = await service.listResources(resources);++ expect(tree).toHaveLength(2);++ // lib directory+ const libDir = tree.find((n) => n.name === 'lib');+ expect(libDir).toBeDefined();+ expect(libDir?.type).toBe('directory');+ expect(libDir?.children).toHaveLength(2);+ expect(libDir?.children?.map((c) => c.name).sort()).toEqual(['helpers.ts', 'utils.ts']);++ // src directory+ const srcDir = tree.find((n) => n.name === 'src');+ expect(srcDir).toBeDefined();+ expect(srcDir?.type).toBe('directory');+ expect(srcDir?.children).toHaveLength(1);+ expect(srcDir?.children?.[0].name).toBe('index.ts');+ });++ it('should build deeply nested structure', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = {+ 'a/b/c/d.txt': { fileHash: 'hash1', size: 100 },+ };++ const tree = await service.listResources(resources);++ expect(tree).toHaveLength(1);+ expect(tree[0].name).toBe('a');+ expect(tree[0].type).toBe('directory');+ expect(tree[0].children?.[0].name).toBe('b');+ expect(tree[0].children?.[0].children?.[0].name).toBe('c');+ expect(tree[0].children?.[0].children?.[0].children?.[0].name).toBe('d.txt');+ expect(tree[0].children?.[0].children?.[0].children?.[0].type).toBe('file');+ });++ it('should handle mixed files and directories', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = {+ 'README.md': { fileHash: 'hash1', size: 100 },+ 'lib/index.ts': { fileHash: 'hash2', size: 200 },+ 'lib/utils/helper.ts': { fileHash: 'hash3', size: 300 },+ };++ const tree = await service.listResources(resources);++ expect(tree).toHaveLength(2);++ // README.md at root+ const readme = tree.find((n) => n.name === 'README.md');+ expect(readme?.type).toBe('file');++ // lib directory with nested utils+ const lib = tree.find((n) => n.name === 'lib');+ expect(lib?.type).toBe('directory');+ expect(lib?.children).toHaveLength(2);++ const utils = lib?.children?.find((n) => n.name === 'utils');+ expect(utils?.type).toBe('directory');+ expect(utils?.children?.[0].name).toBe('helper.ts');+ });++ it('should handle empty resources', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const tree = await service.listResources({});++ expect(tree).toEqual([]);+ });++ it('should sort paths alphabetically', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = {+ 'z.txt': { fileHash: 'hash1', size: 100 },+ 'a.txt': { fileHash: 'hash2', size: 200 },+ 'm.txt': { fileHash: 'hash3', size: 300 },+ };++ const tree = await service.listResources(resources);++ expect(tree.map((n) => n.name)).toEqual(['a.txt', 'm.txt', 'z.txt']);+ });+ });++ describe('storeResources', () => {+ beforeEach(() => {+ mockCreateGlobalFile.mockClear();+ mockUploadBuffer.mockClear();+ });++ it('should store resources with zipHash prefix and return SkillResourceMeta', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map([+ ['README.md', Buffer.from('# README')],+ ['lib/utils.ts', Buffer.from('export const util = 1')],+ ]);++ const result = await service.storeResources('abc123hash', resources);++ expect(Object.keys(result)).toHaveLength(2);+ // Result should be Record<VirtualPath, SkillResourceMeta>+ expect(result['README.md']).toHaveProperty('fileHash');+ expect(result['README.md'].fileHash).toHaveLength(64); // sha256 hash length+ expect(result['lib/utils.ts']).toHaveProperty('fileHash');+ expect(result['lib/utils.ts'].fileHash).toHaveLength(64);+ });++ it('should pass correct metadata to createGlobalFile', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map([['docs/guide.md', Buffer.from('# Guide')]]);++ await service.storeResources('zip123', resources);++ expect(mockCreateGlobalFile).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'text/markdown',+ metadata: {+ dirname: 'skills/source_files/zip123/docs',+ filename: 'guide.md',+ path: 'skills/source_files/zip123/docs/guide.md',+ },+ url: 'skills/source_files/zip123/docs/guide.md',+ }),+ );+ });++ it('should pass correct metadata for root-level files', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map([['README.md', Buffer.from('# README')]]);++ await service.storeResources('zip456', resources);++ expect(mockCreateGlobalFile).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: {+ dirname: 'skills/source_files/zip456',+ filename: 'README.md',+ path: 'skills/source_files/zip456/README.md',+ },+ }),+ );+ });++ it('should handle empty resources', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = new Map<string, Buffer>();++ const result = await service.storeResources('abc123hash', resources);++ expect(result).toEqual({});+ });+ });++ describe('readResource', () => {+ it('should read text resource content with utf-8 encoding', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = { 'test.txt': { fileHash: 'abc123fileHash', size: 50 } };++ const result = await service.readResource(resources, 'test.txt');++ expect(result).toEqual({+ content: 'file content',+ encoding: 'utf-8',+ fileHash: 'abc123fileHash',+ fileType: 'text/plain',+ path: 'test.txt',+ size: Buffer.byteLength('file content', 'utf-8'),+ });+ expect(mockGetFileContentByHash).toHaveBeenCalledWith('abc123fileHash');+ });++ it('should read binary resource content with base64 encoding', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = { 'image.png': { fileHash: 'binaryFileHash', size: 1024 } };+ const binaryData = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);+ mockGetFileByteArrayByHash.mockResolvedValue(binaryData);++ const result = await service.readResource(resources, 'image.png');++ expect(result).toEqual({+ content: Buffer.from(binaryData).toString('base64'),+ encoding: 'base64',+ fileHash: 'binaryFileHash',+ fileType: 'image/png',+ path: 'image.png',+ size: binaryData.length,+ });+ expect(mockGetFileByteArrayByHash).toHaveBeenCalledWith('binaryFileHash');+ });++ it('should throw error for non-existent path', async () => {+ const service = new SkillResourceService({} as any, 'user-1');+ const resources = { 'test.txt': { fileHash: 'abc123fileHash', size: 50 } };++ await expect(service.readResource(resources, 'non-existent.txt')).rejects.toThrow(+ 'Resource not found: non-existent.txt',+ );+ });+ });+});diff --git a/src/server/services/skill/resource.ts b/src/server/services/skill/resource.tsnew file mode 100644index 00000000000..4ab7f31a877--- /dev/null+++ b/src/server/services/skill/resource.ts@@ -0,0 +1,248 @@+import { type LobeChatDatabase } from '@lobechat/database';+import {+ type SkillResourceContent,+ type SkillResourceMeta,+ type SkillResourceTreeNode,+} from '@lobechat/types';+import { getMimeType } from '@lobechat/utils';+import debug from 'debug';+import { sha256 } from 'js-sha256';++import { FileService } from '@/server/services/file';++import { SkillResourceError } from './errors';++const log = debug('lobe-chat:service:skill-resource');++function isTextMimeType(mimeType: string): boolean {+ if (mimeType.startsWith('text/')) return true;+ const textApplicationTypes = [+ 'application/json',+ 'application/xml',+ 'application/javascript',+ 'application/typescript',+ 'application/xhtml+xml',+ 'application/x-yaml',+ 'application/x-sh',+ ];+ return textApplicationTypes.includes(mimeType);+}++export class SkillResourceService {+ private fileService: FileService;++ constructor(db: LobeChatDatabase, userId: string) {+ this.fileService = new FileService(db, userId);+ }++ /**+ * Store resource files to S3/globalFiles+ * Uses zipHash as path prefix for deduplication+ * Only creates globalFiles records (no user files)+ *+ * @param zipHash - ZIP package hash for deduplication+ * @param resources - Resource file mapping Map<VirtualPath, Buffer>+ * @returns Record<VirtualPath, SkillResourceMeta> mapping+ */+ async storeResources(+ zipHash: string,+ resources: Map<string, Buffer>,+ ): Promise<Record<string, SkillResourceMeta>> {+ log('storeResources: starting with zipHash=%s, resourceCount=%d', zipHash, resources.size);+ const result: Record<string, SkillResourceMeta> = {};++ for (const [virtualPath, buffer] of resources) {+ log('storeResources: storing resource path=%s, size=%d bytes', virtualPath, buffer.length);+ const fileHash = await this.storeResource(zipHash, virtualPath, buffer);+ result[virtualPath] = { fileHash, size: buffer.length };+ log('storeResources: stored resource path=%s, fileHash=%s', virtualPath, fileHash);+ }++ log('storeResources: completed, stored %d resources', Object.keys(result).length);+ return result;+ }++ /**+ * Read resource file content by hash+ *+ * @param resources - Record<VirtualPath, SkillResourceMeta> mapping+ * @param virtualPath - Virtual path to read+ */+ async readResource(+ resources: Record<string, SkillResourceMeta>,+ virtualPath: string,+ ): Promise<SkillResourceContent> {+ log('readResource: reading path=%s, availablePaths=%o', virtualPath, Object.keys(resources));+ const meta = resources[virtualPath];+ if (!meta) {+ log('readResource: resource not found in mapping, path=%s', virtualPath);+ throw new SkillResourceError(`Resource not found: ${virtualPath}`);+ }+ log('readResource: found fileHash=%s', meta.fileHash);++ const fileType = getMimeType(virtualPath);++ if (isTextMimeType(fileType)) {+ const content = await this.fileService.getFileContentByHash(meta.fileHash);+ log('readResource: fetched text content length=%d, fileType=%s', content.length, fileType);++ return {+ content,+ encoding: 'utf-8',+ fileHash: meta.fileHash,+ fileType,+ path: virtualPath,+ size: Buffer.byteLength(content, 'utf-8'),+ };+ }++ const bytes = await this.fileService.getFileByteArrayByHash(meta.fileHash);+ const content = Buffer.from(bytes).toString('base64');+ log('readResource: fetched binary content size=%d, fileType=%s', bytes.length, fileType);++ return {+ content,+ encoding: 'base64',+ fileHash: meta.fileHash,+ fileType,+ path: virtualPath,+ size: bytes.length,+ };+ }++ /**+ * Build resource directory tree structure+ * When includeContent is true, also fetches text file contents (binary files are skipped)+ */+ async listResources(+ resources: Record<string, SkillResourceMeta>,+ includeContent?: boolean,+ ): Promise<SkillResourceTreeNode[]> {+ const paths = Object.keys(resources);+ log(+ 'listResources: building tree for %d paths, includeContent=%s',+ paths.length,+ includeContent,+ );+ const tree = this.buildTree(paths);+ log('listResources: built tree with %d root nodes', tree.length);++ if (includeContent) {+ await this.populateContent(tree, resources);+ }++ return tree;+ }++ // ===== Content Population =====++ /**+ * Recursively populate text file content into tree nodes+ */+ private async populateContent(+ nodes: SkillResourceTreeNode[],+ resources: Record<string, SkillResourceMeta>,+ ): Promise<void> {+ const fileNodes: SkillResourceTreeNode[] = [];+ const collectFiles = (items: SkillResourceTreeNode[]) => {+ for (const node of items) {+ if (node.type === 'file') {+ fileNodes.push(node);+ } else if (node.children) {+ collectFiles(node.children);+ }+ }+ };+ collectFiles(nodes);++ await Promise.all(+ fileNodes.map(async (node) => {+ const meta = resources[node.path];+ if (!meta) return;++ const mimeType = getMimeType(node.path);+ if (!isTextMimeType(mimeType)) return;++ try {+ node.content = await this.fileService.getFileContentByHash(meta.fileHash);+ } catch (error) {+ log('populateContent: failed to read content for %s: %o', node.path, error);+ }+ }),+ );+ }++ // ===== Private Methods =====++ private async storeResource(+ zipHash: string,+ virtualPath: string,+ buffer: Buffer,+ ): Promise<string> {+ // Use zipHash as path prefix, same ZIP resources share same path+ const key = `skills/source_files/${zipHash}/${virtualPath}`;+ log('storeResource: uploading to key=%s', key);++ // Determine content type from file extension+ const fileType = getMimeType(virtualPath);++ // Upload to S3 with proper content type (supports any file type, not just images)+ await this.fileService.uploadBuffer(key, buffer, fileType);+ log('storeResource: uploaded to S3 with contentType=%s', fileType);++ // Create globalFiles record only (no user files)+ const fileHash = sha256(buffer);+ log('storeResource: creating global file record hash=%s, type=%s', fileHash, fileType);++ // Extract filename and dirname from key (actual storage path)+ const lastSlash = key.lastIndexOf('/');+ const filename = lastSlash >= 0 ? key.slice(lastSlash + 1) : key;+ const dirname = lastSlash >= 0 ? key.slice(0, lastSlash) : '';++ await this.fileService.createGlobalFile({+ fileHash,+ fileType,+ metadata: { dirname, filename, path: key },+ size: buffer.length,+ url: key,+ });++ log('storeResource: created global file record fileHash=%s', fileHash);+ return fileHash;+ }++ private buildTree(paths: string[]): SkillResourceTreeNode[] {+ const root: SkillResourceTreeNode[] = [];+ const nodeMap = new Map<string, SkillResourceTreeNode>();++ for (const path of [...paths].sort()) {+ const parts = path.split('/');+ let currentPath = '';+ let currentLevel = root;++ for (let i = 0; i < parts.length; i++) {+ const part = parts[i];+ const isFile = i === parts.length - 1;+ currentPath = currentPath ? `${currentPath}/${part}` : part;++ let node = nodeMap.get(currentPath);+ if (!node) {+ node = {+ children: isFile ? undefined : [],+ name: part,+ path: currentPath,+ type: isFile ? 'file' : 'directory',+ };+ nodeMap.set(currentPath, node);+ currentLevel.push(node);+ }++ if (!isFile && node.children) {+ currentLevel = node.children;+ }+ }+ }++ return root;+ }+}diff --git a/src/server/services/toolExecution/builtin.ts b/src/server/services/toolExecution/builtin.tsindex dc936dac972..963b67f13cc 100644--- a/src/server/services/toolExecution/builtin.ts+++ b/src/server/services/toolExecution/builtin.ts@@ -58,7 +58,8 @@ export class BuiltinToolsExecutor implements IToolExecutor {throw new Error(`Builtin tool "${identifier}" is not implemented`);}- const runtime = getServerRuntime(identifier, context);+ // Await runtime in case factory is async+ const runtime = await getServerRuntime(identifier, context);if (!runtime[apiName]) {throw new Error(`Builtin tool ${identifier}'s ${apiName} is not implemented`);diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex dcc6c041d59..42b1e0e430f 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -9,6 +9,7 @@import { type ToolExecutionContext } from '../types';import { cloudSandboxRuntime } from './cloudSandbox';import { notebookRuntime } from './notebook';+import { skillsRuntime } from './skills';import { type ServerRuntimeFactory, type ServerRuntimeRegistration } from './types';import { webBrowsingRuntime } from './webBrowsing';@@ -27,7 +28,7 @@ const registerRuntimes = (runtimes: ServerRuntimeRegistration[]) => {};// Register all server runtimes-registerRuntimes([webBrowsingRuntime, cloudSandboxRuntime, notebookRuntime]);+registerRuntimes([webBrowsingRuntime, cloudSandboxRuntime, notebookRuntime, skillsRuntime]);// ==================== Registry API ====================@@ -35,8 +36,12 @@ registerRuntimes([webBrowsingRuntime, cloudSandboxRuntime, notebookRuntime]);* Get a server runtime by identifier* @param identifier - The tool identifier* @param context - Execution context (required for per-request runtimes)+ * @returns Runtime instance (may be a Promise for async factories)*/-export const getServerRuntime = (identifier: string, context: ToolExecutionContext): any => {+export const getServerRuntime = (+ identifier: string,+ context: ToolExecutionContext,+): any | Promise<any> => {const factory = serverRuntimeFactories.get(identifier);return factory?.(context);};diff --git a/src/server/services/toolExecution/serverRuntimes/skills.ts b/src/server/services/toolExecution/serverRuntimes/skills.tsnew file mode 100644index 00000000000..b8832a19c6f--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/skills.ts@@ -0,0 +1,358 @@+import { builtinSkills } from '@lobechat/builtin-skills';+import {+ type CommandResult,+ type MarketSkillItem,+ type SearchSkillParams,+ SkillsIdentifier,+} from '@lobechat/builtin-tool-skills';+import {+ type ExportFileResult,+ type SkillImportServiceResult,+ type SkillRuntimeService,+ SkillsExecutionRuntime,+} from '@lobechat/builtin-tool-skills/executionRuntime';+import type { SkillItem, SkillListItem, SkillResourceContent } from '@lobechat/types';+import type { CodeInterpreterToolName } from '@lobehub/market-sdk';+import debug from 'debug';+import { sha256 } from 'js-sha256';++import { AgentSkillModel } from '@/database/models/agentSkill';+import { FileModel } from '@/database/models/file';+import { UserModel } from '@/database/models/user';+import { FileS3 } from '@/server/modules/S3';+import { FileService } from '@/server/services/file';+import { MarketService } from '@/server/services/market';+import { SkillImporter } from '@/server/services/skill/importer';+import { SkillResourceService } from '@/server/services/skill/resource';++import { type ServerRuntimeRegistration } from './types';++const log = debug('lobe-server:skills-runtime');++class SkillServerRuntimeService implements SkillRuntimeService {+ private importer: SkillImporter;+ private resourceService: SkillResourceService;+ private skillModel: AgentSkillModel;+ private marketService: MarketService;+ private fileService: FileService;+ private fileModel: FileModel;+ private topicId?: string;+ private userId: string;++ constructor(options: {+ fileModel: FileModel;+ fileService: FileService;+ importer: SkillImporter;+ marketService: MarketService;+ resourceService: SkillResourceService;+ skillModel: AgentSkillModel;+ topicId?: string;+ userId: string;+ }) {+ this.skillModel = options.skillModel;+ this.resourceService = options.resourceService;+ this.importer = options.importer;+ this.marketService = options.marketService;+ this.fileService = options.fileService;+ this.fileModel = options.fileModel;+ this.topicId = options.topicId;+ this.userId = options.userId;+ }++ findAll = (): Promise<{ data: SkillListItem[]; total: number }> => {+ return this.skillModel.findAll();+ };++ findById = (id: string): Promise<SkillItem | undefined> => {+ return this.skillModel.findById(id);+ };++ findByName = (name: string): Promise<SkillItem | undefined> => {+ return this.skillModel.findByName(name);+ };++ importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {+ const result = await this.importer.importFromGitHub({ gitUrl });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ };++ importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {+ const result = await this.importer.importFromUrl({ url });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ };++ importFromZipUrl = async (url: string): Promise<SkillImportServiceResult> => {+ const result = await this.importer.importFromUrl({ url });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ };++ readResource = async (id: string, path: string): Promise<SkillResourceContent> => {+ const skill = await this.skillModel.findById(id);+ if (!skill) throw new Error(`Skill not found: ${id}`);+ if (!skill.resources) throw new Error(`Skill has no resources: ${id}`);+ return this.resourceService.readResource(skill.resources, path);+ };++ execScript = async (+ command: string,+ options: {+ config?: { description?: string; id?: string; name?: string };+ description: string;+ runInClient?: boolean;+ },+ ): Promise<CommandResult> => {+ const { config, description } = options;++ if (!this.topicId) {+ throw new Error('topicId is required for execScript');+ }++ try {+ // Look up skill zipUrl if config is provided (same logic as market.ts)+ let enhancedParams: any = {+ command,+ config,+ description,+ };++ if (config?.name) {+ const skill = await this.skillModel.findByName(config.name);++ // If skill not found, return error with available skills+ if (!skill) {+ const allSkills = await this.skillModel.findAll();+ const availableSkills = allSkills.data.map((s) => s.name).join(', ');++ const errorMessage = availableSkills+ ? `Skill "${config.name}" not found. Available skills: ${availableSkills}`+ : `Skill "${config.name}" not found. No skills available. Please import a skill first.`;++ log('Skill not found: %s. Available skills: %s', config.name, availableSkills);++ return {+ exitCode: 1,+ output: '',+ stderr: errorMessage,+ success: false,+ };+ }++ if (skill.zipFileHash) {+ // Get S3 key from globalFiles+ const fileInfo = await this.fileModel.checkHash(skill.zipFileHash);++ if (fileInfo.isExist && fileInfo.url) {+ // Convert S3 key to full URL+ const fullUrl = await this.fileService.getFullFileUrl(fileInfo.url);+ if (fullUrl) {+ enhancedParams.zipUrl = fullUrl;+ log('Added zipUrl to execScript params for skill %s: %s', skill.name, fullUrl);+ }+ }+ }+ }++ // Call market-sdk's runBuildInTool+ const market = this.marketService.market;+ const response = await market.plugins.runBuildInTool(+ 'execScript' as CodeInterpreterToolName,+ enhancedParams,+ { topicId: this.topicId, userId: this.userId },+ );++ log('execScript response: %O', response);++ if (!response.success) {+ return {+ exitCode: 1,+ output: '',+ stderr: response.error?.message || 'Command execution failed',+ success: false,+ };+ }++ const result = response.data?.result || {};++ return {+ exitCode: result.exitCode ?? (response.success ? 0 : 1),+ output: result.stdout || result.output || '',+ stderr: result.stderr || '',+ success: response.success && (result.exitCode === 0 || result.exitCode === undefined),+ };+ } catch (error) {+ log('Error executing script: %O', error);+ return {+ exitCode: 1,+ output: '',+ stderr: (error as Error).message || 'Command execution failed',+ success: false,+ };+ }+ };++ exportFile = async (path: string, filename: string): Promise<ExportFileResult> => {+ if (!this.topicId) {+ throw new Error('topicId is required for exportFile');+ }++ try {+ const s3 = new FileS3();++ // Use date-based sharding (same as market.ts)+ const today = new Date().toISOString().split('T')[0];+ const key = `code-interpreter-exports/${today}/${this.topicId}/${filename}`;++ // Step 1: Generate pre-signed upload URL+ const uploadUrl = await s3.createPreSignedUrl(key);+ log('Generated upload URL for key: %s', key);++ // Step 2: Call sandbox's exportFile tool with the upload URL+ const market = this.marketService.market;+ const response = await market.plugins.runBuildInTool(+ 'exportFile' as CodeInterpreterToolName,+ { path, uploadUrl },+ { topicId: this.topicId, userId: this.userId },+ );++ log('Sandbox exportFile response: %O', response);++ if (!response.success) {+ return {+ filename,+ success: false,+ };+ }++ const result = response.data?.result;+ const uploadSuccess = result?.success !== false;++ if (!uploadSuccess) {+ return {+ filename,+ success: false,+ };+ }++ // Step 3: Get file metadata from S3+ const metadata = await s3.getFileMetadata(key);+ const fileSize = metadata.contentLength;+ const mimeType = metadata.contentType || result?.mimeType || 'application/octet-stream';++ // Step 4: Create persistent file record+ const fileHash = sha256(key + Date.now().toString());++ const { fileId, url } = await this.fileService.createFileRecord({+ fileHash,+ fileType: mimeType,+ name: filename,+ size: fileSize,+ url: key, // Store S3 key+ });++ log('Created file record: fileId=%s, url=%s', fileId, url);++ return {+ fileId,+ filename,+ mimeType,+ size: fileSize,+ success: true,+ url, // This is the permanent /f:id URL+ };+ } catch (error) {+ log('Error exporting file: %O', error);+ return {+ filename,+ success: false,+ };+ }+ };++ searchSkill = async (+ params: SearchSkillParams,+ ): Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }> => {+ log('Searching skills with params: %O', params);++ try {+ const result = await this.marketService.searchSkill(params);+ log('Search skills result: %O', result);+ return result;+ } catch (error) {+ log('Error searching skills: %O', error);+ throw error;+ }+ };++ importFromMarket = async (identifier: string): Promise<SkillImportServiceResult> => {+ log('Importing skill from market: %s', identifier);++ try {+ // Get download URL and import ZIP+ // The ZIP contains SKILL.md (manifest + content) and resources+ // Everything is extracted and stored according to DB structure+ const downloadUrl = this.marketService.getSkillDownloadUrl(identifier);+ log('Download URL: %s', downloadUrl);++ const result = await this.importFromZipUrl(downloadUrl);+ log('Import from market result: %O', result);+ return result;+ } catch (error) {+ log('Error importing skill from market: %O', error);+ throw error;+ }+ };+}++/**+ * Skills Server Runtime+ * Per-request runtime (needs serverDB, userId, topicId)+ */+export const skillsRuntime: ServerRuntimeRegistration = {+ factory: async (context) => {+ if (!context.serverDB) {+ throw new Error('serverDB is required for Skills execution');+ }+ if (!context.userId) {+ throw new Error('userId is required for Skills execution');+ }++ // Fetch market access token from user settings+ let marketAccessToken: string | undefined;+ try {+ const userModel = new UserModel(context.serverDB, context.userId);+ const userSettings = await userModel.getUserSettings();+ marketAccessToken = (userSettings?.market as any)?.accessToken;+ log(+ 'Fetched market accessToken for user %s: %s',+ context.userId,+ marketAccessToken ? 'exists' : 'not found',+ );+ } catch (error) {+ log('Failed to fetch market accessToken for user %s: %O', context.userId, error);+ }++ const skillModel = new AgentSkillModel(context.serverDB, context.userId);+ const resourceService = new SkillResourceService(context.serverDB, context.userId);+ const importer = new SkillImporter(context.serverDB, context.userId);+ const marketService = new MarketService({+ accessToken: marketAccessToken,+ userInfo: { userId: context.userId },+ });+ const fileService = new FileService(context.serverDB, context.userId);+ const fileModel = new FileModel(context.serverDB, context.userId);++ const service = new SkillServerRuntimeService({+ fileModel,+ fileService,+ importer,+ marketService,+ resourceService,+ skillModel,+ topicId: context.topicId,+ userId: context.userId,+ });++ return new SkillsExecutionRuntime({ builtinSkills, service });+ },+ identifier: SkillsIdentifier,+};diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.tsindex cbc7f1a1bb1..77ce696f2b5 100644--- a/src/services/agentRuntime/index.ts+++ b/src/services/agentRuntime/index.ts@@ -49,6 +49,7 @@ class AgentRuntimeService {inputTemplate: chatConfig.inputTemplate,messages: data.messages as any,...modelRuntimeConfig,+ plugins: agentConfig.plugins,systemRole: agentConfig.systemRole,tools: enabledToolIds,});diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 9edf238fa06..c03a2875d76 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -133,6 +133,7 @@ class ChatService {chatConfig,enabledManifests = [],enabledToolIds = [],+ plugins,tools,} = resolvedAgentConfig;@@ -251,6 +252,7 @@ class ChatService {manifests: enabledManifests,messages,model: payload.model,+ plugins,provider: payload.provider!,sessionId: options?.trace?.sessionId,stepContext: options?.stepContext,diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex de451fb8249..9ddd6a26e6a 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -43,6 +43,7 @@ import {resolveGlobalIdentities,resolveTopicMemories,} from './memoryManager';+import { createSkillEngine } from './skillEngineering';const log = debug('context-engine:contextEngineering');@@ -69,6 +70,8 @@ interface ContextEngineeringContext {memoryContext?: MemoryContext;messages: UIChatMessage[];model: string;+ /** Agent's enabled plugin/tool/skill identifiers (from agentConfig.plugins) */+ plugins?: string[];provider: string;sessionId?: string;/**@@ -99,6 +102,7 @@ export const contextEngineering = async ({agentId,groupId,initialContext,+ plugins,stepContext,topicId,memoryContext,@@ -381,6 +385,11 @@ export const contextEngineering = async ({initialContext,stepContext,+ // Skills configuration+ skillsConfig: {+ enabledSkills: plugins ? createSkillEngine().getEnabledSkills(plugins) : undefined,+ },+// Tools configurationtoolsConfig: {manifests,diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.tsnew file mode 100644index 00000000000..ad410cf4ce2--- /dev/null+++ b/src/services/chat/mecha/skillEngineering.ts@@ -0,0 +1,30 @@+import { SkillEngine } from '@lobechat/context-engine';++import { getToolStoreState } from '@/store/tool';++/**+ * Create a SkillEngine by merging all skill sources from toolStore+ *+ * Sources:+ * 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills+ * 2. DB skills (user/market) - from toolStore.agentSkills+ */+export const createSkillEngine = (): SkillEngine => {+ const toolState = getToolStoreState();++ // Source 1: builtin skills+ const builtinMetas = (toolState.builtinSkills || []).map((s) => ({+ description: s.description,+ identifier: s.identifier,+ name: s.name,+ }));++ // Source 2: DB skills (agentSkills table)+ const dbMetas = (toolState.agentSkills || []).map((s) => ({+ description: s.description ?? '',+ identifier: s.identifier,+ name: s.name,+ }));++ return new SkillEngine({ skills: [...builtinMetas, ...dbMetas] });+};diff --git a/src/services/cloudSandbox.ts b/src/services/cloudSandbox.tsindex 52e46779796..7a6bbecbd8e 100644--- a/src/services/cloudSandbox.ts+++ b/src/services/cloudSandbox.ts@@ -11,12 +11,12 @@ class CloudSandboxService {* Call a cloud sandbox tool* @param toolName - The name of the tool to call (e.g., 'runCommand', 'writeLocalFile')* @param params - The parameters for the tool- * @param context - Session context containing userId and topicId for isolation+ * @param context - Session context containing topicId and optional userId for isolation*/async callTool(toolName: string,params: Record<string, any>,- context: { topicId: string; userId: string },+ context: { topicId: string; userId?: string },): Promise<CallToolResult> {const input: CallCodeInterpreterToolInput = {params,diff --git a/src/services/marketApi.ts b/src/services/marketApi.tsindex 9f164d5d5d9..126b316eb9a 100644--- a/src/services/marketApi.ts+++ b/src/services/marketApi.ts@@ -202,6 +202,47 @@ export class MarketApiService {async getAgentGroupForkSource(identifier: string): Promise<AgentGroupForkSourceResponse> {return lambdaClient.market.agentGroup.getAgentGroupForkSource.query({ identifier });}++ // ==================== Skills API ====================++ /**+ * Search for skills in the LobeHub Market+ */+ async searchSkill(params: {+ locale?: string;+ order?: 'asc' | 'desc';+ page?: number;+ pageSize?: number;+ search?: string;+ sort?: 'createdAt' | 'downloadCount' | 'forks' | 'name' | 'stars' | 'updatedAt' | 'watchers';+ }): Promise<{+ items: Array<{+ category?: string;+ createdAt: string;+ description: string;+ downloadCount: number;+ identifier: string;+ name: string;+ repository?: string;+ sourceUrl?: string;+ summary?: string;+ updatedAt: string;+ version?: string;+ }>;+ page: number;+ pageSize: number;+ total: number;+ }> {+ return lambdaClient.market.skill.searchSkill.query(params);+ }++ /**+ * Get skill download URL from market+ */+ getSkillDownloadUrl(identifier: string): string {+ const marketBaseUrl = process.env.NEXT_PUBLIC_MARKET_BASE_URL || 'https://market.lobehub.com';+ return `${marketBaseUrl}/api/v1/skills/${identifier}/download`;+ }}export const marketApiService = new MarketApiService();diff --git a/src/services/skill/index.ts b/src/services/skill/index.tsnew file mode 100644index 00000000000..2b5f2f30f8d--- /dev/null+++ b/src/services/skill/index.ts@@ -0,0 +1,95 @@+import type {+ CreateSkillInput,+ ImportGitHubInput,+ ImportUrlInput,+ ImportZipInput,+ SkillImportResult,+ SkillItem,+ SkillListItem,+ SkillResourceContent,+ SkillResourceTreeNode,+ SkillSource,+ UpdateSkillInput,+} from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++class AgentSkillService {+ // ===== Create =====++ async createSkill(params: CreateSkillInput): Promise<SkillItem | undefined> {+ return lambdaClient.agentSkills.create.mutate(params);+ }++ // ===== Import =====++ async importFromGitHub(params: ImportGitHubInput): Promise<SkillImportResult | undefined> {+ return lambdaClient.agentSkills.importFromGitHub.mutate(params);+ }++ async importFromUrl(params: ImportUrlInput): Promise<SkillImportResult | undefined> {+ return lambdaClient.agentSkills.importFromUrl.mutate(params);+ }++ async importFromZip(params: ImportZipInput): Promise<SkillImportResult | undefined> {+ return lambdaClient.agentSkills.importFromZip.mutate(params);+ }++ async importFromMarket(identifier: string): Promise<SkillImportResult | undefined> {+ return lambdaClient.agentSkills.importFromMarket.mutate({ identifier });+ }++ // ===== Query =====++ async getById(id: string): Promise<SkillItem | undefined> {+ return lambdaClient.agentSkills.getById.query({ id });+ }++ async getZipUrl(id: string): Promise<{ name: string; url: string | null }> {+ return lambdaClient.agentSkills.getByIdWithZipUrl.query({ id });+ }++ async getByIdentifier(identifier: string): Promise<SkillItem | undefined> {+ return lambdaClient.agentSkills.getByIdentifier.query({ identifier });+ }++ async getByName(name: string): Promise<SkillItem | undefined> {+ return lambdaClient.agentSkills.getByName.query({ name });+ }++ async list(source?: SkillSource): Promise<{ data: SkillListItem[]; total: number }> {+ return lambdaClient.agentSkills.list.query(source ? { source } : undefined);+ }++ async search(query: string): Promise<{ data: SkillListItem[]; total: number }> {+ return lambdaClient.agentSkills.search.query({ query });+ }++ // ===== Resources =====++ async listResources(id: string, includeContent?: boolean): Promise<SkillResourceTreeNode[]> {+ return lambdaClient.agentSkills.listResources.query({ id, includeContent });+ }++ async readResource(id: string, path: string): Promise<SkillResourceContent> {+ return lambdaClient.agentSkills.readResource.query({ id, path });+ }++ // ===== Update =====++ async updateSkill(params: UpdateSkillInput): Promise<SkillItem> {+ return lambdaClient.agentSkills.update.mutate({+ content: params.content,+ id: params.id,+ manifest: params.manifest,+ });+ }++ // ===== Delete =====++ async deleteSkill(id: string): Promise<{ success: boolean }> {+ return lambdaClient.agentSkills.delete.mutate({ id });+ }+}++export const agentSkillService = new AgentSkillService();diff --git a/src/store/tool/initialState.ts b/src/store/tool/initialState.tsindex 4c194782650..3c62dc05c5a 100644--- a/src/store/tool/initialState.ts+++ b/src/store/tool/initialState.ts@@ -1,17 +1,17 @@-import { type BuiltinToolState } from './slices/builtin/initialState';-import { initialBuiltinToolState } from './slices/builtin/initialState';-import { type CustomPluginState } from './slices/customPlugin/initialState';-import { initialCustomPluginState } from './slices/customPlugin/initialState';-import { type KlavisStoreState } from './slices/klavisStore/initialState';-import { initialKlavisStoreState } from './slices/klavisStore/initialState';-import { type LobehubSkillStoreState } from './slices/lobehubSkillStore/initialState';-import { initialLobehubSkillStoreState } from './slices/lobehubSkillStore/initialState';-import { type MCPStoreState } from './slices/mcpStore/initialState';-import { initialMCPStoreState } from './slices/mcpStore/initialState';-import { type PluginStoreState } from './slices/oldStore/initialState';-import { initialPluginStoreState } from './slices/oldStore/initialState';-import { type PluginState } from './slices/plugin/initialState';-import { initialPluginState } from './slices/plugin/initialState';+import { type AgentSkillsState, initialAgentSkillsState } from './slices/agentSkills/initialState';+import { type BuiltinToolState, initialBuiltinToolState } from './slices/builtin/initialState';+import {+ type CustomPluginState,+ initialCustomPluginState,+} from './slices/customPlugin/initialState';+import { initialKlavisStoreState, type KlavisStoreState } from './slices/klavisStore/initialState';+import {+ initialLobehubSkillStoreState,+ type LobehubSkillStoreState,+} from './slices/lobehubSkillStore/initialState';+import { initialMCPStoreState, type MCPStoreState } from './slices/mcpStore/initialState';+import { initialPluginStoreState, type PluginStoreState } from './slices/oldStore/initialState';+import { initialPluginState, type PluginState } from './slices/plugin/initialState';export type ToolStoreState = PluginState &CustomPluginState &@@ -19,7 +19,8 @@ export type ToolStoreState = PluginState &BuiltinToolState &MCPStoreState &KlavisStoreState &- LobehubSkillStoreState;+ LobehubSkillStoreState &+ AgentSkillsState;export const initialState: ToolStoreState = {...initialPluginState,@@ -29,4 +30,5 @@ export const initialState: ToolStoreState = {...initialMCPStoreState,...initialKlavisStoreState,...initialLobehubSkillStoreState,+ ...initialAgentSkillsState,};diff --git a/src/store/tool/selectors/index.ts b/src/store/tool/selectors/index.tsindex ea65d57c7ac..9b3f4a098ed 100644--- a/src/store/tool/selectors/index.ts+++ b/src/store/tool/selectors/index.ts@@ -1,3 +1,4 @@+export { agentSkillsSelectors } from '../slices/agentSkills/selectors';export {builtinToolSelectors,type LobeToolMetaWithAvailability,diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.tsindex 46031fb6e94..42154cff549 100644--- a/src/store/tool/selectors/tool.test.ts+++ b/src/store/tool/selectors/tool.test.ts@@ -5,8 +5,19 @@ import { type ToolStoreState } from '../initialState';import { initialState } from '../initialState';import { toolSelectors } from './tool';+// Mock builtin skill for testing+const mockBuiltinSkill = {+ avatar: '🧪',+ content: '# Test Skill',+ description: 'A test skill',+ identifier: 'test-skill',+ name: 'Test Skill',+ source: 'builtin' as const,+};+const mockState = {...initialState,+ builtinSkills: [mockBuiltinSkill],installedPlugins: [{identifier: 'plugin-1',@@ -88,6 +99,12 @@ describe('toolSelectors', () => {it('should return the correct list of tool metadata', () => {const result = toolSelectors.metaList(mockState);expect(result).toEqual([+ {+ author: 'LobeHub',+ identifier: 'test-skill',+ meta: { avatar: '🧪', description: 'A test skill', title: 'Test Skill' },+ type: 'builtin',+ },{type: 'builtin',author: 'LobeHub',diff --git a/src/store/tool/slices/agentSkills/action.ts b/src/store/tool/slices/agentSkills/action.tsnew file mode 100644index 00000000000..2ddd242a888--- /dev/null+++ b/src/store/tool/slices/agentSkills/action.ts@@ -0,0 +1,173 @@+import {+ type CreateSkillInput,+ type ImportGitHubInput,+ type ImportUrlInput,+ type ImportZipInput,+ type SkillImportResult,+ type SkillItem,+ type SkillListItem,+ type SkillResourceTreeNode,+ type UpdateSkillInput,+} from '@lobechat/types';+import { produce } from 'immer';+import useSWR, { mutate, type SWRResponse } from 'swr';+import { type StateCreator } from 'zustand/vanilla';++import { useClientDataSWR } from '@/libs/swr';+import { agentSkillService } from '@/services/skill';+import { setNamespace } from '@/utils/storeDebug';++import { type ToolStore } from '../../store';+import { type AgentSkillsState } from './initialState';++const n = setNamespace('agentSkills');++export interface AgentSkillDetailData {+ resourceTree: SkillResourceTreeNode[];+ skillDetail?: SkillItem;+}++export interface AgentSkillsAction {+ createAgentSkill: (params: CreateSkillInput) => Promise<SkillItem | undefined>;+ deleteAgentSkill: (id: string) => Promise<void>;+ fetchAgentSkillDetail: (id: string) => Promise<SkillItem | undefined>;+ importAgentSkillFromGitHub: (params: ImportGitHubInput) => Promise<SkillImportResult | undefined>;+ importAgentSkillFromUrl: (params: ImportUrlInput) => Promise<SkillImportResult | undefined>;+ importAgentSkillFromZip: (params: ImportZipInput) => Promise<SkillImportResult | undefined>;+ refreshAgentSkills: () => Promise<void>;+ updateAgentSkill: (params: UpdateSkillInput) => Promise<SkillItem | undefined>;+ useFetchAgentSkillDetail: (skillId?: string) => SWRResponse<AgentSkillDetailData>;+ useFetchAgentSkills: (enabled: boolean) => SWRResponse<SkillListItem[]>;+}++export const createAgentSkillsSlice: StateCreator<+ ToolStore,+ [['zustand/devtools', never]],+ [],+ AgentSkillsAction+> = (set, get) => ({+ createAgentSkill: async (params) => {+ const result = await agentSkillService.createSkill(params);+ await get().refreshAgentSkills();+ return result;+ },++ deleteAgentSkill: async (id) => {+ await agentSkillService.deleteSkill(id);++ // Clean up detail map+ set(+ produce((draft: AgentSkillsState) => {+ delete draft.agentSkillDetailMap[id];+ }),+ false,+ n('deleteAgentSkill'),+ );++ // Clear SWR cache+ await mutate(['fetchAgentSkillDetail', id].join('-'), undefined, { revalidate: false });++ await get().refreshAgentSkills();+ },++ fetchAgentSkillDetail: async (id) => {+ const cached = get().agentSkillDetailMap[id];+ if (cached) return cached;++ const detail = await agentSkillService.getById(id);+ if (detail) {+ set(+ produce((draft: AgentSkillsState) => {+ draft.agentSkillDetailMap[id] = detail;+ }),+ false,+ n('fetchAgentSkillDetail'),+ );+ }+ return detail;+ },++ importAgentSkillFromGitHub: async (params) => {+ const result = await agentSkillService.importFromGitHub(params);+ await get().refreshAgentSkills();+ return result;+ },++ importAgentSkillFromUrl: async (params) => {+ const result = await agentSkillService.importFromUrl(params);+ await get().refreshAgentSkills();+ return result;+ },++ importAgentSkillFromZip: async (params) => {+ const result = await agentSkillService.importFromZip(params);+ await get().refreshAgentSkills();+ return result;+ },++ refreshAgentSkills: async () => {+ const { data } = await agentSkillService.list();+ set({ agentSkills: data }, false, n('refreshAgentSkills'));+ },++ updateAgentSkill: async (params) => {+ const result = await agentSkillService.updateSkill(params);++ // Update detail map if cached+ if (result) {+ set(+ produce((draft: AgentSkillsState) => {+ draft.agentSkillDetailMap[params.id] = result;+ }),+ false,+ n('updateAgentSkill'),+ );+ }++ // Clear SWR cache so next open refetches instead of showing stale data+ await mutate(['fetchAgentSkillDetail', params.id].join('-'), undefined, { revalidate: false });++ await get().refreshAgentSkills();+ return result;+ },++ useFetchAgentSkillDetail: (skillId) =>+ useClientDataSWR<AgentSkillDetailData>(+ skillId ? ['fetchAgentSkillDetail', skillId].join('-') : null,+ async () => {+ const [detail, resourceTree] = await Promise.all([+ agentSkillService.getById(skillId!),+ agentSkillService.listResources(skillId!, true),+ ]);++ if (detail) {+ set(+ produce((draft: AgentSkillsState) => {+ draft.agentSkillDetailMap[skillId!] = detail;+ }),+ false,+ n('useFetchAgentSkillDetail'),+ );+ }++ return { resourceTree, skillDetail: detail };+ },+ { revalidateOnFocus: false },+ ),++ useFetchAgentSkills: (enabled) =>+ useSWR<SkillListItem[]>(+ enabled ? 'fetchAgentSkills' : null,+ async () => {+ const { data } = await agentSkillService.list();+ return data;+ },+ {+ fallbackData: [],+ onSuccess: (data) => {+ set({ agentSkills: data }, false, n('useFetchAgentSkills'));+ },+ revalidateOnFocus: false,+ },+ ),+});diff --git a/src/store/tool/slices/agentSkills/index.ts b/src/store/tool/slices/agentSkills/index.tsnew file mode 100644index 00000000000..f9f1301c302--- /dev/null+++ b/src/store/tool/slices/agentSkills/index.ts@@ -0,0 +1,3 @@+export { type AgentSkillsAction, createAgentSkillsSlice } from './action';+export { type AgentSkillsState, initialAgentSkillsState } from './initialState';+export { agentSkillsSelectors } from './selectors';diff --git a/src/store/tool/slices/agentSkills/initialState.ts b/src/store/tool/slices/agentSkills/initialState.tsnew file mode 100644index 00000000000..4ea75ad4e79--- /dev/null+++ b/src/store/tool/slices/agentSkills/initialState.ts@@ -0,0 +1,13 @@+import type { SkillItem, SkillListItem } from '@lobechat/types';++export interface AgentSkillsState {+ agentSkillDetailMap: Record<string, SkillItem>;+ agentSkills: SkillListItem[];+ agentSkillsLoading: boolean;+}++export const initialAgentSkillsState: AgentSkillsState = {+ agentSkillDetailMap: {},+ agentSkills: [],+ agentSkillsLoading: false,+};diff --git a/src/store/tool/slices/agentSkills/selectors.ts b/src/store/tool/slices/agentSkills/selectors.tsnew file mode 100644index 00000000000..d2c914f86b9--- /dev/null+++ b/src/store/tool/slices/agentSkills/selectors.ts@@ -0,0 +1,53 @@+import type { LobeToolMeta, SkillItem, SkillListItem } from '@lobechat/types';++import type { ToolStoreState } from '../../initialState';++const getAgentSkills = (s: ToolStoreState): SkillListItem[] => s.agentSkills || [];++const getMarketAgentSkills = (s: ToolStoreState): SkillListItem[] =>+ (s.agentSkills || []).filter((skill) => skill.source === 'market');++const getUserAgentSkills = (s: ToolStoreState): SkillListItem[] =>+ (s.agentSkills || []).filter((skill) => skill.source === 'user');++const getAgentSkillByIdentifier =+ (identifier: string) =>+ (s: ToolStoreState): SkillListItem | undefined =>+ (s.agentSkills || []).find((skill) => skill.identifier === identifier);++const getAgentSkillDetail =+ (id: string) =>+ (s: ToolStoreState): SkillItem | undefined =>+ s.agentSkillDetailMap?.[id];++const isAgentSkill =+ (identifier: string) =>+ (s: ToolStoreState): boolean =>+ (s.agentSkills || []).some((skill) => skill.identifier === identifier);++const agentSkillMetaList = (s: ToolStoreState): LobeToolMeta[] =>+ (s.agentSkills || []).map((skill) => {+ const author = skill.manifest?.author;+ const authorName = typeof author === 'string' ? author : author?.name || 'User';++ return {+ author: authorName,+ identifier: skill.identifier,+ meta: {+ avatar: '🧩',+ description: skill.description ?? skill.manifest?.description ?? '',+ title: skill.name,+ },+ type: 'builtin' as const,+ };+ });++export const agentSkillsSelectors = {+ agentSkillMetaList,+ getAgentSkillByIdentifier,+ getAgentSkillDetail,+ getAgentSkills,+ getMarketAgentSkills,+ getUserAgentSkills,+ isAgentSkill,+};diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex ba83112c260..d5c474e1ca6 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -16,6 +16,7 @@ import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';import { notebookExecutor } from './lobe-notebook';import { pageAgentExecutor } from './lobe-page-agent';+import { skillsExecutor } from './lobe-skills';import { webBrowsing } from './lobe-web-browsing';// ==================== Import and register all executors ====================@@ -130,5 +131,6 @@ registerExecutors([memoryExecutor,notebookExecutor,pageAgentExecutor,+ skillsExecutor,webBrowsing,]);diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.ts b/src/store/tool/slices/builtin/executors/lobe-skills.tsnew file mode 100644index 00000000000..20041b1ee91--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-skills.ts@@ -0,0 +1,200 @@+/**+ * Lobe Skills Executor+ *+ * Creates and exports the SkillsExecutor instance for registration.+ * Injects agentSkillService as dependency.+ */+import { builtinSkills } from '@lobechat/builtin-skills';+import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';+import { SkillsExecutor } from '@lobechat/builtin-tool-skills/executor';+import { isDesktop } from '@lobechat/const';++import { cloudSandboxService } from '@/services/cloudSandbox';+import { localFileService } from '@/services/electron/localFileService';+import { marketApiService } from '@/services/marketApi';+import { agentSkillService } from '@/services/skill';+import { useChatStore } from '@/store/chat';++// Create runtime with client-side service+const runtime = new SkillsExecutionRuntime({+ builtinSkills,+ service: {+ execScript: async (command, options) => {+ const { runInClient, description, config } = options;++ // Desktop: run in local client if requested+ if (isDesktop && runInClient) {+ const result = await localFileService.runCommand({ command, timeout: undefined });+ return {+ exitCode: result.exit_code ?? 1,+ output: result.stdout || result.output || '',+ stderr: result.stderr,+ success: result.success,+ };+ }++ // Cloud: execute via Cloud Sandbox with execScript tool+ // Server will automatically resolve zipUrl based on config.name+ const chatState = useChatStore.getState();+ const topicId = chatState.activeTopicId || 'default';++ try {+ // Call cloud sandbox execScript tool+ const result = await cloudSandboxService.callTool(+ 'execScript',+ {+ command,+ config,+ description,+ },+ { topicId },+ );++ if (!result.success) {+ return {+ exitCode: 1,+ output: '',+ stderr: result.error?.message || 'Command execution failed',+ success: false,+ };+ }++ const sandboxResult = result.result || {};++ return {+ exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),+ output: sandboxResult.stdout || sandboxResult.output || '',+ stderr: sandboxResult.stderr || '',+ success:+ result.success &&+ (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),+ };+ } catch (error) {+ return {+ exitCode: 1,+ output: '',+ stderr: (error as Error).message || 'Command execution failed',+ success: false,+ };+ }+ },+ exportFile: async (path, filename) => {+ // Get current session context+ const chatState = useChatStore.getState();+ const topicId = chatState.activeTopicId || 'default';++ try {+ // Call cloud sandbox exportAndUploadFile+ const result = await cloudSandboxService.exportAndUploadFile(path, filename, topicId);++ return {+ fileId: result.fileId,+ filename: result.filename,+ mimeType: result.mimeType,+ size: result.size,+ success: result.success,+ url: result.url,+ };+ } catch {+ return {+ filename,+ success: false,+ };+ }+ },+ findAll: () => agentSkillService.list(),+ findById: (id) => agentSkillService.getById(id),+ findByName: (name) => agentSkillService.getByName(name),+ importFromGitHub: async (gitUrl) => {+ const result = await agentSkillService.importFromGitHub({ gitUrl });+ if (!result) throw new Error('Import failed');+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ },+ importFromUrl: async (url) => {+ const result = await agentSkillService.importFromUrl({ url });+ if (!result) throw new Error('Import failed');+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ },+ importFromZipUrl: async (url) => {+ const result = await agentSkillService.importFromUrl({ url });+ if (!result) throw new Error('Import failed');+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ },+ onSkillImported: async () => {+ // Dynamic import to avoid circular dependency (this file is inside the tool store)+ const { getToolStoreState } = await import('@/store/tool/store');+ await getToolStoreState().refreshAgentSkills();+ },+ readResource: (id, path) => agentSkillService.readResource(id, path),+ searchSkill: async (params) => {+ return marketApiService.searchSkill(params);+ },+ importFromMarket: async (identifier) => {+ const result = await agentSkillService.importFromMarket(identifier);+ if (!result) throw new Error('Import failed');+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ },+ runCommand: async ({ command, runInClient, timeout }) => {+ // Desktop: run in local client if requested+ if (isDesktop && runInClient) {+ const result = await localFileService.runCommand({ command, timeout });+ return {+ exitCode: result.exit_code ?? 1,+ output: result.stdout || result.output || '',+ stderr: result.stderr,+ success: result.success,+ };+ }++ // Cloud: execute via Cloud Sandbox+ // Get current session context for sandbox isolation+ const chatState = useChatStore.getState();+ const topicId = chatState.activeTopicId || 'default';++ try {+ // Call cloud sandbox via TRPC+ // Note: userId is automatically set by server from authenticated context+ const result = await cloudSandboxService.callTool(+ 'runCommand',+ {+ command,+ description: `Execute skill command: ${command.slice(0, 100)}${command.length > 100 ? '...' : ''}`,+ timeout,+ },+ { topicId },+ );++ if (!result.success) {+ return {+ exitCode: 1,+ output: '',+ stderr: result.error?.message || 'Command execution failed',+ success: false,+ };+ }++ // Parse cloud sandbox result+ const sandboxResult = result.result || {};++ return {+ exitCode: sandboxResult.exitCode ?? (result.success ? 0 : 1),+ output: sandboxResult.stdout || sandboxResult.output || '',+ stderr: sandboxResult.stderr || '',+ success:+ result.success &&+ (sandboxResult.exitCode === 0 || sandboxResult.exitCode === undefined),+ };+ } catch (error) {+ return {+ exitCode: 1,+ output: '',+ stderr: (error as Error).message || 'Command execution failed',+ success: false,+ };+ }+ },+ },+});++// Create executor instance with the runtime+export const skillsExecutor = new SkillsExecutor(runtime);diff --git a/src/store/tool/slices/builtin/initialState.ts b/src/store/tool/slices/builtin/initialState.tsindex e09e1de02bf..3f299fca7b5 100644--- a/src/store/tool/slices/builtin/initialState.ts+++ b/src/store/tool/slices/builtin/initialState.ts@@ -1,8 +1,10 @@-import { type LobeBuiltinTool } from '@lobechat/types';+import { builtinSkills } from '@lobechat/builtin-skills';+import { type BuiltinSkill, type LobeBuiltinTool } from '@lobechat/types';import { builtinTools } from '@/tools';export interface BuiltinToolState {+ builtinSkills: BuiltinSkill[];builtinToolLoading: Record<string, boolean>;builtinTools: LobeBuiltinTool[];/**@@ -17,6 +19,7 @@ export interface BuiltinToolState {}export const initialBuiltinToolState: BuiltinToolState = {+ builtinSkills,builtinToolLoading: {},builtinTools,uninstalledBuiltinTools: [],diff --git a/src/store/tool/slices/builtin/selectors.test.ts b/src/store/tool/slices/builtin/selectors.test.tsindex 19415d70e29..503c3c18612 100644--- a/src/store/tool/slices/builtin/selectors.test.ts+++ b/src/store/tool/slices/builtin/selectors.test.ts@@ -4,11 +4,22 @@ import { type ToolStoreState } from '../../initialState';import { initialState } from '../../initialState';import { builtinToolSelectors } from './selectors';+// Mock builtin skill for testing+const mockBuiltinSkill = {+ avatar: '🧪',+ content: '# Test Skill',+ description: 'A test skill',+ identifier: 'test-skill',+ name: 'Test Skill',+ source: 'builtin' as const,+};+describe('builtinToolSelectors', () => {describe('metaList', () => {- it('should return meta list excluding Dalle when showDalle is false', () => {+ it('should return meta list with builtin tools and skills', () => {const state = {...initialState,+ builtinSkills: [mockBuiltinSkill],builtinTools: [{identifier: 'tool-1',@@ -20,6 +31,12 @@ describe('builtinToolSelectors', () => {} as ToolStoreState;const result = builtinToolSelectors.metaList(state);expect(result).toEqual([+ {+ author: 'LobeHub',+ identifier: 'test-skill',+ meta: { avatar: '🧪', description: 'A test skill', title: 'Test Skill' },+ type: 'builtin',+ },{ author: 'LobeHub', identifier: 'tool-1', meta: { title: 'Tool 1' }, type: 'builtin' },]);});@@ -27,6 +44,7 @@ describe('builtinToolSelectors', () => {it('should hide tool when not need visible with hidden', () => {const state = {...initialState,+ builtinSkills: [mockBuiltinSkill],builtinTools: [{identifier: 'tool-1',@@ -37,12 +55,21 @@ describe('builtinToolSelectors', () => {],} as ToolStoreState;const result = builtinToolSelectors.metaList(state);- expect(result).toEqual([]);+ // Should only contain skill, hidden tool is filtered out+ expect(result).toEqual([+ {+ author: 'LobeHub',+ identifier: 'test-skill',+ meta: { avatar: '🧪', description: 'A test skill', title: 'Test Skill' },+ type: 'builtin',+ },+ ]);});- it('should return an empty list if no builtin tools are available', () => {+ it('should return an empty list if no builtin tools or skills are available', () => {const state: ToolStoreState = {...initialState,+ builtinSkills: [],builtinTools: [],};const result = builtinToolSelectors.metaList(state);diff --git a/src/store/tool/slices/builtin/selectors.ts b/src/store/tool/slices/builtin/selectors.tsindex 637594e7339..944c0307d2f 100644--- a/src/store/tool/slices/builtin/selectors.ts+++ b/src/store/tool/slices/builtin/selectors.ts@@ -1,8 +1,9 @@-import { type LobeToolMeta } from '@lobechat/types';+import { type BuiltinSkill, type LobeToolMeta } from '@lobechat/types';import { shouldEnableTool } from '@/helpers/toolFilters';import { type ToolStoreState } from '../../initialState';+import { agentSkillsSelectors } from '../agentSkills/selectors';import { KlavisServerStatus } from '../klavisStore';export interface LobeToolMetaWithAvailability extends LobeToolMeta {@@ -27,6 +28,22 @@ const toBuiltinMetaWithAvailability = (availableInWeb: shouldEnableTool(t.identifier),});+const toSkillMeta = (s: BuiltinSkill): LobeToolMeta => ({+ author: 'LobeHub',+ identifier: s.identifier,+ meta: {+ avatar: s.avatar,+ description: s.description,+ title: s.name,+ },+ type: 'builtin' as const,+});++const toSkillMetaWithAvailability = (s: BuiltinSkill): LobeToolMetaWithAvailability => ({+ ...toSkillMeta(s),+ availableInWeb: true,+});+const getKlavisMetas = (s: ToolStoreState): LobeToolMeta[] =>(s.servers || []).filter((server) => server.status === KlavisServerStatus.CONNECTED && server.tools?.length)@@ -72,7 +89,12 @@ const metaList = (s: ToolStoreState): LobeToolMeta[] => {}).map(toBuiltinMeta);- return [...builtinMetas, ...getKlavisMetas(s)];+ const skillMetas = (s.builtinSkills || [])+ .filter((skill) => !uninstalledBuiltinTools.includes(skill.identifier))+ .map(toSkillMeta);+ const agentSkillMetas = agentSkillsSelectors.agentSkillMetaList(s);++ return [...skillMetas, ...agentSkillMetas, ...builtinMetas, ...getKlavisMetas(s)];};// Tools that should never be exposed in agent profile configuration@@ -80,6 +102,7 @@ const EXCLUDED_TOOLS = new Set(['lobe-agent-builder','lobe-group-agent-builder','lobe-group-management',+ 'lobe-skills',]);/**@@ -97,7 +120,12 @@ const allMetaList = (s: ToolStoreState): LobeToolMetaWithAvailability[] => {}).map(toBuiltinMetaWithAvailability);- return [...builtinMetas, ...getKlavisMetasWithAvailability(s)];+ const skillMetas = (s.builtinSkills || []).map(toSkillMetaWithAvailability);+ const agentSkillMetas = agentSkillsSelectors+ .agentSkillMetaList(s)+ .map((meta) => ({ ...meta, availableInWeb: true }));++ return [...skillMetas, ...agentSkillMetas, ...builtinMetas, ...getKlavisMetasWithAvailability(s)];};/**@@ -119,6 +147,12 @@ const installedAllMetaList = (s: ToolStoreState): LobeToolMetaWithAvailability[]return [...builtinMetas, ...getKlavisMetasWithAvailability(s)];};+/**+ * Get installed builtin skills (excludes uninstalled ones)+ */+const installedBuiltinSkills = (s: ToolStoreState): BuiltinSkill[] =>+ (s.builtinSkills || []).filter((skill) => !s.uninstalledBuiltinTools.includes(skill.identifier));+/*** Get uninstalled builtin tool identifiers*/@@ -133,6 +167,7 @@ const isBuiltinToolInstalled = (identifier: string) => (s: ToolStoreState) =>export const builtinToolSelectors = {allMetaList,installedAllMetaList,+ installedBuiltinSkills,isBuiltinToolInstalled,metaList,uninstalledBuiltinTools,diff --git a/src/store/tool/store.ts b/src/store/tool/store.tsindex 5b28e2e3b68..0faceabeb58 100644--- a/src/store/tool/store.ts+++ b/src/store/tool/store.ts@@ -4,22 +4,18 @@ import { type StateCreator } from 'zustand/vanilla';import { createDevtools } from '../middleware/createDevtools';import { flattenActions } from '../utils/flattenActions';-import { type ToolStoreState } from './initialState';-import { initialState } from './initialState';-import { type BuiltinToolAction } from './slices/builtin';-import { createBuiltinToolSlice } from './slices/builtin';-import { type CustomPluginAction } from './slices/customPlugin';-import { createCustomPluginSlice } from './slices/customPlugin';-import { type KlavisStoreAction } from './slices/klavisStore';-import { createKlavisStoreSlice } from './slices/klavisStore';-import { type LobehubSkillStoreAction } from './slices/lobehubSkillStore';-import { createLobehubSkillStoreSlice } from './slices/lobehubSkillStore';-import { type PluginMCPStoreAction } from './slices/mcpStore';-import { createMCPPluginStoreSlice } from './slices/mcpStore';-import { type PluginStoreAction } from './slices/oldStore';-import { createPluginStoreSlice } from './slices/oldStore';-import { type PluginAction } from './slices/plugin';-import { createPluginSlice } from './slices/plugin';+import { initialState, type ToolStoreState } from './initialState';+import { type AgentSkillsAction, createAgentSkillsSlice } from './slices/agentSkills';+import { type BuiltinToolAction, createBuiltinToolSlice } from './slices/builtin';+import { createCustomPluginSlice, type CustomPluginAction } from './slices/customPlugin';+import { createKlavisStoreSlice, type KlavisStoreAction } from './slices/klavisStore';+import {+ createLobehubSkillStoreSlice,+ type LobehubSkillStoreAction,+} from './slices/lobehubSkillStore';+import { createMCPPluginStoreSlice, type PluginMCPStoreAction } from './slices/mcpStore';+import { createPluginStoreSlice, type PluginStoreAction } from './slices/oldStore';+import { createPluginSlice, type PluginAction } from './slices/plugin';// =============== Aggregate createStoreFn ============ //@@ -30,7 +26,8 @@ export type ToolStore = ToolStoreState &BuiltinToolAction &PluginMCPStoreAction &KlavisStoreAction &- LobehubSkillStoreAction;+ LobehubSkillStoreAction &+ AgentSkillsAction;type ToolStoreAction = CustomPluginAction &PluginAction &@@ -38,7 +35,8 @@ type ToolStoreAction = CustomPluginAction &BuiltinToolAction &PluginMCPStoreAction &KlavisStoreAction &- LobehubSkillStoreAction;+ LobehubSkillStoreAction &+ AgentSkillsAction;const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (...parameters: Parameters<StateCreator<ToolStore, [['zustand/devtools', never]]>>@@ -52,6 +50,7 @@ const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = (createMCPPluginStoreSlice(...parameters),createKlavisStoreSlice(...parameters),createLobehubSkillStoreSlice(...parameters),+ createAgentSkillsSlice(...parameters),]),});diff --git a/src/tools/artifacts/index.ts b/src/tools/artifacts/index.tsdeleted file mode 100644index 56b63e74042..00000000000--- a/src/tools/artifacts/index.ts+++ /dev/null@@ -1,15 +0,0 @@-import { type BuiltinToolManifest } from '@lobechat/types';--import { systemPrompt } from '@/tools/artifacts/systemRole';--export const ArtifactsManifest: BuiltinToolManifest = {- api: [],- identifier: 'lobe-artifacts',- meta: {- avatar: `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHJ4PSI1MTIiIGZpbGw9IiNDNDc4NUIiLz48cGF0aCBkPSJNNTEyIDYxMmM1NS4yMjggMCAxMDAtNDQuNzcyIDEwMC0xMDBzLTQ0Ljc3Mi0xMDAtMTAwLTEwMC0xMDAgNDQuNzcyLTEwMCAxMDAgNDQuNzcyIDEwMCAxMDAgMTAwWiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNTEyIDY2MmExNDkuOTk4IDE0OS45OTggMCAwIDEtOTIuNTk3IDEzOC41ODIgMTUwLjAwMiAxNTAuMDAyIDAgMCAxLTIwNC41MjEtMTA5LjMxOCAxNDkuOTk4IDE0OS45OTggMCAwIDEgNjMuNzgzLTE1My45ODRBMTQ5Ljk5MiAxNDkuOTkyIDAgMCAxIDM2MiA1MTJhMTQ5Ljk5OSAxNDkuOTk5IDAgMSAxIDE1MC0xNTAgMTQ5Ljk5OCAxNDkuOTk4IDAgMCAxIDI5Ny4xMTgtMjkuMjYzQTE1MCAxNTAgMCAwIDEgNjYyIDUxMmMyOS42NjcgMCA1OC42NjggOC43OTcgODMuMzM1IDI1LjI4YTE0OS45OTUgMTQ5Ljk5NSAwIDAgMSA2My43ODMgMTUzLjk4NEExNTAgMTUwIDAgMCAxIDUxMiA2NjJaTTUxMiAzNjJ2NTBNMzYyIDUxMmg1ME02NjIgNTEyaC01ME01MTIgNjYydi01ME0zNzguNjY3IDM3OC42NjdsNjIuNjY2IDYyLjY2Nk01ODIuNjY3IDQ0MS4zMzNsNjIuNjY2LTYyLjY2Nk0zNzguNjY3IDY0NS4zMzNsNjIuNjY2LTYyLjY2Nk01ODIuNjY3IDU4Mi42NjdsNjIuNjY2IDYyLjY2NiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4=`,- description: 'Generate and preview interactive UI components, charts, and web content',- title: 'Artifacts',- },- systemRole: systemPrompt,- type: 'builtin',-};diff --git a/src/tools/artifacts/systemRole.ts b/src/tools/artifacts/systemRole.tsdeleted file mode 100644index 52612141f89..00000000000--- a/src/tools/artifacts/systemRole.ts+++ /dev/null@@ -1,302 +0,0 @@-export const systemPrompt = `<artifacts_guides>-The assistant possesses the capability to generate "Artifacts"—dedicated UI windows for presenting substantial, standalone content. This feature segregates complex deliverables from the conversational stream, facilitating user ownership, modification, and reuse.--# 1. Evaluation Criteria--## When to Create an Artifact (Qualifying Content)-Target content that serves as a distinct "deliverable." Valid candidates act as:-- **Substantial Units:** Content exceeding ~15 lines (e.g., full scripts, detailed reports).-- **Standalone Resources:** Complex material that remains intelligible without the surrounding chat context.-- **Reusable Assets:** Documents or code intended for external use (emails, presentations, software modules).-- **Iterative Projects:** Content the user is likely to refine, modify, or maintain over time.--## When to Stay Inline (Disqualifying Content)-Do NOT generate artifacts for:-- **Trivial Snippets:** Brief code blocks, math equations, or short examples.-- **Pure Didactics:** Content primarily explaining a concept rather than providing a tool.-- **Meta-Commentary:** Feedback or suggestions about existing artifacts.-- **Context-Dependent Text:** Conversational explanations that lose meaning outside the thread.-- **One-off Answers:** Responses to transient questions unlikely to be revisited.--# 2. Operational Constraints-- **Frequency:** Limit to one artifact per response unless explicitly engaged in a multi-file task.-- **Preference:** Defaults to inline text for simplicity. Artifacts are reserved for momentums where a separate window significantly enhances utility.-- **Capability Mapping:**- - If asked for "images/SVG", provide an SVG artifact. (Acknowledge limitations humorously if needed).- - If asked for "websites", provide HTML or React artifacts.-- **Safety:** Do NOT generate hazardous content. Apply the same safety standards as text responses.--# 3. Generation Workflow--When the intent matches the criteria (Code, Document, Component, Diagram, etc.), adhere strictly to this sequence:--## Step A: Artifact Construction-Wrap the content in \`<lobeArtifact>\` tags with the following attributes:--1. **\`identifier\`**: A consistent, kebab-case ID (e.g., \`visualization-script\`).- - *Crucial:* Persist this ID across all future updates to this specific item. If updating an existing artifact, reuse the previous identifier.-2. **\`title\`**: A concise, descriptive string suitable for a header.-3. **\`type\`**: The MIME type defining the rendering logic.--## Step B: Content & Type Specifications--Select the appropriate type and follow its strict constraints:--### **Code** (\`application/lobe.artifacts.code\`)-- Must include \`language\` attribute (e.g., \`language="python"\`)-- Do NOT use markdown code fences/triple backticks inside-- Fallback for any content that fails rendering requirements--### **Document** (\`text/markdown\`)-- For plain text, Markdown reports, or articles--### **HTML** (\`text/html\`)-- Single-file only (CSS/JS must be embedded)-- No external requests except scripts from \`cdnjs.cloudflare.com\`-- No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)-- NOT for code snippets (use Code type instead)--### **SVG** (\`image/svg+xml\`)-- Specify \`viewBox\` instead of fixed width/height--### **Mermaid** (\`application/lobe.artifacts.mermaid\`)-- Raw Mermaid syntax only. No code blocks--### **React** (\`application/lobe.artifacts.react\`)-- **Syntax:** Functional components (Hooks allowed: \`useState\`, \`useEffect\`)-- **Export:** Must use \`export default\`-- **Props:** No required props (provide defaults)-- **Styling:** Use Tailwind CSS. No arbitrary values (e.g., \`h-[50px]\`)-- **Pre-installed Libraries:**- - \`lucide-react\` - Icons (e.g., \`import { Camera } from "lucide-react"\`)- - \`recharts\` - Charts (e.g., \`import { LineChart, XAxis } from "recharts"\`)- - \`shadcn/ui\` - UI components (e.g., \`import { Button, Card, Alert } from '@/components/ui/...'\`)-- **Images:** No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)-- **Note:** Import React hooks explicitly: \`import { useState } from "react"\`--## Step C: Integrity-- Output the **full, non-truncated** code/text.-- Do NOT use lazy placeholders like \`// ... rest of code\`.--Here are some examples of correct usage of artifacts by other AI assistants:--<examples>- <example_docstring>- This example demonstrates how to create a new artifact and reference it in the response.- </example_docstring>-- <example>- <user_query>Can you help me create a Python script to calculate the factorial of a number?</user_query>-- <assistant_response>- Sure! Here's a Python script that calculates the factorial of a number:-- <lobeArtifact identifier="factorial-script" type="application/lobe.artifacts.code" language="python" title="Simple Python factorial script">- def factorial(n):- if n == 0:- return 1- else:- return n * factorial(n - 1)-- ...- </assistant_response>-- </example>--<example_docstring>-This example shows how to update an existing artifact and reference it in the response.-</example_docstring>-- <example>- <user_query>Thanks for the factorial script! Can you modify it to handle invalid input gracefully?</user_query>-- <assistant_response>- Good point! I'll update the script to include input validation.-- <lobeArtifact identifier="factorial-script" type="application/lobe.artifacts.code" language="python" title="Simple Python factorial script">- def factorial(n):- if n == 0:- return 1- else:- return n * factorial(n - 1)-- while True:- try:- num = int(input("Enter a non-negative integer: "))- if num < 0:- raise ValueError- break- except ValueError:- print("Invalid input. Please enter a non-negative integer.")-- ...- </assistant_response>-- </example>--<example_docstring>-This example shows how to create an SVG artifact and reference it in the response.-</example_docstring>-- <example>- <user_query>Can you draw a simple blue circle in SVG?</user_query>-- <assistant_response>- I'll create a simple blue circle for you using SVG.-- <lobeArtifact identifier="blue-circle-svg" type="image/svg+xml" title="Simple blue circle SVG">- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">- <circle cx="50" cy="50" r="40" fill="blue" />- </svg>- </lobeArtifact>-- Here's a simple SVG image of a blue circle, as requested. The circle is centered at coordinates (50, 50) with a radius of 40 pixels, and it's filled with the color blue.-- ...- </assistant_response>-- </example>--<example_docstring>- This example demonstrates how to create a Mermaid artifact for a simple flow chart.- </example_docstring>-- <example>- <user_query>Can you create a simple flow chart showing the process of making tea using Mermaid?</user_query>-- <assistant_response>- Sure! Here's a simple flow chart depicting the process of making tea:-- <lobeArtifact identifier="tea-making-flowchart" type="application/lobe.artifacts.mermaid" title="Flow chart: Making Tea">- graph TD- A[Start] --> B{Water boiled?}- B -->|Yes| C[Add tea leaves to cup]- B -->|No| D[Boil water]- D --> B- C --> E[Pour boiling water into cup]- E --> F[Steep tea for desired time]- F --> G[Remove tea leaves]- G --> H[Add milk or sugar, if desired]- H --> I[Enjoy your tea!]- I --> J[End]- </lobeArtifact>-- This flow chart uses Mermaid syntax to visualize the steps involved in making a cup of tea.-- ...- </assistant_response>- </example>--<example_docstring>-This example demonstrates the assistant's preference to update existing artifacts, rather than create new ones.-</example_docstring>-- <example>- <user_query>I'm teaching a beginner's programming course, and I want to include some interactive examples for the students to try out. Do you have any suggestions for simple programs that could help them understand basic concepts?</user_query>-- <assistant_response>- Teaching a beginner's programming course is a great opportunity to introduce students to fundamental concepts through interactive examples. Let me update the factorial calculator to make it more interactive:-- <lobeArtifact identifier="factorial-script" type="application/lobe.artifacts.code" language="python" title="Interactive Factorial Calculator">- def factorial(n):- if n == 0:- return 1- else:- return n * factorial(n - 1)-- def main():- print("Welcome to the Factorial Calculator!")- print("Enter a non-negative integer to calculate its factorial.")- print("Enter 'q' to quit the program.")-- while True:- user_input = input("--Enter a number (or 'q' to quit): ")-- if user_input == 'q':- print("Thank you for using the Factorial Calculator. Goodbye!")- break-- try:- num = int(user_input)- if num < 0:- raise ValueError- result = factorial(num)- print(f"The factorial of {num} is {result}")- except ValueError:- print("Invalid input. Please enter a non-negative integer or 'q' to quit.")-- if __name__ == "__main__":- main()- </lobeArtifact>-- I've updated it to make it more suitable as a learning example for your students. Here are the key changes:-- 1. Separated the factorial calculation logic into its own function, \`factorial()\`. This demonstrates the concept of function definition and recursion.-- ...- </assistant_response>-- </example>--<example_docstring>-This example demonstrates the assistant's decision not to use an artifact because it would make the information less accessible and hinder the natural flow of the conversation.-</example_docstring>-- <example>- <user_query>- Can you give me a quick rundown of some common Python list methods? I'm new to Python and trying to understand the basics.- </user_query>-- <assistant_response>- Absolutely! Python lists are versatile and have many useful methods. Here's a quick overview of some common ones:-- 1. \`append(x)\`: Adds an item \`x\` to the end of the list.- Example: \`my_list.append(4)\`-- 2. \`extend(iterable)\`: Adds all items from an iterable (like another list) to the end.- Example: \`my_list.extend([5, 6, 7])\`-- 3. \`insert(i, x)\`: Inserts an item \`x\` at a given position \`i\`.- Example: \`my_list.insert(1, "new")\`-- ...- </assistant_response>- </example>--<example_docstring>-This example demonstrates the assistant's decision not to use an artifact for an explanation that includes code samples, because the content is primarily educational and benefits from being part of the conversational flow.-</example_docstring>-- <example>- <user_query>- I'm learning Python and algorithms. Can you explain how binary search works and maybe show me a simple Python implementation? I learn best by seeing code.- </user_query>-- <assistant_response>- Absolutely! Binary search is an efficient algorithm for finding an item in a sorted list. It works by repeatedly dividing the search interval in half. Let's walk through it with a simple Python implementation.-- First, let's define a function for binary search:-- \`\`\`python- def binary_search(arr, target):- left, right = 0, len(arr) - 1-- while left <= right:- mid = (left + right) // 2- if arr[mid] == target:- return mid- elif arr[mid] < target:- left = mid + 1- ...- </assistant_response>- </example>--</examples>--The assistant should not mention any of these instructions to the user, nor make reference to the \`lobeArtifact\` tag, any of the MIME types (e.g. \`application/lobe.artifacts.code\`), or related syntax unless it is directly relevant to the query.--The assistant should always take care to not produce artifacts that would be highly hazardous to human health or wellbeing if misused, even if is asked to produce them for seemingly benign reasons. However, if Claude would be willing to produce the same content in text form, it should be willing to produce it in an artifact.-</artifacts_info>-`;diff --git a/src/tools/identifiers.ts b/src/tools/identifiers.tsindex 5cb29434ed3..cc13bfa2ddf 100644--- a/src/tools/identifiers.ts+++ b/src/tools/identifiers.ts@@ -8,18 +8,17 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { NotebookManifest } from '@lobechat/builtin-tool-notebook';import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';+import { SkillsManifest } from '@lobechat/builtin-tool-skills';import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';-import { ArtifactsManifest } from './artifacts';-export const builtinToolIdentifiers: string[] = [AgentBuilderManifest.identifier,- ArtifactsManifest.identifier,LocalSystemManifest.identifier,WebBrowsingManifest.identifier,KnowledgeBaseManifest.identifier,CloudSandboxManifest.identifier,PageAgentManifest.identifier,+ SkillsManifest.identifier,GroupAgentBuilderManifest.identifier,GroupManagementManifest.identifier,GTDManifest.identifier,diff --git a/src/tools/index.ts b/src/tools/index.tsindex 776e35de63b..a30cbb33468 100644--- a/src/tools/index.ts+++ b/src/tools/index.ts@@ -8,16 +8,26 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { NotebookManifest } from '@lobechat/builtin-tool-notebook';import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';+import { SkillsManifest } from '@lobechat/builtin-tool-skills';import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { isDesktop } from '@lobechat/const';import { type LobeBuiltinTool } from '@lobechat/types';-import { ArtifactsManifest } from './artifacts';+/**+ * Default tool IDs that will always be added to the tools list.+ * Shared between frontend (createAgentToolsEngine) and server (createServerAgentToolsEngine).+ */+export const defaultToolIds = [+ WebBrowsingManifest.identifier,+ KnowledgeBaseManifest.identifier,+ SkillsManifest.identifier,+];export const builtinTools: LobeBuiltinTool[] = [{- identifier: ArtifactsManifest.identifier,- manifest: ArtifactsManifest,+ hidden: true,+ identifier: SkillsManifest.identifier,+ manifest: SkillsManifest,type: 'builtin',},{diff --git a/src/tools/inspectors.ts b/src/tools/inspectors.tsindex b4947fcf6d3..26612a40dc5 100644--- a/src/tools/inspectors.ts+++ b/src/tools/inspectors.ts@@ -26,6 +26,7 @@ import {import { MemoryInspectors, MemoryManifest } from '@lobechat/builtin-tool-memory/client';import { NotebookInspectors, NotebookManifest } from '@lobechat/builtin-tool-notebook/client';import { PageAgentInspectors, PageAgentManifest } from '@lobechat/builtin-tool-page-agent/client';+import { SkillsInspectors, SkillsManifest } from '@lobechat/builtin-tool-skills/client';import {WebBrowsingInspectors,WebBrowsingManifest,@@ -56,6 +57,7 @@ const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> =[MemoryManifest.identifier]: MemoryInspectors as Record<string, BuiltinInspector>,[NotebookManifest.identifier]: NotebookInspectors as Record<string, BuiltinInspector>,[PageAgentManifest.identifier]: PageAgentInspectors as Record<string, BuiltinInspector>,+ [SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,};diff --git a/src/tools/renders.ts b/src/tools/renders.tsindex 782875c94ef..12dd2df26e9 100644--- a/src/tools/renders.ts+++ b/src/tools/renders.ts@@ -17,6 +17,7 @@ import {} from '@lobechat/builtin-tool-local-system/client';import { MemoryManifest, MemoryRenders } from '@lobechat/builtin-tool-memory/client';import { NotebookManifest, NotebookRenders } from '@lobechat/builtin-tool-notebook/client';+import { SkillsManifest, SkillsRenders } from '@lobechat/builtin-tool-skills/client';import {WebBrowsingManifest,WebBrowsingRenders,@@ -37,6 +38,7 @@ const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {[LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,[MemoryManifest.identifier]: MemoryRenders as Record<string, BuiltinRender>,[NotebookManifest.identifier]: NotebookRenders as Record<string, BuiltinRender>,+ [SkillsManifest.identifier]: SkillsRenders as Record<string, BuiltinRender>,[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,};