using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Nexus.Api.Data; using Nexus.Api.DTOs; using Nexus.Api.Helpers; using Nexus.Api.Integrations; using Nexus.Api.Repositories; using Nexus.Api.Services; namespace Nexus.Api.Controllers; [ApiController] [Route("api/v1/agents")] public class AgentsController( IAgentService agentService, IAgentRuntime runtime, IActivityRepository activityRepo, ILogger logger) : ControllerBase { [HttpGet] public async Task GetAgents(CancellationToken ct) { var agents = await agentService.GetAgentsAsync(ct); return Results.Ok(agents.Select(a => new AgentListResponse( a.Id, a.Name, a.Role, a.Model, a.Status.ToString(), a.LastSeen, a.Workspace, a.Description ))); } [HttpGet("{id}")] public async Task GetAgent(string id, CancellationToken ct) { var agent = await agentService.GetAgentAsync(id, ct); if (agent is null) return Results.NotFound(); return Results.Ok(new AgentDetailResponse( agent.Id, agent.Name, agent.Role, agent.Model, agent.Status.ToString(), agent.LastSeen, agent.Workspace, agent.AgentDir, agent.Description, agent.SubAgents, agent.IdentityName )); } [HttpGet("{id}/activity")] public async Task GetAgentActivity(string id, CancellationToken ct) { var items = await activityRepo.GetByAgentAsync(id, 50, ct); return Results.Ok(items.Select(x => new { x.Id, x.Type, x.Message, at = x.CreatedAt })); } [HttpPost("{id}/command")] [EnableRateLimiting("agents")] public async Task SendCommand(string id, [FromBody] AgentCommandRequest request, CancellationToken ct) { var message = request.Message?.Trim(); if (string.IsNullOrWhiteSpace(message) || message.Length > 8000) return Results.ValidationProblem(new Dictionary { ["message"] = ["Message must contain between 1 and 8000 characters."] }); var conversationId = $"nexus-command-{id}-{Guid.NewGuid():N}"; try { var result = await runtime.ChatAsync(message, conversationId, id, ct); await activityRepo.AddAsync(new ActivityEvent { Type = "agent", Message = $"Command sent to agent {id}: {message[..Math.Min(message.Length, 80)]}" }, ct); return Results.Ok(new AgentCommandResponse(result.Runtime, result.AgentId, result.ConversationId, result.Content)); } catch (Exception exception) { logger.LogWarning(exception, "Agent command failed for {AgentId}", id); return Results.Problem( title: "Agent command failed", detail: $"Could not send command to agent {id}: {exception.Message}", statusCode: StatusCodes.Status503ServiceUnavailable); } } // ========== Agent Config Editor ========== [HttpGet("{id}/config")] public IResult GetConfig(string id) { var workspacePath = $"/mnt/workspace-{id}"; if (!Directory.Exists(workspacePath)) return Results.Ok(Array.Empty()); var allowedFiles = new HashSet(StringComparer.OrdinalIgnoreCase) { "IDENTITY.md", "SOUL.md", "AGENTS.md", "TOOLS.md", "HEARTBEAT.md", "USER.md", "MEMORY.md" }; var files = Directory.GetFiles(workspacePath, "*.md") .Select(f => new FileInfo(f)) .Where(f => allowedFiles.Contains(f.Name)) .OrderBy(f => f.Name) .Select(f => new { fileName = f.Name, size = f.Length, modifiedAt = f.LastWriteTimeUtc }) .ToList(); return Results.Ok(files); } [HttpGet("{id}/config/{fileName}")] public async Task GetConfigFile(string id, string fileName, CancellationToken ct) { if (!PathSecurityHelper.IsValidConfigFileName(fileName)) return Results.BadRequest(new { error = "Invalid filename. Only .md files with alphanumeric characters, dots, hyphens, and underscores are allowed." }); var workspacePath = $"/mnt/workspace-{id}"; if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath) || !System.IO.File.Exists(safePath)) return Results.NotFound(); var content = await System.IO.File.ReadAllTextAsync(safePath!, ct); var fi = new FileInfo(safePath!); return Results.Ok(new { fileName, content, size = fi.Length, modifiedAt = fi.LastWriteTimeUtc }); } [HttpPut("{id}/config/{fileName}")] public async Task SaveConfigFile(string id, string fileName, [FromBody] SaveConfigRequest request, CancellationToken ct) { if (!PathSecurityHelper.IsValidConfigFileName(fileName)) return Results.BadRequest(new { error = "Invalid filename. Only .md files with alphanumeric characters, dots, hyphens, and underscores are allowed." }); if (request.Content is null) return Results.BadRequest(new { error = "Content is required." }); if (request.Content.Length > 500 * 1024) return Results.BadRequest(new { error = "Content exceeds maximum size of 500KB." }); var workspacePath = $"/mnt/workspace-{id}"; if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath)) return Results.NotFound(); var tempPath = safePath + ".tmp"; try { await System.IO.File.WriteAllTextAsync(tempPath, request.Content, ct); System.IO.File.Move(tempPath, safePath, overwrite: true); } catch { if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); throw; } var fi = new FileInfo(safePath); return Results.Ok(new { fileName, size = fi.Length, modifiedAt = fi.LastWriteTimeUtc }); } }