Skip to content

🤯 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.

✨ feat(skills): discover and import skills from GitHub collections (#23409)

AmAzing-10f86c673d85
diff --git a/apps/server/src/modules/GitHub/index.ts b/apps/server/src/modules/GitHub/index.ts
index 0c76c9d5c54..87cd2a076b9 100644
--- a/apps/server/src/modules/GitHub/index.ts
+++ b/apps/server/src/modules/GitHub/index.ts
@@ -81,7 +81,11 @@ export class GitHub {
}
}
if (path) {
- result.path = path;
+ try {
+ result.path = decodeURIComponent(path).replace(/\/+$/, '');
+ } catch {
+ throw new GitHubParseError('Invalid GitHub path encoding');
+ }
}
}
@@ -131,7 +135,11 @@ export class GitHub {
* Build the ZIP download URL for a GitHub repository
*/
buildRepoZipUrl(info: GitHubRepoInfo): string {
- return `https://github.com/${info.owner}/${info.repo}/archive/refs/heads/${info.branch}.zip`;
+ const ref =
+ info.branch === 'HEAD' || /^[a-f0-9]{40}$/.test(info.branch)
+ ? info.branch
+ : 'refs/heads/' + info.branch;
+ return `https://github.com/${info.owner}/${info.repo}/archive/${ref}.zip`;
}
/**
@@ -141,6 +149,41 @@ export class GitHub {
return `https://raw.githubusercontent.com/${info.owner}/${info.repo}/${info.branch}/${info.filePath}`;
}
+ async resolveCommit(info: GitHubRepoInfo) {
+ const repoUrl = `https://api.github.com/repos/${encodeURIComponent(info.owner)}/${encodeURIComponent(info.repo)}`;
+ const response = await fetch(`${repoUrl}/commits/${encodeURIComponent(info.branch)}`, {
+ headers: { 'Accept': 'application/vnd.github.sha', 'User-Agent': this.userAgent },
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok)
+ throw new GitHubDownloadError(`Could not resolve GitHub revision (HTTP ${response.status})`);
+ const commit = (await response.text()).trim();
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new GitHubDownloadError('Invalid GitHub revision');
+ return commit;
+ }
+
+ async downloadCommitZip(info: GitHubRepoInfo, commit: string) {
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new GitHubParseError('Invalid commit SHA');
+ const url = `https://codeload.github.com/${encodeURIComponent(info.owner)}/${encodeURIComponent(info.repo)}/zip/${commit}`;
+ const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
+ if (!response.ok || !response.body)
+ throw new GitHubDownloadError(`Could not download repository (HTTP ${response.status})`);
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > 32 * 1024 * 1024) {
+ await reader.cancel();
+ throw new GitHubDownloadError('Repository exceeds the 32 MiB download limit');
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks, size);
+ }
+
/**
* Download repository as ZIP buffer
*/
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.ts
index bddb86a828c..13b013e0011 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
@@ -918,7 +918,7 @@ Body`,
expect(result).toBeDefined();
expect(result!.skill.name).toBe('skill-creator');
- expect(result!.skill.identifier).toBe('openclaw-openclaw-skill-creator');
+ expect(result!.skill.identifier).toMatch(/^openclaw-openclaw-skill-creator-[a-f0-9]{20}$/);
expect(result!.skill.source).toBe('market');
expect(result!.skill.manifest).toMatchObject({
repository: 'https://github.com/openclaw/openclaw',
@@ -928,12 +928,13 @@ Body`,
// Verify parseRepoUrl was called with correct URL
expect(mockGitHubInstance.parseRepoUrl).toHaveBeenCalledWith(
'https://github.com/openclaw/openclaw/tree/main/skills/skill-creator',
- undefined,
+ 'HEAD',
);
- // Verify parseZipPackage was called with basePath and repackSkillZip
+ // Verify parseZipPackage was called with basePath, the directory name as fallback, and repackSkillZip
expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(expect.any(Buffer), {
basePath: 'skills/skill-creator',
+ fallbackName: 'skill-creator',
repackSkillZip: true,
});
});
diff --git a/apps/server/src/routers/lambda/agentSkills.ts b/apps/server/src/routers/lambda/agentSkills.ts
index b241fdd4216..02c7eb38de6 100644
--- a/apps/server/src/routers/lambda/agentSkills.ts
+++ b/apps/server/src/routers/lambda/agentSkills.ts
@@ -198,6 +198,24 @@ export const agentSkillsRouter = router({
return ctx.skillModel.findByName(input.name);
}),
+ discoverGitHubSkills: skillWriteProcedure
+ .input(z.object({ gitUrl: z.string().url() }))
+ .mutation(({ ctx, input }) => ctx.skillImporter.discoverGitHubSkills(input.gitUrl)),
+
+ importGitHubSkills: skillWriteProcedure
+ .input(
+ z.object({
+ commit: z.string().regex(/^[a-f0-9]{40}$/),
+ gitUrl: z.string().url(),
+ scope: z.string(),
+ selections: z
+ .array(z.object({ path: z.string(), revision: z.string().nullable() }))
+ .min(1)
+ .max(200),
+ }),
+ )
+ .mutation(({ ctx, input }) => ctx.skillImporter.importGitHubSkills(input)),
+
importFromGitHub: skillWriteProcedure
.input(
z.object({
diff --git a/apps/server/src/services/skill/githubArchive.test.ts b/apps/server/src/services/skill/githubArchive.test.ts
new file mode 100644
index 00000000000..b97e6e39b83
--- /dev/null
+++ b/apps/server/src/services/skill/githubArchive.test.ts
@@ -0,0 +1,35 @@
+import { strToU8, zipSync } from 'fflate';
+import { describe, expect, it } from 'vitest';
+
+import { readGitHubArchive } from './githubArchive';
+import { SkillParser } from './parser';
+
+const archive = () =>
+ Buffer.from(
+ zipSync(
+ Object.fromEntries(
+ Object.entries({
+ 'repo-sha/SKILL.md': '# Router\n\nRoute requests',
+ 'repo-sha/docs/guide.md': 'guide',
+ 'repo-sha/.agents/skills/review/SKILL.md': '# Review\n\nReview code',
+ 'repo-sha/.agents/skills/review/script.js': 'run',
+ 'repo-sha/node_modules/tool/SKILL.md': '# Dependency',
+ }).map(([path, body]) => [path, strToU8(body)]),
+ ),
+ ),
+ );
+
+describe('GitHub collections', () => {
+ it('finds nested skills and assigns resources to the closest owning skill', async () => {
+ const skills = await readGitHubArchive(archive());
+ expect([...skills.keys()].sort()).toEqual(['', '.agents/skills/review']);
+ const root = await new SkillParser().parseGitHubDirectory(skills.get('')!, 'repo');
+ expect([...root.resources.keys()]).toEqual(['docs/guide.md']);
+ const child = await new SkillParser().parseGitHubDirectory(
+ skills.get('.agents/skills/review')!,
+ 'review',
+ );
+ expect(child.manifest.name).toBe('Review');
+ expect([...child.resources.keys()]).toEqual(['script.js']);
+ });
+});
diff --git a/apps/server/src/services/skill/githubArchive.ts b/apps/server/src/services/skill/githubArchive.ts
new file mode 100644
index 00000000000..90306eff843
--- /dev/null
+++ b/apps/server/src/services/skill/githubArchive.ts
@@ -0,0 +1,73 @@
+import { unzip } from 'fflate';
+
+import { SkillParseError } from './errors';
+
+export interface GitHubSkillDirectory {
+ markdown: string;
+ resources: Map<string, Buffer>;
+}
+
+const ignored = new Set(['.git', 'node_modules', '__MACOSX']);
+
+export async function readGitHubArchive(buffer: Buffer, basePath = '') {
+ let count = 0;
+ let size = 0;
+ const files = await new Promise<Record<string, Uint8Array>>((resolve, reject) => {
+ unzip(
+ buffer,
+ {
+ filter(entry) {
+ if (++count > 50_000)
+ throw new SkillParseError('Repository exceeds the file-count limit');
+ const relative = entry.name.slice(entry.name.indexOf('/') + 1);
+ if (basePath && !relative.startsWith(basePath + '/')) return false;
+ size += entry.originalSize;
+ if (size > 128 * 1024 * 1024)
+ throw new SkillParseError('Repository exceeds the archive scan limit');
+ const parts = entry.name.split('/');
+ return (
+ !entry.name.endsWith('/') &&
+ !parts.some((part) => ignored.has(part) || !part || part === '..' || part === '.')
+ );
+ },
+ },
+ (error, data) => (error ? reject(error) : resolve(data)),
+ );
+ });
+
+ // GitHub adds one wrapper directory. Also support plain skill ZIPs for the
+ // single-package parser when its caller requests a repacked download.
+ const paths = Object.keys(files);
+ const firstDirectory = paths[0]?.split('/')[0] + '/';
+ const prefix = paths.every((path) => path.startsWith(firstDirectory)) ? firstDirectory : '';
+ const skills = new Map<string, GitHubSkillDirectory>();
+ for (const path of paths) {
+ if (path.split('/').at(-1) !== 'SKILL.md') continue;
+ if (skills.size >= 200)
+ throw new SkillParseError('Repository exceeds the 200 skill scan limit');
+ const relative = path.slice(prefix.length);
+ skills.set(relative.split('/').slice(0, -1).join('/'), {
+ markdown: new TextDecoder().decode(files[path]),
+ resources: new Map(),
+ });
+ }
+ for (const path of paths) {
+ const relative = path.slice(prefix.length);
+ const parts = relative.split('/');
+ if (parts.pop() === 'SKILL.md') continue;
+ // The nearest enclosing SKILL.md owns this resource.
+ while (true) {
+ const directory = parts.join('/');
+ const skill = skills.get(directory);
+ if (skill) {
+ const key = directory ? relative.slice(directory.length + 1) : relative;
+ const bytes = files[path];
+ skill.resources.set(key, Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
+ break;
+ }
+ if (!parts.length) break;
+ parts.pop();
+ }
+ }
+ return skills;
+}
diff --git a/apps/server/src/services/skill/importer.githubCollection.test.ts b/apps/server/src/services/skill/importer.githubCollection.test.ts
new file mode 100644
index 00000000000..d2f7d49b5a6
--- /dev/null
+++ b/apps/server/src/services/skill/importer.githubCollection.test.ts
@@ -0,0 +1,171 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { globalFiles, users, workspaces } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { strToU8, zipSync } from 'fflate';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentSkillModel } from '@/database/models/agentSkill';
+import { GitHub } from '@/server/modules/GitHub';
+
+import { SkillImporter } from './importer';
+
+vi.mock('@/server/services/file/impls', () => ({
+ createFileServiceModule: () => ({ uploadBuffer: vi.fn().mockResolvedValue({ key: 'test' }) }),
+}));
+
+const repo = 'https://github.com/owner/collection';
+const commit = 'a'.repeat(40);
+const review = 'skills/team/review';
+const other = 'skills/other/review';
+const doc = (name: string) =>
+ strToU8(`---\nname: ${name}\ndescription: Tests\n---\nReview changes`);
+const zip = Buffer.from(
+ zipSync({
+ ['repo-sha/' + review + '/SKILL.md']: doc('review'),
+ ['repo-sha/' + other + '/SKILL.md']: doc('Review'),
+ 'repo-sha/.agents/skills/other/SKILL.md': doc('other'),
+ 'repo-sha/skills/broken/SKILL.md': strToU8('---\nname: nope\n---'),
+ }),
+);
+
+describe('GitHub skill collection import', () => {
+ let userId: string;
+ let db: Awaited<ReturnType<typeof getTestDB>>;
+ let importer: SkillImporter;
+ let model: AgentSkillModel;
+
+ beforeEach(async () => {
+ userId = randomUUID();
+ db = await getTestDB();
+ await db.insert(users).values({ id: userId });
+ importer = new SkillImporter(db, userId);
+ model = new AgentSkillModel(db, userId);
+ vi.spyOn(GitHub.prototype, 'resolveCommit').mockResolvedValue(commit);
+ vi.spyOn(GitHub.prototype, 'downloadCommitZip').mockResolvedValue(zip);
+ vi.spyOn(GitHub.prototype, 'downloadRepoZip').mockResolvedValue(zip);
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await db.delete(users).where(eq(users.id, userId));
+ await db.delete(globalFiles).where(eq(globalFiles.creator, userId));
+ });
+
+ it('pins a batch, isolates errors, and reuses the row from the single import entry', async () => {
+ const scan = await importer.discoverGitHubSkills(repo);
+ expect(scan.candidates).toHaveLength(4);
+ expect(scan.candidates.find((item) => item.path === 'skills/broken')?.status).toBe('invalid');
+ const batch = {
+ ...scan,
+ gitUrl: repo,
+ selections: [
+ { path: review, revision: null },
+ { path: other, revision: null },
+ ],
+ };
+ expect(await importer.importGitHubSkills(batch)).toEqual([
+ { path: review, status: 'created' },
+ { path: other, status: 'conflict' },
+ ]);
+ expect(GitHub.prototype.resolveCommit).toHaveBeenCalledTimes(1);
+ expect(GitHub.prototype.downloadCommitZip).toHaveBeenCalledTimes(2);
+ expect(GitHub.prototype.downloadCommitZip).toHaveBeenLastCalledWith(expect.anything(), commit);
+ expect(
+ (await importer.importFromGitHub({ gitUrl: repo + '/tree/main/' + review })).status,
+ ).toBe('unchanged');
+ expect((await importer.importGitHubSkills(batch))[0].status).toBe('unchanged');
+ expect((await model.findAll()).total).toBe(1);
+ });
+
+ it('coalesces concurrent submissions of the same selection', async () => {
+ const scan = await importer.discoverGitHubSkills(repo);
+ const batch = { ...scan, gitUrl: repo, selections: [{ path: review, revision: null }] };
+ const results = await Promise.all([
+ importer.importGitHubSkills(batch),
+ importer.importGitHubSkills(batch),
+ ]);
+ expect(results.map(([row]) => row.status).sort()).toEqual(['created', 'unchanged']);
+ expect((await model.findAll()).total).toBe(1);
+ });
+
+ it('limits collection and file URLs to their original scope', async () => {
+ const url = repo + '/tree/main/skills/team';
+ const scan = await importer.discoverGitHubSkills(url);
+ expect(scan.candidates.map((row) => row.path)).toEqual([review]);
+ expect(
+ (await importer.discoverGitHubSkills(repo + '/blob/main/' + review + '/SKILL.md')).candidates,
+ ).toEqual(scan.candidates);
+ expect(
+ await importer.importGitHubSkills({
+ ...scan,
+ gitUrl: url,
+ selections: [{ path: other, revision: null }],
+ }),
+ ).toEqual([{ path: other, status: 'failed' }]);
+ expect((await model.findAll()).total).toBe(0);
+ });
+
+ it('preserves a legacy row, rejects stale previews and keeps local edits', async () => {
+ const row = await model.create({
+ content: 'Old',
+ description: 'Old',
+ identifier: 'owner-collection-review',
+ name: 'review',
+ source: 'market',
+ manifest: { name: 'review', description: 'Old', sourceUrl: repo + '/tree/main/' + review },
+ });
+ const scan = await importer.discoverGitHubSkills(repo);
+ const selection = scan.candidates.find((item) => item.path === review)!;
+ expect(selection.status).toBe('update');
+ expect(scan.candidates.find((item) => item.path === other)?.status).toBe('conflict');
+ await model.update(row.id, { content: 'Concurrent edit' });
+ expect(
+ await importer.importGitHubSkills({ ...scan, gitUrl: repo, selections: [selection] }),
+ ).toEqual([{ path: review, status: 'conflict' }]);
+ expect((await model.findById(row.id))?.content).toBe('Concurrent edit');
+ const fresh = await importer.discoverGitHubSkills(repo);
+ expect(
+ (
+ await importer.importGitHubSkills({
+ ...fresh,
+ gitUrl: repo,
+ selections: fresh.candidates.filter((item) => item.path === review),
+ })
+ )[0].status,
+ ).toBe('updated');
+ expect((await model.findById(row.id))?.identifier).toBe(row.identifier);
+ });
+
+ it('checks the library and creator permissions again when committing', async () => {
+ const workspaceId = randomUUID();
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Skill imports',
+ slug: workspaceId,
+ primaryOwnerId: userId,
+ });
+ try {
+ const owner = new SkillImporter(db, userId, workspaceId, { workspaceRole: 'owner' });
+ const scan = await owner.discoverGitHubSkills(repo);
+ const batch = { ...scan, gitUrl: repo, selections: [{ path: review, revision: null }] };
+ await expect(importer.importGitHubSkills(batch)).rejects.toThrow(/library changed/);
+ expect((await owner.importGitHubSkills(batch))[0].status).toBe('created');
+ const workspace = new AgentSkillModel(db, userId, workspaceId);
+ const [row] = (await workspace.findAll()).data;
+ await workspace.update(row.id, { content: 'Local edit' });
+ const member = new SkillImporter(db, randomUUID(), workspaceId, { workspaceRole: 'member' });
+ const preview = await member.discoverGitHubSkills(repo);
+ const selected = preview.candidates.find((item) => item.path === review)!;
+ expect(selected.status).toBe('forbidden');
+ expect(
+ (await member.importGitHubSkills({ ...preview, gitUrl: repo, selections: [selected] }))[0]
+ .status,
+ ).toBe('forbidden');
+ } finally {
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ }
+ });
+});
diff --git a/apps/server/src/services/skill/importer.test.ts b/apps/server/src/services/skill/importer.test.ts
index 4712207054a..9bc0d038abd 100644
--- a/apps/server/src/services/skill/importer.test.ts
+++ b/apps/server/src/services/skill/importer.test.ts
@@ -384,7 +384,7 @@ describe('SkillImporter', () => {
expect(result).toBeDefined();
expect(result.status).toBe('created');
expect(result.skill.name).toBe('GitHub Skill');
- expect(result.skill.identifier).toBe('lobehub-skill-demo');
+ expect(result.skill.identifier).toMatch(/^lobehub-skill-demo-[a-f0-9]{20}$/);
expect(result.skill.source).toBe('market');
// Verify manifest contains repository info
@@ -418,11 +418,11 @@ describe('SkillImporter', () => {
expect(result).toBeDefined();
expect(result.status).toBe('created');
- expect(result.skill.identifier).toBe('openclaw-openclaw-skill-creator');
+ expect(result.skill.identifier).toMatch(/^openclaw-openclaw-skill-creator-[a-f0-9]{20}$/);
- // Verify parseZipPackage was called with basePath and repackSkillZip
expect(mockParserInstance.parseZipPackage).toHaveBeenCalledWith(expect.any(Buffer), {
basePath: 'skills/skill-creator',
+ fallbackName: 'skill-creator',
repackSkillZip: true,
});
});
@@ -473,7 +473,7 @@ describe('SkillImporter', () => {
.select()
.from(agentSkills)
.where(
- and(eq(agentSkills.userId, userId), eq(agentSkills.identifier, 'lobehub-skill-update')),
+ and(eq(agentSkills.userId, userId), eq(agentSkills.identifier, first.skill.identifier)),
);
expect(dbSkills).toHaveLength(1);
});
@@ -727,7 +727,7 @@ describe('SkillImporter', () => {
const dbSkills = await db
.select()
.from(agentSkills)
- .where(eq(agentSkills.identifier, 'lobehub-skill-dedup'));
+ .where(eq(agentSkills.identifier, first.skill.identifier));
expect(dbSkills).toHaveLength(1);
});
@@ -1275,7 +1275,7 @@ description: A nested skill
// Second user should not be able to create skill with same identifier
// because findByIdentifier filters by userId
- const otherResult = await otherImporter.createUserSkill({
+ await otherImporter.createUserSkill({
content: '# User 2 Skill',
description: 'User 2 skill',
identifier: 'isolation-test-skill', // Same identifier, different user
diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.ts
index 615322c7e45..20621342465 100644
--- a/apps/server/src/services/skill/importer.ts
+++ b/apps/server/src/services/skill/importer.ts
@@ -1,26 +1,51 @@
+import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { type LobeChatDatabase } from '@lobechat/database';
import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import {
type CreateSkillInput,
+ type GitHubSkillBatchInput,
+ type GitHubSkillCandidate,
+ type GitHubSkillDiscovery,
+ type GitHubSkillOutcome,
type ImportGitHubInput,
type ImportUrlInput,
type ImportZipInput,
+ type ParsedZipSkill,
type SkillImportResult,
+ type SkillItem,
type SkillManifest,
} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import debug from 'debug';
import { AgentSkillModel } from '@/database/models/agentSkill';
-import { GitHub, GitHubNotFoundError, GitHubParseError } from '@/server/modules/GitHub';
+import {
+ GitHub,
+ GitHubNotFoundError,
+ GitHubParseError,
+ type GitHubRepoInfo,
+} from '@/server/modules/GitHub';
import { FileService } from '@/server/services/file';
import { SkillImportError, SkillManifestError } from './errors';
+import { readGitHubArchive } from './githubArchive';
import { SkillParser } from './parser';
import { SkillResourceService } from './resource';
+const sourceKey = (info: GitHubRepoInfo) =>
+ JSON.stringify([info.owner.toLowerCase(), info.repo.toLowerCase(), info.path ?? '']);
+const digest = (value: string) => createHash('sha256').update(value).digest('hex');
+const revisionOf = (skill?: SkillItem) =>
+ skill ? skill.id + '/' + skill.updatedAt.toISOString() : null;
+const unchanged = (skill: SkillItem, parsed: ParsedZipSkill) =>
+ !!parsed.zipHash &&
+ skill.zipFileHash === parsed.zipHash &&
+ skill.content === parsed.content &&
+ skill.name === parsed.manifest.name &&
+ skill.description === parsed.manifest.description;
+
const log = debug('lobe-chat:service:skill-importer');
export class SkillImporter {
@@ -171,7 +196,7 @@ export class SkillImporter {
// 1. Parse GitHub URL
let repoInfo;
try {
- repoInfo = this.github.parseRepoUrl(input.gitUrl, input.branch);
+ repoInfo = this.github.parseRepoUrl(input.gitUrl, input.branch ?? 'HEAD');
log('importFromGitHub: parsed repoInfo=%o', repoInfo);
} catch (error) {
log('importFromGitHub: failed to parse URL, error=%s', (error as Error).message);
@@ -200,34 +225,61 @@ export class SkillImporter {
// 3. Parse ZIP package (pass basePath for subdirectory imports, repack to save only skill files)
log('importFromGitHub: parsing ZIP package with basePath=%s', repoInfo.path);
- const { manifest, content, resources, zipHash, skillZipBuffer } =
- await this.parser.parseZipPackage(zipBuffer, {
- basePath: repoInfo.path,
- repackSkillZip: true,
- });
- log(
- 'importFromGitHub: parsed manifest=%o, resources count=%d, zipHash=%s, skillZipSize=%d',
- manifest,
- resources.size,
- zipHash,
- skillZipBuffer?.length ?? 0,
- );
+ const parsed = await this.parser.parseZipPackage(zipBuffer, {
+ basePath: repoInfo.path,
+ fallbackName: repoInfo.path?.split('/').at(-1) || repoInfo.repo,
+ repackSkillZip: true,
+ });
+ return this.saveGitHubSkill(repoInfo, input.gitUrl, parsed, zipBuffer);
+ }
- // 4. Generate identifier (use GitHub info for uniqueness, include path for subdirectory imports)
- const identifier = this.github.generateIdentifier(repoInfo);
- log('importFromGitHub: identifier=%s', identifier);
+ private gitHubIdentifiers(info: GitHubRepoInfo) {
+ const legacy = this.github.generateIdentifier(info);
+ return { legacy, identifier: `${legacy}-${digest(sourceKey(info)).slice(0, 20)}` };
+ }
- // 5. Check for existing skill with same zipHash (deduplication)
- // Also re-import if content is missing (e.g. from a previous buggy import)
- const existing = await this.skillModel.findByIdentifier(identifier);
- if (existing && existing.zipFileHash === zipHash && existing.content != null) {
- log(
- 'importFromGitHub: skill unchanged (same zipHash=%s), skipping update id=%s',
- zipHash,
- existing.id,
- );
- return { skill: existing, status: 'unchanged' };
+ private gitHubTarget(info: GitHubRepoInfo, byIdentifier: Map<string, SkillItem>) {
+ const { identifier, legacy } = this.gitHubIdentifiers(info);
+ const exact = byIdentifier.get(identifier);
+ const existing = exact ?? byIdentifier.get(legacy);
+ if (existing?.manifest.sourceUrl) {
+ try {
+ if (sourceKey(this.github.parseRepoUrl(existing.manifest.sourceUrl)) === sourceKey(info))
+ return { existing, identifier: existing.identifier };
+ } catch (error) {
+ log('Ignoring unrecognized legacy source: %s', error);
+ }
}
+ if (exact) throw new SkillImportError('Source identifier already in use', 'CONFLICT');
+ return { existing: undefined, identifier };
+ }
+
+ private async saveGitHubSkill(
+ info: GitHubRepoInfo,
+ sourceUrl: string,
+ parsed: ParsedZipSkill,
+ originalZip?: Buffer,
+ expectedRevision?: string | null,
+ ): Promise<SkillImportResult> {
+ const { content, manifest, resources, zipHash, skillZipBuffer } = parsed;
+ const inspect = async (model: AgentSkillModel, expected?: string | null) => {
+ const { identifier, legacy } = this.gitHubIdentifiers(info);
+ const rows = await model.findImportMatches([identifier, legacy], [manifest.name]);
+ const target = this.gitHubTarget(info, new Map(rows.map((row) => [row.identifier, row])));
+
+ const { existing } = target;
+ if (existing && unchanged(existing, parsed)) return target;
+ if (expected !== undefined && revisionOf(existing) !== expected)
+ throw new SkillImportError('The installed skill changed. Find skills again.', 'CONFLICT');
+ if (existing) this.assertCanOverwrite(existing);
+ const named = rows.find((row) => row.name.toLowerCase() === manifest.name.toLowerCase());
+ if (named && named.id !== existing?.id)
+ throw new SkillImportError('Skill name already in use', 'CONFLICT');
+ return target;
+ };
+ const before = await inspect(this.skillModel, expectedRevision);
+ if (before.existing && unchanged(before.existing, parsed))
+ return { skill: before.existing, status: 'unchanged' };
// 6. Store resource files (only if skill is new or changed)
log('importFromGitHub: storing %d resources...', resources.size);
@@ -239,14 +291,14 @@ export class SkillImporter {
// 7. Build manifest with repository info
const fullManifest: SkillManifest = {
...manifest,
- repository: `https://github.com/${repoInfo.owner}/${repoInfo.repo}`,
- sourceUrl: input.gitUrl,
+ repository: `https://github.com/${info.owner}/${info.repo}`,
+ sourceUrl,
};
// 8. Upload ZIP file to S3 and create globalFiles record (for zipFileHash foreign key)
// Use skillZipBuffer (repacked skill-only ZIP) instead of full repo zipBuffer
let zipFileHash: string | undefined;
- const zipToUpload = skillZipBuffer ?? zipBuffer;
+ const zipToUpload = skillZipBuffer ?? originalZip;
if (zipHash && zipToUpload) {
const zipKey = `skills/zip/${zipHash}.zip`;
await this.fileService.uploadBuffer(zipKey, zipToUpload, 'application/zip');
@@ -270,36 +322,151 @@ export class SkillImporter {
);
}
- // 9. Update existing skill or create new
- if (existing) {
- this.assertCanOverwrite(existing);
- log('importFromGitHub: skill exists but content changed, updating id=%s', existing.id);
- const skill = await this.skillModel.update(existing.id, {
+ return this.skillModel.withImportLock(async (model) => {
+ const { identifier, existing } = await inspect(model, revisionOf(before.existing));
+ if (existing && unchanged(existing, parsed)) return { skill: existing, status: 'unchanged' };
+ const data = {
content,
description: manifest.description,
manifest: fullManifest,
name: manifest.name,
resources: resourceIds,
zipFileHash,
+ };
+ if (existing) {
+ const skill = await model.replaceImportedSkill(existing, data);
+ if (!skill)
+ throw new SkillImportError('The installed skill changed. Find skills again.', 'CONFLICT');
+ return { skill, status: 'updated' };
+ }
+ const skill = await model.create({ ...data, identifier, source: 'market' });
+ return { skill, status: 'created' };
+ });
+ }
+
+ private get importScope() {
+ return digest(JSON.stringify([this.userId, this.workspaceId ?? null]));
+ }
+
+ private async gitHubCollection(gitUrl: string, pinnedCommit?: string) {
+ const url = new URL(gitUrl);
+ const info = this.github.parseRepoUrl(url.origin + url.pathname.replace(/\/+$/, ''), 'HEAD');
+ const commit = pinnedCommit ?? (await this.github.resolveCommit(info));
+ const base = info.path ?? '';
+ const archive = await readGitHubArchive(
+ await this.github.downloadCommitZip(info, commit),
+ base,
+ );
+ const exact = url.pathname.split('/')[3] === 'blob' || (!!base && archive.has(base));
+ const directories = [...archive].filter(([path]) =>
+ exact ? path === base : !base || path === base || path.startsWith(base + '/'),
+ );
+ return { commit, directories, info };
+ }
+
+ async discoverGitHubSkills(gitUrl: string): Promise<GitHubSkillDiscovery> {
+ const { commit, directories, info } = await this.gitHubCollection(gitUrl);
+ const entries = directories.map(([path, directory]) => {
+ const fallbackName = path.split('/').at(-1) || info.repo;
+ const source = { ...info, path };
+ try {
+ const { manifest } = this.parser.parseSkillMd(directory.markdown, { fallbackName });
+ return { path, directory, source, fallbackName, manifest };
+ } catch {
+ return { path, directory, source, fallbackName };
+ }
+ });
+ const rows = await this.skillModel.findImportMatches(
+ entries.flatMap(({ source }) => Object.values(this.gitHubIdentifiers(source))),
+ entries.flatMap(({ manifest }) => (manifest ? [manifest.name] : [])),
+ );
+ const byIdentifier = new Map(rows.map((row) => [row.identifier, row]));
+ const byName = new Map(rows.map((row) => [row.name.toLowerCase(), row]));
+ const candidates: GitHubSkillCandidate[] = [];
+ for (const { path, directory, source, manifest, fallbackName } of entries) {
+ if (!manifest) {
+ candidates.push({
+ description: '',
+ name: fallbackName,
+ path,
+ revision: null,
+ status: 'invalid',
+ });
+ continue;
+ }
+ const named = byName.get(manifest.name.toLowerCase());
+ let existing: SkillItem | undefined;
+ try {
+ existing = this.gitHubTarget(source, byIdentifier).existing;
+ } catch (error) {
+ if (!(error instanceof SkillImportError)) throw error;
+ candidates.push({
+ description: manifest.description,
+ name: manifest.name,
+ path,
+ revision: null,
+ status: 'conflict',
+ });
+ continue;
+ }
+ let status: GitHubSkillCandidate['status'] = 'new';
+ if (named && named.id !== existing?.id) status = 'conflict';
+ else if (existing) {
+ const parsed = await this.parser.parseGitHubDirectory(directory, fallbackName);
+ if (unchanged(existing, parsed)) status = 'unchanged';
+ else if (
+ this.workspaceId &&
+ this.workspaceRole !== 'owner' &&
+ existing.userId !== this.userId
+ )
+ status = 'forbidden';
+ else status = 'update';
+ }
+ candidates.push({
+ description: manifest.description,
+ name: manifest.name,
+ path,
+ revision: revisionOf(existing),
+ status,
});
- log('importFromGitHub: updated skill id=%s', skill.id);
- return { skill, status: 'updated' };
}
+ candidates.sort((a, b) => a.path.localeCompare(b.path));
+ return { candidates, commit, scope: this.importScope };
+ }
- // 10. Create new skill record
- log('importFromGitHub: creating new skill...');
- const skill = await this.skillModel.create({
- content,
- description: (manifest as any).description,
- identifier,
- manifest: fullManifest,
- name: manifest.name,
- resources: resourceIds,
- source: 'market', // GitHub source marked as market
- zipFileHash,
- });
- log('importFromGitHub: created skill id=%s', skill.id);
- return { skill, status: 'created' };
+ async importGitHubSkills(input: GitHubSkillBatchInput): Promise<GitHubSkillOutcome[]> {
+ if (this.importScope !== input.scope)
+ throw new SkillImportError('The active library changed. Find skills again.', 'CONFLICT');
+ const { directories, info } = await this.gitHubCollection(input.gitUrl, input.commit);
+ const available = new Map(directories);
+ const results: GitHubSkillOutcome[] = [];
+ for (const { path, revision } of input.selections) {
+ try {
+ const directory = available.get(path);
+ if (!directory) throw new SkillImportError('Skill outside selected scope', 'NOT_FOUND');
+ const parsed = await this.parser.parseGitHubDirectory(
+ directory,
+ path.split('/').at(-1) || info.repo,
+ );
+ const sourceUrl = `https://github.com/${info.owner}/${info.repo}/tree/${input.commit}${path ? '/' + path.split('/').map(encodeURIComponent).join('/') : ''}`;
+ const result = await this.saveGitHubSkill(
+ { ...info, path },
+ sourceUrl,
+ parsed,
+ undefined,
+ revision,
+ );
+ results.push({ path, status: result.status });
+ } catch (error) {
+ log('GitHub skill import failed for %s: %O', path, error);
+ const code = error instanceof SkillImportError ? error.code : undefined;
+ results.push({
+ path,
+ status: code === 'CONFLICT' ? 'conflict' : code === 'FORBIDDEN' ? 'forbidden' : 'failed',
+ });
+ }
+ }
+ return results;
}
/**
diff --git a/apps/server/src/services/skill/parser.ts b/apps/server/src/services/skill/parser.ts
index 7a6ed93f44e..e8bee85bb0a 100644
--- a/apps/server/src/services/skill/parser.ts
+++ b/apps/server/src/services/skill/parser.ts
@@ -15,6 +15,7 @@ import { marked, type Token, type Tokens } from 'marked';
import { safeMatterOptions } from '@/server/utils/safeMatterOptions';
import { SkillManifestError, SkillParseError } from './errors';
+import { type GitHubSkillDirectory, readGitHubArchive } from './githubArchive';
export interface ParseSkillMdOptions {
/**
@@ -130,6 +131,16 @@ export class SkillParser {
}
}
+ async parseGitHubDirectory(
+ directory: GitHubSkillDirectory,
+ fallbackName?: string,
+ ): Promise<ParsedZipSkill> {
+ const { markdown, resources } = directory;
+ const { manifest, content } = this.parseSkillMd(markdown, { fallbackName });
+ const skillZipBuffer = await this.repackSkillZip(markdown, resources);
+ return { content, manifest, resources, skillZipBuffer, zipHash: sha256(skillZipBuffer) };
+ }
+
/**
* Parse ZIP package
* @param buffer - ZIP file Buffer
@@ -138,6 +149,12 @@ export class SkillParser {
*/
async parseZipPackage(buffer: Buffer, options?: ParseZipOptions): Promise<ParsedZipSkill> {
try {
+ if (options?.repackSkillZip) {
+ const path = options.basePath?.replaceAll(/^\/|\/$/g, '') ?? '';
+ const directory = (await readGitHubArchive(buffer, path)).get(path);
+ if (!directory) throw new SkillParseError('SKILL.md not found in zip package');
+ return this.parseGitHubDirectory(directory, options.fallbackName || path.split('/').at(-1));
+ }
const unzipped = await this.unzipBuffer(buffer);
// Find SKILL.md (support root directory, first-level subdirectory, or specified basePath)
@@ -155,13 +172,6 @@ export class SkillParser {
// Extract resource files
const resources = this.extractResources(unzipped, skillMdPath);
- // If repackSkillZip is true, create a new ZIP with only the skill files
- if (options?.repackSkillZip) {
- const skillZipBuffer = await this.repackSkillZip(skillMdContent, resources);
- const zipHash = sha256(skillZipBuffer);
- return { content, manifest, resources, skillZipBuffer, zipHash };
- }
-
// Calculate ZIP hash from original buffer
const zipHash = sha256(buffer);
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 25bd447629e..df3c9825132 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -199,7 +199,29 @@
"agentSkillModal.contentPlaceholder": "Enter skill content in Markdown format...",
"agentSkillModal.description": "Description",
"agentSkillModal.descriptionPlaceholder": "Briefly describe this skill",
+ "agentSkillModal.github.clear": "Clear selection",
+ "agentSkillModal.github.collectionHint": "Enter a public GitHub repository or skill directory URL.",
"agentSkillModal.github.desc": "Paste the URL of a skill directory from a public GitHub repository. The directory must contain a SKILL.md file.",
+ "agentSkillModal.github.empty": "No SKILL.md found at this URL. Try another repository or directory.",
+ "agentSkillModal.github.find": "Find skills",
+ "agentSkillModal.github.findFailed": "Couldn’t read this GitHub link. Check the URL and try again.",
+ "agentSkillModal.github.importFailed": "Couldn’t import the selected skills. Find skills again, then retry.",
+ "agentSkillModal.github.install": "Import {{count}} ({{updates}} updates)",
+ "agentSkillModal.github.noMatch": "No matching skills",
+ "agentSkillModal.github.retry": "Retry failed imports",
+ "agentSkillModal.github.sameName": "Choose one of the skills with this name.",
+ "agentSkillModal.github.search": "Search by name, description or path",
+ "agentSkillModal.github.select": "Select all unambiguous matches",
+ "agentSkillModal.github.status.conflict": "Conflict · check the library and scan again",
+ "agentSkillModal.github.status.created": "Imported",
+ "agentSkillModal.github.status.failed": "Import failed",
+ "agentSkillModal.github.status.forbidden": "Update requires the creator or a workspace owner",
+ "agentSkillModal.github.status.invalid": "Invalid SKILL.md",
+ "agentSkillModal.github.status.new": "New",
+ "agentSkillModal.github.status.unchanged": "Up to date",
+ "agentSkillModal.github.status.update": "Update available",
+ "agentSkillModal.github.status.updated": "Updated",
+ "agentSkillModal.github.summary": "{{success}} imported or up to date · {{failed}} failed",
"agentSkillModal.github.title": "Import from GitHub",
"agentSkillModal.github.urlPlaceholder": "https://github.com/username/repo/tree/main/skills/my-skill",
"agentSkillModal.importError": "Import failed: {{error}}",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 1eba149f284..00cab96f407 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -199,7 +199,29 @@
"agentSkillModal.contentPlaceholder": "输入 Markdown 格式的技能内容...",
"agentSkillModal.description": "描述",
"agentSkillModal.descriptionPlaceholder": "简要描述该技能",
+ "agentSkillModal.github.clear": "清空选择",
+ "agentSkillModal.github.collectionHint": "输入公开 GitHub 仓库或技能目录的链接。",
"agentSkillModal.github.desc": "粘贴公开 GitHub 仓库中技能目录的 URL,该目录下需包含 SKILL.md 文件。",
+ "agentSkillModal.github.empty": "此链接下没有找到 SKILL.md,请尝试其他仓库或目录。",
+ "agentSkillModal.github.find": "查找技能",
+ "agentSkillModal.github.findFailed": "无法读取这个 GitHub 链接,请检查链接后重试。",
+ "agentSkillModal.github.importFailed": "未能导入所选技能,请重新查找后再试。",
+ "agentSkillModal.github.install": "导入 {{count}} 项(含 {{updates}} 项更新)",
+ "agentSkillModal.github.noMatch": "没有匹配的技能",
+ "agentSkillModal.github.retry": "重试失败项",
+ "agentSkillModal.github.sameName": "同名技能只能选择一个。",
+ "agentSkillModal.github.search": "搜索名称、描述或路径",
+ "agentSkillModal.github.select": "全选无重名的匹配项",
+ "agentSkillModal.github.status.conflict": "存在冲突,请检查技能库后重新查找",
+ "agentSkillModal.github.status.created": "已导入",
+ "agentSkillModal.github.status.failed": "导入失败",
+ "agentSkillModal.github.status.forbidden": "仅创建者或工作区所有者可更新",
+ "agentSkillModal.github.status.invalid": "SKILL.md 格式无效",
+ "agentSkillModal.github.status.new": "可导入",
+ "agentSkillModal.github.status.unchanged": "已是最新",
+ "agentSkillModal.github.status.update": "可更新",
+ "agentSkillModal.github.status.updated": "已更新",
+ "agentSkillModal.github.summary": "{{success}} 项已导入或已是最新,{{failed}} 项失败",
"agentSkillModal.github.title": "从 GitHub 导入",
"agentSkillModal.github.urlPlaceholder": "https://github.com/username/repo/tree/main/skills/my-skill",
"agentSkillModal.importError": "导入失败:{{error}}",
diff --git a/packages/database/src/models/agentSkill.ts b/packages/database/src/models/agentSkill.ts
index d3475e72d1c..b0f6064ada4 100644
--- a/packages/database/src/models/agentSkill.ts
+++ b/packages/database/src/models/agentSkill.ts
@@ -82,6 +82,23 @@ export class AgentSkillModel {
return result;
};
+ findImportMatches = async (identifiers: string[], names: string[]): Promise<SkillItem[]> =>
+ this.db
+ .select(skillItemColumns)
+ .from(agentSkills)
+ .where(
+ and(
+ this.scopeWhere(),
+ or(
+ inArray(agentSkills.identifier, identifiers),
+ inArray(
+ sql`lower(${agentSkills.name})`,
+ names.map((name) => name.toLowerCase()),
+ ),
+ ),
+ ),
+ );
+
findByName = async (name: string): Promise<SkillItem | undefined> => {
const [result] = await this.db
.select(skillItemColumns)
@@ -151,6 +168,30 @@ export class AgentSkillModel {
return result;
};
+ // Serialize GitHub create/name decisions within a library. Only final row
+ // writes take this lock; archive downloads and object uploads run outside it.
+ withImportLock = <T>(write: (model: AgentSkillModel) => Promise<T>) =>
+ this.db.transaction(async (tx) => {
+ const scope = this.workspaceId ? `workspace:${this.workspaceId}` : `user:${this.userId}`;
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${'skill-import:' + scope}))`);
+ return write(new AgentSkillModel(tx, this.userId, this.workspaceId));
+ });
+
+ replaceImportedSkill = async (existing: SkillItem, data: Partial<NewAgentSkill>) => {
+ const [row] = await this.db
+ .update(agentSkills)
+ .set({ ...data, updatedAt: new Date() })
+ .where(
+ and(
+ this.scopeWhere(),
+ eq(agentSkills.id, existing.id),
+ sql`date_trunc('milliseconds', ${agentSkills.updatedAt}) = ${existing.updatedAt.toISOString()}::timestamptz`,
+ ),
+ )
+ .returning(skillItemColumns);
+ return row;
+ };
+
// ========== Delete ==========
delete = async (id: string): Promise<{ success: boolean }> => {
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index 7823f63e674..0ebbdb8bf3e 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -159,7 +159,15 @@ export class FileModel {
};
createGlobalFile = async (file: Omit<NewGlobalFile, 'id' | 'userId'>) => {
- return this.db.insert(globalFiles).values(file).returning();
+ return this.db
+ .insert(globalFiles)
+ .values(file)
+ .onConflictDoUpdate({
+ target: globalFiles.hashId,
+ set: { metadata: file.metadata, url: file.url },
+ setWhere: ne(globalFiles.url, file.url),
+ })
+ .returning();
};
updateGlobalFile = async (
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 9612414f023..4ff79a4750d 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -333,6 +333,32 @@ export default {
'agentSkillModal.descriptionPlaceholder': 'Briefly describe this skill',
'agentSkillModal.github.desc':
'Paste the URL of a skill directory from a public GitHub repository. The directory must contain a SKILL.md file.',
+ 'agentSkillModal.github.clear': 'Clear selection',
+ 'agentSkillModal.github.collectionHint':
+ 'Enter a public GitHub repository or skill directory URL.',
+ 'agentSkillModal.github.empty':
+ 'No SKILL.md found at this URL. Try another repository or directory.',
+ 'agentSkillModal.github.find': 'Find skills',
+ 'agentSkillModal.github.findFailed':
+ 'Couldn’t read this GitHub link. Check the URL and try again.',
+ 'agentSkillModal.github.importFailed':
+ 'Couldn’t import the selected skills. Find skills again, then retry.',
+ 'agentSkillModal.github.install': 'Import {{count}} ({{updates}} updates)',
+ 'agentSkillModal.github.noMatch': 'No matching skills',
+ 'agentSkillModal.github.retry': 'Retry failed imports',
+ 'agentSkillModal.github.sameName': 'Choose one of the skills with this name.',
+ 'agentSkillModal.github.search': 'Search by name, description or path',
+ 'agentSkillModal.github.select': 'Select all unambiguous matches',
+ 'agentSkillModal.github.status.conflict': 'Conflict · check the library and scan again',
+ 'agentSkillModal.github.status.created': 'Imported',
+ 'agentSkillModal.github.status.failed': 'Import failed',
+ 'agentSkillModal.github.status.forbidden': 'Update requires the creator or a workspace owner',
+ 'agentSkillModal.github.status.invalid': 'Invalid SKILL.md',
+ 'agentSkillModal.github.status.new': 'New',
+ 'agentSkillModal.github.status.unchanged': 'Up to date',
+ 'agentSkillModal.github.status.update': 'Update available',
+ 'agentSkillModal.github.status.updated': 'Updated',
+ 'agentSkillModal.github.summary': '{{success}} imported or up to date · {{failed}} failed',
'agentSkillModal.github.title': 'Import from GitHub',
'agentSkillModal.github.urlPlaceholder':
'https://github.com/username/repo/tree/main/skills/my-skill',
diff --git a/packages/types/src/skill/index.ts b/packages/types/src/skill/index.ts
index 0db492b8569..b60ee4f4d4f 100644
--- a/packages/types/src/skill/index.ts
+++ b/packages/types/src/skill/index.ts
@@ -203,3 +203,35 @@ export interface SkillImportResult {
skill: SkillItem;
status: SkillImportStatus;
}
+
+export interface GitHubSkillSelection {
+ path: string;
+ /** Installed row and revision observed during discovery, or null for a new skill. */
+ revision: string | null;
+}
+
+export interface GitHubSkillCandidate extends GitHubSkillSelection {
+ description: string;
+ name: string;
+ status: 'new' | 'update' | 'unchanged' | 'conflict' | 'forbidden' | 'invalid';
+}
+
+export interface GitHubSkillDiscovery {
+ candidates: GitHubSkillCandidate[];
+ /** Commit the scan was read at; the import pins the same one. */
+ commit: string;
+ /** Library the scan ran against; an import into another library is refused. */
+ scope: string;
+}
+
+export interface GitHubSkillBatchInput {
+ commit: string;
+ gitUrl: string;
+ scope: string;
+ selections: GitHubSkillSelection[];
+}
+
+export interface GitHubSkillOutcome {
+ path: string;
+ status: SkillImportStatus | 'failed' | 'conflict' | 'forbidden';
+}
diff --git a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
index 94fe7d4d829..ef3e2c13059 100644
--- a/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
+++ b/src/features/SkillStore/SkillList/ImportFromGithubModal.tsx
@@ -1,99 +1,225 @@
'use client';
+import type { GitHubSkillCandidate } from '@lobechat/types';
import {
- Alert,
Button,
+ Checkbox,
createModal,
Flexbox,
- Icon,
Input,
type ModalInstance,
Text,
- toast,
useModalContext,
} from '@lobehub/ui';
-import { GithubIcon } from '@lobehub/ui/icons';
-import { ArrowLeftRight, Sparkles } from 'lucide-react';
-import { memo, useEffect, useState } from 'react';
+import { memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
-import { usePermission } from '@/hooks/usePermission';
-import { useToolStore } from '@/store/tool';
+import AsyncError from '@/components/AsyncError';
+
+import { useGithubSkillImport } from './useGithubSkillImport';
+
+const eligible = (item: GitHubSkillCandidate) => item.status === 'new' || item.status === 'update';
const ImportFromGithubContent = memo(() => {
const { t } = useTranslation(['setting', 'common']);
const { close, setCanDismissByClickOutside } = useModalContext();
-
- const importAgentSkillFromGitHub = useToolStore((s) => s.importAgentSkillFromGitHub);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [url, setUrl] = useState('');
- const { allowed: canCreate } = usePermission('create_content');
+ const {
+ canCreate,
+ candidates,
+ discover,
+ failure,
+ install,
+ loading,
+ query,
+ results,
+ scan,
+ selected,
+ setQuery,
+ setSelected,
+ setUrl,
+ url,
+ } = useGithubSkillImport();
useEffect(() => {
setCanDismissByClickOutside(!loading);
}, [loading, setCanDismissByClickOutside]);
- const handleImport = async () => {
- const trimmed = url.trim();
- if (!canCreate || !trimmed) return;
-
- setLoading(true);
- setError(null);
-
- try {
- await importAgentSkillFromGitHub({ gitUrl: trimmed });
- toast.success(t('agentSkillModal.importSuccess'));
- close();
- } catch (err: any) {
- setError(err?.message || String(err));
- } finally {
- setLoading(false);
- }
- };
+ const chosen = candidates.filter((item) => selected.includes(item.path));
+ const selectedNames = new Set(chosen.map((item) => item.name.toLowerCase()));
+ const visible = candidates.filter(({ name, path, description }) =>
+ [name, path, description].some((field) =>
+ field.toLowerCase().includes(query.trim().toLowerCase()),
+ ),
+ );
+ const finished = results.length > 0;
+ const failed = results.filter((item) => item.status === 'failed').map((item) => item.path);
+ const failureCount = results.filter((item) =>
+ ['failed', 'conflict', 'forbidden'].includes(item.status),
+ ).length;
+ const duplicateNames = new Set<string>();
+ const allNames = new Set<string>();
+ for (const item of candidates.filter(eligible)) {
+ const name = item.name.toLowerCase();
+ if (allNames.has(name)) duplicateNames.add(name);
+ allNames.add(name);
+ }
+ const bulk = visible.filter(
+ (item) => eligible(item) && !duplicateNames.has(item.name.toLowerCase()),
+ );
return (
- <Flexbox gap={16}>
- <Flexbox align="center" gap={16} padding={'16px 0'}>
- <Flexbox horizontal align="center" gap={8}>
- <Icon icon={GithubIcon} size={28} />
- <Icon
- icon={ArrowLeftRight}
- size={16}
- style={{ color: 'var(--lobe-color-text-tertiary)' }}
- />
- <Icon icon={Sparkles} size={28} />
- </Flexbox>
-
- <Flexbox align="center" gap={4}>
- <Text as={'h4'} style={{ margin: 0 }}>
- {t('agentSkillModal.github.title')}
- </Text>
- <Text align={'center'} type={'secondary'}>
- {t('agentSkillModal.github.desc')}
- </Text>
- </Flexbox>
- </Flexbox>
-
- {error && <Alert showIcon title={t('agentSkillModal.importError', { error })} type="error" />}
-
- <Flexbox gap={8}>
- <Text strong>URL</Text>
- <Input
- disabled={!canCreate}
- placeholder={t('agentSkillModal.github.urlPlaceholder')}
- value={url}
- onPressEnter={handleImport}
- onChange={(e) => {
- setUrl(e.target.value);
- if (error) setError(null);
- }}
+ <Flexbox gap={12}>
+ <Text as="h4">{t('agentSkillModal.github.title')}</Text>
+ {failure && (
+ <AsyncError
+ align="start"
+ details={failure.details}
+ variant="inline"
+ title={t(
+ failure.stage === 'find'
+ ? 'agentSkillModal.github.findFailed'
+ : 'agentSkillModal.github.importFailed',
+ )}
/>
- </Flexbox>
-
- <Button block disabled={!canCreate} loading={loading} type="primary" onClick={handleImport}>
- {t('common:import')}
- </Button>
+ )}
+ <Input
+ aria-label="GitHub URL"
+ disabled={loading}
+ placeholder={t('agentSkillModal.github.urlPlaceholder')}
+ value={url}
+ onChange={(event) => setUrl(event.target.value)}
+ onPressEnter={discover}
+ />
+ {!scan && (
+ <>
+ <Text type="secondary">{t('agentSkillModal.github.collectionHint')}</Text>
+ <Button
+ disabled={!canCreate || !url.trim()}
+ loading={loading}
+ type="primary"
+ onClick={discover}
+ >
+ {t('agentSkillModal.github.find')}
+ </Button>
+ </>
+ )}
+ {scan && (
+ <>
+ {finished && (
+ <Text role="status">
+ {t('agentSkillModal.github.summary', {
+ success: results.length - failureCount,
+ failed: failureCount,
+ })}
+ </Text>
+ )}
+ {!finished && candidates.length > 1 && (
+ <>
+ <Input
+ aria-label={t('agentSkillModal.github.search')}
+ placeholder={t('agentSkillModal.github.search')}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ <Flexbox horizontal gap={8}>
+ <Button
+ disabled={loading || !bulk.length}
+ size="small"
+ onClick={() =>
+ setSelected([...new Set([...selected, ...bulk.map((item) => item.path)])])
+ }
+ >
+ {t('agentSkillModal.github.select')}
+ </Button>
+ <Button
+ disabled={loading || !selected.length}
+ size="small"
+ onClick={() => setSelected([])}
+ >
+ {t('agentSkillModal.github.clear')}
+ </Button>
+ </Flexbox>
+ </>
+ )}
+ <Flexbox gap={12} style={{ maxHeight: '45vh', overflowY: 'auto' }}>
+ {!visible.length && (
+ <Text>
+ {t(
+ candidates.length
+ ? 'agentSkillModal.github.noMatch'
+ : 'agentSkillModal.github.empty',
+ )}
+ </Text>
+ )}
+ {visible.map((item) => {
+ const result = results.find((row) => row.path === item.path);
+ if (finished && !result) return null;
+ const checked = selected.includes(item.path);
+ const duplicate = duplicateNames.has(item.name.toLowerCase());
+ return (
+ <Flexbox gap={2} key={item.path}>
+ <Flexbox horizontal align="center" gap={8}>
+ {!finished && (
+ <Checkbox
+ aria-label={item.name + ' ' + (item.path || '/')}
+ checked={checked}
+ disabled={
+ loading ||
+ !eligible(item) ||
+ (!checked && selectedNames.has(item.name.toLowerCase()))
+ }
+ onChange={() =>
+ setSelected(
+ checked
+ ? selected.filter((path) => path !== item.path)
+ : [...selected, item.path],
+ )
+ }
+ />
+ )}
+ <Text strong>{item.name}</Text>
+ <Text type="secondary">
+ {t(`agentSkillModal.github.status.${result?.status ?? item.status}`)}
+ </Text>
+ </Flexbox>
+ <Text type="secondary">{item.path || '/'}</Text>
+ {item.description && <Text>{item.description}</Text>}
+ {duplicate && !finished && (
+ <Text type="secondary">{t('agentSkillModal.github.sameName')}</Text>
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ {finished ? (
+ <Flexbox horizontal gap={8}>
+ <Button disabled={loading} onClick={discover}>
+ {t('agentSkillModal.github.find')}
+ </Button>
+ {failed.length > 0 && (
+ <Button loading={loading} onClick={() => install(failed)}>
+ {t('agentSkillModal.github.retry')}
+ </Button>
+ )}
+ <Button disabled={loading} onClick={close}>
+ {t('common:close')}
+ </Button>
+ </Flexbox>
+ ) : (
+ <Button
+ disabled={!canCreate || !chosen.length}
+ loading={loading}
+ type="primary"
+ onClick={() => install(selected)}
+ >
+ {t('agentSkillModal.github.install', {
+ count: chosen.length,
+ updates: chosen.filter((item) => item.status === 'update').length,
+ })}
+ </Button>
+ )}
+ </>
+ )}
</Flexbox>
);
});
@@ -105,5 +231,5 @@ export const openImportFromGithubModal = (): ModalInstance =>
content: <ImportFromGithubContent />,
footer: null,
maskClosable: true,
- width: 480,
+ width: 520,
});
diff --git a/src/features/SkillStore/SkillList/useGithubSkillImport.test.ts b/src/features/SkillStore/SkillList/useGithubSkillImport.test.ts
new file mode 100644
index 00000000000..5897b5e12ac
--- /dev/null
+++ b/src/features/SkillStore/SkillList/useGithubSkillImport.test.ts
@@ -0,0 +1,132 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGithubSkillImport } from './useGithubSkillImport';
+
+const mocks = vi.hoisted(() => ({
+ discoverGitHubSkills: vi.fn(),
+ importGitHubSkills: vi.fn(),
+ refresh: vi.fn(),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (state: unknown) => unknown) =>
+ selector({ refreshAgentSkills: mocks.refresh }),
+}));
+vi.mock('@/services/skill', () => ({
+ agentSkillService: {
+ discoverGitHubSkills: mocks.discoverGitHubSkills,
+ importGitHubSkills: mocks.importGitHubSkills,
+ },
+}));
+
+const commit = 'a'.repeat(40);
+const demo = {
+ description: 'Demo',
+ name: 'demo',
+ path: 'skills/demo',
+ revision: null,
+ status: 'new' as const,
+};
+
+const scanned = async () => {
+ const hook = renderHook(() => useGithubSkillImport());
+ act(() => hook.result.current.setUrl(' https://github.com/lobehub/skills '));
+ await act(() => hook.result.current.discover());
+ return hook;
+};
+
+describe('useGithubSkillImport', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('treats a response without candidates as an empty scan', async () => {
+ mocks.discoverGitHubSkills.mockResolvedValue({ commit, scope: 'scope' });
+
+ const { result } = await scanned();
+
+ expect(result.current.failure).toBeUndefined();
+ expect(result.current.scan).toEqual({ candidates: [], commit, scope: 'scope' });
+ expect(result.current.candidates).toEqual([]);
+ expect(result.current.selected).toEqual([]);
+ });
+
+ it('preselects the only new skill of a scan', async () => {
+ mocks.discoverGitHubSkills.mockResolvedValue({ candidates: [demo], commit, scope: 'scope' });
+
+ const { result } = await scanned();
+
+ expect(mocks.discoverGitHubSkills).toHaveBeenCalledWith('https://github.com/lobehub/skills');
+ expect(result.current.selected).toEqual(['skills/demo']);
+ });
+
+ it('records a failed scan with its raw message as details', async () => {
+ mocks.discoverGitHubSkills.mockRejectedValue(new Error('[{"code":"invalid_format"}]'));
+
+ const { result } = await scanned();
+
+ expect(result.current.failure).toEqual({
+ details: '[{"code":"invalid_format"}]',
+ stage: 'find',
+ });
+ expect(result.current.scan).toBeUndefined();
+ expect(result.current.loading).toBe(false);
+ });
+
+ it('pins the scanned commit and scope, and reports a failed batch as an import failure', async () => {
+ mocks.discoverGitHubSkills.mockResolvedValue({ candidates: [demo], commit, scope: 'scope' });
+ mocks.importGitHubSkills.mockRejectedValue(new Error('The active library changed.'));
+
+ const { result } = await scanned();
+ await act(() => result.current.install(['skills/demo']));
+
+ expect(mocks.importGitHubSkills).toHaveBeenCalledWith({
+ commit,
+ gitUrl: 'https://github.com/lobehub/skills',
+ scope: 'scope',
+ selections: [{ path: 'skills/demo', revision: null }],
+ });
+ expect(result.current.failure).toEqual({
+ details: 'The active library changed.',
+ stage: 'import',
+ });
+ expect(result.current.results).toEqual([]);
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ });
+
+ it('replaces the outcomes of retried paths and refreshes the library', async () => {
+ mocks.discoverGitHubSkills.mockResolvedValue({
+ candidates: [demo, { ...demo, name: 'other', path: 'skills/other' }],
+ commit,
+ scope: 'scope',
+ });
+ mocks.importGitHubSkills
+ .mockResolvedValueOnce([
+ { path: 'skills/demo', status: 'created' },
+ { path: 'skills/other', status: 'failed' },
+ ])
+ .mockResolvedValueOnce([{ path: 'skills/other', status: 'created' }]);
+
+ const { result } = await scanned();
+ await act(() => result.current.install(['skills/demo', 'skills/other']));
+ await act(() => result.current.install(['skills/other']));
+
+ expect(result.current.results).toEqual([
+ { path: 'skills/demo', status: 'created' },
+ { path: 'skills/other', status: 'created' },
+ ]);
+ expect(mocks.refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops the scan and the failure when the URL is edited', async () => {
+ mocks.discoverGitHubSkills.mockResolvedValue({ candidates: [demo], commit, scope: 'scope' });
+
+ const { result } = await scanned();
+ act(() => result.current.setUrl('https://github.com/lobehub/other'));
+
+ expect(result.current.scan).toBeUndefined();
+ expect(result.current.failure).toBeUndefined();
+ });
+});
diff --git a/src/features/SkillStore/SkillList/useGithubSkillImport.ts b/src/features/SkillStore/SkillList/useGithubSkillImport.ts
new file mode 100644
index 00000000000..7a3a1804a44
--- /dev/null
+++ b/src/features/SkillStore/SkillList/useGithubSkillImport.ts
@@ -0,0 +1,99 @@
+import type { GitHubSkillDiscovery, GitHubSkillOutcome } from '@lobechat/types';
+import { useState } from 'react';
+
+import { usePermission } from '@/hooks/usePermission';
+import { agentSkillService } from '@/services/skill';
+import { useToolStore } from '@/store/tool';
+
+export interface GithubSkillImportFailure {
+ /** Raw message from the server, folded behind "Show details". */
+ details: string;
+ stage: 'find' | 'import';
+}
+
+const detailsOf = (err: unknown) => (err instanceof Error ? err.message : String(err));
+
+/**
+ * The scan → select → import state of the GitHub import modal: one request at
+ * a time, and a failure kept apart from the per-skill outcomes of a batch.
+ */
+export const useGithubSkillImport = () => {
+ const refresh = useToolStore((s) => s.refreshAgentSkills);
+ const { allowed: canCreate } = usePermission('create_content');
+ const [loading, setLoading] = useState(false);
+ const [failure, setFailure] = useState<GithubSkillImportFailure>();
+ const [url, setUrlValue] = useState('');
+ const [query, setQuery] = useState('');
+ const [scan, setScan] = useState<GitHubSkillDiscovery>();
+ const [selected, setSelected] = useState<string[]>([]);
+ const [results, setResults] = useState<GitHubSkillOutcome[]>([]);
+
+ const candidates = scan?.candidates ?? [];
+
+ /** A scan belongs to the URL it was read from, so editing the URL drops it. */
+ const setUrl = (value: string) => {
+ setUrlValue(value);
+ setScan(undefined);
+ setResults([]);
+ setFailure(undefined);
+ };
+
+ const discover = async () => {
+ if (!canCreate || !url.trim() || loading) return;
+ setLoading(true);
+ setFailure(undefined);
+ try {
+ const next = await agentSkillService.discoverGitHubSkills(url.trim());
+ // A server that predates a field must not take the modal down with it.
+ const found = next.candidates ?? [];
+ setScan({ ...next, candidates: found });
+ setQuery('');
+ setResults([]);
+ setSelected(found.length === 1 && found[0].status === 'new' ? [found[0].path] : []);
+ } catch (err) {
+ setFailure({ details: detailsOf(err), stage: 'find' });
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const install = async (paths: string[]) => {
+ if (!canCreate || !scan || !paths.length || loading) return;
+ setLoading(true);
+ setFailure(undefined);
+ try {
+ const batch = await agentSkillService.importGitHubSkills({
+ commit: scan.commit,
+ gitUrl: url.trim(),
+ scope: scan.scope,
+ selections: candidates
+ .filter((item) => paths.includes(item.path))
+ .map(({ path, revision }) => ({ path, revision })),
+ });
+ setResults((prev) => [...prev.filter((item) => !paths.includes(item.path)), ...batch]);
+ setQuery('');
+ await refresh();
+ } catch (err) {
+ setFailure({ details: detailsOf(err), stage: 'import' });
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return {
+ canCreate,
+ candidates,
+ discover,
+ failure,
+ install,
+ loading,
+ query,
+ results,
+ scan,
+ selected,
+ setQuery,
+ setSelected,
+ setUrl,
+ url,
+ };
+};
diff --git a/src/services/skill/index.ts b/src/services/skill/index.ts
index 331e8373dfd..deea648b4fb 100644
--- a/src/services/skill/index.ts
+++ b/src/services/skill/index.ts
@@ -1,5 +1,8 @@
import type {
CreateSkillInput,
+ GitHubSkillBatchInput,
+ GitHubSkillDiscovery,
+ GitHubSkillOutcome,
ImportGitHubInput,
ImportUrlInput,
ImportZipInput,
@@ -23,6 +26,14 @@ class AgentSkillService {
// ===== Import =====
+ discoverGitHubSkills(gitUrl: string): Promise<GitHubSkillDiscovery> {
+ return lambdaClient.agentSkills.discoverGitHubSkills.mutate({ gitUrl });
+ }
+
+ importGitHubSkills(input: GitHubSkillBatchInput): Promise<GitHubSkillOutcome[]> {
+ return lambdaClient.agentSkills.importGitHubSkills.mutate(input);
+ }
+
async importFromGitHub(params: ImportGitHubInput): Promise<SkillImportResult | undefined> {
return lambdaClient.agentSkills.importFromGitHub.mutate(params);
}