| 1 | using AgentForge.Plugin.Sdk; |
| 2 | using AgentForge.Contracts; |
| 3 | using AgentForge.Data; |
| 4 | using AgentForge.Models; |
| 5 | using AgentForge.Services; |
| 6 | |
| 7 | namespace AgentForge.Endpoints; |
| 8 | |
| 9 | internal static class ForgeAdminEndpoints |
| 10 | { |
| 11 | internal static RouteGroupBuilder MapAdminEndpoints(this RouteGroupBuilder api) |
| 12 | { |
| 13 | api.MapPost("/admin/tokens", CreateApiToken); |
| 14 | api.MapGet("/admin/plugins/status", GetPluginStatus); |
| 15 | api.MapPost("/admin/plugins/reload", ReloadPlugins); |
| 16 | return api; |
| 17 | } |
| 18 | |
| 19 | private static IResult CreateApiToken( |
| 20 | CreateApiTokenRequest request, |
| 21 | HttpContext context, |
| 22 | ForgeAuthService auth, |
| 23 | ForgeRepoAccessService access) |
| 24 | { |
| 25 | access.EnsureHostAdmin(access.Resolve(context)); |
| 26 | |
| 27 | var (entity, plain) = auth.CreateToken(request.Name, request.Scopes); |
| 28 | return Results.Created( |
| 29 | $"/api/v1/admin/tokens/{entity.Id}", |
| 30 | new ApiTokenResponse( |
| 31 | entity.Id, |
| 32 | entity.Name, |
| 33 | plain, |
| 34 | entity.Scopes.ToStorage(), |
| 35 | entity.CreatedAt)); |
| 36 | } |
| 37 | |
| 38 | private static IResult GetPluginStatus( |
| 39 | HttpContext context, |
| 40 | ForgeRepoAccessService access, |
| 41 | ForgePluginReloadService reload) |
| 42 | { |
| 43 | access.EnsureHostAdminRead(access.Resolve(context)); |
| 44 | return Results.Ok(reload.GetStatus()); |
| 45 | } |
| 46 | |
| 47 | private static async Task<IResult> ReloadPlugins( |
| 48 | HttpContext context, |
| 49 | ForgeRepoAccessService access, |
| 50 | ForgePluginReloadService reload, |
| 51 | string? mode, |
| 52 | CancellationToken cancellationToken) |
| 53 | { |
| 54 | access.EnsureHostAdmin(access.Resolve(context)); |
| 55 | var response = await reload.ReloadAsync(mode, cancellationToken).ConfigureAwait(false); |
| 56 | if (response.RestartScheduled) |
| 57 | { |
| 58 | context.Response.Headers.RetryAfter = "3"; |
| 59 | return Results.Json(response, statusCode: StatusCodes.Status202Accepted); |
| 60 | } |
| 61 | |
| 62 | return Results.Ok(response); |
| 63 | } |
| 64 | } |
| 65 | |