🤯 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
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { unzip, zip } from 'fflate';
import { sha256 } from 'js-sha256';
import { afterAll, beforeAll, describe, expect, it, vi } 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('rejects JavaScript frontmatter without executing it', () => {
const executed = vi.fn();
vi.stubGlobal('__skillFrontmatterExecuted', executed);
const content = `---js
(() => { globalThis.__skillFrontmatterExecuted(); throw new Error('Executed frontmatter'); })()
---
# Skill
Skill description.`;
try {
expect(() => parser.parseSkillMd(content)).toThrow(SkillParseError);
expect(executed).not.toHaveBeenCalled();
} finally {
vi.unstubAllGlobals();
}
});
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('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 = {
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');
});
});
// Regression tests for the ReDoS vulnerability reported in lobehub/lobehub#16494.
// `basePath` is derived from the fully user-controlled GitHub URL path segment
// (https://github.com/owner/repo/tree/branch/<path>) and used to be interpolated
// directly into `new RegExp('^[^/]+/<basePath>/SKILL\\.md$')` inside findSkillMd.
// That allowed catastrophic backtracking (event-loop DoS) and SyntaxError crashes.
describe('findSkillMd basePath security (ReDoS regression, #16494)', () => {
it('should not hang on a malicious ReDoS basePath', async () => {
// A long run of "a" followed by a non-matching char makes the old
// `^[^/]+/(a+)+/SKILL\.md$` regex backtrack exponentially (~2^40 steps).
const evilDecoy = 'a'.repeat(40);
const testFiles = {
[`repo-main/${evilDecoy}X/data.txt`]: new TextEncoder().encode('x'),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
const start = performance.now();
// No SKILL.md exists, so it should reject with "not found" — the point is that
// it does so quickly instead of blocking the event loop for tens of seconds.
await expect(parser.parseZipPackage(buffer, { basePath: '(a+)+' })).rejects.toThrow(
'SKILL.md not found',
);
const elapsed = performance.now() - start;
expect(elapsed).toBeLessThan(1000);
});
it('should not throw SyntaxError for a basePath with invalid regex syntax', async () => {
// `[invalid` is not a valid RegExp; the old code threw a SyntaxError (HTTP 500).
// It must now be treated as a literal string and fail gracefully as "not found".
const testFiles = {
'repo-main/skills/demo/SKILL.md': new TextEncoder().encode(
'---\nname: demo\ndescription: demo\n---\nDemo',
),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
await expect(parser.parseZipPackage(buffer, { basePath: '[invalid' })).rejects.toThrow(
'SKILL.md not found',
);
});
it('should treat regex metacharacters in basePath as literals (no "any char" matching)', async () => {
// Path uses "aXb"; basePath "a.b" must NOT match it (the old regex treated "." as
// "any char" and would have matched). The literal directory "a.b" does not exist.
const testFiles = {
'repo-main/aXb/SKILL.md': new TextEncoder().encode(
'---\nname: axb\ndescription: axb\n---\naXb',
),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
await expect(parser.parseZipPackage(buffer, { basePath: 'a.b' })).rejects.toThrow(
'SKILL.md not found',
);
});
it('should still match a directory whose literal name contains regex metacharacters', async () => {
// A real directory literally named "a.b" must be found (via exact-path lookup).
const skillMd = `---
name: literal-dot-skill
description: Skill in a dir literally named a.b
---
Literal dot content`;
const testFiles = {
'repo-main/a.b/SKILL.md': new TextEncoder().encode(skillMd),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
const result = await parser.parseZipPackage(buffer, { basePath: 'a.b' });
expect(result.manifest.name).toBe('literal-dot-skill');
});
it('should report "not found" (not silently import the root skill) when basePath misses', async () => {
// User explicitly requested a subdirectory via the GitHub URL path, but no SKILL.md
// exists there. Even though the repo has a root-level SKILL.md, we must NOT fall
// through and silently import that unrelated skill — it must be reported as missing.
const testFiles = {
'repo-main/SKILL.md': new TextEncoder().encode(
'---\nname: root\ndescription: root\n---\nRoot',
),
'repo-main/README.md': new TextEncoder().encode('# Repo'),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
// Nonexistent subpath
await expect(
parser.parseZipPackage(buffer, { basePath: 'skills/does-not-exist' }),
).rejects.toThrow('SKILL.md not found');
// Invalid-regex-looking subpath must behave the same (no silent root import)
await expect(parser.parseZipPackage(buffer, { basePath: '[invalid' })).rejects.toThrow(
'SKILL.md not found',
);
});
it('should still resolve the basePath via the fallback when the root prefix differs', async () => {
// When findGitHubRootPrefix picks a prefix that does not match the SKILL.md's
// top-level directory, the exact lookup misses and the fallback must still find
// `<single-segment>/<basePath>/SKILL.md`. Insert the decoy first so it becomes
// the detected root prefix.
const skillMd = `---
name: fallback-skill
description: Found via fallback
---
Fallback content`;
const testFiles = {
'decoy-dir/other.txt': new TextEncoder().encode('decoy'),
'repo-main/skills/demo/SKILL.md': new TextEncoder().encode(skillMd),
};
const zipped = await createZip(testFiles);
const buffer = Buffer.from(zipped);
const result = await parser.parseZipPackage(buffer, { basePath: 'skills/demo' });
expect(result.manifest.name).toBe('fallback-skill');
});
});
describe('parseZipPackage with repackSkillZip', () => {
it('should repack to the same bytes in any server time zone', async () => {
const skillMd = `---
name: tz-skill
description: Time zone independent repack
---
Content`;
const zipped = Buffer.from(
await createZip({
'repo/SKILL.md': new TextEncoder().encode(skillMd),
'repo/notes.txt': new TextEncoder().encode('notes'),
}),
);
const originalTz = process.env.TZ;
const hashes: string[] = [];
try {
// ZIP stores local time; west of UTC a UTC-midnight 1980 date falls in 1979.
for (const tz of ['America/New_York', 'UTC', 'Asia/Shanghai']) {
process.env.TZ = tz;
const result = await parser.parseZipPackage(zipped, { repackSkillZip: true });
hashes.push(result.zipHash!);
}
} finally {
if (originalTz === undefined) delete process.env.TZ;
else process.env.TZ = originalTz;
}
expect(process.env.TZ).toBe(originalTz);
expect(new Set(hashes).size).toBe(1);
});
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);
});
});
});