Merge pull request #457 from iceljc/features/add-agent-user-role

Features/add agent user role
This commit is contained in:
C. Oceania 2024-05-28 20:55:25 -05:00 committed by GitHub
commit 5acc6c89e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 188 additions and 56 deletions

View file

@ -48,5 +48,7 @@ public interface IAgentService
string GetDataDir();
string GetAgentDataDir(string agentId);
List<Agent> GetAgentsByUser(string userId);
PluginDef GetPlugin(string agentId);
}

View file

@ -19,6 +19,9 @@ public class PluginMenuDef
[JsonIgnore]
public int Weight { get; set; }
[JsonIgnore]
public List<string>? Roles { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<PluginMenuDef>? SubMenu { get; set; }

View file

@ -1,6 +1,7 @@
using BotSharp.Abstraction.MLTasks;
using BotSharp.Abstraction.Plugins.Models;
using BotSharp.Abstraction.Settings;
using BotSharp.Abstraction.Users.Enums;
using Microsoft.Extensions.Configuration;
namespace BotSharp.Core.Agents;
@ -43,8 +44,8 @@ public class AgentPlugin : IBotSharpPlugin
{
SubMenu = new List<PluginMenuDef>
{
new PluginMenuDef("Routing", link: "page/agent/router"), // icon: "bx bx-map-pin"
new PluginMenuDef("Evaluating", link: "page/agent/evaluator"), // icon: "bx bx-task"
new PluginMenuDef("Routing", link: "page/agent/router") { Roles = new List<string> { UserRole.Admin } }, // icon: "bx bx-map-pin"
new PluginMenuDef("Evaluating", link: "page/agent/evaluator") { Roles = new List<string> { UserRole.Admin } }, // icon: "bx bx-task"
new PluginMenuDef("Agents", link: "page/agent"), // icon: "bx bx-bot"
}
});

View file

@ -1,8 +1,4 @@
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Functions.Models;
using BotSharp.Abstraction.Repositories;
using BotSharp.Abstraction.Tasks.Models;
using BotSharp.Abstraction.Users.Models;
using System.IO;
using System.Text.RegularExpressions;
@ -26,32 +22,13 @@ public partial class AgentService
var dbSettings = _services.GetRequiredService<BotSharpDatabaseSettings>();
var agentSettings = _services.GetRequiredService<AgentSettings>();
var filePath = Path.Combine(dbSettings.FileRepository, agentSettings.DataDir);
var foundAgent = FetchAgentFileByName(agent.Name, filePath);
if (foundAgent != null)
{
agentRecord.SetId(foundAgent.Id)
.SetName(foundAgent.Name)
.SetDescription(foundAgent.Description)
.SetIsPublic(foundAgent.IsPublic)
.SetDisabled(foundAgent.Disabled)
.SetAgentType(foundAgent.Type)
.SetProfiles(foundAgent.Profiles)
.SetRoutingRules(foundAgent.RoutingRules)
.SetInstruction(foundAgent.Instruction)
.SetTemplates(foundAgent.Templates)
.SetFunctions(foundAgent.Functions)
.SetResponses(foundAgent.Responses)
.SetLlmConfig(foundAgent.LlmConfig);
}
var user = _db.GetUserById(_user.Id);
var userAgentRecord = new UserAgent
{
Id = Guid.NewGuid().ToString(),
UserId = user.Id,
AgentId = foundAgent?.Id ?? agentRecord.Id,
AgentId = agentRecord.Id,
Editable = false,
CreatedTime = DateTime.UtcNow,
UpdatedTime = DateTime.UtcNow
@ -65,7 +42,7 @@ public partial class AgentService
Utilities.ClearCache();
return agentRecord;
return await Task.FromResult(agentRecord);
}
private Agent FetchAgentFileByName(string agentName, string filePath)

View file

@ -1,9 +1,20 @@
using BotSharp.Abstraction.Users.Enums;
namespace BotSharp.Core.Agents.Services;
public partial class AgentService
{
public async Task<bool> DeleteAgent(string id)
{
throw new NotImplementedException();
var user = _db.GetUserById(_user.Id);
var agent = _db.GetAgentsByUser(_user.Id).FirstOrDefault(x => x.Id.IsEqualTo(id));
if (user?.Role != UserRole.Admin && agent == null)
{
return false;
}
var deleted = _db.DeleteAgent(id);
return await Task.FromResult(deleted);
}
}

View file

@ -1,5 +1,6 @@
using BotSharp.Abstraction.Repositories.Enums;
using BotSharp.Abstraction.Routing.Models;
using BotSharp.Abstraction.Users.Enums;
using System.IO;
namespace BotSharp.Core.Agents.Services;
@ -8,6 +9,10 @@ public partial class AgentService
{
public async Task UpdateAgent(Agent agent, AgentField updateField)
{
var userService = _services.GetRequiredService<IUserService>();
var user = await userService.GetUser(_user.Id);
if (user?.Role != UserRole.Admin) return;
if (agent == null || string.IsNullOrEmpty(agent.Id)) return;
var record = _db.GetAgent(agent.Id);

View file

@ -47,4 +47,10 @@ public partial class AgentService : IAgentService
}
return dir;
}
public List<Agent> GetAgentsByUser(string userId)
{
var agents = _db.GetAgentsByUser(userId);
return agents;
}
}

View file

@ -269,4 +269,20 @@ public class PluginLoader
}
});
}
public List<PluginMenuDef> GetPluginMenuByRoles(List<PluginMenuDef> plugins, string userRole)
{
if (plugins.IsNullOrEmpty()) return plugins;
var filtered = new List<PluginMenuDef>();
foreach (var plugin in plugins)
{
if (plugin.Roles.IsNullOrEmpty() || plugin.Roles.Contains(userRole))
{
plugin.SubMenu = GetPluginMenuByRoles(plugin.SubMenu, userRole);
filtered.Add(plugin);
}
}
return filtered;
}
}

View file

@ -436,7 +436,40 @@ namespace BotSharp.Core.Repository
public bool DeleteAgent(string agentId)
{
return false;
if (string.IsNullOrEmpty(agentId)) return false;
try
{
var agentDir = GetAgentDataDir(agentId);
if (string.IsNullOrEmpty(agentDir)) return false;
// Delete agent user relationships
var usersDir = Path.Combine(_dbSettings.FileRepository, "users");
if (Directory.Exists(usersDir))
{
foreach (var userDir in Directory.GetDirectories(usersDir))
{
var userAgentFile = Directory.GetFiles(userDir).FirstOrDefault(x => Path.GetFileName(x) == USER_AGENT_FILE);
if (string.IsNullOrEmpty(userAgentFile)) continue;
var text = File.ReadAllText(userAgentFile);
var userAgents = JsonSerializer.Deserialize<List<UserAgent>>(text, _options);
if (userAgents.IsNullOrEmpty()) continue;
userAgents = userAgents.Where(x => x.AgentId != agentId).ToList();
File.WriteAllText(userAgentFile, JsonSerializer.Serialize(userAgents, _options));
}
}
// Delete agent folder
Directory.Delete(agentDir, true);
return true;
}
catch
{
return false;
}
}
}
}

View file

@ -1,3 +1,4 @@
using BotSharp.Abstraction.Users.Enums;
using BotSharp.Abstraction.Users.Models;
using System.IO;

View file

@ -1,5 +1,6 @@
using BotSharp.Abstraction.Plugins.Models;
using BotSharp.Abstraction.Tasks;
using BotSharp.Abstraction.Users.Enums;
using BotSharp.Core.Tasks.Services;
using Microsoft.Extensions.Configuration;
@ -19,7 +20,10 @@ public class TaskPlugin : IBotSharpPlugin
public bool AttachMenu(List<PluginMenuDef> menu)
{
var section = menu.First(x => x.Label == "Apps");
menu.Add(new PluginMenuDef("Task", link: "page/task", icon: "bx bx-task", weight: section.Weight + 8));
menu.Add(new PluginMenuDef("Task", link: "page/task", icon: "bx bx-task", weight: section.Weight + 8)
{
Roles = new List<string> { UserRole.Admin }
});
return true;
}

View file

@ -1,4 +1,5 @@
using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Users.Enums;
namespace BotSharp.OpenAPI.Controllers;
@ -7,11 +8,13 @@ namespace BotSharp.OpenAPI.Controllers;
public class AgentController : ControllerBase
{
private readonly IAgentService _agentService;
private readonly IUserIdentity _user;
private readonly IServiceProvider _services;
public AgentController(IAgentService agentService, IServiceProvider services)
public AgentController(IAgentService agentService, IUserIdentity user, IServiceProvider services)
{
_agentService = agentService;
_user = user;
_services = services;
}
@ -23,7 +26,7 @@ public class AgentController : ControllerBase
}
[HttpGet("/agent/{id}")]
public async Task<AgentViewModel> GetAgent([FromRoute] string id)
public async Task<AgentViewModel?> GetAgent([FromRoute] string id)
{
var agents = await GetAgents(new AgentFilter
{
@ -31,6 +34,8 @@ public class AgentController : ControllerBase
});
var targetAgent = agents.Items.FirstOrDefault();
if (targetAgent == null) return null;
var redirectAgentIds = targetAgent.RoutingRules
.Where(x => !string.IsNullOrEmpty(x.RedirectTo))
.Select(x => x.RedirectTo).ToList();
@ -45,6 +50,17 @@ public class AgentController : ControllerBase
rule.RedirectToAgentName = found.Name;
}
var editable = true;
var userService = _services.GetRequiredService<IUserService>();
var user = await userService.GetUser(_user.Id);
if (user?.Role != UserRole.Admin)
{
var userAgents = _agentService.GetAgentsByUser(user?.Id);
editable = userAgents?.Select(x => x.Id)?.Contains(targetAgent.Id) ?? false;
}
targetAgent.Editable = editable;
return targetAgent;
}
@ -118,4 +134,10 @@ public class AgentController : ControllerBase
model.Id = agentId;
return await _agentService.PatchAgentTemplate(model);
}
[HttpDelete("/agent/{agentId}")]
public async Task<bool> DeleteAgent([FromRoute] string agentId)
{
return await _agentService.DeleteAgent(agentId);
}
}

View file

@ -1,5 +1,6 @@
using BotSharp.Abstraction.Options;
using BotSharp.Abstraction.Routing;
using BotSharp.Abstraction.Users.Enums;
namespace BotSharp.OpenAPI.Controllers;
@ -41,20 +42,23 @@ public class ConversationController : ControllerBase
[HttpPost("/conversations")]
public async Task<PagedItems<ConversationViewModel>> GetConversations([FromBody] ConversationFilter filter)
{
var service = _services.GetRequiredService<IConversationService>();
var conversations = await service.GetConversations(filter);
var convService = _services.GetRequiredService<IConversationService>();
var userService = _services.GetRequiredService<IUserService>();
var user = await userService.GetUser(_user.Id);
if (user == null)
{
return new PagedItems<ConversationViewModel>();
}
filter.UserId = user.Role != UserRole.Admin ? user.Id : null;
var conversations = await convService.GetConversations(filter);
var agentService = _services.GetRequiredService<IAgentService>();
var list = conversations.Items
.Select(x => ConversationViewModel.FromSession(x))
.ToList();
var list = conversations.Items.Select(x => ConversationViewModel.FromSession(x)).ToList();
foreach (var item in list)
{
var user = await userService.GetUser(item.User.Id);
user = await userService.GetUser(item.User.Id);
item.User = UserViewModel.FromUser(user);
var agent = await agentService.GetAgent(item.AgentId);
item.AgentName = agent?.Name;
}
@ -119,21 +123,30 @@ public class ConversationController : ControllerBase
}
[HttpGet("/conversation/{conversationId}")]
public async Task<ConversationViewModel> GetConversation([FromRoute] string conversationId)
public async Task<ConversationViewModel?> GetConversation([FromRoute] string conversationId)
{
var service = _services.GetRequiredService<IConversationService>();
var conversations = await service.GetConversations(new ConversationFilter
{
Id = conversationId
});
var userService = _services.GetRequiredService<IUserService>();
var result = ConversationViewModel.FromSession(conversations.Items.First());
var user = await userService.GetUser(_user.Id);
if (user == null)
{
return null;
}
var filter = new ConversationFilter
{
Id = conversationId,
UserId = user.Role != UserRole.Admin ? user.Id : null
};
var conversations = await service.GetConversations(filter);
if (conversations.Items.IsNullOrEmpty())
{
return null;
}
var result = ConversationViewModel.FromSession(conversations.Items.First());
var state = _services.GetRequiredService<IConversationStateService>();
result.States = state.Load(conversationId, isReadOnly: true);
var user = await userService.GetUser(result.User.Id);
result.User = UserViewModel.FromUser(user);
return result;
@ -178,7 +191,22 @@ public class ConversationController : ControllerBase
[HttpDelete("/conversation/{conversationId}")]
public async Task<bool> DeleteConversation([FromRoute] string conversationId)
{
var userService = _services.GetRequiredService<IUserService>();
var conversationService = _services.GetRequiredService<IConversationService>();
var user = await userService.GetUser(_user.Id);
var filter = new ConversationFilter
{
Id = conversationId,
UserId = user.Role != UserRole.Admin ? user.Id : null
};
var conversations = await conversationService.GetConversations(filter);
if (conversations.Items.IsNullOrEmpty())
{
return false;
}
var response = await conversationService.DeleteConversations(new List<string> { conversationId });
return response;
}

View file

@ -1,4 +1,5 @@
using BotSharp.Abstraction.Plugins.Models;
using BotSharp.Abstraction.Users.Enums;
using BotSharp.Core.Plugins;
namespace BotSharp.OpenAPI.Controllers;
@ -8,23 +9,32 @@ namespace BotSharp.OpenAPI.Controllers;
public class PluginController : ControllerBase
{
private readonly IServiceProvider _services;
private readonly IUserIdentity _user;
private readonly PluginSettings _settings;
public PluginController(IServiceProvider services, PluginSettings settings)
public PluginController(IServiceProvider services, IUserIdentity user, PluginSettings settings)
{
_services = services;
_user = user;
_settings = settings;
}
[HttpGet("/plugins")]
public PagedItems<PluginDef> GetPlugins([FromQuery] PluginFilter filter)
public async Task<PagedItems<PluginDef>> GetPlugins([FromQuery] PluginFilter filter)
{
var userService = _services.GetRequiredService<IUserService>();
var user = await userService.GetUser(_user.Id);
if (user?.Role != UserRole.Admin)
{
return new PagedItems<PluginDef>();
}
var loader = _services.GetRequiredService<PluginLoader>();
return loader.GetPagedPlugins(_services, filter);
}
[HttpGet("/plugin/menu")]
public List<PluginMenuDef> GetPluginMenu()
public async Task<List<PluginMenuDef>> GetPluginMenu()
{
var menu = new List<PluginMenuDef>
{
@ -33,11 +43,18 @@ public class PluginController : ControllerBase
IsHeader = true,
},
new PluginMenuDef("System", weight: 30)
{
IsHeader = true
{
IsHeader = true,
Roles = new List<string> { UserRole.Admin }
},
new PluginMenuDef("Plugins", link: "page/plugin", icon: "bx bx-plug", weight: 31),
new PluginMenuDef("Settings", link: "page/setting", icon: "bx bx-cog", weight: 32),
new PluginMenuDef("Plugins", link: "page/plugin", icon: "bx bx-plug", weight: 31)
{
Roles = new List<string> { UserRole.Admin }
},
new PluginMenuDef("Settings", link: "page/setting", icon: "bx bx-cog", weight: 32)
{
Roles = new List<string> { UserRole.Admin }
}
};
var loader = _services.GetRequiredService<PluginLoader>();
@ -49,6 +66,10 @@ public class PluginController : ControllerBase
}
plugin.Module.AttachMenu(menu);
}
var userService = _services.GetRequiredService<IUserService>();
var user = await userService.GetUser(_user.Id);
menu = loader.GetPluginMenuByRoles(menu, user?.Role);
menu = menu.OrderBy(x => x.Weight).ToList();
return menu;
}

View file

@ -42,6 +42,8 @@ public class AgentViewModel
public PluginDef Plugin { get; set; }
public bool Editable { get; set; }
[JsonPropertyName("created_datetime")]
public DateTime CreatedDateTime { get; set; }