mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
refactor: extract core service domain layer to @shumai/core
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { skillService } from '@shumai/core/src/skill/skill'
|
||||
import AdmZip from 'adm-zip'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
describe('SkillService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('should list skills', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(team.id)
|
||||
expect(skills).toHaveLength(1)
|
||||
expect(skills[0].name).toBe('Skill 1')
|
||||
})
|
||||
|
||||
it('should upsert skill from asset', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
|
||||
// Create a dummy zip buffer
|
||||
const zip = new AdmZip()
|
||||
zip.addFile(
|
||||
'SKILL.md',
|
||||
Buffer.from('---\nname: "Test Skill"\ndescription: "This is a test skill."\n---'),
|
||||
)
|
||||
const zipBuffer = zip.toBuffer()
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.zip',
|
||||
storageKey: { create: { key: 'test.zip' } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockResolvedValue({
|
||||
buffer: zipBuffer,
|
||||
contentType: 'application/zip',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
|
||||
|
||||
const skill = await skillService.upsertSkill(team.id, {
|
||||
assetId: asset.id,
|
||||
})
|
||||
|
||||
expect(skill.name).toBe('Test Skill')
|
||||
expect(skill.description).toBe('This is a test skill.')
|
||||
expect(getObjectSpy).toHaveBeenCalled()
|
||||
expect(putObjectSpy).toHaveBeenCalled()
|
||||
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: skill.id },
|
||||
})
|
||||
expect(dbSkill).toBeDefined()
|
||||
expect(dbSkill?.name).toBe('Test Skill')
|
||||
|
||||
getObjectSpy.mockRestore()
|
||||
putObjectSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should upsert skill from github url with path', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
|
||||
// Create a dummy github zip buffer (nested structure)
|
||||
const zip = new AdmZip()
|
||||
const rootDir = 'repo-main'
|
||||
zip.addFile(`${rootDir}/`, Buffer.from(''))
|
||||
zip.addFile(`${rootDir}/skills/`, Buffer.from(''))
|
||||
zip.addFile(
|
||||
`${rootDir}/skills/pptx-generator/SKILL.md`,
|
||||
Buffer.from('---\nname: "PPTX Generator"\ndescription: "Generate powerpoint files."\n---'),
|
||||
)
|
||||
zip.addFile(`${rootDir}/skills/pptx-generator/index.ts`, Buffer.from('console.log("hello")'))
|
||||
// Add some noise
|
||||
zip.addFile(`${rootDir}/README.md`, Buffer.from('root readme'))
|
||||
const zipBuffer = zip.toBuffer()
|
||||
|
||||
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: async () => zipBuffer.buffer,
|
||||
} as Response)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
|
||||
|
||||
const skill = await skillService.upsertSkill(team.id, {
|
||||
githubUrl: 'https://github.com/owner/repo/tree/main/skills/pptx-generator',
|
||||
})
|
||||
|
||||
expect(skill.name).toBe('PPTX Generator')
|
||||
expect(skill.description).toBe('Generate powerpoint files.')
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
|
||||
)
|
||||
|
||||
// Verify repacking
|
||||
expect(putObjectSpy).toHaveBeenCalled()
|
||||
const repackedBuffer = putObjectSpy.mock.calls[0][2] as Buffer
|
||||
const repackedZip = new AdmZip(repackedBuffer)
|
||||
const entries = repackedZip.getEntries().map((e) => e.entryName)
|
||||
expect(entries).toContain('SKILL.md')
|
||||
expect(entries).toContain('index.ts')
|
||||
|
||||
fetchSpy.mockRestore()
|
||||
putObjectSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should upsert skill from github url using "blob" marker', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
|
||||
const zip = new AdmZip()
|
||||
const rootDir = 'repo-main'
|
||||
zip.addFile(
|
||||
`${rootDir}/SKILL.md`,
|
||||
Buffer.from('---\nname: "Blob Skill"\ndescription: "From blob URL."\n---'),
|
||||
)
|
||||
const zipBuffer = zip.toBuffer()
|
||||
|
||||
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: async () => zipBuffer.buffer,
|
||||
} as Response)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
|
||||
|
||||
const skill = await skillService.upsertSkill(team.id, {
|
||||
githubUrl: 'https://github.com/owner/repo/blob/main/SKILL.md',
|
||||
})
|
||||
|
||||
expect(skill.name).toBe('Blob Skill')
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
|
||||
)
|
||||
|
||||
fetchSpy.mockRestore()
|
||||
putObjectSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should upsert skill from github url using direct path (no tree/blob)', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
|
||||
const zip = new AdmZip()
|
||||
const rootDir = 'repo-main'
|
||||
zip.addFile(
|
||||
`${rootDir}/my-path/SKILL.md`,
|
||||
Buffer.from('---\nname: "Direct Skill"\ndescription: "From direct path."\n---'),
|
||||
)
|
||||
const zipBuffer = zip.toBuffer()
|
||||
|
||||
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: async () => zipBuffer.buffer,
|
||||
} as Response)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const putObjectSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined as any)
|
||||
|
||||
const skill = await skillService.upsertSkill(team.id, {
|
||||
githubUrl: 'https://github.com/owner/repo/my-path',
|
||||
})
|
||||
|
||||
expect(skill.name).toBe('Direct Skill')
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'https://codeload.github.com/owner/repo/zip/refs/heads/main',
|
||||
)
|
||||
|
||||
fetchSpy.mockRestore()
|
||||
putObjectSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should delete skill', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Delete Me',
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(skill.id)
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: skill.id },
|
||||
})
|
||||
expect(dbSkill).toBeNull()
|
||||
})
|
||||
|
||||
it('should update skill config', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
name: 'Config Skill',
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
const newConfig = {
|
||||
environmentVariables: [{ name: 'MY_VAR', default: 'my_val' }],
|
||||
}
|
||||
const updatedSkill = await skillService.updateSkillConfig(skill.id, newConfig)
|
||||
|
||||
expect(updatedSkill.config).toEqual(newConfig)
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: skill.id },
|
||||
})
|
||||
expect(dbSkill?.config).toEqual(newConfig)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,285 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { SkillInfo, UpsertSkillRequest } from '@shumai/dtos'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as crypto from 'crypto'
|
||||
import { ulid } from 'ulid'
|
||||
import { parseFrontmatter } from '@/utils/frontmatter'
|
||||
|
||||
interface SkillFrontmatter extends Record<string, unknown> {
|
||||
name?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export class SkillService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
async upsertSkill(teamId: string, req: UpsertSkillRequest): Promise<SkillInfo> {
|
||||
let zipBuffer: Buffer
|
||||
let requestedPath: string | undefined
|
||||
|
||||
if (req.githubUrl) {
|
||||
const { downloadUrl, path } = this.parseGithubUrl(req.githubUrl)
|
||||
requestedPath = path
|
||||
zipBuffer = await this.downloadGithubZip(downloadUrl)
|
||||
} else if (req.assetId) {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
zipBuffer = buffer
|
||||
} else {
|
||||
throw new Error('Either assetId or githubUrl must be provided')
|
||||
}
|
||||
|
||||
const { name, description, repackedZip } = await this.processSkillZip(zipBuffer, requestedPath)
|
||||
|
||||
// Check for existing skill if override is not requested
|
||||
const existingSkill = await this.prismaClient.skill.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
teamId_name: {
|
||||
teamId,
|
||||
name,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (existingSkill && !req.override) {
|
||||
const err = new Error(`Skill with name "${name}" already exists.`)
|
||||
err.name = 'ConflictError'
|
||||
throw err
|
||||
}
|
||||
|
||||
const hash = crypto.createHash('sha256').update(repackedZip).digest('hex')
|
||||
|
||||
// Upload repacked zip to S3
|
||||
const assetKey = `skills/${ulid()}.zip`
|
||||
await s3Service.putObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
assetKey,
|
||||
repackedZip,
|
||||
repackedZip.length,
|
||||
'application/zip',
|
||||
)
|
||||
|
||||
// Create a new asset record for the repacked zip
|
||||
const skillAsset = await this.prismaClient.asset.create({
|
||||
data: {
|
||||
name: `${name}.zip`,
|
||||
storageKey: { create: { key: assetKey } },
|
||||
type: 'file',
|
||||
mediaType: 'application/zip',
|
||||
sizeByte: repackedZip.length,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const skill = await this.prismaClient.skill.upsert({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
teamId_name: {
|
||||
teamId,
|
||||
name,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
description,
|
||||
assetId: skillAsset.id,
|
||||
hash,
|
||||
},
|
||||
create: {
|
||||
name,
|
||||
description,
|
||||
assetId: skillAsset.id,
|
||||
hash,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
|
||||
return this.toSkillInfo(skill)
|
||||
}
|
||||
|
||||
async deleteSkill(id: string): Promise<void> {
|
||||
const skill = await this.prismaClient.skill.findUnique({
|
||||
where: { id },
|
||||
})
|
||||
if (!skill) return
|
||||
|
||||
await this.prismaClient.skill.delete({
|
||||
where: { id },
|
||||
})
|
||||
|
||||
// Optionally delete the asset as well, though it might be shared or kept for history.
|
||||
// For now, let's keep it simple and just delete the DB record.
|
||||
}
|
||||
|
||||
async updateSkillConfig(id: string, config: PrismaJson.SkillConfig): Promise<SkillInfo> {
|
||||
const skill = await this.prismaClient.skill.update({
|
||||
where: { id },
|
||||
data: { config },
|
||||
})
|
||||
return this.toSkillInfo(skill)
|
||||
}
|
||||
|
||||
async listSkills(teamId: string): Promise<SkillInfo[]> {
|
||||
const skills = await this.prismaClient.skill.findMany({
|
||||
where: { teamId },
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return skills.map((s: any) => this.toSkillInfo(s))
|
||||
}
|
||||
|
||||
private parseGithubUrl(url: string): { downloadUrl: string; path?: string } {
|
||||
// Standard GitHub URL patterns:
|
||||
// 1. https://github.com/owner/repo/tree/branch/path
|
||||
// 2. https://github.com/owner/repo/blob/branch/path
|
||||
// 3. https://github.com/owner/repo/path (direct path, main branch)
|
||||
|
||||
const parsed = new URL(url)
|
||||
const parts = parsed.pathname.split('/').filter(Boolean)
|
||||
|
||||
if (parts.length < 2) {
|
||||
throw new Error('Invalid GitHub URL: missing owner or repo')
|
||||
}
|
||||
|
||||
const owner = parts[0]
|
||||
const repo = parts[1]
|
||||
let ref = 'main'
|
||||
let path: string | undefined
|
||||
|
||||
if (parts.length > 2) {
|
||||
if (parts[2] === 'tree' || parts[2] === 'blob') {
|
||||
if (parts.length < 4) {
|
||||
throw new Error('Invalid GitHub URL: missing ref or path')
|
||||
}
|
||||
ref = parts[3]
|
||||
path = parts.slice(4).join('/')
|
||||
} else {
|
||||
// Fallback: assume everything after repo is the path on 'main'
|
||||
path = parts.slice(2).join('/')
|
||||
}
|
||||
}
|
||||
|
||||
const downloadUrl = `https://codeload.github.com/${owner}/${repo}/zip/refs/heads/${ref}`
|
||||
|
||||
return { downloadUrl, path }
|
||||
}
|
||||
|
||||
private async downloadGithubZip(url: string): Promise<Buffer> {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
// Try 'master' if 'main' fails and it was a default guess
|
||||
if (url.endsWith('/refs/heads/main')) {
|
||||
const fallbackUrl = url.replace('/refs/heads/main', '/refs/heads/master')
|
||||
const fallbackRes = await fetch(fallbackUrl)
|
||||
if (fallbackRes.ok) {
|
||||
return Buffer.from(await fallbackRes.arrayBuffer())
|
||||
}
|
||||
}
|
||||
throw new Error(`Failed to download GitHub ZIP from ${url}`)
|
||||
}
|
||||
return Buffer.from(await res.arrayBuffer())
|
||||
}
|
||||
|
||||
private async processSkillZip(
|
||||
buffer: Buffer,
|
||||
requestedPath?: string,
|
||||
): Promise<{
|
||||
name: string
|
||||
description: string
|
||||
repackedZip: Buffer
|
||||
}> {
|
||||
const zip = new AdmZip(buffer)
|
||||
const entries = zip.getEntries()
|
||||
|
||||
if (entries.length === 0) {
|
||||
throw new Error('The provided ZIP file is empty')
|
||||
}
|
||||
|
||||
// Extract search path from entries
|
||||
const firstEntryName = entries[0].entryName
|
||||
const firstPart = firstEntryName.split('/')[0]
|
||||
const isGithubStructure = entries.every((e) => e.entryName.startsWith(`${firstPart}/`))
|
||||
|
||||
let effectiveRequestedPath = requestedPath || ''
|
||||
if (effectiveRequestedPath.toLowerCase().endsWith('skill.md')) {
|
||||
effectiveRequestedPath = effectiveRequestedPath.substring(
|
||||
0,
|
||||
effectiveRequestedPath.toLowerCase().lastIndexOf('skill.md'),
|
||||
)
|
||||
}
|
||||
|
||||
let searchPath = ''
|
||||
if (isGithubStructure) {
|
||||
searchPath = effectiveRequestedPath
|
||||
? `${firstPart}/${effectiveRequestedPath.replace(/\/$/, '')}/`
|
||||
: `${firstPart}/`
|
||||
} else {
|
||||
searchPath = effectiveRequestedPath ? `${effectiveRequestedPath.replace(/\/$/, '')}/` : ''
|
||||
}
|
||||
|
||||
// Find SKILL.md in the searchPath (case-insensitive)
|
||||
const skillMdEntry = entries.find((e) => {
|
||||
const entryLower = e.entryName.toLowerCase()
|
||||
const searchLower = searchPath.toLowerCase()
|
||||
return entryLower.startsWith(searchLower) && entryLower.endsWith('skill.md')
|
||||
})
|
||||
|
||||
if (!skillMdEntry) {
|
||||
throw new Error(`SKILL.md not found in ${requestedPath || 'root'}`)
|
||||
}
|
||||
|
||||
const content = skillMdEntry.getData().toString('utf8')
|
||||
const { name, description } = this.parseSkillMd(content)
|
||||
|
||||
// Repack: ensure the found SKILL.md's directory becomes the root
|
||||
const newZip = new AdmZip()
|
||||
const prefix = skillMdEntry.entryName.substring(
|
||||
0,
|
||||
skillMdEntry.entryName.toLowerCase().lastIndexOf('skill.md'),
|
||||
)
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory) continue
|
||||
if (entry.entryName.startsWith(prefix)) {
|
||||
const relPath = entry.entryName.substring(prefix.length)
|
||||
newZip.addFile(relPath, entry.getData())
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
repackedZip: newZip.toBuffer(),
|
||||
}
|
||||
}
|
||||
|
||||
private parseSkillMd(content: string): { name: string; description: string } {
|
||||
const { frontmatter } = parseFrontmatter<SkillFrontmatter>(content)
|
||||
const name = frontmatter.name || 'Unnamed Skill'
|
||||
const description = frontmatter.description || ''
|
||||
|
||||
return { name, description }
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private toSkillInfo(s: any): SkillInfo {
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
config: s.config as PrismaJson.SkillConfig,
|
||||
assetId: s.assetId,
|
||||
hash: s.hash,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
updatedAt: s.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const skillService = new SkillService()
|
||||
Reference in New Issue
Block a user