import { Body, Controller, Delete, ForbiddenException, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Patch, Post, UseGuards, } from '@nestjs/common'; import type { Brain } from '@mosaic/brain'; import { BRAIN } from '../brain/brain.tokens.js'; import { AuthGuard } from '../auth/auth.guard.js'; import { CurrentUser } from '../auth/current-user.decorator.js'; import { CreateAgentConfigDto, UpdateAgentConfigDto } from './agent-config.dto.js'; @Controller('api/agents') @UseGuards(AuthGuard) export class AgentConfigsController { constructor(@Inject(BRAIN) private readonly brain: Brain) {} @Get() async list(@CurrentUser() user: { id: string; role?: string }) { return this.brain.agents.findAccessible(user.id); } @Get(':id') async findOne(@Param('id') id: string, @CurrentUser() user: { id: string }) { const agent = await this.brain.agents.findById(id); if (!agent) throw new NotFoundException('Agent not found'); if (!agent.isSystem && agent.ownerId !== user.id) { throw new ForbiddenException('Agent does not belong to the current user'); } return agent; } @Post() async create(@Body() dto: CreateAgentConfigDto, @CurrentUser() user: { id: string }) { return this.brain.agents.create({ ...dto, ownerId: user.id, isSystem: false, }); } @Patch(':id') async update( @Param('id') id: string, @Body() dto: UpdateAgentConfigDto, @CurrentUser() user: { id: string; role?: string }, ) { const agent = await this.brain.agents.findById(id); if (!agent) throw new NotFoundException('Agent not found'); if (agent.isSystem && user.role !== 'admin') { throw new ForbiddenException('Only admins can update system agents'); } if (!agent.isSystem && agent.ownerId !== user.id) { throw new ForbiddenException('Agent does not belong to the current user'); } const updated = await this.brain.agents.update(id, dto); if (!updated) throw new NotFoundException('Agent not found'); return updated; } @Delete(':id') @HttpCode(HttpStatus.NO_CONTENT) async remove(@Param('id') id: string, @CurrentUser() user: { id: string; role?: string }) { const agent = await this.brain.agents.findById(id); if (!agent) throw new NotFoundException('Agent not found'); if (agent.isSystem) { throw new ForbiddenException('Cannot delete system agents'); } if (agent.ownerId !== user.id) { throw new ForbiddenException('Agent does not belong to the current user'); } const deleted = await this.brain.agents.remove(id); if (!deleted) throw new NotFoundException('Agent not found'); } }