🤯 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
🐛 fix(skill): import market skills whose SKILL.md has no front-matter (#20080)
Arvin Xu19b23d294d80
diff --git a/apps/server/src/services/skill/importer.test.ts b/apps/server/src/services/skill/importer.test.tsindex 270b1d01cad..d41fc2c5150 100644--- a/apps/server/src/services/skill/importer.test.ts+++ b/apps/server/src/services/skill/importer.test.ts@@ -9,6 +9,7 @@ import { AgentSkillModel } from '@/database/models/agentSkill';import { SkillImportError } from './errors';import { SkillImporter } from './importer';+import type * as ParserModule from './parser';// Mock external dependencies only (GitHub, S3, parser)const normalizeIdentifierPart = (part: string) =>@@ -1026,6 +1027,53 @@ description: A nested skill// Regression: the imported body is stored and returned to the caller, so a raw fetch here// is a full-read SSRF. The fetch must go through the SSRF guard. See GHSA-53h9-fmjf-frwr / #16536.+ it('should import a market ZIP whose SKILL.md has no front-matter (importFromMarket path)', async () => {+ // Use the real parser for this case: the regression lives in manifest derivation+ const { SkillParser: RealSkillParser } = (await vi.importActual(+ './parser',+ )) as typeof ParserModule;+ const realParser = new RealSkillParser();+ mockParserInstance.parseZipPackage.mockImplementation((buffer, options) =>+ realParser.parseZipPackage(buffer, options),+ );++ // Real shape of market package brainbytes-dev-everything-claude-finance-aml-kyc+ const skillMd = `# AML/KYC Compliance++> Customer due diligence, suspicious activity reporting, PEP screening, sanctions — Anti-Money Laundering and Know Your Customer compliance.++## When to Activate++- Customer onboarding and KYC process design+`;+ const { zipSync } = await import('fflate');+ const zipped = zipSync({ 'SKILL.md': new TextEncoder().encode(skillMd) });++ mockSsrfSafeFetch.mockResolvedValue({+ arrayBuffer: async () =>+ zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength),+ headers: new Headers({ 'content-type': 'application/zip' }),+ ok: true,+ status: 200,+ });++ const identifier = 'brainbytes-dev-everything-claude-finance-aml-kyc';+ // Same call shape as agentSkillsRouter.importFromMarket+ const result = await importer.importFromUrl(+ { url: `https://market.lobehub.com/api/v1/skills/${identifier}/download` },+ { identifier, source: 'market' },+ );++ expect(result.status).toBe('created');+ expect(result.skill.identifier).toBe(identifier);+ expect(result.skill.name).toBe('AML/KYC Compliance');+ expect(result.skill.description).toMatch(/^Customer due diligence/);+ expect(result.skill.source).toBe('market');+ expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(expect.any(Buffer), {+ fallbackName: identifier,+ });+ });+describe('SSRF protection (#16536)', () => {it('should fetch the user URL through ssrfSafeFetch, not raw global fetch', async () => {mockSsrfSafeFetch.mockResolvedValue({diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.tsindex 71bd5ba0f08..a99dd46d7c1 100644--- a/apps/server/src/services/skill/importer.ts+++ b/apps/server/src/services/skill/importer.ts@@ -381,7 +381,9 @@ export class SkillImporter {// Handle ZIP filelog('importFromUrl: detected ZIP file, parsing as package...');zipBuffer = Buffer.from(await response.arrayBuffer());- const parsed = await this.parser.parseZipPackage(zipBuffer);+ const parsed = await this.parser.parseZipPackage(zipBuffer, {+ fallbackName: options?.identifier,+ });manifest = parsed.manifest;skillContent = parsed.content;zipHash = parsed.zipHash;@@ -391,7 +393,7 @@ export class SkillImporter {// Handle plain SKILL.mdlog('importFromUrl: detected SKILL.md, parsing as markdown...');const content = await response.text();- const parsed = this.parser.parseSkillMd(content);+ const parsed = this.parser.parseSkillMd(content, { fallbackName: options?.identifier });manifest = parsed.manifest;skillContent = parsed.content;log('importFromUrl: parsed SKILL.md, manifest=%o', manifest);diff --git a/apps/server/src/services/skill/parser.test.ts b/apps/server/src/services/skill/parser.test.tsindex f4c7505403e..0a05e1ec575 100644--- a/apps/server/src/services/skill/parser.test.ts+++ b/apps/server/src/services/skill/parser.test.ts@@ -140,6 +140,276 @@ description: test});});+ describe('parseSkillMd without front-matter (market skills)', () => {+ // Real shape of market package brainbytes-dev-everything-claude-finance-aml-kyc+ const amlKycSkillMd = `# AML/KYC Compliance++> Customer due diligence, suspicious activity reporting, PEP screening, sanctions — Anti-Money Laundering and Know Your Customer compliance.++## When to Activate++- Customer onboarding and KYC process design+- Risk classification of customers (CDD, EDD, SDD)+`;++ // Real shape of market package openclaw-skills-a-stock-watcher+ const stockWatcherSkillMd = `# A 股盯盘技能 - 多数据源增强版++基于东方财富/腾讯财经/新浪财经的 A 股实时监控技能。++## 功能++### 基础功能+- 📈 **实时查价** - 获取 A 股实时行情(延迟 5-15 秒)+`;++ it('should derive name from H1 and description from the blockquote', () => {+ const result = parser.parseSkillMd(amlKycSkillMd);++ expect(result.manifest.name).toBe('AML/KYC Compliance');+ expect(result.manifest.description).toBe(+ 'Customer due diligence, suspicious activity reporting, PEP screening, sanctions — Anti-Money Laundering and Know Your Customer compliance.',+ );+ expect(result.content).toBe(amlKycSkillMd.trim());+ });++ it('should derive description from the first paragraph after the H1', () => {+ const result = parser.parseSkillMd(stockWatcherSkillMd);++ expect(result.manifest.name).toBe('A 股盯盘技能 - 多数据源增强版');+ expect(result.manifest.description).toBe(+ '基于东方财富/腾讯财经/新浪财经的 A 股实时监控技能。',+ );+ });++ it('should use fallbackName when there is no H1', () => {+ const result = parser.parseSkillMd(+ 'Plain instructions for the agent.\n\n## Usage\n\nDo it.',+ {+ fallbackName: 'my-market-skill',+ },+ );++ expect(result.manifest.name).toBe('my-market-skill');+ expect(result.manifest.description).toBe('Plain instructions for the agent.');+ });++ it('should prefer the H1 over fallbackName', () => {+ const result = parser.parseSkillMd(amlKycSkillMd, { fallbackName: 'identifier' });++ expect(result.manifest.name).toBe('AML/KYC Compliance');+ });++ it('should skip code fences and cap long derived descriptions', () => {+ const long = 'word '.repeat(200).trim();+ const result = parser.parseSkillMd(`# Title\n\n\`\`\`bash\nnpm i x\n\`\`\`\n\n${long}\n`);++ expect(result.manifest.name).toBe('Title');+ expect(result.manifest.description!.length).toBeLessThanOrEqual(300);+ expect(result.manifest.description!.endsWith('…')).toBe(true);+ expect(result.manifest.description).not.toContain('npm');+ });++ it('should still reject a genuinely empty SKILL.md', () => {+ expect(() => parser.parseSkillMd('', { fallbackName: 'x' })).toThrow(SkillManifestError);+ expect(() =>+ parser.parseSkillMd('\n\n## Only a subheading\n', { fallbackName: 'x' }),+ ).toThrow(SkillManifestError);+ });++ it('should still reject a heading-only SKILL.md (no description text)', () => {+ expect(() => parser.parseSkillMd('# Just a title\n')).toThrow(SkillManifestError);+ });++ it('should not derive fields when front-matter is present but incomplete', () => {+ const content = `---+name: test-skill+---+# Title++Some paragraph that must not become the description.`;++ expect(() => parser.parseSkillMd(content)).toThrow(SkillManifestError);+ });++ it('should not derive fields when an empty or comment-only front-matter block is present', () => {+ // gray-matter parses both to `{}`, same as an absent block — the block+ // must still be authoritative.+ const body = '# Title\n\nBody that must not become the description.';+ expect(() => parser.parseSkillMd(`---\n---\n${body}`)).toThrow(SkillManifestError);+ expect(() => parser.parseSkillMd(`---\n# just a yaml comment\n---\n${body}`)).toThrow(+ SkillManifestError,+ );+ });++ it('should still take the H1 and its summary when a preamble line precedes the title', () => {+ const result = parser.parseSkillMd(+ '[English](README.md) | [中文](README.zh.md)\n\n# Stock Watcher\n\nWatches A-share prices and alerts on moves.\n',+ { fallbackName: 'openclaw-skills-a-stock-watcher' },+ );++ expect(result.manifest.name).toBe('Stock Watcher');+ expect(result.manifest.description).toBe('Watches A-share prices and alerts on moves.');+ });++ it('should skip linked badge lines after the title', () => {+ const result = parser.parseSkillMd(+ '# Stock Watcher\n\n[](https://ci.example.com) [](https://npm.im/x)\n\nWatches A-share prices and alerts on moves.\n',+ );++ expect(result.manifest.name).toBe('Stock Watcher');+ expect(result.manifest.description).toBe('Watches A-share prices and alerts on moves.');+ });++ it('should keep a nested fence inside its longer outer fence', () => {+ const result = parser.parseSkillMd(+ '# Title\n\n````md\n```js\ninternal code\n```\n````\n\nReal summary.\n',+ );++ expect(result.manifest.description).toBe('Real summary.');+ });++ it('should treat an unterminated HTML comment as hiding the rest of the file', () => {+ expect(() =>+ parser.parseSkillMd('# Title\n\n<!--\ninternal metadata\n', { fallbackName: 'x' }),+ ).toThrow(SkillManifestError);+ });++ it('should ignore a literal comment opener inside a fenced example', () => {+ const result = parser.parseSkillMd(+ '# Title\n\n```html\n<!-- example opener\n```\n\nReal summary.\n',+ );++ expect(result.manifest.description).toBe('Real summary.');+ });++ it('should not open a fence from a marker inside a comment', () => {+ const result = parser.parseSkillMd('# Title\n\n<!--\n```\n-->\n\nReal summary.\n');++ expect(result.manifest.description).toBe('Real summary.');+ });++ it('should derive a plain-text description from inline Markdown', () => {+ const result = parser.parseSkillMd(+ '# Stock Watcher\n\nA **fast** [stock watcher](https://example.com) for `A-share` prices, _lightweight_ and ~~noisy~~ quiet.\n',+ );++ expect(result.manifest.description).toBe(+ 'A fast stock watcher for A-share prices, lightweight and noisy quiet.',+ );+ });++ it('should derive a plain-text name from an H1 with inline Markdown', () => {+ for (const heading of [+ '**Stock Watcher**',+ '`Stock Watcher`',+ '[Stock Watcher](https://example.com)',+ ]) {+ const result = parser.parseSkillMd(`# ${heading}\n\nWatches prices.\n`);+ expect(result.manifest.name).toBe('Stock Watcher');+ }+ });++ it('should not split a surrogate pair when truncating the description', () => {+ const result = parser.parseSkillMd(`# Title\n\n${'a'.repeat(298)}😀zz\n`);+ const description = result.manifest.description;++ expect(description.endsWith('😀…')).toBe(true);+ expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(description)).toBe(false);+ });++ it('should skip an indented code block', () => {+ for (const indent of [' ', '\t']) {+ const result = parser.parseSkillMd(+ `# Installer\n\n${indent}npm install x\n\nActual summary.\n`,+ );+ expect(result.manifest.description).toBe('Actual summary.');+ }+ });++ it('should decode HTML entities in the derived name and description', () => {+ const result = parser.parseSkillMd(+ '# Research © Analysis\n\nFast — reliable & <b>not</b> "quoted" © ☺ & …\n',+ );++ expect(result.manifest.name).toBe('Research © Analysis');+ expect(result.manifest.description).toBe('Fast — reliable & not "quoted" © ☺ & …');+ });++ it('should keep entity text literal inside code spans and backslash escapes', () => {+ const result = parser.parseSkillMd(+ '# Use `©` safely\n\nWrite `a & b` or \\© literally; © renders.\n',+ );++ expect(result.manifest.name).toBe('Use © safely');+ expect(result.manifest.description).toBe('Write a & b or © literally; © renders.');+ });++ it('should turn inline HTML line breaks into spaces', () => {+ const result = parser.parseSkillMd(+ '# Stock<br>Watcher\n\nFast<br />monitoring, <BR/>daily <span>alerts</span>.\n',+ );++ expect(result.manifest.name).toBe('Stock Watcher');+ expect(result.manifest.description).toBe('Fast monitoring, daily alerts.');+ });++ it('should never take a multi-line HTML comment body as the description', () => {+ expect(() =>+ parser.parseSkillMd('# Title\n\n<!--\ninternal metadata\n-->\n', { fallbackName: 'x' }),+ ).toThrow(SkillManifestError);++ const result = parser.parseSkillMd(+ '# Title\n\n<!--\ninternal metadata\n-->\n\nThe real summary.\n',+ );+ expect(result.manifest.description).toBe('The real summary.');+ });++ it('should read front-matter that is preceded by an HTML comment', () => {+ // Real shape of market package frank-luongt-faos-skills-marketplace-nanogpt+ const content = `<!-- AUTO-GENERATED by export-skills.py — DO NOT EDIT -->+---+name: nanogpt+description: NanoGPT minimal GPT training implementation. Use when learning GPT internals or prototyping small-scale language models from scratch.+tags: [nanogpt, model-architecture, training]+---++# nanoGPT - Minimalist GPT Training++## Quick start+`;++ const result = parser.parseSkillMd(content);++ expect(result.manifest.name).toBe('nanogpt');+ expect(result.manifest.description).toMatch(/^NanoGPT minimal GPT training/);+ expect((result.manifest as any).tags).toEqual(['nanogpt', 'model-architecture', 'training']);+ expect(result.content).toBe('# nanoGPT - Minimalist GPT Training\n\n## Quick start');+ });++ it('should import a front-matter-less market ZIP package', async () => {+ const zipped = await createZip({ 'SKILL.md': new TextEncoder().encode(amlKycSkillMd) });++ const result = await parser.parseZipPackage(Buffer.from(zipped), {+ fallbackName: 'brainbytes-dev-everything-claude-finance-aml-kyc',+ });++ expect(result.manifest.name).toBe('AML/KYC Compliance');+ expect(result.manifest.description).toMatch(/^Customer due diligence/);+ });++ it('should fall back to the skill directory name inside a ZIP when there is no H1', async () => {+ const zipped = await createZip({+ 'aml-kyc/SKILL.md': new TextEncoder().encode('Screening guidance for onboarding.\n'),+ });++ const result = await parser.parseZipPackage(Buffer.from(zipped));++ expect(result.manifest.name).toBe('aml-kyc');+ expect(result.manifest.description).toBe('Screening guidance for onboarding.');+ });+ });+describe('validateManifest', () => {it('should validate valid manifest', () => {const data = {diff --git a/apps/server/src/services/skill/parser.ts b/apps/server/src/services/skill/parser.tsindex 3d93f319426..fa1926dcc7c 100644--- a/apps/server/src/services/skill/parser.ts+++ b/apps/server/src/services/skill/parser.ts@@ -6,13 +6,27 @@ import {type SkillManifest,skillManifestSchema,} from '@lobechat/types';+import { decodeHTML } from 'entities';import { unzip as fflateUnzip, zip as fflateZip } from 'fflate';import matter from 'gray-matter';import { sha256 } from 'js-sha256';+import { marked, type Token, type Tokens } from 'marked';import { SkillManifestError, SkillParseError } from './errors';-export interface ParseZipOptions {+export interface ParseSkillMdOptions {+ /**+ * Fallback skill name used when SKILL.md has no YAML front-matter AND no+ * `# H1` heading to derive a name from (e.g. the market identifier or the+ * skill directory name).+ */+ fallbackName?: string;+}++/** Max length of a description derived from SKILL.md body text */+const DERIVED_DESCRIPTION_MAX_LENGTH = 300;++export interface ParseZipOptions extends ParseSkillMdOptions {/*** Base path within the ZIP to look for SKILL.md* Used when importing from GitHub subdirectory URLs like:@@ -29,16 +43,62 @@ export interface ParseZipOptions {repackSkillZip?: boolean;}+/**+ * Visible plain text of inline Markdown tokens: link labels, emphasis and code+ * span contents are kept; images and inline HTML (comments, tags) are dropped,+ * and `<br>` becomes a space.+ */+const inlineToPlainText = (tokens: Token[] = []): string =>+ flattenInline(tokens).replaceAll(/\s+/g, ' ').trim();++const flattenInline = (tokens: Token[]): string =>+ tokens+ .map((token): string => {+ switch (token.type) {+ case 'image': {+ return '';+ }+ // Inline HTML is dropped, except a `<br>` which renders as a line break+ case 'html': {+ return /^<br\s*\/?>$/i.test((token as Tokens.HTML).text.trim()) ? ' ' : '';+ }+ case 'br': {+ return ' ';+ }+ // Rendered literally: a code span or a backslash escape keeps `©` as typed+ case 'codespan':+ case 'escape': {+ return (token as Tokens.Codespan).text;+ }+ default: {+ const nested = (token as { tokens?: Token[] }).tokens;+ if (nested) return flattenInline(nested);+ // Plain text is where Markdown interprets entities (`©` → ©), so+ // decode only here — the metadata is stored and shown as plain text.+ const text = (token as { text?: string }).text ?? '';+ return token.type === 'text' ? decodeHTML(text) : text;+ }+ }+ })+ .join('');+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 {+ parseSkillMd(fileContent: string, options?: ParseSkillMdOptions): ParsedSkill {try {- const { data, content } = matter(fileContent);- const manifest = this.validateManifest(data);+ const source = this.stripLeadingCommentsBeforeFrontMatter(fileContent);+ const { data, content } = matter(source);+ // gray-matter yields the same empty `data` for an absent block and for an+ // empty / comment-only one (`---\n---`), so presence is detected on the+ // source: a present-but-incomplete block must stay authoritative.+ const hasFrontMatter = /^\uFEFF?---\s*\n/.test(source);+ const manifest = this.validateManifest(+ hasFrontMatter ? data : this.deriveManifestWithoutFrontMatter(content, options),+ );return {content: content.trim(),@@ -84,8 +144,11 @@ export class SkillParser {throw new SkillParseError('SKILL.md not found in zip package');}- // Parse SKILL.md- const { content, manifest } = this.parseSkillMd(skillMdContent);+ // Parse SKILL.md (a nested SKILL.md's directory name is the last-resort name fallback)+ const skillDirName = skillMdPath.includes('/') ? skillMdPath.split('/').at(-2) : undefined;+ const { content, manifest } = this.parseSkillMd(skillMdContent, {+ fallbackName: options?.fallbackName || skillDirName,+ });// Extract resource filesconst resources = this.extractResources(unzipped, skillMdPath);@@ -109,6 +172,96 @@ export class SkillParser {}}+ /**+ * Some exported skills prepend an HTML comment (e.g.+ * `<!-- AUTO-GENERATED ... -->`) before the `---` front-matter block, which+ * makes gray-matter miss the front-matter entirely. Strip leading BOM /+ * whitespace / HTML comments, but only when front-matter follows them.+ */+ private stripLeadingCommentsBeforeFrontMatter(fileContent: string): string {+ const stripped = fileContent.replace(/^\uFEFF?(?:\s*<!--[\s\S]*?-->)*\s*/, '');+ return stripped !== fileContent && stripped.startsWith('---') ? stripped : fileContent;+ }++ /**+ * Many published skills (Claude Code style) ship a SKILL.md with no YAML+ * front-matter at all — it starts straight with `# Title` followed by a+ * blockquote/paragraph summary. For those, derive `name` from the first H1+ * (falling back to `options.fallbackName`) and `description` from the first+ * text block after it, so the manifest can still be validated.+ *+ * Only called when no front-matter block exists — a present block stays+ * authoritative (missing fields there are still reported as validation+ * errors). Genuinely empty bodies derive nothing and keep failing validation.+ */+ private deriveManifestWithoutFrontMatter(+ content: string,+ options?: ParseSkillMdOptions,+ ): Record<string, unknown> {+ // Tokenize with a real Markdown lexer instead of scanning lines, so fenced+ // and indented code, HTML blocks/comments (terminated or not), images and+ // badges are classified exactly as they render.+ let name: string | undefined;+ let description: string | undefined;+ // Text before the H1 (a language selector, …) is only a fallback.+ let preamble: string | undefined;++ const firstText = (tokens: Token[]): string | undefined => {+ for (const token of tokens) {+ if (token.type === 'paragraph' || token.type === 'text') {+ const text = inlineToPlainText((token as Tokens.Paragraph).tokens);+ if (text) return text;+ } else if (token.type === 'blockquote') {+ const text = firstText((token as Tokens.Blockquote).tokens);+ if (text) return text;+ } else if (token.type === 'list') {+ for (const item of (token as Tokens.List).items) {+ const text = firstText(item.tokens);+ if (text) return text;+ }+ }+ }+ return undefined;+ };++ for (const token of marked.lexer(content)) {+ if (token.type === 'heading') {+ if (!name && (token as Tokens.Heading).depth === 1) {+ name = inlineToPlainText((token as Tokens.Heading).tokens) || undefined;+ }+ continue;+ }+ const text = firstText([token]);+ if (!text) continue;+ if (name) {+ description = text;+ break;+ }+ preamble ??= text;+ }+ description ??= preamble;++ // Truncate by code point so an emoji at the boundary is never split into+ // an unpaired surrogate.+ const chars = description ? [...description] : [];+ if (chars.length > DERIVED_DESCRIPTION_MAX_LENGTH) {+ description =+ chars+ .slice(0, DERIVED_DESCRIPTION_MAX_LENGTH - 1)+ .join('')+ .trimEnd() + '…';+ }++ // Only fall back to the caller-supplied name when the body has real text,+ // so an empty SKILL.md is still rejected.+ if (!name && description) name = options?.fallbackName;++ return {+ ...(description && { description }),+ ...(name && { name }),+ };+ }+/*** Validate manifest data*/diff --git a/package.json b/package.jsonindex 1e2e9edad88..08f1e5a65bb 100644--- a/package.json+++ b/package.json@@ -378,6 +378,7 @@"docx-preview": "^0.4.0","drizzle-orm": "^0.45.2","drizzle-zod": "^0.8.3",+ "entities": "^8.1.0","epub2": "^3.0.2","es-toolkit": "^1.50.0","exceljs": "^4.4.0",