🤯 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(agent-documents): convert a document into an agent skill (#15939)
Arvin Xu35cd15e39e6b
diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentSkills.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentSkills.integration.test.tsindex c36424f17e1..7ab272da103 100644--- a/apps/server/src/routers/lambda/__tests__/integration/agentSkills.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/agentSkills.integration.test.ts@@ -647,6 +647,161 @@ describe('Skill Router Integration Tests', () => {});});+ describe('convertDocumentToSkill', () => {+ it('should migrate an existing document into a managed skill in place', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ const doc = await caller.createDocument({+ agentId,+ content: '# Weekly Report\n\nSummarize the week.',+ title: 'Weekly Report',+ });++ const sourceAgentDocumentId = doc!.id;++ const skill = await caller.convertDocumentToSkill({+ agentId,+ description: 'Generate the weekly report.',+ name: 'weekly-report',+ sourceAgentDocumentId,+ title: 'Weekly Report',+ });++ expect(skill.name).toBe('weekly-report');+ expect(skill.content).toContain('name: weekly-report');+ expect(skill.content).toContain('description: Generate the weekly report.');+ expect(skill.content).toContain('Summarize the week.');++ // The original document row is reused as the SKILL.md index (id preserved).+ expect(skill.index.agentDocumentId).toBe(sourceAgentDocumentId);++ const indexRow = await new AgentDocumentModel(serverDB, userId).findById(+ sourceAgentDocumentId,+ );+ expect(indexRow?.fileType).toBe(SKILL_INDEX_FILE_TYPE);+ expect(indexRow?.filename).toBe(SKILL_INDEX_FILENAME);+ expect(indexRow?.templateId).toBe(AGENT_SKILL_TEMPLATE_ID);++ // A bundle parent was created to hold the index.+ const bundleRow = await new AgentDocumentModel(serverDB, userId).findById(+ skill.bundle.agentDocumentId,+ );+ expect(bundleRow?.fileType).toBe(SKILL_BUNDLE_FILE_TYPE);+ expect(bundleRow?.filename).toBe('weekly-report');+ expect(indexRow?.parentId).toBe(bundleRow?.documentId);+ });++ it('should surface NOT_FOUND when the source document does not exist', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ await expect(+ caller.convertDocumentToSkill({+ agentId,+ description: 'desc',+ name: 'missing-doc',+ sourceAgentDocumentId: '00000000-0000-0000-0000-000000000000',+ title: 'Missing',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('should surface BAD_REQUEST for an invalid skill name', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ const doc = await caller.createDocument({+ agentId,+ content: '# Doc\n\nBody.',+ title: 'Doc',+ });++ await expect(+ caller.convertDocumentToSkill({+ agentId,+ description: 'desc',+ name: 'Bad Name',+ sourceAgentDocumentId: doc!.id,+ title: 'Doc',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('should reject converting an existing managed skill index', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ const doc = await caller.createDocument({+ agentId,+ content: '# Existing Skill\n\nBody.',+ title: 'Existing Skill',+ });++ const skill = await caller.convertDocumentToSkill({+ agentId,+ description: 'An existing skill.',+ name: 'existing-skill',+ sourceAgentDocumentId: doc!.id,+ title: 'Existing Skill',+ });++ // Converting the managed skill index again would reparent it under a new+ // bundle and strip the original bundle of its SKILL.md, corrupting it.+ await expect(+ caller.convertDocumentToSkill({+ agentId,+ description: 'desc',+ name: 'another-skill',+ sourceAgentDocumentId: skill.index.agentDocumentId,+ title: 'Another Skill',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });+ });++ describe('generateSkillMeta', () => {+ it('should surface NOT_FOUND when the source document does not exist', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ await expect(+ caller.generateSkillMeta({+ agentId,+ sourceAgentDocumentId: '00000000-0000-0000-0000-000000000000',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('should reject generating meta for an existing managed skill', async () => {+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));+ const agentId = await createTestAgent(serverDB, userId);++ const doc = await caller.createDocument({+ agentId,+ content: '# Existing Skill\n\nBody.',+ title: 'Existing Skill',+ });++ const skill = await caller.convertDocumentToSkill({+ agentId,+ description: 'An existing skill.',+ name: 'existing-skill',+ sourceAgentDocumentId: doc!.id,+ title: 'Existing Skill',+ });++ // Shares the convert guard: managed skill rows are not convertible, so+ // meta generation must reject before reaching the model.+ await expect(+ caller.generateSkillMeta({+ agentId,+ sourceAgentDocumentId: skill.index.agentDocumentId,+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });+ });+describe('listResources', () => {it('should return empty array for skill without resources', async () => {const caller = agentSkillsRouter.createCaller(createTestContext(userId));diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.tsindex c68f25fe64f..4a075544211 100644--- a/apps/server/src/routers/lambda/agentDocument.ts+++ b/apps/server/src/routers/lambda/agentDocument.ts@@ -3,13 +3,15 @@ import {DocumentLoadFormat,DocumentLoadRule,} from '@lobechat/agent-templates';+import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';import { TRPCError } from '@trpc/server';+import matter from 'gray-matter';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { TopicTrigger } from '@/const/topic';-import { AgentDocumentModel } from '@/database/models/agentDocuments';+import { AgentDocumentModel, deriveAgentDocumentFields } from '@/database/models/agentDocuments';import { TopicModel } from '@/database/models/topic';import { TopicDocumentModel } from '@/database/models/topicDocument';import { router } from '@/libs/trpc/lambda';@@ -19,6 +21,8 @@ import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocumimport { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';+import { SystemAgentService } from '@/server/services/systemAgent';const MAX_METADATA_BYTES = 16 * 1024;const MAX_RULE_REGEXP_LENGTH = 512;@@ -160,6 +164,8 @@ const agentDocumentProcedure = wsCompatProcedure.use(serverDatabase).use(async (agentDocumentModel: new AgentDocumentModel(ctx.serverDB, ctx.userId, wsId),agentDocumentService: new AgentDocumentsService(ctx.serverDB, ctx.userId, wsId),agentDocumentVfsService: new AgentDocumentVfsService(ctx.serverDB, ctx.userId, wsId),+ skillManagementService: new SkillManagementDocumentService(ctx.serverDB, ctx.userId, wsId),+ systemAgentService: new SystemAgentService(ctx.serverDB, ctx.userId, wsId),topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),},@@ -210,6 +216,76 @@ const emitCreateDocumentToolOutcome = async (input: {});};+/**+ * Strips a leading YAML frontmatter block from Markdown so it can be re-fed as+ * `bodyMarkdown` to the skill-management service (which renders its own+ * frontmatter and rejects bodies that already contain one).+ */+const stripLeadingFrontmatter = (content: string): string => {+ try {+ const parsed = matter(content);+ return parsed.matter ? parsed.content.trimStart() : content;+ } catch {+ return content;+ }+};++const convertSkillErrorToTRPC = (error: unknown): never => {+ if (error instanceof TRPCError) throw error;++ if (error instanceof Error) {+ if (/already exists/i.test(error.message)) {+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: error.message });+ }+ if (/invalid skill name|required|frontmatter/i.test(error.message)) {+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });+ }+ }++ throw error;+};++/**+ * Resolve the markdown body of a document that is eligible to become a skill.+ *+ * Shared by `convertDocumentToSkill` and `generateSkillMeta`. Rejects missing+ * documents, and — same as the convert path — folders, web sources, and+ * managed skill bundle/index rows. `createSkill` reparents the source row under+ * a new bundle, so converting an existing skill index would strip its original+ * bundle of its SKILL.md and corrupt it. The UI hides the action for these, but+ * a stale/scripted client could still call through, so enforce it server-side.+ */+const resolveConvertibleDocumentBody = async (+ service: AgentDocumentsService,+ agentId: string,+ sourceAgentDocumentId: string,+): Promise<string> => {+ const source = await service.getDocumentById(sourceAgentDocumentId, agentId);++ if (!source) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Source document not found' });+ }++ const { category, isFolder } = deriveAgentDocumentFields(source);+ if (category !== AGENT_DOCUMENT_CATEGORY || isFolder) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only a plain agent document can be converted into a skill',+ });+ }++ const bodyMarkdown = stripLeadingFrontmatter(source.content ?? '').trim();++ if (!bodyMarkdown) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Cannot convert an empty document into a skill',+ });+ }++ return bodyMarkdown;+};+export const agentDocumentRouter = router({/*** Get all available template sets@@ -579,6 +655,71 @@ export const agentDocumentRouter = router({}}),+ /**+ * Converts an existing agent document into a managed skill (direct migration).+ *+ * The source document row is reused as the skill's `SKILL.md` index (its+ * `documents.id` / `agent_documents.id` are preserved), and a new+ * `skills/bundle` parent is created to hold it. After this call the original+ * document no longer appears at its previous location in the tree.+ */+ convertDocumentToSkill: agentDocumentProcedureWrite+ .input(+ z.object({+ agentId: z.string(),+ description: z.string().trim().min(1),+ name: z.string().trim().min(1),+ sourceAgentDocumentId: z.string(),+ title: z.string().trim().min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const bodyMarkdown = await resolveConvertibleDocumentBody(+ ctx.agentDocumentService,+ input.agentId,+ input.sourceAgentDocumentId,+ );++ try {+ return await ctx.skillManagementService.createSkill({+ agentId: input.agentId,+ bodyMarkdown,+ description: input.description,+ name: input.name,+ sourceAgentDocumentId: input.sourceAgentDocumentId,+ title: input.title,+ });+ } catch (error) {+ return convertSkillErrorToTRPC(error);+ }+ }),++ /**+ * Generates skill metadata (name / title / description) from a document's+ * content, used to prefill the convert-to-skill form. Does not mutate the+ * document; returns `null` when generation fails so the caller can fall back+ * to its own defaults.+ */+ generateSkillMeta: agentDocumentProcedureWrite+ .input(+ z.object({+ agentId: z.string(),+ sourceAgentDocumentId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const bodyMarkdown = await resolveConvertibleDocumentBody(+ ctx.agentDocumentService,+ input.agentId,+ input.sourceAgentDocumentId,+ );++ return ctx.systemAgentService.generateSkillMeta({+ agentId: input.agentId,+ content: bodyMarkdown,+ });+ }),+updateSkillByPath: agentDocumentProcedureWrite.input(updateMountedSkillSchema).mutation(async ({ ctx, input }) => {diff --git a/apps/server/src/services/systemAgent/index.ts b/apps/server/src/services/systemAgent/index.tsindex 24f9bea41ef..13b22c15d24 100644--- a/apps/server/src/services/systemAgent/index.ts+++ b/apps/server/src/services/systemAgent/index.ts@@ -1,4 +1,14 @@-import { chainSummaryTitle } from '@lobechat/prompts';+import { randomUUID } from 'node:crypto';++import { TRACING_SCENARIOS } from '@lobechat/const';+import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import {+ chainGenerateSkillMeta,+ chainSummaryTitle,+ GENERATE_SKILL_META_PROMPT_VERSION,+ GENERATE_SKILL_META_SCHEMA,+ GENERATE_SKILL_META_SCHEMA_NAME,+} from '@lobechat/prompts';import type { UserSystemAgentConfig, UserSystemAgentConfigKey } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import debug from 'debug';@@ -97,6 +107,74 @@ export class SystemAgentService {}}+ /**+ * Generate skill metadata (name / title / description) from a document body,+ * used to prefill the "convert document to skill" form.+ *+ * Emits an `llm_generation_tracing` row under a pre-allocated `tracingId` and+ * returns it so the client can later record implicit feedback (whether the+ * user edited the generated values before saving).+ *+ * @returns The generated metadata + tracingId, or null on failure+ */+ async generateSkillMeta(params: {+ agentId?: string;+ content: string;+ }): Promise<{ description: string; name: string; title: string; tracingId: string } | null> {+ const { agentId, content } = params;+ if (!content.trim()) return null;++ try {+ const { model, provider } = await this.getTaskModelConfig('agentMeta');+ const locale = await this.getUserLocale();++ log('generateSkillMeta: locale=%s, model=%s, provider=%s', locale, model, provider);++ const payload = chainGenerateSkillMeta({ content, responseLanguage: locale });+ const tracingId = randomUUID();++ const modelRuntime = await initModelRuntimeFromDB(+ this.db,+ this.userId,+ provider,+ this.workspaceId,+ );+ const result = await modelRuntime.generateObject(+ {+ messages: payload.messages as any[],+ model,+ schema: GENERATE_SKILL_META_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.Api },+ tracing: {+ agentId,+ promptVersion: GENERATE_SKILL_META_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.DocumentToSkillMeta,+ schemaName: GENERATE_SKILL_META_SCHEMA_NAME,+ tracingId,+ } satisfies TracingOptions,+ },+ );++ const meta = result as { description?: string; name?: string; title?: string };+ const name = meta?.name?.trim();+ const title = meta?.title?.trim();+ const description = meta?.description?.trim();++ if (!name || !title || !description) {+ log('generateSkillMeta: LLM returned incomplete meta');+ return null;+ }++ log('generateSkillMeta: generated name="%s", title="%s"', name, title);+ return { description, name, title, tracingId };+ } catch (error) {+ console.error('SystemAgentService.generateSkillMeta failed:', error);+ return null;+ }+ }+// ============== Private Helpers ============== ///**diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex da260803ad8..7f74ea48635 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1105,6 +1105,7 @@"workingPanel.resources.renameEmpty": "Title cannot be empty","workingPanel.resources.renameError": "Failed to rename document","workingPanel.resources.renameSuccess": "Document renamed",+ "workingPanel.resources.tree.convertToSkill": "Convert to skill","workingPanel.resources.tree.createError": "Failed to create","workingPanel.resources.tree.deleteSelected": "Delete selected ({{count}})","workingPanel.resources.tree.moveError": "Failed to move",@@ -1159,6 +1160,20 @@"workingPanel.skills.actions.delete": "Delete","workingPanel.skills.actions.rename": "Rename","workingPanel.skills.actions.view": "View",+ "workingPanel.skills.convert.action": "Convert",+ "workingPanel.skills.convert.descriptionLabel": "Description",+ "workingPanel.skills.convert.descriptionPlaceholder": "Describe when this skill should be used, so the agent knows when to load it.",+ "workingPanel.skills.convert.generateError": "Failed to generate skill details. Please fill them in manually.",+ "workingPanel.skills.convert.generateHint": "Auto-filled from the document — edit anything before saving.",+ "workingPanel.skills.convert.generating": "Generating skill details from the document…",+ "workingPanel.skills.convert.nameHint": "Lowercase letters, digits, and hyphens only.",+ "workingPanel.skills.convert.nameInvalid": "Use lowercase letters, digits, and hyphens only (e.g. weekly-report).",+ "workingPanel.skills.convert.nameLabel": "Skill name",+ "workingPanel.skills.convert.namePlaceholder": "e.g. weekly-report",+ "workingPanel.skills.convert.regenerate": "Regenerate",+ "workingPanel.skills.convert.title": "Convert document to skill",+ "workingPanel.skills.convert.titleLabel": "Title",+ "workingPanel.skills.convert.titlePlaceholder": "e.g. Weekly Report","workingPanel.skills.delete.agentConfirm": "Remove the skill “{{name}}” from this agent? This cannot be undone.","workingPanel.skills.delete.error": "Failed to delete skill","workingPanel.skills.delete.success": "Skill deleted",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 62b4f67d736..32ef4364821 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1105,6 +1105,7 @@"workingPanel.resources.renameEmpty": "标题不能为空","workingPanel.resources.renameError": "重命名失败","workingPanel.resources.renameSuccess": "重命名成功",+ "workingPanel.resources.tree.convertToSkill": "转换为技能","workingPanel.resources.tree.createError": "创建失败","workingPanel.resources.tree.deleteSelected": "删除所选({{count}})","workingPanel.resources.tree.moveError": "移动失败",@@ -1159,6 +1160,20 @@"workingPanel.skills.actions.delete": "删除","workingPanel.skills.actions.rename": "重命名","workingPanel.skills.actions.view": "查看",+ "workingPanel.skills.convert.action": "转换",+ "workingPanel.skills.convert.descriptionLabel": "描述",+ "workingPanel.skills.convert.descriptionPlaceholder": "描述这个技能在什么场景下使用,让智能体知道何时加载它。",+ "workingPanel.skills.convert.generateError": "生成技能信息失败,请手动填写。",+ "workingPanel.skills.convert.generateHint": "已根据文档自动填写,保存前可随意修改。",+ "workingPanel.skills.convert.generating": "正在根据文档生成技能信息…",+ "workingPanel.skills.convert.nameHint": "仅支持小写字母、数字和连字符。",+ "workingPanel.skills.convert.nameInvalid": "仅支持小写字母、数字和连字符(例如 weekly-report)。",+ "workingPanel.skills.convert.nameLabel": "技能名称",+ "workingPanel.skills.convert.namePlaceholder": "例如 weekly-report",+ "workingPanel.skills.convert.regenerate": "重新生成",+ "workingPanel.skills.convert.title": "将文档转换为技能",+ "workingPanel.skills.convert.titleLabel": "标题",+ "workingPanel.skills.convert.titlePlaceholder": "例如 周报","workingPanel.skills.delete.agentConfirm": "确定从当前智能体移除技能「{{name}}」?此操作不可撤销。","workingPanel.skills.delete.error": "删除技能失败","workingPanel.skills.delete.success": "技能已删除",diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 09447a89de6..6b7bb0f05ec 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -9,6 +9,7 @@export const TRACING_SCENARIOS = {AgentSignal: 'agent_signal',AgentWelcome: 'agent_welcome',+ DocumentToSkillMeta: 'document_to_skill_meta',FollowUp: 'follow_up',HomeBrief: 'home_brief',InputCompletion: 'input_completion',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 48343183195..42ad9d80e46 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1150,6 +1150,7 @@ export default {'workingPanel.resources.renameEmpty': 'Title cannot be empty','workingPanel.resources.renameError': 'Failed to rename document','workingPanel.resources.renameSuccess': 'Document renamed',+ 'workingPanel.resources.tree.convertToSkill': 'Convert to skill','workingPanel.resources.tree.createError': 'Failed to create','workingPanel.resources.tree.deleteSelected': 'Delete selected ({{count}})','workingPanel.resources.tree.moveError': 'Failed to move',@@ -1177,6 +1178,24 @@ export default {'workingPanel.skills.actions.delete': 'Delete','workingPanel.skills.actions.rename': 'Rename','workingPanel.skills.actions.view': 'View',+ 'workingPanel.skills.convert.action': 'Convert',+ 'workingPanel.skills.convert.descriptionLabel': 'Description',+ 'workingPanel.skills.convert.descriptionPlaceholder':+ 'Describe when this skill should be used, so the agent knows when to load it.',+ 'workingPanel.skills.convert.generateError':+ 'Failed to generate skill details. Please fill them in manually.',+ 'workingPanel.skills.convert.generateHint':+ 'Auto-filled from the document — edit anything before saving.',+ 'workingPanel.skills.convert.generating': 'Generating skill details from the document…',+ 'workingPanel.skills.convert.nameHint': 'Lowercase letters, digits, and hyphens only.',+ 'workingPanel.skills.convert.nameInvalid':+ 'Use lowercase letters, digits, and hyphens only (e.g. weekly-report).',+ 'workingPanel.skills.convert.nameLabel': 'Skill name',+ 'workingPanel.skills.convert.namePlaceholder': 'e.g. weekly-report',+ 'workingPanel.skills.convert.regenerate': 'Regenerate',+ 'workingPanel.skills.convert.title': 'Convert document to skill',+ 'workingPanel.skills.convert.titleLabel': 'Title',+ 'workingPanel.skills.convert.titlePlaceholder': 'e.g. Weekly Report','workingPanel.skills.delete.agentConfirm':'Remove the skill “{{name}}” from this agent? This cannot be undone.','workingPanel.skills.delete.error': 'Failed to delete skill',diff --git a/packages/prompts/src/chains/__tests__/generateSkillMeta.test.ts b/packages/prompts/src/chains/__tests__/generateSkillMeta.test.tsnew file mode 100644index 00000000000..b71db7777bd--- /dev/null+++ b/packages/prompts/src/chains/__tests__/generateSkillMeta.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { chainGenerateSkillMeta, GENERATE_SKILL_META_SCHEMA } from '../generateSkillMeta';++describe('chainGenerateSkillMeta', () => {+ const baseParams = {+ content: '# Weekly Report\n\nSummarize the week and highlight blockers.',+ responseLanguage: 'zh-CN',+ };++ it('instructs the model to emit name / title / description', () => {+ const payload = chainGenerateSkillMeta(baseParams);+ const system = (payload.messages?.[0] as { content: string }).content;++ expect(system).toMatch(/"name"/);+ expect(system).toMatch(/"title"/);+ expect(system).toMatch(/"description"/);+ // The description must describe WHEN to use the skill, not just restate the title.+ expect(system).toMatch(/WHEN the agent should use it/i);+ });++ it('keeps name ASCII kebab-case regardless of the document language', () => {+ const payload = chainGenerateSkillMeta(baseParams);+ const system = (payload.messages?.[0] as { content: string }).content;++ expect(system).toMatch(/kebab-case/i);+ expect(system).toContain('zh-CN');+ expect(system).toMatch(/name.*always.*ASCII/i);+ });++ it('embeds the document content in the user message', () => {+ const payload = chainGenerateSkillMeta(baseParams);+ const user = (payload.messages?.[1] as { content: string }).content;++ expect(user).toContain('Summarize the week and highlight blockers.');+ });+});++describe('GENERATE_SKILL_META_SCHEMA', () => {+ it('requires name, title, and description', () => {+ expect(GENERATE_SKILL_META_SCHEMA.schema.required).toEqual(['name', 'title', 'description']);+ expect(Object.keys(GENERATE_SKILL_META_SCHEMA.schema.properties).sort()).toEqual([+ 'description',+ 'name',+ 'title',+ ]);+ });+});diff --git a/packages/prompts/src/chains/generateSkillMeta.ts b/packages/prompts/src/chains/generateSkillMeta.tsnew file mode 100644index 00000000000..8dacc50f1f9--- /dev/null+++ b/packages/prompts/src/chains/generateSkillMeta.ts@@ -0,0 +1,68 @@+import type { ChatStreamPayload } from '@lobechat/types';++/**+ * Bump when editing the system prompt or schema below. Plumbed through tracing+ * at the call site so per-call tracing groups runs by prompt iteration.+ */+export const GENERATE_SKILL_META_PROMPT_VERSION = 'v1.0';++export const GENERATE_SKILL_META_SCHEMA_NAME = 'skill_meta';++/**+ * Generate the metadata (name / title / description) for a managed skill from+ * the markdown body of an existing agent document.+ *+ * A skill's `description` is the single most important field: the agent reads+ * it to decide WHEN to load the skill, so it must state what the skill does and+ * the situations that should trigger it — not merely restate the title. The+ * `name` is a stable kebab-case identifier (filesystem-safe); the `title` is a+ * short human-readable label.+ */+export const chainGenerateSkillMeta = (params: {+ /** Markdown body of the source document (frontmatter already stripped). */+ content: string;+ /** Target output language, e.g. `zh-CN`. */+ responseLanguage: string;+}): Partial<ChatStreamPayload> => {+ const systemContent = `You are turning an existing document into a reusable agent skill. Read the document and produce concise metadata for it.++Output a JSON object with these fields:+- "name": string. A stable, filesystem-safe identifier in lowercase kebab-case (lowercase letters, digits, and single hyphens only; no spaces, no leading/trailing hyphen; max 80 chars), e.g. "weekly-report" or "pdf-form-filler". Derive it from the document's purpose, NOT a transliteration of the title. Always ASCII regardless of the document language.+- "title": string. A short, human-readable label (max 60 chars).+- "description": string. One or two sentences describing WHAT the skill does AND WHEN the agent should use it, so the agent can decide whether to load it. Lead with the trigger situation. Do not just repeat the title.++Language:+- Output "title" and "description" in ${params.responseLanguage}.+- "name" must always be ASCII lowercase kebab-case, even when the document is in another language.++Output ONLY the JSON object, no markdown fences or explanations.`;++ return {+ messages: [+ { content: systemContent, role: 'system' },+ { content: `Document:\n${params.content}`, role: 'user' },+ ],+ temperature: 0.2,+ };+};++export const GENERATE_SKILL_META_SCHEMA = {+ name: GENERATE_SKILL_META_SCHEMA_NAME,+ schema: {+ additionalProperties: false,+ properties: {+ description: {+ description: 'One or two sentences: what the skill does and when to use it.',+ type: 'string',+ },+ name: {+ description: 'Lowercase kebab-case identifier (ASCII, max 80 chars).',+ type: 'string',+ },+ title: { description: 'Short human-readable label (max 60 chars).', type: 'string' },+ },+ required: ['name', 'title', 'description'],+ type: 'object' as const,+ },+ strict: true,+};diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex 77db79da101..72008f16abe 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -3,6 +3,7 @@ export * from './agentSignal/analyzeIntent';export * from './answerWithContext';export * from './compressContext';export * from './generateBrief';+export * from './generateSkillMeta';export * from './inputCompletion';export * from './judgeBriefEmit';export * from './langDetect';diff --git a/src/features/AgentDocumentsExplorer/ConvertToSkillModal.tsx b/src/features/AgentDocumentsExplorer/ConvertToSkillModal.tsxnew file mode 100644index 00000000000..b684dc44f7f--- /dev/null+++ b/src/features/AgentDocumentsExplorer/ConvertToSkillModal.tsx@@ -0,0 +1,302 @@+'use client';++import { Button, Flexbox, Input, Text, TextArea } from '@lobehub/ui';+import { createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { type InputRef } from 'antd';+import { cssVar } from 'antd-style';+import { t } from 'i18next';+import { Sparkles } from 'lucide-react';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useClientDataSWR } from '@/libs/swr';++const GENERATE_SWR_KEY = 'document-to-skill-meta';+const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const MAX_SKILL_NAME_LENGTH = 80;++/**+ * Derives a default skill name from a document title: lowercase, non-alphanumeric+ * runs collapsed to hyphens, trimmed. Returns '' when nothing usable remains+ * (e.g. a CJK-only title), in which case the user must type a name.+ */+export const slugifySkillName = (input: string): string =>+ input+ .toLowerCase()+ .replaceAll(/[^a-z0-9]+/g, '-')+ .replaceAll(/^-+|-+$/g, '')+ .slice(0, MAX_SKILL_NAME_LENGTH)+ .replaceAll(/-+$/g, '');++/** Skill metadata the auto-generator returns and the form collects. */+export interface ConvertSkillMeta {+ description: string;+ name: string;+ title: string;+}++/** Generation result: the prefilled values plus the tracing id feedback attaches to. */+export interface GeneratedSkillMeta extends ConvertSkillMeta {+ tracingId: string;+}++/**+ * Implicit-feedback payload assembled on save when the form was prefilled by+ * generation: whether (and which fields) the user edited before saving, the+ * generated baseline, and the tracing id to attribute the signal to.+ */+export interface SkillMetaGenerationFeedback {+ edited: boolean;+ editedFields: string[];+ generated: ConvertSkillMeta;+ tracingId: string;+}++interface ConvertToSkillContentProps {+ defaultDescription: string;+ defaultName: string;+ defaultTitle: string;+ /**+ * Stable SWR cache key for the generation request. Required alongside+ * `onGenerate` so the auto-generation dedupes and is lifecycle-safe.+ */+ generateCacheKey?: unknown;+ /**+ * Auto-generate skill metadata from the document content. Runs automatically+ * when the modal opens (via SWR), and again when the user clicks regenerate.+ * Return the metadata to prefill the form, or undefined when generation fails+ * (an inline error is shown). Omit to disable auto-generation entirely.+ */+ onGenerate?: () => Promise<GeneratedSkillMeta | undefined>;+ /**+ * Convert the document into a skill. Return an error message to show inline and+ * keep the modal open; return undefined on success (the modal closes). When the+ * form was prefilled by generation, `generation` carries the edit diff for+ * implicit feedback.+ */+ onSubmit: (+ params: ConvertSkillMeta & { generation?: SkillMetaGenerationFeedback },+ ) => Promise<string | undefined>;+}++const ConvertToSkillContent = memo<ConvertToSkillContentProps>(+ ({ defaultName, defaultTitle, defaultDescription, generateCacheKey, onGenerate, onSubmit }) => {+ const { t: tChat } = useTranslation('chat');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ const [name, setName] = useState(defaultName);+ const [title, setTitle] = useState(defaultTitle);+ const [description, setDescription] = useState(defaultDescription);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string>();+ const nameRef = useRef<InputRef>(null);+ // The last generation's prefilled values + tracing id, used on save to+ // record whether the user edited the generation (implicit feedback).+ const generatedRef = useRef<{ tracingId: string; values: ConvertSkillMeta } | undefined>(+ undefined,+ );++ useEffect(() => {+ queueMicrotask(() => nameRef.current?.focus());+ }, []);++ // Auto-generate on open via SWR: runs once on mount and dedupes rapid+ // re-mounts (e.g. StrictMode). Focus/reconnect revalidation and error retry+ // are disabled — regenerating burns tokens + writes a tracing row, so it+ // must only fire on open or via the explicit Regenerate action (`mutate`).+ const { isValidating: generating, mutate: regenerate } = useClientDataSWR<+ GeneratedSkillMeta | undefined+ >(onGenerate ? (generateCacheKey ?? GENERATE_SWR_KEY) : null, () => onGenerate!(), {+ dedupingInterval: 2000,+ onError: () => setError(tChat('workingPanel.skills.convert.generateError')),+ onSuccess: (meta) => {+ if (!meta) {+ setError(tChat('workingPanel.skills.convert.generateError'));+ return;+ }+ // The model is instructed to return kebab-case, but slugify+ // defensively so an off-spec name still lands in a valid state. The+ // baseline for the edit diff is the value actually placed in the form+ // (post-slugify), so a pure normalization never reads as a user edit.+ const values: ConvertSkillMeta = {+ description: meta.description,+ name: slugifySkillName(meta.name) || meta.name,+ title: meta.title,+ };+ setName(values.name);+ setTitle(values.title);+ setDescription(values.description);+ setError(undefined);+ generatedRef.current = { tracingId: meta.tracingId, values };+ // Fields are disabled while generating, so the mount focus no-ops;+ // focus the name once values land so the user can edit immediately.+ queueMicrotask(() => nameRef.current?.focus());+ },+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ shouldRetryOnError: false,+ });++ const handleRegenerate = useCallback(() => {+ setError(undefined);+ void regenerate();+ }, [regenerate]);++ const trimmedName = name.trim();+ const trimmedTitle = title.trim();+ const trimmedDescription = description.trim();+ const nameInvalid = useMemo(+ () => !!trimmedName && !SKILL_NAME_PATTERN.test(trimmedName),+ [trimmedName],+ );+ const busy = loading || generating;+ const canSubmit = !!trimmedName && !nameInvalid && !!trimmedTitle && !!trimmedDescription;++ const handleSubmit = useCallback(async () => {+ if (busy || !canSubmit) return;+ setLoading(true);+ try {+ const values: ConvertSkillMeta = {+ description: trimmedDescription,+ name: trimmedName,+ title: trimmedTitle,+ };+ let generation: SkillMetaGenerationFeedback | undefined;+ const gen = generatedRef.current;+ if (gen) {+ const editedFields = (['name', 'title', 'description'] as const).filter(+ (field) => values[field] !== gen.values[field],+ );+ generation = {+ edited: editedFields.length > 0,+ editedFields,+ generated: gen.values,+ tracingId: gen.tracingId,+ };+ }+ const message = await onSubmit({ ...values, generation });+ if (message) {+ setError(message);+ return;+ }+ close();+ } finally {+ setLoading(false);+ }+ }, [busy, canSubmit, close, onSubmit, trimmedDescription, trimmedName, trimmedTitle]);++ return (+ <Flexbox gap={16}>+ {onGenerate ? (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {generating+ ? tChat('workingPanel.skills.convert.generating')+ : tChat('workingPanel.skills.convert.generateHint')}+ </Text>+ <Button icon={Sparkles} loading={generating} size={'small'} onClick={handleRegenerate}>+ {tChat('workingPanel.skills.convert.regenerate')}+ </Button>+ </Flexbox>+ ) : null}+ <Flexbox gap={6}>+ <Text type={'secondary'}>{tChat('workingPanel.skills.convert.nameLabel')}</Text>+ <Input+ disabled={generating}+ placeholder={tChat('workingPanel.skills.convert.namePlaceholder')}+ ref={nameRef}+ value={name}+ onChange={(e) => {+ setName(e.target.value);+ setError(undefined);+ }}+ />+ {nameInvalid ? (+ <Text style={{ color: cssVar.colorError, fontSize: 12 }}>+ {tChat('workingPanel.skills.convert.nameInvalid')}+ </Text>+ ) : (+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {tChat('workingPanel.skills.convert.nameHint')}+ </Text>+ )}+ </Flexbox>+ <Flexbox gap={6}>+ <Text type={'secondary'}>{tChat('workingPanel.skills.convert.titleLabel')}</Text>+ <Input+ disabled={generating}+ placeholder={tChat('workingPanel.skills.convert.titlePlaceholder')}+ value={title}+ onChange={(e) => {+ setTitle(e.target.value);+ setError(undefined);+ }}+ />+ </Flexbox>+ <Flexbox gap={6}>+ <Text type={'secondary'}>{tChat('workingPanel.skills.convert.descriptionLabel')}</Text>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 2 }}+ disabled={generating}+ placeholder={tChat('workingPanel.skills.convert.descriptionPlaceholder')}+ value={description}+ onChange={(e) => {+ setDescription(e.target.value);+ setError(undefined);+ }}+ />+ </Flexbox>+ {error ? <Text style={{ color: cssVar.colorError, fontSize: 12 }}>{error}</Text> : null}+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={busy} onClick={close}>+ {tCommon('cancel')}+ </Button>+ <Button+ disabled={!canSubmit || generating}+ loading={loading}+ type={'primary'}+ onClick={handleSubmit}+ >+ {tChat('workingPanel.skills.convert.action')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ },+);++ConvertToSkillContent.displayName = 'ConvertToSkillContent';++/**+ * Collects a skill name / title / description, then converts an existing agent+ * document into a managed skill (direct migration — the original document+ * becomes the skill's SKILL.md). When `onGenerate` is provided, the fields are+ * auto-filled from the document on open and the user can regenerate or edit.+ */+export const openConvertToSkillModal = (options: {+ defaultDescription: string;+ defaultName: string;+ defaultTitle: string;+ generateCacheKey?: unknown;+ onGenerate?: () => Promise<GeneratedSkillMeta | undefined>;+ onSubmit: (+ params: ConvertSkillMeta & { generation?: SkillMetaGenerationFeedback },+ ) => Promise<string | undefined>;+}): ModalInstance =>+ createModal({+ content: (+ <ConvertToSkillContent+ defaultDescription={options.defaultDescription}+ defaultName={options.defaultName}+ defaultTitle={options.defaultTitle}+ generateCacheKey={options.generateCacheKey}+ onGenerate={options.onGenerate}+ onSubmit={options.onSubmit}+ />+ ),+ footer: null,+ maskClosable: true,+ styles: { header: { borderBottom: 'none' } },+ title: t('workingPanel.skills.convert.title', { ns: 'chat' }),+ width: 'min(90vw, 480px)',+ });diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex e0c00ab6022..154ecf28964 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -21,7 +21,9 @@ import {HIDE_POINTER_FOCUS_RING_CSS,} from '@/features/ExplorerTree';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { agentDocumentService } from '@/services/agentDocument';+import { openConvertToSkillModal, slugifySkillName } from './ConvertToSkillModal';import DocumentExplorerToolbar from './DocumentExplorerToolbar';import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';import type { AgentDocumentItem } from './types';@@ -178,6 +180,54 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen[focusNewRowForRename, ops],);+ const handleConvertToSkill = useCallback(+ (doc: AgentDocumentItem) => {+ const fallbackTitle = doc.title || doc.filename || '';+ openConvertToSkillModal({+ defaultDescription: doc.description ?? '',+ defaultName: slugifySkillName(fallbackTitle),+ defaultTitle: fallbackTitle,+ generateCacheKey: ['document-to-skill-meta', agentId, doc.id],+ onGenerate: async () => {+ const meta = await agentDocumentService.generateSkillMeta({+ agentId,+ sourceAgentDocumentId: doc.id,+ });+ return meta ?? undefined;+ },+ onSubmit: async ({ name, description, title, generation }) => {+ try {+ await agentDocumentService.convertDocumentToSkill({+ agentId,+ description,+ name,+ sourceAgentDocumentId: doc.id,+ title,+ });+ // Record implicit feedback: saving the generated values unchanged is+ // a positive signal, editing them is negative. Best-effort.+ if (generation) {+ void agentDocumentService.recordSkillMetaFeedback({+ data: {+ editedFields: generation.editedFields,+ final: { description, name, title },+ generated: generation.generated,+ },+ edited: generation.edited,+ tracingId: generation.tracingId,+ });+ }+ await mutate();+ return undefined;+ } catch (error) {+ return error instanceof Error ? error.message : String(error);+ }+ },+ });+ },+ [agentId, mutate],+ );+const handleNodeClick = useCallback((node: ExplorerTreeNode<AgentDocumentItem>) => {const doc = node.data;@@ -285,6 +335,18 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen});}+ // Only plain agent documents (not folders, web sources, or existing+ // skills) can be migrated into a managed skill.+ const isConvertibleToSkill =+ !isFolder && !isSkill && node.data?.category === AGENT_DOCUMENT_CATEGORY;+ if (isConvertibleToSkill && !isMulti) {+ items.push({+ key: 'convert-to-skill',+ label: t('workingPanel.resources.tree.convertToSkill'),+ onClick: () => handleConvertToSkill(node.data!),+ });+ }+items.push({danger: true,icon: <Trash2Icon size={14} />,@@ -299,6 +361,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen},[agentId,+ handleConvertToSkill,handleCreateDocument,handleCreateFolder,isRecoverableSkillBundle,diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex 579d0d2e7a1..dccea25616b 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -220,6 +220,58 @@ class AgentDocumentService {return result;};+ convertDocumentToSkill = async (params: {+ agentId: string;+ description: string;+ name: string;+ sourceAgentDocumentId: string;+ title: string;+ }) => {+ const result = await lambdaClient.agentDocument.convertDocumentToSkill.mutate(params);+ // The conversion reparents the same row into a skill bundle, preserving its+ // documents.id / agent_documents.id. An editor that still has the document+ // open is cached as plain markdown, so invalidate its editor caches too —+ // otherwise the next autosave from that stale editor would overwrite the+ // generated SKILL.md frontmatter/body via the document save path.+ await invalidateDocumentMutation({+ agentDocumentId: result.index.agentDocumentId,+ agentId: params.agentId,+ cause: 'agent-document',+ documentId: result.index.documentId,+ });++ return result;+ };++ generateSkillMeta = async (params: { agentId: string; sourceAgentDocumentId: string }) => {+ return lambdaClient.agentDocument.generateSkillMeta.mutate(params);+ };++ /**+ * Records implicit feedback on an auto-generated skill-meta generation: when+ * the user saves without editing the generated values it's a positive signal,+ * otherwise negative. Best-effort — never block the save on a feedback write.+ */+ recordSkillMetaFeedback = async (params: {+ data?: Record<string, unknown>;+ edited: boolean;+ tracingId: string;+ }) => {+ try {+ await lambdaClient.llmGenerationTracing.recordFeedback.mutate(+ {+ data: params.data,+ signal: params.edited ? 'negative' : 'positive',+ source: 'convert_to_skill',+ tracingId: params.tracingId,+ },+ { context: { showNotification: false } },+ );+ } catch (error) {+ console.warn('[agentDocument] Failed to record skill-meta feedback:', error);+ }+ };+createFolder = async (params: { agentId: string; path: string; recursive?: boolean }) => {const result = await lambdaClient.agentDocument.mkdirDocumentByPath.mutate(params);await revalidateAgentDocuments(params.agentId);