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,223 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { AgentService } from './agent'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db'
|
||||
|
||||
describe('AgentService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async function setupTestData(db: any) {
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'Google',
|
||||
teamId: team.id,
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini-pro',
|
||||
name: 'Gemini Pro',
|
||||
providerId: provider.id,
|
||||
config: {},
|
||||
},
|
||||
})
|
||||
|
||||
const skill = await db.skill.create({
|
||||
data: {
|
||||
name: 'Test Skill',
|
||||
teamId: team.id,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
},
|
||||
})
|
||||
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: 'Bot 1',
|
||||
email: 'bot1@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
const agent = await db.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
soul: 'Test soul',
|
||||
config: {
|
||||
provider: provider.id,
|
||||
model: model.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await db.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
},
|
||||
})
|
||||
|
||||
return { team, provider, model, skill, agent }
|
||||
}
|
||||
|
||||
describe('create, update, delete agents', () => {
|
||||
test('Create Agent with Provider and Model', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model } = await setupTestData(db)
|
||||
|
||||
const agent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'New Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
thinkingLevel: 'medium',
|
||||
systemPrompt: 'You are helpful',
|
||||
soul: 'I am a soul',
|
||||
})
|
||||
|
||||
expect(agent?.id).toBeDefined()
|
||||
expect(agent?.user.name).toBe('New Agent')
|
||||
expect(agent?.providerId).toBe(provider.id)
|
||||
expect(agent?.modelId).toBe(model.id)
|
||||
expect(agent?.soul).toBe('I am a soul')
|
||||
|
||||
const teamMember = await db.teamMember.findFirst({
|
||||
where: { userId: agent?.id, teamId: team.id },
|
||||
})
|
||||
expect(teamMember).toBeDefined()
|
||||
})
|
||||
|
||||
test('Create Agent with Skills', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, provider, model, skill } = await setupTestData(db)
|
||||
|
||||
const agent = await svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Skill Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
thinkingLevel: 'medium',
|
||||
skills: [skill.id],
|
||||
})
|
||||
|
||||
expect(agent?.skills?.length).toBe(1)
|
||||
expect(agent?.skills?.[0].skillId).toBe(skill.id)
|
||||
})
|
||||
|
||||
test('Create Agent validation fails if model mismatch', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team, model } = await setupTestData(db)
|
||||
|
||||
const otherProvider = await db.provider.create({
|
||||
data: {
|
||||
name: 'Other',
|
||||
teamId: team.id,
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
svc.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'Fail Agent',
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: otherProvider.id,
|
||||
modelId: model.id,
|
||||
thinkingLevel: 'medium',
|
||||
}),
|
||||
).rejects.toThrow('model does not belong to provider')
|
||||
})
|
||||
|
||||
test('Update Agent and Skills', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { agent, skill } = await setupTestData(db)
|
||||
|
||||
const updated = await svc.updateAgent({
|
||||
agentId: agent.id,
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: agent.providerId!,
|
||||
modelId: agent.modelId!,
|
||||
thinkingLevel: 'high',
|
||||
soul: 'New soul',
|
||||
skills: [], // Disable all skills
|
||||
})
|
||||
|
||||
expect(updated.user.name).toBe('Updated Agent')
|
||||
expect(updated.type).toBe('autofill')
|
||||
expect(updated.soul).toBe('New soul')
|
||||
expect(updated.skills?.length).toBe(0)
|
||||
|
||||
const reUpdated = await svc.updateAgent({
|
||||
agentId: agent.id,
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: agent.providerId!,
|
||||
modelId: agent.modelId!,
|
||||
thinkingLevel: 'high',
|
||||
soul: 'New soul',
|
||||
skills: [skill.id], // Re-enable one
|
||||
})
|
||||
expect(reUpdated.skills?.length).toBe(1)
|
||||
})
|
||||
|
||||
test('Delete Agent', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { agent } = await setupTestData(db)
|
||||
|
||||
await svc.deleteAgent({ agentId: agent.id })
|
||||
|
||||
const deletedAgent = await db.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
})
|
||||
expect(deletedAgent).toBeNull()
|
||||
|
||||
const deletedUser = await db.user.findUnique({
|
||||
where: { id: agent.id },
|
||||
})
|
||||
expect(deletedUser).toBeNull()
|
||||
})
|
||||
|
||||
test('List Agents', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team } = await setupTestData(db)
|
||||
|
||||
const agents = await svc.listAgents({ teamId: team.id })
|
||||
expect(agents.length).toBe(1)
|
||||
expect(agents[0].user.name).toBe('Bot 1')
|
||||
expect(agents[0].provider).toBeDefined()
|
||||
expect(agents[0].modelRef).toBeDefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,330 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import {
|
||||
CreateAgentParams,
|
||||
DeleteAgentParams,
|
||||
ListAgentsParams,
|
||||
UpdateAgentParams,
|
||||
} from '@shumai/dtos'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
export class AgentService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
async getSkillContent(skillId: string): Promise<string> {
|
||||
const skill = await this.prismaClient.skill.findUnique({
|
||||
where: { id: skillId },
|
||||
})
|
||||
|
||||
if (!skill) {
|
||||
throw new Error(`Skill with ID ${skillId} not found.`)
|
||||
}
|
||||
|
||||
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
|
||||
const hashFile = path.join(skillDir, '.hash')
|
||||
let needsDownload = true
|
||||
|
||||
if (fs.existsSync(hashFile)) {
|
||||
const localHash = fs.readFileSync(hashFile, 'utf8')
|
||||
if (localHash === skill.hash) {
|
||||
needsDownload = false
|
||||
}
|
||||
}
|
||||
|
||||
if (needsDownload) {
|
||||
if (fs.existsSync(skillDir)) {
|
||||
fs.rmSync(skillDir, { recursive: true, force: true })
|
||||
}
|
||||
fs.mkdirSync(skillDir, { recursive: true })
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: skill.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
if (!asset || !asset.storageKey?.key) {
|
||||
throw new Error('Skill asset not found or has no key')
|
||||
}
|
||||
|
||||
const { buffer: zipBuffer } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
asset.storageKey.key,
|
||||
)
|
||||
|
||||
const zip = new AdmZip(zipBuffer)
|
||||
zip.extractAllTo(skillDir, true)
|
||||
|
||||
fs.writeFileSync(hashFile, skill.hash)
|
||||
}
|
||||
|
||||
// Read SKILL.md
|
||||
let skillMdPath = path.join(skillDir, 'SKILL.md')
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
skillMdPath = path.join(skillDir, 'skill.md')
|
||||
}
|
||||
|
||||
if (!fs.existsSync(skillMdPath)) {
|
||||
throw new Error(`Skill downloaded but SKILL.md not found in ${skillDir}`)
|
||||
}
|
||||
|
||||
return fs.readFileSync(skillMdPath, 'utf8')
|
||||
}
|
||||
|
||||
async getSkillEnvs(skillId: string): Promise<Record<string, string>> {
|
||||
const skill = await this.prismaClient.skill.findUnique({
|
||||
where: { id: skillId },
|
||||
})
|
||||
if (!skill) return {}
|
||||
|
||||
const config = skill.config as unknown as PrismaJson.SkillConfig
|
||||
const envs: Record<string, string> = {}
|
||||
if (config?.environmentVariables && Array.isArray(config.environmentVariables)) {
|
||||
for (const envVar of config.environmentVariables) {
|
||||
const value =
|
||||
envVar.default !== undefined && envVar.default !== null && envVar.default !== ''
|
||||
? envVar.default
|
||||
: process.env[envVar.name]
|
||||
if (value !== undefined) {
|
||||
envs[envVar.name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
return envs
|
||||
}
|
||||
|
||||
async createAgent(params: CreateAgentParams) {
|
||||
const {
|
||||
teamId,
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
} = params
|
||||
|
||||
if (type === 'embedding' || type === 'autofill') {
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
throw new Error(`Agent of type ${type} already exists for this team`)
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'chat' || type === 'autofill') {
|
||||
if (!providerId || !modelId) {
|
||||
throw new Error('providerId and modelId are required for chat/autofill agents')
|
||||
}
|
||||
const model = await this.prismaClient.model.findUnique({
|
||||
where: { id: modelId },
|
||||
})
|
||||
if (!model) throw new Error('model not found')
|
||||
if (model.providerId !== providerId) {
|
||||
throw new Error('model does not belong to provider')
|
||||
}
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
const team = await tx.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
if (!team) throw new Error('team not found')
|
||||
|
||||
const agentConfig: PrismaJson.AgentConfig = {
|
||||
provider: providerId || '',
|
||||
model: modelId || '',
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
}
|
||||
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
name,
|
||||
email: `agent-${Date.now()}-${Math.random().toString(36).substring(7)}@shumai.ai`,
|
||||
type: 'agent',
|
||||
image: avatar,
|
||||
},
|
||||
})
|
||||
|
||||
const agent = await tx.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId,
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: agentConfig as any,
|
||||
skills: {
|
||||
create:
|
||||
skills?.map((skillId) => ({
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await tx.teamMember.create({
|
||||
data: {
|
||||
teamId,
|
||||
userId: user.id,
|
||||
role: 'reviewer', // Default role for agents
|
||||
},
|
||||
})
|
||||
|
||||
return tx.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async updateAgent(params: UpdateAgentParams) {
|
||||
const {
|
||||
agentId,
|
||||
name,
|
||||
type,
|
||||
enabled,
|
||||
avatar,
|
||||
providerId,
|
||||
modelId,
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
soul,
|
||||
skills,
|
||||
} = params
|
||||
|
||||
const agent = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: { user: { include: { teamMembers: true } } },
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('agent not found')
|
||||
|
||||
if (type === 'embedding' || type === 'autofill') {
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type,
|
||||
id: { not: agentId },
|
||||
teamId: agent.teamId,
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
throw new Error(`Agent of type ${type} already exists for this team`)
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'chat' || type === 'autofill') {
|
||||
if (!providerId || !modelId) {
|
||||
throw new Error('providerId and modelId are required for chat/autofill agents')
|
||||
}
|
||||
const model = await this.prismaClient.model.findUnique({
|
||||
where: { id: modelId },
|
||||
})
|
||||
if (!model) throw new Error('model not found')
|
||||
if (model.providerId !== providerId) {
|
||||
throw new Error('model does not belong to provider')
|
||||
}
|
||||
}
|
||||
|
||||
const agentConfig: PrismaJson.AgentConfig = {
|
||||
provider: providerId || '',
|
||||
model: modelId || '',
|
||||
thinkingLevel,
|
||||
systemPrompt,
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
name,
|
||||
image: avatar,
|
||||
},
|
||||
})
|
||||
|
||||
// Update skills: easier to delete all and recreate
|
||||
await tx.agentSkill.deleteMany({
|
||||
where: { agentId },
|
||||
})
|
||||
|
||||
return tx.agent.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
type,
|
||||
enabled: enabled ?? true,
|
||||
providerId: providerId || null,
|
||||
modelId: modelId || null,
|
||||
soul,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: agentConfig as any,
|
||||
skills: {
|
||||
create:
|
||||
skills?.map((skillId) => ({
|
||||
skillId,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
include: { user: true, skills: { include: { skill: true } } },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async deleteAgent(params: DeleteAgentParams) {
|
||||
const { agentId } = params
|
||||
|
||||
const agent = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('agent not found')
|
||||
|
||||
// Deleting user will cascade to agent and teamMember due to schema definition
|
||||
await this.prismaClient.user.delete({
|
||||
where: { id: agentId },
|
||||
})
|
||||
}
|
||||
|
||||
async listAgents(params: ListAgentsParams) {
|
||||
return this.prismaClient.agent.findMany({
|
||||
where: {
|
||||
teamId: params.teamId,
|
||||
},
|
||||
orderBy: {
|
||||
id: 'desc',
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
skills: {
|
||||
include: {
|
||||
skill: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async getSessionEntries(params: { sessionId: string }) {
|
||||
return this.prismaClient.agentSessionEntry.findMany({
|
||||
where: { sessionId: params.sessionId },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const agentService = new AgentService()
|
||||
Reference in New Issue
Block a user