From 82d2311018db23b29991abcb9b6257e075bc023b Mon Sep 17 00:00:00 2001
From: Jicheng Lu <103353@smsassist.com>
Date: Tue, 30 Sep 2025 17:28:35 -0500
Subject: [PATCH] complete db on code scripts
---
.../Agents/IAgentService.cs | 1 -
.../Agents/Models/AgentCodeScript.cs | 8 +-
.../Repositories/IBotSharpRepository.cs | 15 ++-
.../Services/AgentService.CreateAgent.cs | 24 ++++
.../Services/AgentService.RefreshAgents.cs | 7 +-
.../Services/AgentService.UpdateAgent.cs | 107 +---------------
.../FileRepository.AgentCode.cs | 107 +++++++++++++++-
.../FileRepository.AgentTask.cs | 25 ++--
.../Tasks/Services/AgentTaskService.cs | 2 +-
.../Controllers/AgentController.cs | 6 -
.../Collections/AgentCodeDocument.cs | 32 +++++
.../MongoDbContext.cs | 3 +
.../Repository/MongoRepository.Agent.cs | 7 +-
.../Repository/MongoRepository.AgentCode.cs | 116 ++++++++++++++++++
.../Repository/MongoRepository.AgentTask.cs | 42 +++----
15 files changed, 337 insertions(+), 165 deletions(-)
create mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Collections/AgentCodeDocument.cs
create mode 100644 src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCode.cs
diff --git a/src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs b/src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs
index c195df5e..a2f2a17f 100644
--- a/src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs
+++ b/src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs
@@ -59,7 +59,6 @@ public interface IAgentService
///
///
Task PatchAgentTemplate(Agent agent);
- Task UpdateAgentFromFile(string id);
string GetDataDir();
string GetAgentDataDir(string agentId);
diff --git a/src/Infrastructure/BotSharp.Abstraction/Agents/Models/AgentCodeScript.cs b/src/Infrastructure/BotSharp.Abstraction/Agents/Models/AgentCodeScript.cs
index ca328d13..9782f848 100644
--- a/src/Infrastructure/BotSharp.Abstraction/Agents/Models/AgentCodeScript.cs
+++ b/src/Infrastructure/BotSharp.Abstraction/Agents/Models/AgentCodeScript.cs
@@ -2,6 +2,8 @@ namespace BotSharp.Abstraction.Agents.Models;
public class AgentCodeScript
{
+ public string Id { get; set; }
+ public string AgentId { get; set; }
public string Name { get; set; }
public string Content { get; set; }
@@ -9,12 +11,6 @@ public class AgentCodeScript
{
}
- public AgentCodeScript(string name, string content)
- {
- Name = name;
- Content = content;
- }
-
public override string ToString()
{
return Name;
diff --git a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs
index 3da95e02..3d23352a 100644
--- a/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs
+++ b/src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs
@@ -98,21 +98,24 @@ public interface IBotSharpRepository : IHaveServiceProvider
=> throw new NotImplementedException();
void InsertAgentTask(AgentTask task)
=> throw new NotImplementedException();
- void BulkInsertAgentTasks(List tasks)
+ void BulkInsertAgentTasks(string agentId, List tasks)
=> throw new NotImplementedException();
void UpdateAgentTask(AgentTask task, AgentTaskField field)
=> throw new NotImplementedException();
- bool DeleteAgentTask(string agentId, List taskIds)
- => throw new NotImplementedException();
- bool DeleteAgentTasks()
+ bool DeleteAgentTasks(string agentId, List? taskIds = null)
=> throw new NotImplementedException();
#endregion
#region Agent Code
+ List GetAgentCodeScripts(string agentId, List? scriptNames = null)
+ => throw new NotImplementedException();
string? GetAgentCodeScript(string agentId, string scriptName)
=> throw new NotImplementedException();
-
- bool PatchAgentCodeScript(string agentId, AgentCodeScript script)
+ bool UpdateAgentCodeScript(string agentId, AgentCodeScript script)
+ => throw new NotImplementedException();
+ bool BulkInsertAgentCodeScripts(string agentId, List scripts)
+ => throw new NotImplementedException();
+ bool DeleteAgentCodeScripts(string agentId, List? scriptNames)
=> throw new NotImplementedException();
#endregion
diff --git a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.CreateAgent.cs b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.CreateAgent.cs
index fb4d49c4..95b8e27f 100644
--- a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.CreateAgent.cs
+++ b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.CreateAgent.cs
@@ -218,4 +218,28 @@ public partial class AgentService
task.Content = content.Substring(suffix.Length).Trim();
return task;
}
+
+ private List GetCodeScriptsFromFile(string fileDir)
+ {
+ var scripts = new List();
+ var codeDir = Path.Combine(fileDir, "codes");
+ if (!Directory.Exists(codeDir))
+ {
+ return scripts;
+ }
+
+ var agentId = fileDir.Split(Path.DirectorySeparatorChar).Last();
+ foreach (var file in Directory.GetFiles(codeDir))
+ {
+ var script = new AgentCodeScript
+ {
+ AgentId = agentId,
+ Name = Path.GetFileName(file),
+ Content = File.ReadAllText(file)
+ };
+ scripts.Add(script);
+ }
+
+ return scripts;
+ }
}
diff --git a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.RefreshAgents.cs b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.RefreshAgents.cs
index 506e00bb..cc38a151 100644
--- a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.RefreshAgents.cs
+++ b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.RefreshAgents.cs
@@ -60,13 +60,16 @@ public partial class AgentService
.SetSamples(samples);
var tasks = GetTasksFromFile(dir);
+ var codeScripts = GetCodeScriptsFromFile(dir);
var isAgentDeleted = _db.DeleteAgent(agent.Id);
if (isAgentDeleted)
{
await Task.Delay(100);
- _db.BulkInsertAgents(new List { agent });
- _db.BulkInsertAgentTasks(tasks);
+ _db.BulkInsertAgents([agent]);
+ _db.BulkInsertAgentTasks(agent.Id, tasks);
+ _db.BulkInsertAgentCodeScripts(agent.Id, codeScripts);
+
refreshedAgents.Add(agent.Name);
_logger.LogInformation($"Agent {agent.Name} has been migrated.");
}
diff --git a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.UpdateAgent.cs b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.UpdateAgent.cs
index d99b39d9..4a2e1ec5 100644
--- a/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.UpdateAgent.cs
+++ b/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.UpdateAgent.cs
@@ -1,8 +1,5 @@
-using BotSharp.Abstraction.Repositories.Enums;
-using BotSharp.Abstraction.Repositories.Settings;
using BotSharp.Abstraction.Users.Enums;
using BotSharp.Abstraction.Users.Models;
-using System.IO;
namespace BotSharp.Core.Agents.Services;
@@ -13,7 +10,7 @@ public partial class AgentService
if (agent == null || string.IsNullOrEmpty(agent.Id)) return;
var userService = _services.GetRequiredService();
- var auth = await userService.GetUserAuthorizations(new List { agent.Id });
+ var auth = await userService.GetUserAuthorizations([agent.Id]);
var allowEdit = auth.IsAgentActionAllowed(agent.Id, UserAction.Edit);
if (!allowEdit)
@@ -57,81 +54,6 @@ public partial class AgentService
await Task.CompletedTask;
}
- public async Task UpdateAgentFromFile(string id)
- {
- string updateResult;
- var dbSettings = _services.GetRequiredService();
- var agentSettings = _services.GetRequiredService();
-
- if (dbSettings.Default == RepositoryEnum.FileRepository)
- {
- updateResult = $"Invalid database repository setting: {dbSettings.Default}";
- _logger.LogWarning(updateResult);
- return updateResult;
- }
-
- var agent = _db.GetAgent(id);
- if (agent == null)
- {
- updateResult = $"Cannot find agent ${id}";
- _logger.LogError(updateResult);
- return updateResult;
- }
-
- var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
- dbSettings.FileRepository,
- agentSettings.DataDir);
-
- var clonedAgent = Agent.Clone(agent);
- var foundAgent = GetAgentFileById(agent.Id, filePath);
- if (foundAgent == null)
- {
- updateResult = $"Cannot find agent {agent.Name} in file directory: {filePath}";
- _logger.LogError(updateResult);
- return updateResult;
- }
-
- try
- {
- clonedAgent.SetId(foundAgent.Id)
- .SetName(foundAgent.Name)
- .SetType(foundAgent.Type)
- .SetRoutingMode(foundAgent.Mode)
- .SetFuncVisMode(foundAgent.FuncVisMode)
- .SetIsPublic(foundAgent.IsPublic)
- .SetDisabled(foundAgent.Disabled)
- .SetDescription(foundAgent.Description)
- .SetMergeUtility(foundAgent.MergeUtility)
- .SetProfiles(foundAgent.Profiles)
- .SetLabels(foundAgent.Labels)
- .SetRoutingRules(foundAgent.RoutingRules)
- .SetInstruction(foundAgent.Instruction)
- .SetChannelInstructions(foundAgent.ChannelInstructions)
- .SetTemplates(foundAgent.Templates)
- .SetFunctions(foundAgent.Functions)
- .SetResponses(foundAgent.Responses)
- .SetSamples(foundAgent.Samples)
- .SetUtilities(foundAgent.Utilities)
- .SetMcpTools(foundAgent.McpTools)
- .SetKnowledgeBases(foundAgent.KnowledgeBases)
- .SetRules(foundAgent.Rules)
- .SetLlmConfig(foundAgent.LlmConfig);
-
- _db.UpdateAgent(clonedAgent, AgentField.All);
- Utilities.ClearCache();
-
- updateResult = $"Agent {agent.Name} has been migrated!";
- _logger.LogInformation(updateResult);
- return updateResult;
- }
- catch (Exception ex)
- {
- updateResult = $"Failed to migrate agent {agent.Name} in file directory {filePath}.\r\nError: {ex.Message}";
- _logger.LogError(updateResult);
- return updateResult;
- }
- }
-
public async Task PatchAgentTemplate(Agent agent)
{
@@ -184,31 +106,4 @@ public partial class AgentService
return patchResult;
}
-
- private Agent? GetAgentFileById(string agentId, string filePath)
- {
- if (!Directory.Exists(filePath)) return null;
-
- foreach (var dir in Directory.GetDirectories(filePath))
- {
- var agentJson = File.ReadAllText(Path.Combine(dir, "agent.json"));
- var agent = JsonSerializer.Deserialize(agentJson, _options);
- if (agent != null && agent.Id == agentId)
- {
- var (defaultInstruction, channelInstructions) = GetInstructionsFromFile(dir);
- var functions = GetFunctionsFromFile(dir);
- var responses = GetResponsesFromFile(dir);
- var templates = GetTemplatesFromFile(dir);
- var samples = GetSamplesFromFile(dir);
- return agent.SetInstruction(defaultInstruction)
- .SetChannelInstructions(channelInstructions)
- .SetTemplates(templates)
- .SetFunctions(functions)
- .SetResponses(responses)
- .SetSamples(samples);
- }
- }
-
- return null;
- }
}
diff --git a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCode.cs b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCode.cs
index a60d8146..69934174 100644
--- a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCode.cs
+++ b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCode.cs
@@ -5,6 +5,39 @@ namespace BotSharp.Core.Repository;
public partial class FileRepository
{
#region Code
+ public List GetAgentCodeScripts(string agentId, List? scriptNames = null)
+ {
+ if (string.IsNullOrWhiteSpace(agentId))
+ {
+ return [];
+ }
+
+ var dir = BuildAgentCodeDir(agentId);
+ if (!Directory.Exists(dir))
+ {
+ return [];
+ }
+
+ var results = new List();
+ foreach (var file in Directory.GetFiles(dir))
+ {
+ var fileName = Path.GetFileName(file);
+ if (scriptNames != null || !scriptNames.Contains(fileName))
+ {
+ continue;
+ }
+
+ var script = new AgentCodeScript
+ {
+ AgentId = agentId,
+ Name = fileName,
+ Content = File.ReadAllText(file)
+ };
+ results.Add(script);
+ }
+ return results;
+ }
+
public string? GetAgentCodeScript(string agentId, string scriptName)
{
if (string.IsNullOrWhiteSpace(agentId)
@@ -13,7 +46,7 @@ public partial class FileRepository
return null;
}
- var dir = Path.Combine(_dbSettings.FileRepository, _agentSettings.DataDir, agentId, AGENT_CODES_FOLDER);
+ var dir = BuildAgentCodeDir(agentId);
if (!Directory.Exists(dir))
{
return null;
@@ -30,14 +63,14 @@ public partial class FileRepository
return string.Empty;
}
- public bool PatchAgentCodeScript(string agentId, AgentCodeScript script)
+ public bool UpdateAgentCodeScript(string agentId, AgentCodeScript script)
{
- if (string.IsNullOrEmpty(agentId) || script == null)
+ if (string.IsNullOrWhiteSpace(agentId) || script == null)
{
return false;
}
- var dir = Path.Combine(_dbSettings.FileRepository, _agentSettings.DataDir, agentId, AGENT_CODES_FOLDER);
+ var dir = BuildAgentCodeDir(agentId);
if (!Directory.Exists(dir))
{
return false;
@@ -57,5 +90,71 @@ public partial class FileRepository
File.WriteAllText(found, script.Content);
return true;
}
+
+ public bool BulkInsertAgentCodeScripts(string agentId, List scripts)
+ {
+ if (string.IsNullOrWhiteSpace(agentId) || scripts.IsNullOrEmpty())
+ {
+ return false;
+ }
+
+ var dir = BuildAgentCodeDir(agentId);
+ if (!Directory.Exists(dir))
+ {
+ return false;
+ }
+
+ foreach (var script in scripts)
+ {
+ if (string.IsNullOrWhiteSpace(script.Name))
+ {
+ continue;
+ }
+
+ var path = Path.Combine(dir, script.Name);
+ File.WriteAllText(path, script.Content);
+ }
+
+ return true;
+ }
+
+ public bool DeleteAgentCodeScripts(string agentId, List? scriptNames)
+ {
+ if (string.IsNullOrWhiteSpace(agentId))
+ {
+ return false;
+ }
+
+ var dir = BuildAgentCodeDir(agentId);
+ if (!Directory.Exists(dir))
+ {
+ return false;
+ }
+
+ if (scriptNames == null)
+ {
+ Directory.Delete(dir, true);
+ return true;
+ }
+ else if (!scriptNames.Any())
+ {
+ return false;
+ }
+
+ foreach (var file in Directory.GetFiles(dir))
+ {
+ var fileName = Path.GetFileName(file);
+ if (scriptNames.Contains(fileName))
+ {
+ File.Delete(file);
+ }
+ }
+ return true;
+ }
#endregion
+
+ private string BuildAgentCodeDir(string agentId)
+ {
+ return Path.Combine(_dbSettings.FileRepository, _agentSettings.DataDir, agentId, AGENT_CODES_FOLDER);
+ }
}
diff --git a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentTask.cs b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentTask.cs
index 2b84f212..b3926e66 100644
--- a/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentTask.cs
+++ b/src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentTask.cs
@@ -137,7 +137,7 @@ public partial class FileRepository
File.WriteAllText(taskFile, fileContent);
}
- public void BulkInsertAgentTasks(List tasks)
+ public void BulkInsertAgentTasks(string agentId, List tasks)
{
}
@@ -194,13 +194,25 @@ public partial class FileRepository
File.WriteAllText(taskFile, fileContent);
}
- public bool DeleteAgentTask(string agentId, List taskIds)
+ public bool DeleteAgentTasks(string agentId, List? taskIds = null)
{
var agentDir = Path.Combine(_dbSettings.FileRepository, _agentSettings.DataDir, agentId);
- if (!Directory.Exists(agentDir) || taskIds.IsNullOrEmpty()) return false;
+ if (!Directory.Exists(agentDir))
+ {
+ return false;
+ }
var taskDir = Path.Combine(agentDir, AGENT_TASKS_FOLDER);
- if (!Directory.Exists(taskDir)) return false;
+ if (!Directory.Exists(taskDir))
+ {
+ return false;
+ }
+
+ if (taskIds == null)
+ {
+ Directory.Delete(taskDir, true);
+ return true;
+ }
var deletedTasks = new List();
foreach (var taskId in taskIds)
@@ -215,11 +227,6 @@ public partial class FileRepository
return deletedTasks.Any();
}
- public bool DeleteAgentTasks()
- {
- return false;
- }
-
private string? FindTaskFileById(string taskDir, string taskId)
{
if (!Directory.Exists(taskDir) || string.IsNullOrEmpty(taskId)) return null;
diff --git a/src/Infrastructure/BotSharp.Core/Tasks/Services/AgentTaskService.cs b/src/Infrastructure/BotSharp.Core/Tasks/Services/AgentTaskService.cs
index 5ae52a73..c6ac878d 100644
--- a/src/Infrastructure/BotSharp.Core/Tasks/Services/AgentTaskService.cs
+++ b/src/Infrastructure/BotSharp.Core/Tasks/Services/AgentTaskService.cs
@@ -91,7 +91,7 @@ public class AgentTaskService : IAgentTaskService
public async Task DeleteTask(string agentId, string taskId)
{
var db = _services.GetRequiredService();
- var isDeleted = db.DeleteAgentTask(agentId, new List { taskId });
+ var isDeleted = db.DeleteAgentTasks(agentId, new List { taskId });
return await Task.FromResult(isDeleted);
}
}
diff --git a/src/Infrastructure/BotSharp.OpenAPI/Controllers/AgentController.cs b/src/Infrastructure/BotSharp.OpenAPI/Controllers/AgentController.cs
index b6950e04..6aff56ae 100644
--- a/src/Infrastructure/BotSharp.OpenAPI/Controllers/AgentController.cs
+++ b/src/Infrastructure/BotSharp.OpenAPI/Controllers/AgentController.cs
@@ -115,12 +115,6 @@ public class AgentController : ControllerBase
return await _agentService.RefreshAgents(request?.AgentIds);
}
- [HttpPut("/agent/file/{agentId}")]
- public async Task UpdateAgentFromFile([FromRoute] string agentId)
- {
- return await _agentService.UpdateAgentFromFile(agentId);
- }
-
[HttpPut("/agent/{agentId}")]
public async Task UpdateAgent([FromRoute] string agentId, [FromBody] AgentUpdateModel agent)
{
diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/AgentCodeDocument.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/AgentCodeDocument.cs
new file mode 100644
index 00000000..f37db77d
--- /dev/null
+++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Collections/AgentCodeDocument.cs
@@ -0,0 +1,32 @@
+using BotSharp.Abstraction.Agents.Models;
+
+namespace BotSharp.Plugin.MongoStorage.Collections;
+
+public class AgentCodeDocument : MongoBase
+{
+ public string AgentId { get; set; } = default!;
+ public string Name { get; set; } = default!;
+ public string Content { get; set; } = default!;
+
+ public static AgentCodeDocument ToMongoModel(AgentCodeScript script)
+ {
+ return new AgentCodeDocument
+ {
+ Id = script.Id,
+ AgentId = script.AgentId,
+ Name = script.Name,
+ Content = script.Content
+ };
+ }
+
+ public static AgentCodeScript ToDomainModel(AgentCodeDocument script)
+ {
+ return new AgentCodeScript
+ {
+ Id = script.Id,
+ AgentId = script.AgentId,
+ Name = script.Name,
+ Content = script.Content
+ };
+ }
+}
diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs
index 992dc6f8..6f171cb3 100644
--- a/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs
+++ b/src/Plugins/BotSharp.Plugin.MongoStorage/MongoDbContext.cs
@@ -160,6 +160,9 @@ public class MongoDbContext
public IMongoCollection AgentTasks
=> CreateAgentTaskIndex();
+ public IMongoCollection AgentCodes
+ => GetCollectionOrCreate("AgentCodes");
+
public IMongoCollection Conversations
=> CreateConversationIndex();
diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs
index 40558e13..407832d9 100644
--- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs
+++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs
@@ -2,6 +2,7 @@ using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Functions.Models;
using BotSharp.Abstraction.Repositories.Filters;
using BotSharp.Abstraction.Routing.Models;
+using MongoDB.Driver;
namespace BotSharp.Plugin.MongoStorage.Repository;
@@ -593,6 +594,8 @@ public partial class MongoRepository
{
_dc.UserAgents.DeleteMany(Builders.Filter.Empty);
_dc.RoleAgents.DeleteMany(Builders.Filter.Empty);
+ _dc.AgentTasks.DeleteMany(Builders.Filter.Empty);
+ _dc.AgentCodes.DeleteMany(Builders.Filter.Empty);
_dc.Agents.DeleteMany(Builders.Filter.Empty);
return true;
}
@@ -612,11 +615,13 @@ public partial class MongoRepository
var userAgentFilter = Builders.Filter.Eq(x => x.AgentId, agentId);
var roleAgentFilter = Builders.Filter.Eq(x => x.AgentId, agentId);
var agentTaskFilter = Builders.Filter.Eq(x => x.AgentId, agentId);
+ var agentCodeFilter = Builders.Filter.Eq(x => x.AgentId, agentId);
- _dc.Agents.DeleteOne(agentFilter);
_dc.UserAgents.DeleteMany(userAgentFilter);
_dc.RoleAgents.DeleteMany(roleAgentFilter);
_dc.AgentTasks.DeleteMany(agentTaskFilter);
+ _dc.AgentCodes.DeleteMany(agentCodeFilter);
+ _dc.Agents.DeleteOne(agentFilter);
return true;
}
catch
diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCode.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCode.cs
new file mode 100644
index 00000000..c0fd21b7
--- /dev/null
+++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCode.cs
@@ -0,0 +1,116 @@
+using BotSharp.Abstraction.Agents.Models;
+
+namespace BotSharp.Plugin.MongoStorage.Repository;
+
+public partial class MongoRepository
+{
+ #region Code
+ public List GetAgentCodeScripts(string agentId, List? scriptNames = null)
+ {
+ if (string.IsNullOrWhiteSpace(agentId))
+ {
+ return [];
+ }
+
+ var builder = Builders.Filter;
+ var filters = new List>()
+ {
+ builder.Eq(x => x.AgentId, agentId)
+ };
+
+ if (!scriptNames.IsNullOrEmpty())
+ {
+ filters.Add(builder.In(x => x.Name, scriptNames));
+ }
+
+ var found = _dc.AgentCodes.Find(builder.And(filters)).ToList();
+ return found.Select(x => AgentCodeDocument.ToDomainModel(x)).ToList();
+ }
+
+ public string? GetAgentCodeScript(string agentId, string scriptName)
+ {
+ if (string.IsNullOrWhiteSpace(agentId)
+ || string.IsNullOrWhiteSpace(scriptName))
+ {
+ return null;
+ }
+
+ var builder = Builders.Filter;
+ var filters = new List>()
+ {
+ builder.Eq(x => x.AgentId, agentId),
+ builder.Eq(x => x.Name, scriptName)
+ };
+
+ var found = _dc.AgentCodes.Find(builder.And(filters)).FirstOrDefault();
+ return found?.Content;
+ }
+
+ public bool UpdateAgentCodeScript(string agentId, AgentCodeScript script)
+ {
+ if (string.IsNullOrWhiteSpace(agentId) || script == null)
+ {
+ return false;
+ }
+
+ var builder = Builders.Filter;
+ var filters = new List>()
+ {
+ builder.Eq(x => x.AgentId, agentId),
+ builder.Eq(x => x.Name, script.Name)
+ };
+ var filterDef = builder.And(filters);
+
+ var found = _dc.AgentCodes.Find(filterDef).FirstOrDefault();
+ if (found == null)
+ {
+ return false;
+ }
+
+ var update = Builders.Update.Set(x => x.Content, script.Content);
+ _dc.AgentCodes.UpdateOne(filterDef, update);
+ return true;
+ }
+
+ public bool InsertAgentCodeScripts(string agentId, List scripts)
+ {
+ if (string.IsNullOrWhiteSpace(agentId) || scripts.IsNullOrEmpty())
+ {
+ return false;
+ }
+
+ var docs = scripts.Select(x =>
+ {
+ var script = AgentCodeDocument.ToMongoModel(x);
+ script.AgentId = agentId;
+ script.Id = !string.IsNullOrEmpty(x.Id) ? x.Id : Guid.NewGuid().ToString();
+ return script;
+ }).ToList();
+
+ _dc.AgentCodes.InsertMany(docs);
+ return true;
+ }
+
+ public bool BulkInsertAgentCodeScripts(string agentId, List? scriptNames)
+ {
+ if (string.IsNullOrWhiteSpace(agentId))
+ {
+ return false;
+ }
+
+ var filterDef = Builders.Filter.Empty;
+ if (scriptNames != null)
+ {
+ var builder = Builders.Filter;
+ var filters = new List>
+ {
+ builder.In(x => x.Name, scriptNames)
+ };
+ filterDef = builder.And(filters);
+ }
+
+ var deleted = _dc.AgentCodes.DeleteMany(filterDef);
+ return deleted.DeletedCount > 0;
+ }
+ #endregion
+}
diff --git a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentTask.cs b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentTask.cs
index 85f14215..060994d4 100644
--- a/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentTask.cs
+++ b/src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentTask.cs
@@ -1,5 +1,6 @@
using BotSharp.Abstraction.Repositories.Filters;
using BotSharp.Abstraction.Tasks.Models;
+using MongoDB.Driver;
namespace BotSharp.Plugin.MongoStorage.Repository;
@@ -86,13 +87,17 @@ public partial class MongoRepository
_dc.AgentTasks.InsertOne(taskDoc);
}
- public void BulkInsertAgentTasks(List tasks)
+ public void BulkInsertAgentTasks(string agentId, List tasks)
{
- if (tasks.IsNullOrEmpty()) return;
+ if (string.IsNullOrWhiteSpace(agentId) || tasks.IsNullOrEmpty())
+ {
+ return;
+ }
var taskDocs = tasks.Select(x =>
{
var task = AgentTaskDocument.ToMongoModel(x);
+ task.AgentId = agentId;
task.Id = !string.IsNullOrEmpty(x.Id) ? x.Id : Guid.NewGuid().ToString();
return task;
}).ToList();
@@ -138,30 +143,21 @@ public partial class MongoRepository
_dc.AgentTasks.ReplaceOne(filter, taskDoc);
}
- public bool DeleteAgentTask(string agentId, List taskIds)
+ public bool DeleteAgentTasks(string agentId, List? taskIds = null)
{
- if (taskIds.IsNullOrEmpty()) return false;
-
- var builder = Builders.Filter;
- var filters = new List>
+ var filterDef = Builders.Filter.Empty;
+ if (taskIds != null)
{
- builder.In(x => x.Id, taskIds)
- };
- var taskDeleted = _dc.AgentTasks.DeleteMany(builder.And(filters));
+ var builder = Builders.Filter;
+ var filters = new List>
+ {
+ builder.In(x => x.Id, taskIds)
+ };
+ filterDef = builder.And(filters);
+ }
+
+ var taskDeleted = _dc.AgentTasks.DeleteMany(filterDef);
return taskDeleted.DeletedCount > 0;
}
-
- public bool DeleteAgentTasks()
- {
- try
- {
- _dc.AgentTasks.DeleteMany(Builders.Filter.Empty);
- return true;
- }
- catch
- {
- return false;
- }
- }
#endregion
}