using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using System.Security.Claims; using Nexus.Api.DTOs; 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, IAgentConfigService agentConfigService, IDashboardService dashboardService, 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); var activity = items .Select(x => new AgentActivityResponse(x.Id, x.Type, x.Message, x.CreatedAt, "activity")) .ToList(); var gatewayEntries = await dashboardService.GetAgentActivityAsync(id, 10); foreach (var entry in gatewayEntries) activity.Add(new AgentActivityResponse(null, "thinking", entry.Text, entry.Timestamp, entry.Source, entry.Time)); return Results.Ok(activity .OrderByDescending(x => x.At) .Take(50)); } [HttpGet("{id}/summary")] public async Task GetAgentSummary(string id, CancellationToken ct) { var recent = await activityRepo.GetByAgentAsync(id, 25, ct); var gatewayEntries = await dashboardService.GetAgentActivityAsync(id, 8); return Results.Ok(AgentSummaryBuilder.Build(recent, gatewayEntries, DateTimeOffset.UtcNow)); } [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 Data.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); } } // ── Config Editor ── [HttpGet("{id}/config")] public IResult GetConfig(string id) => Results.Ok(agentConfigService.GetConfigFiles(id)); [HttpGet("{id}/config/{fileName}")] public async Task GetConfigFile(string id, string fileName, CancellationToken ct) { var file = await agentConfigService.GetConfigFileAsync(id, fileName, ct); return file is null ? Results.NotFound() : Results.Ok(new { file.FileName, file.Content, file.Size, file.ModifiedAt }); } [HttpPut("{id}/config/{fileName}")] [Authorize(Roles = "owner")] public async Task SaveConfigFile(string id, string fileName, [FromBody] SaveConfigRequest request, CancellationToken ct) { if (request.Content is null) return Results.BadRequest(new { error = "Content is required." }); try { var attempt = await agentConfigService.SaveConfigFileAsync(id, fileName, request.Content, ct); var caller = DescribeCaller(HttpContext.User); if (attempt.Failure is not null) { await activityRepo.AddAsync(new Data.ActivityEvent { Type = "config_audit", Message = $"Config save rejected agent={id} file={fileName} caller={caller} validation={attempt.Failure.Validation.Status} backup={attempt.Failure.Backup.Status} reload={attempt.Failure.ReloadCheck.Status} code={attempt.Failure.Code}", }, ct); return Results.ValidationProblem(new Dictionary { ["content"] = attempt.Failure.Validation.Errors.ToArray() }); } var result = attempt.SaveResult!; await activityRepo.AddAsync(new Data.ActivityEvent { Type = "config_audit", Message = $"Config save agent={id} file={fileName} caller={caller} validation={result.Validation.Status} backup={result.Backup.Status} reload={result.ReloadCheck.Status}", }, ct); return Results.Ok(new { result.FileName, result.Size, result.ModifiedAt, result.Validation, result.Backup, ReloadCheck = result.ReloadCheck }); } catch (UnauthorizedAccessException ex) { logger.LogError(ex, "Permission denied saving config file {FileName} for agent {AgentId}", fileName, id); return Results.Problem( title: "Permission denied", detail: $"Cannot write config file '{fileName}' for agent '{id}'. The target path may be owned by a different user.", statusCode: StatusCodes.Status500InternalServerError); } catch (IOException ex) { logger.LogError(ex, "I/O error saving config file {FileName} for agent {AgentId}", fileName, id); return Results.Problem( title: "File write error", detail: $"Failed to write config file '{fileName}' for agent '{id}': {ex.Message}", statusCode: StatusCodes.Status500InternalServerError); } } private static string DescribeCaller(ClaimsPrincipal user) { var subject = user.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? user.FindFirst(ClaimTypes.Email)?.Value ?? user.Identity?.Name ?? "unknown"; var role = user.FindFirst(ClaimTypes.Role)?.Value ?? "owner"; return $"{role}:{subject}".ToLowerInvariant(); } } public sealed record AgentActivityResponse( long? Id, string Type, string Message, DateTimeOffset At, string Source, string? RelativeTime = null ); public sealed record AgentSummaryResponse( AgentSummaryItemResponse Now, AgentSummaryItemResponse Today, DateTimeOffset GeneratedAt ); public sealed record AgentSummaryItemResponse( string Text, string Source, DateTimeOffset? Timestamp ); public static class AgentSummaryBuilder { public static AgentSummaryResponse Build( IReadOnlyList activity, IReadOnlyList gatewayEntries, DateTimeOffset nowUtc) { var points = activity .Select(entry => new SummaryPoint(entry.Message, entry.CreatedAt, "nexus-activity")) .Concat(gatewayEntries.Select(entry => new SummaryPoint(entry.Text, entry.Timestamp, entry.Source))) .Select(point => point with { Text = AgentActivityText.RedactForDisplay(point.Text) }) .Where(point => !string.IsNullOrWhiteSpace(point.Text)) .OrderByDescending(point => point.Timestamp) .ToList(); var current = points.FirstOrDefault(); var now = current is null ? new AgentSummaryItemResponse("Keine aktuelle Aktivitaet.", "none", null) : new AgentSummaryItemResponse(current.Text, current.Source, current.Timestamp); var windowStart = nowUtc.AddHours(-24); var todayPoints = points .Where(point => point.Timestamp >= windowStart) .ToList(); AgentSummaryItemResponse today; if (todayPoints.Count == 0) { today = new AgentSummaryItemResponse("Heute keine verwertbaren Checkpoints.", "none", null); } else { var snippets = todayPoints .Select(point => point.Text) .Distinct(StringComparer.OrdinalIgnoreCase) .Take(3) .ToList(); var extraCount = Math.Max(0, todayPoints.Count - snippets.Count); var text = $"Letzte 24h: {string.Join(" | ", snippets)}"; if (extraCount > 0) text += $" (+{extraCount} weitere)"; var source = todayPoints.Select(point => point.Source).Distinct(StringComparer.OrdinalIgnoreCase).Count() == 1 ? todayPoints[0].Source : "derived-mixed"; today = new AgentSummaryItemResponse(text, source, todayPoints[0].Timestamp); } return new AgentSummaryResponse(now, today, nowUtc); } private sealed record SummaryPoint(string Text, DateTimeOffset Timestamp, string Source); }