Skip to content

Conversation

@iceljc
Copy link
Collaborator

@iceljc iceljc commented Oct 22, 2025

PR Type

Enhancement


Description

  • Refactored LLM model capabilities system: Replaced boolean ImageGeneration flag with comprehensive Capabilities enum supporting 12 capability types (Text, Chat, ImageReading, ImageGeneration, AudioGeneration, etc.)

  • Enhanced filtering and configuration: Introduced LlmConfigFilter to replace LlmConfigOptions, enabling advanced filtering by model type, ID, name, and capabilities across LLM provider services

  • Extended agent management: Added conditional agent deletion with AgentDeleteOptions, code script management endpoints, and AI-powered code generation via LLM integration

  • New controller organization: Refactored monolithic controllers into partial classes (InstructModeController, ConversationController, AgentController) with specialized endpoint files for better maintainability

  • Added multi-modal capabilities: Implemented new endpoints for image reading, audio processing (speech-to-text, text-to-speech), and PDF file processing

  • Performance optimizations: Replaced Directory.GetDirectories() and Directory.GetFiles() with Directory.EnumerateDirectories() and Directory.EnumerateFiles() throughout file repositories for better memory efficiency

  • Code quality improvements: Standardized conditional block formatting to multi-line format, improved null-safety checks, and enhanced error reporting with type information

  • New features: Added conversation file attachment management, conversation state management, visualization/dashboard endpoints, and SQL chart processor for data visualization

  • Extended object cloning: Added generic DeepClone<TInput, TOutput> overload for cross-type cloning with detailed error reporting

  • Bug fixes: Improved MongoDB filter construction for agent code scripts and enhanced null safety in knowledge base vector search


Diagram Walkthrough

flowchart LR
  A["LLM Model Settings<br/>Capabilities Enum"] -->|replaces| B["Boolean Flags<br/>ImageGeneration"]
  C["LlmConfigFilter"] -->|replaces| D["LlmConfigOptions"]
  E["Partial Controllers<br/>InstructMode, Conversation, Agent"] -->|organizes| F["Specialized Endpoint Files<br/>Image, Audio, File, PDF"]
  G["AgentDeleteOptions"] -->|enables| H["Conditional Deletion<br/>User/Role Agents"]
  I["Directory.Enumerate*"] -->|optimizes| J["Directory.Get*<br/>Performance"]
  K["CodeGenerationOptions"] -->|enables| L["AI-Powered Code<br/>Generation via LLM"]
Loading

File Walkthrough

Relevant files
Enhancement
35 files
FileRepository.Agent.cs
Code formatting and performance improvements with conditional delete
options

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Agent.cs

  • Added import for BotSharp.Abstraction.Agents.Options namespace
  • Reformatted all early return statements to use multi-line block format
    for consistency
  • Replaced Directory.GetDirectories() and Directory.GetFiles() with
    Directory.EnumerateDirectories() and Directory.EnumerateFiles() for
    better performance
  • Updated DeleteAgent() method signature to accept optional
    AgentDeleteOptions parameter for conditional deletion of user agents
    and role agents
+283/-91
MongoRepository.Agent.cs
MongoDB repository agent deletion with conditional options support

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs

  • Added import for BotSharp.Abstraction.Agents.Options namespace
  • Reformatted all early return statements to use multi-line block format
  • Updated DeleteAgent() method signature to accept optional
    AgentDeleteOptions parameter
  • Refactored agent deletion logic to conditionally delete user agents,
    role agents, and code scripts based on options
+134/-38
InstructModeController.Image.cs
Image controller refactoring and multi-modal endpoint additions

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.Image.cs

  • Refactored ImageGenerationController class into a partial class
    InstructModeController
  • Changed error response property from Message to ErrorMsg for
    consistency
  • Added Success = true flag to successful image operation responses
  • Added new multi-modal completion endpoints for reading images
+92/-24 
CompletionProvider.cs
Completion provider refactoring with capability-based filtering

src/Infrastructure/BotSharp.Core/Infrastructures/CompletionProvider.cs

  • Reformatted method signatures to place parameters on separate lines
    for consistency
  • Updated GetImageCompletion() method to accept IEnumerable instead of
    bool imageGenerate parameter
  • Updated internal method calls to use new capabilities parameter
    instead of imageGenerate
+20/-13 
LlmProviderService.cs
LLM provider service refactoring with enhanced filtering capabilities

src/Infrastructure/BotSharp.Core/Infrastructures/LlmProviderService.cs

  • Added import for BotSharp.Abstraction.MLTasks.Filters namespace
  • Updated GetProviderModel() method signature to use IEnumerable instead
    of bool imageGenerate
  • Replaced LlmConfigOptions with LlmConfigFilter in GetLlmConfigs()
    method
  • Enhanced filtering logic to support multiple model types, IDs, names,
    and capabilities
  • Improved code formatting and null-safety checks
+55/-23 
ConversationController.File.cs
New conversation file attachment management endpoints       

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.File.cs

  • New file containing file attachment management endpoints for
    conversations
  • Implements list, upload, download, and retrieval of conversation
    attachments
  • Provides endpoints for message file operations with support for
    multiple file sources
+117/-0 
InstructModeController.cs
New instruct mode controller with completion endpoints     

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.cs

  • New file containing base InstructModeController partial class with
    core instruction endpoints
  • Implements text completion, chat completion, and instruction execution
    endpoints
  • Manages conversation state and integrates with instruction services
+123/-0 
AgentService.Coding.cs
New agent code script service implementation                         

src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.Coding.cs

  • New file providing agent code script management functionality
  • Implements methods for retrieving, updating, deleting, and generating
    agent code scripts
  • Supports code script filtering and conditional deletion options
+110/-0 
InstructModeController.Audio.cs
New audio processing endpoints for speech operations         

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.Audio.cs

  • New file containing audio processing endpoints for speech-to-text and
    text-to-speech
  • Implements both file-based and form-based request handling for audio
    operations
  • Integrates with file instruction service and state management
+101/-0 
LocalFileStorageService.Conversation.cs
File storage service directory enumeration optimization   

src/Infrastructure/BotSharp.Core/Files/Services/Storage/LocalFileStorageService.Conversation.cs

  • Replaced Directory.GetDirectories() and Directory.GetFiles() with
    Directory.EnumerateDirectories() and Directory.EnumerateFiles()
  • Improved performance by using enumeration instead of array allocation
  • Maintained existing functionality while optimizing directory traversal
+8/-8     
InstructModeController.File.cs
New PDF file processing endpoints                                               

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.File.cs

  • New file containing PDF file processing endpoints
  • Implements PDF completion endpoints with both file and form-based
    request handling
  • Integrates with file instruction service for PDF reading operations
+81/-0   
AgentController.Coding.cs
New agent code script API endpoints                                           

src/Infrastructure/BotSharp.OpenAPI/Controllers/Agent/AgentController.Coding.cs

  • New file providing agent code script management API endpoints
  • Implements endpoints for retrieving, updating, deleting, and
    generating code scripts
  • Includes state management for code generation options
+63/-0   
FileRepository.AgentCodeScript.cs
Agent code script repository optimization and upsert support

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentCodeScript.cs

  • Replaced Directory.GetFiles() with Directory.EnumerateFiles() for
    performance optimization
  • Enhanced UpdateAgentCodeScripts() to support upsert operations with
    directory creation
  • Improved DeleteAgentCodeScripts() with better null-safety and
    directory existence checks
  • Updated BulkInsertAgentCodeScripts() to use upsert option
+19/-9   
ObjectExtensions.cs
Enhanced object cloning with generic type conversion support

src/Infrastructure/BotSharp.Abstraction/Utilities/ObjectExtensions.cs

  • Renamed DefaultJsonOptions to _defaultJsonOptions following naming
    conventions
  • Refactored DeepClone method with improved parameter naming (obj
    inputObj, newObjoutputObj)
  • Enhanced error message to include type information in exception
    logging
  • Added new generic DeepClone overload for cross-type
    cloning with detailed error reporting
+36/-9   
PyCodeInterpreter.cs
Added code generation capability with LLM integration       

src/Plugins/BotSharp.Plugin.PythonInterpreter/Services/PyCodeInterpreter.cs

  • Added using statement for BotSharp.Abstraction.Coding.Models
  • Implemented new GenerateCodeScriptAsync method for AI-powered code
    generation using LLM
  • Added #region and #endregion markers to organize private methods
  • New method supports custom agent configuration, template-based
    instructions, and LLM provider selection
+55/-0   
LlmModelSetting.cs
Refactored LLM model capabilities from boolean flags to enum

src/Infrastructure/BotSharp.Abstraction/MLTasks/Settings/LlmModelSetting.cs

  • Added Capabilities property as list of LlmModelCapability enum values
  • Removed ImageGeneration boolean property in favor of
    capabilities-based approach
  • Fixed typo in comment: "vidoes" → "videos"
  • Added new LlmModelType enum values: All and Web
  • Created new LlmModelCapability enum with 12 capability types (Text,
    Chat, ImageReading, ImageGeneration, etc.)
+21/-6   
AgentPlugin.cs
Added code script execution and menu management features 

src/Infrastructure/BotSharp.Core/Agents/AgentPlugin.cs

  • Added using BotSharp.Core.Coding import
  • Registered CodeScriptExecutor as singleton in DI container
  • Reordered menu items and added new "Coding" menu option with
    admin/root role restriction
  • Updated collection initializer syntax from new List { ... } to [...]
    for "Evaluating" menu roles
+6/-2     
AgentController.cs
Refactored agent controller with partial class and enhanced deletion

src/Infrastructure/BotSharp.OpenAPI/Controllers/Agent/AgentController.cs

  • Changed class from public to public partial to support partial class
    organization
  • Added IAgentTaskService dependency injection
  • Updated DeleteAgent method to accept AgentDeleteRequest with optional
    delete options
  • Modified GetAgentLabels to accept optional size query parameter with
    default value of 1000
+9/-5     
InstructService.Execute.cs
Refactored code instruction options and context handling 

src/Infrastructure/BotSharp.Core/Instructs/Services/InstructService.Execute.cs

  • Renamed CodeScriptName property to ScriptName in code options
  • Added ScriptType extraction from options with fallback to
    AgentCodeScriptType.Src
  • Updated CodeInstructContext to include ScriptType property
  • Improved code script retrieval with dynamic script type parameter
+5/-3     
QdrantDb.cs
Added vector search parameter support to Qdrant integration

src/Plugins/BotSharp.Plugin.Qdrant/QdrantDb.cs

  • Expanded single-line conditional returns to multi-line blocks for
    consistency
  • Added SearchParams construction from VectorSearchParamModel with new
    BuildSearchParam method
  • Integrated search parameters into vector search operation
  • New method handles exact search parameter configuration
+25/-2   
IAgentService.cs
Extended agent service with code generation and deletion capabilities

src/Infrastructure/BotSharp.Abstraction/Agents/IAgentService.cs

  • Added imports for BotSharp.Abstraction.Coding.Models and
    CodeGenerationOptions
  • Updated DeleteAgent signature to accept optional AgentDeleteOptions
    parameter
  • Added DeleteAgentCodeScripts method with optional code scripts
    parameter
  • Added GenerateCodeScript method for AI-powered code generation
+9/-1     
ConversationController.Visualization.cs
Added conversation visualization and dashboard management endpoints

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.Visualization.cs

  • New file with partial ConversationController class
  • Implemented chart data retrieval endpoint with provider-based
    processor selection
  • Added dashboard conversation pinning/unpinning endpoints
  • Organized endpoints into Chart and Dashboard regions
+40/-0   
SqlChartProcessor.cs
Implemented SQL driver chart processor for data visualization

src/Plugins/BotSharp.Plugin.SqlDriver/Services/SqlChartProcessor.cs

  • New file implementing IChartProcessor interface for SQL-based chart
    data retrieval
  • Provides provider name "sql_driver" for chart processing
  • Retrieves conversation state data and returns chart data results
  • Includes dummy data for testing purposes
+47/-0   
LlmProviderController.cs
Refactored LLM provider controller with filter-based configuration

src/Infrastructure/BotSharp.OpenAPI/Controllers/Setting/LlmProviderController.cs

  • Added using BotSharp.Abstraction.MLTasks.Filters import
  • Updated GetLlmProviderModels to accept modelType query parameter with
    default LlmModelType.Chat
  • Renamed GetLlmConfigs parameter from LlmConfigOptions to
    LlmConfigFilter
  • Added blank line for improved code formatting
+6/-4     
ICodeProcessor.cs
Extended code processor interface with generation capability

src/Infrastructure/BotSharp.Abstraction/Coding/ICodeProcessor.cs

  • Added using BotSharp.Abstraction.Coding.Models import
  • Added XML documentation comments for RunAsync method
  • Implemented new GenerateCodeScriptAsync method with XML documentation
  • Both methods provide default NotImplementedException behavior
+18/-0   
AgentCodeScriptViewModel.cs
Created agent code script view model with conversion methods

src/Infrastructure/BotSharp.OpenAPI/ViewModels/Agents/View/AgentCodeScriptViewModel.cs

  • New file providing view model for agent code scripts
  • Implements From and To conversion methods for model transformation
  • Supports JSON serialization with camelCase property naming
  • Handles null safety in conversion methods
+52/-0   
CodeGenerationOptions.cs
Created code generation options configuration class           

src/Infrastructure/BotSharp.Abstraction/Coding/Options/CodeGenerationOptions.cs

  • New file defining options for code generation functionality
  • Extends LlmConfigBase for LLM configuration inheritance
  • Includes agent ID, template name, programming language, and template
    data properties
  • All properties support JSON serialization with null-value exclusion
+32/-0   
CodeInstructOptions.cs
Refactored code instruction options with improved documentation

src/Infrastructure/BotSharp.Abstraction/Instructs/Options/CodeInstructOptions.cs

  • Added XML documentation comments for all properties
  • Renamed CodeScriptName property to ScriptName for consistency
  • Added new ScriptType property for script type specification
  • Enhanced documentation clarity for processor and arguments properties
+18/-2   
AgentController.Task.cs
Consolidated agent task endpoints into main controller     

src/Infrastructure/BotSharp.OpenAPI/Controllers/Agent/AgentController.Task.cs

  • Converted standalone AgentTaskController class to partial
    AgentController method
  • Removed class-level controller attributes and constructor
  • Moved task-related endpoints into main agent controller as partial
    class
  • Expanded single-line conditional return to multi-line block
+5/-15   
AgentService.DeleteAgent.cs
Enhanced agent deletion with configurable delete options 

src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.DeleteAgent.cs

  • Added using BotSharp.Abstraction.Agents.Options import
  • Updated DeleteAgent method signature to accept optional
    AgentDeleteOptions parameter
  • Passed delete options to repository delete method
+3/-2     
CodeProcessOptions.cs
Created code processing options with persistence configuration

src/Infrastructure/BotSharp.Abstraction/Coding/Options/CodeProcessOptions.cs

  • New file defining comprehensive code processing options
  • Extends CodeGenerationOptions for code generation inheritance
  • Includes processor, save-to-db flag, script name, and script type
    properties
  • Provides default script type of AgentCodeScriptType.Src
+28/-0   
ILlmProviderService.cs
Refactored LLM provider service with capabilities-based filtering

src/Infrastructure/BotSharp.Abstraction/MLTasks/ILlmProviderService.cs

  • Added using BotSharp.Abstraction.MLTasks.Filters import
  • Updated GetSetting and GetProviderModel return types to nullable
  • Replaced imageGenerate boolean parameter with capabilities enum
    collection
  • Renamed LlmConfigOptions parameter to LlmConfigFilter in GetLlmConfigs
    method
+4/-3     
AgentCodeScriptUpdateModel.cs
Created agent code script request models for API operations

src/Infrastructure/BotSharp.OpenAPI/ViewModels/Agents/Request/AgentCodeScriptUpdateModel.cs

  • New file providing request models for code script operations
  • AgentCodeScriptUpdateModel supports code scripts list and update
    options
  • AgentCodeScriptDeleteModel supports code scripts list for deletion
  • Both models support JSON serialization with null-value exclusion
+23/-0   
ConversationController.State.cs
Added conversation state management endpoints                       

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.State.cs

  • New file with partial ConversationController class
  • Implemented conversation state key search endpoint
  • Added conversation latest state migration endpoint with batch size and
    error limit parameters
  • Organized endpoints into Search state keys and Migrate Latest States
    regions
+24/-0   
IBotSharpRepository.cs
Extended repository interface with delete options support

src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs

  • Added using BotSharp.Abstraction.Agents.Options import
  • Updated DeleteAgent method signature to accept optional
    AgentDeleteOptions parameter
+2/-1     
Formatting
12 files
FileRepository.Conversation.cs
Code formatting standardization and directory enumeration optimization

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Conversation.cs

  • Removed unused imports (BotSharp.Abstraction.Users.Models and System)
  • Reformatted all early return statements to use multi-line block format
  • Replaced Directory.GetDirectories() and Directory.GetFiles() with
    Directory.EnumerateDirectories() and Directory.EnumerateFiles()
    throughout the file
  • Applied consistent code formatting to improve readability
+183/-57
ConversationController.cs
Conversation controller refactoring for partial class support

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.cs

  • Removed unused imports (BotSharp.Abstraction.Chart and
    BotSharp.Abstraction.Files.Utilities)
  • Changed class from sealed to partial for extensibility
  • Reformatted constructor parameters for better readability
+3/-181 
FileRepository.Log.cs
Log repository formatting and directory enumeration optimization

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Log.cs

  • Removed unused import Microsoft.IdentityModel.Logging
  • Reformatted all early return statements to use multi-line block format
  • Replaced Directory.GetFiles() with Directory.EnumerateFiles() for
    performance optimization
  • Applied consistent code formatting throughout the file
+81/-31 
FileRepository.AgentTask.cs
Agent task repository formatting and enumeration optimization

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.AgentTask.cs

  • Reformatted all early return and continue statements to use multi-line
    block format
  • Replaced Directory.GetDirectories() and Directory.GetFiles() with
    Directory.EnumerateDirectories() and Directory.EnumerateFiles()
  • Applied consistent code formatting for improved readability
+83/-23 
FileRepository.User.cs
User repository code formatting standardization                   

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.User.cs

  • Reformatted all early return statements to use multi-line block format
  • Applied consistent code formatting throughout user repository methods
  • Improved readability of null-check conditions
+40/-10 
FileRepository.KnowledgeBase.cs
Improved code formatting and performance optimization       

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.KnowledgeBase.cs

  • Expanded single-line conditional returns to multi-line blocks for
    improved readability
  • Changed Directory.GetDirectories() to Directory.EnumerateDirectories()
    for better performance
  • Applied consistent formatting to all early-return conditions
    throughout the file
+25/-7   
MongoRepository.AgentTask.cs
Improved code formatting and removed unused imports           

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentTask.cs

  • Removed unused using MongoDB.Driver import
  • Expanded single-line conditional returns to multi-line blocks
    throughout the file
  • Applied consistent formatting to all early-return conditions
+16/-5   
StringExtensions.cs
Standardized conditional block formatting in string utilities

src/Infrastructure/BotSharp.Abstraction/Utilities/StringExtensions.cs

  • Expanded all single-line conditional blocks to multi-line format for
    consistency
  • Applied formatting improvements to SubstringMax, IsEqualTo, and
    CleanStr methods
  • Enhanced code readability with explicit block structure
+14/-2   
FileRepository.Crontab.cs
Improved crontab file repository formatting and performance

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Crontab.cs

  • Removed unnecessary blank line at method start
  • Changed Directory.GetDirectories() to Directory.EnumerateDirectories()
    for performance
  • Expanded single-line conditional returns to multi-line blocks for
    consistency
+13/-6   
FileRepository.Role.cs
Standardized conditional block formatting in role repository

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Role.cs

  • Expanded all single-line conditional returns to multi-line blocks
  • Applied consistent formatting to role validation and retrieval methods
  • Enhanced code readability throughout the file
+16/-4   
LocalFileStorageService.User.cs
Improved code formatting in user file storage service       

src/Infrastructure/BotSharp.Core/Files/Services/Storage/LocalFileStorageService.User.cs

  • Expanded single-line conditional returns to multi-line blocks
  • Applied consistent formatting to user avatar retrieval and storage
    methods
  • Enhanced code readability with explicit block structure
+12/-3   
BasicAgentHook.cs
Standardized conditional block formatting in agent hooks 

src/Infrastructure/BotSharp.Core/Agents/Hooks/BasicAgentHook.cs

  • Expanded single-line conditional continue statements to multi-line
    blocks
  • Applied consistent formatting to utility visibility checking logic
  • Enhanced code readability with explicit block structure
+8/-2     
Bug fix
2 files
MongoRepository.AgentCodeScript.cs
Improved MongoDB filter construction and null safety         

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.AgentCodeScript.cs

  • Removed unused using BotSharp.Abstraction.Repositories.Models import
  • Added null-coalescing operator ! to Guid.NewGuid().ToString()
    assignment
  • Refactored DeleteAgentCodeScripts to use filter builder pattern with
    proper AgentId filtering
  • Improved filter construction for both conditional and unconditional
    deletion scenarios
+9/-5     
KnowledgeBaseController.cs
Improved null safety in knowledge base vector search         

src/Infrastructure/BotSharp.OpenAPI/Controllers/KnowledgeBase/KnowledgeBaseController.cs

  • Added null-safe property access using ?. operator throughout vector
    search options
  • Added SearchParam property to vector search options
  • Improved null handling with default values for all request properties
  • Enhanced robustness of vector knowledge search functionality
+7/-6     
Additional files
59 files
AgentRule.cs +2/-2     
AgentCodeScriptUpdateOptions.cs +2/-1     
AgentDeleteOptions.cs +14/-0   
IBotSharpChartService.cs +0/-15   
IChartProcessor.cs +12/-0   
ChartCodeResult.cs +0/-7     
CodeGenerationResult.cs +7/-0     
CodeInterpretResponse.cs +1/-3     
SelectFileOptions.cs +1/-1     
FileHandleResponse.cs +1/-3     
CodeInstructContext.cs +1/-0     
FileInstructOptions.cs +3/-0     
LlmConfigFilter.cs +13/-0   
LlmConfigOptions.cs +0/-8     
ResponseBase.cs +11/-0   
AgentCodeScriptFilter.cs +1/-1     
AgentCodeScriptDbUpdateOptions.cs +1/-0     
VectorSearchParamModel.cs +7/-0     
VectorSearchOptions.cs +1/-0     
CrontabWatcher.cs +2/-1     
AgentService.CodeScripts.cs +0/-46   
AgentService.RefreshAgents.cs +7/-1     
AgentService.Rendering.cs +1/-1     
LocalFileStorageService.Audio.cs +4/-1     
LocalFileStorageService.Common.cs +4/-1     
LocalFileStorageService.KnowledgeBase.cs +4/-1     
FileRepository.Translation.cs +4/-1     
Using.cs +1/-0     
AgentController.Rule.cs +1/-11   
ApplicationController.cs [link]   
DashboardController.cs +1/-0     
EvaluatorController.cs [link]   
GoogleController.cs [link]   
TranslationController.cs [link]   
TextEmbeddingController.cs [link]   
FileController.cs [link]   
InstructModeController.cs +0/-342 
LoggerController.cs [link]   
McpController.cs [link]   
RealtimeController.cs [link]   
PluginController.cs [link]   
RouterController.cs [link]   
SettingController.cs [link]   
RoleController.cs [link]   
UserController.cs [link]   
AgentCodeScriptGenerationRequest.cs +14/-0   
AgentDeleteRequest.cs +11/-0   
ConversationChartDataResponse.cs +1/-22   
InstructBaseViewModel.cs +1/-5     
SearchVectorKnowledgeRequest.cs +3/-0     
HandleEmailReaderFn.cs +1/-1     
KnowledgeService.Vector.cs +4/-2     
ImageClientExtensions.cs +1/-0     
SequentialPlanner.cs +1/-1     
PackageInstallResult.cs +4/-3     
SqlChartService.cs +0/-156 
SqlDriverPlugin.cs +1/-1     
appsettings.json +69/-10 
TestAgentService.cs +2/-1     

@iceljc iceljc marked this pull request as draft October 22, 2025 21:57
@qodo-merge-pro
Copy link

qodo-merge-pro bot commented Oct 22, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
- [ ] Create ticket/issue <!-- /create_ticket --create_ticket=true -->

</details></td></tr>
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-merge-pro
Copy link

qodo-merge-pro bot commented Oct 22, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent crash when no models match
Suggestion Impact:The commit updated GetProviderModel to return a nullable type and added an empty-check (IsNullOrEmpty) before random selection, returning null when no models are available, which prevents the crash.

code diff:

@@ -63,6 +63,11 @@
             models = models.Where(x => x.Capabilities != null && capabilities.Any(y => x.Capabilities.Contains(y)));
         }
 
+        if (models.IsNullOrEmpty())
+        {
+            return null;
+        }
+
         var random = new Random();
         var index = random.Next(0, models.Count());
         var modelSetting = models.ElementAt(index);

Prevent a potential ArgumentOutOfRangeException in GetProviderModel by checking
if the filtered models collection is empty. If it is, return null instead of
attempting to select an element, which would cause a crash.

src/Infrastructure/BotSharp.Core/Infrastructures/LlmProviderService.cs [61-69]

 if (capabilities != null)
 {
     models = models.Where(x => x.Capabilities != null && capabilities.Any(y => x.Capabilities.Contains(y)));
 }
 
+var availableModels = models.ToList();
+if (!availableModels.Any())
+{
+    return null;
+}
+
 var random = new Random();
-var index = random.Next(0, models.Count());
-var modelSetting = models.ElementAt(index);
+var index = random.Next(0, availableModels.Count);
+var modelSetting = availableModels.ElementAt(index);
 return modelSetting;

[Suggestion processed]

Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a bug that will cause an ArgumentOutOfRangeException if no models match the filter criteria, leading to a runtime crash. The proposed fix aligns with the expected nullable return type, as evidenced by the null-conditional access (?.Name) at its call site.

High
Correctly handle 'All' model type filter

In GetLlmProviderModels, handle the LlmModelType.All case for the modelType
query parameter. Add a condition to return the entire list of models without
filtering when modelType is LlmModelType.All.

src/Infrastructure/BotSharp.OpenAPI/Controllers/LlmProviderController.cs [26-31]

 [HttpGet("/llm-provider/{provider}/models")]
 public IEnumerable<LlmModelSetting> GetLlmProviderModels([FromRoute] string provider, [FromQuery] LlmModelType modelType = LlmModelType.Chat)
 {
     var list = _llmProvider.GetProviderModels(provider);
+    if (modelType == LlmModelType.All)
+    {
+        return list;
+    }
     return list.Where(x => x.Type == modelType);
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a logic flaw where the newly added LlmModelType.All enum member would not work as intended. The fix correctly implements the "select all" behavior, which is crucial for the usability of the new query parameter.

Medium
High-level
Refine capability filtering logic

The suggestion proposes enhancing LlmConfigFilter to support both "any" (OR) and
"all" (AND) logic when filtering models by capabilities. This would make the
filtering more robust for different use cases.

Examples:

src/Infrastructure/BotSharp.Core/Infrastructures/LlmProviderService.cs [151]
                models = models.Where(x => x.Capabilities != null && filter.ModelCapabilities.Any(y => x.Capabilities.Contains(y)));
src/Infrastructure/BotSharp.Core/Infrastructures/LlmProviderService.cs [63]
            models = models.Where(x => x.Capabilities != null && capabilities.Any(y => x.Capabilities.Contains(y)));

Solution Walkthrough:

Before:

// In LlmProviderService.cs
public List<LlmProviderSetting> GetLlmConfigs(LlmConfigFilter? filter = null)
{
    // ...
    IEnumerable<LlmModelSetting> models = provider.Models ?? [];
    // ...
    if (filter.ModelCapabilities != null)
    {
        // Only checks if a model has ANY of the requested capabilities
        models = models.Where(x => x.Capabilities != null && 
                              filter.ModelCapabilities.Any(y => x.Capabilities.Contains(y)));
    }
    // ...
    return configs;
}

After:

// In LlmConfigFilter.cs
public class LlmConfigFilter
{
    // ...
    public List<LlmModelCapability>? ModelCapabilities { get; set; }
    public bool MatchAllCapabilities { get; set; } // New property
}

// In LlmProviderService.cs
public List<LlmProviderSetting> GetLlmConfigs(LlmConfigFilter? filter = null)
{
    // ...
    if (filter.ModelCapabilities != null)
    {
        if (filter.MatchAllCapabilities) { // AND logic
            models = models.Where(x => x.Capabilities != null && filter.ModelCapabilities.All(y => x.Capabilities.Contains(y)));
        } else { // OR logic (current behavior)
            models = models.Where(x => x.Capabilities != null && filter.ModelCapabilities.Any(y => x.Capabilities.Contains(y)));
        }
    }
    // ...
}
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the new capability filtering only supports "OR" logic (Any) and proposes adding "AND" logic, which is a significant design improvement that greatly enhances the flexibility of the new LlmConfigFilter.

Medium
General
Use case-insensitive model ID filtering
Suggestion Impact:The commit updated the ModelIds filtering to use a case-insensitive comparer (stored in a variable 'comparer'), aligning with the suggestion's intent.

code diff:

             if (filter.ModelIds != null)
             {
-                models = models.Where(x => filter.ModelIds.Contains(x.Id));
+                models = models.Where(x => filter.ModelIds.Contains(x.Id, comparer));
             }

Update the model ID filtering logic in GetLlmConfigs to be case-insensitive. Use
StringComparer.OrdinalIgnoreCase when checking if filter.ModelIds contains a
model's ID to ensure consistent and robust filtering.

src/Infrastructure/BotSharp.Core/Infrastructures/LlmProviderService.cs [139-142]

 if (filter.ModelIds != null)
 {
-    models = models.Where(x => filter.ModelIds.Contains(x.Id));
+    models = models.Where(x => filter.ModelIds.Contains(x.Id, StringComparer.OrdinalIgnoreCase));
 }

[Suggestion processed]

Suggestion importance[1-10]: 6

__

Why: The suggestion improves robustness by making the model ID filtering case-insensitive, which is consistent with how ModelNames are filtered in the same method. This enhances usability and prevents unexpected filtering failures due to casing differences.

Low
  • Update

@iceljc iceljc marked this pull request as ready for review October 29, 2025 03:48
@qodo-merge-pro
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

🔴
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Error Detail Exposure: User-facing responses set ErrorMsg with raw exception messages (ex.Message), potentially
exposing internal details to clients.

Referred Code
{
    var error = $"Error in image composition. {ex.Message}";
    _logger.LogError(ex, error);
    imageViewModel.ErrorMsg = error;
    return imageViewModel;
}
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing Auditing: New endpoints handling file/image operations and multi-modal processing do not include
explicit audit logging of critical actions or outcomes, making it unclear if these actions
are captured in audit trails.

Referred Code
#region Read image
[HttpPost("/instruct/multi-modal")]
public async Task<string> MultiModalCompletion([FromBody] MultiModalFileRequest input)
{
    var state = _services.GetRequiredService<IConversationStateService>();
    input.States.ForEach(x => state.SetState(x.Key, x.Value, source: StateSource.External));

    try
    {
        var fileInstruct = _services.GetRequiredService<IFileInstructService>();
        var content = await fileInstruct.ReadImages(input.Text, input.Files, new InstructOptions
        {
            Provider = input.Provider,
            Model = input.Model,
            AgentId = input.AgentId,
            TemplateName = input.TemplateName
        });
        return content;
    }
    catch (Exception ex)
    {



 ... (clipped 41 lines)
Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status:
PII In Logs Risk: Controllers log exceptions with full messages while also returning those messages to
clients; without redaction, logs may capture sensitive request-derived data.

Referred Code
    var error = $"Error in reading multi-modal files. {ex.Message}";
    _logger.LogError(ex, error);
    return error;
}
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Input Validation Gaps: New endpoints accept files and text but perform minimal validation (e.g., content type,
size, count), leaving potential for unsafe inputs or oversized uploads.

Referred Code
[HttpPost("/instruct/multi-modal/form")]
public async Task<MultiModalViewModel> MultiModalCompletion([FromForm] IEnumerable<IFormFile> files, [FromForm] MultiModalRequest request)
{
    var state = _services.GetRequiredService<IConversationStateService>();
    request?.States?.ForEach(x => state.SetState(x.Key, x.Value, source: StateSource.External));
    var viewModel = new MultiModalViewModel();

    try
    {
        var fileModels = files.Select(x => new InstructFileModel
        {
            FileData = FileUtility.BuildFileDataFromFile(x),
            ContentType = x.ContentType
        }).ToList();

        var fileInstruct = _services.GetRequiredService<IFileInstructService>();
        var content = await fileInstruct.ReadImages(request?.Text ?? string.Empty, fileModels, new InstructOptions
        {
            Provider = request?.Provider,
            Model = request?.Model,
            AgentId = request?.AgentId,



 ... (clipped 14 lines)
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-merge-pro
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Refactor controllers into specialized services

Refactor business logic out of API controllers like InstructModeController and
into dedicated service classes. This will create a cleaner separation of
concerns, making the code more reusable and easier to test.

Examples:

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.cs [24-50]
src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.File.cs [9-27]

Solution Walkthrough:

Before:

// In InstructModeController.cs
public partial class InstructModeController : ControllerBase
{
    private readonly IServiceProvider _services;
    // ...

    public async Task<InstructResult> InstructCompletion([FromRoute] string agentId, [FromBody] InstructMessageModel input)
    {
        // Logic to get services and manage state is inside the controller
        var state = _services.GetRequiredService<IConversationStateService>();
        input.States.ForEach(x => state.SetState(x.Key, x.Value, ...));
        state.SetState("provider", input.Provider, ...);
        // ... more state management

        // Business logic orchestration is inside the controller
        var instructor = _services.GetRequiredService<IInstructService>();
        var result = await instructor.Execute(agentId, ...);

        result.States = state.GetStates();
        return result;
    }
}

After:

// New dedicated service
public class InstructOrchestrationService : IInstructOrchestrationService
{
    private readonly IInstructService _instructor;
    private readonly IConversationStateService _state;
    // ... other dependencies

    public async Task<InstructResult> ExecuteInstructCompletion(string agentId, InstructMessageModel input)
    {
        // All business and orchestration logic is now in the service
        input.States.ForEach(x => _state.SetState(x.Key, x.Value, ...));
        _state.SetState("provider", input.Provider, ...);
        // ... more state management

        var result = await _instructor.Execute(agentId, ...);
        result.States = _state.GetStates();
        return result;
    }
}

// Controller becomes thin
public partial class InstructModeController : ControllerBase
{
    private readonly IInstructOrchestrationService _instructOrchestrator;
    // ...

    public async Task<InstructResult> InstructCompletion([FromRoute] string agentId, [FromBody] InstructMessageModel input)
    {
        // Controller just delegates to the service
        return await _instructOrchestrator.ExecuteInstructCompletion(agentId, input);
    }
}
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a significant architectural issue where business logic is coupled with controllers, impacting maintainability and testability across many new files.

Medium
Possible issue
Fix orphaned data after deletion

Restore the missing logic to delete AgentCodeScriptDocument records in the
DeleteAgent method to prevent orphaned data in the database.

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.Agent.cs [689-722]

 public bool DeleteAgent(string agentId, AgentDeleteOptions? options = null)
 {
     try
     {
         if (string.IsNullOrEmpty(agentId))
         {
             return false;
         }
 
         if (options == null || options.DeleteUserAgents)
         {
             var userAgentFilter = Builders<UserAgentDocument>.Filter.Eq(x => x.AgentId, agentId);
             _dc.UserAgents.DeleteMany(userAgentFilter);
         }
         
         if (options == null || options.DeleteRoleAgents)
         {
             var roleAgentFilter = Builders<RoleAgentDocument>.Filter.Eq(x => x.AgentId, agentId);
             _dc.RoleAgents.DeleteMany(roleAgentFilter);
         }
 
-        DeleteAgentCodeScripts(agentId, options?.ToDeleteCodeScripts);
+        if (options == null || options.DeleteCodeScripts)
+        {
+            var agentCodeFilter = Builders<AgentCodeScriptDocument>.Filter.Eq(x => x.AgentId, agentId);
+            _dc.AgentCodeScripts.DeleteMany(agentCodeFilter);
+        }
 
         var agentTaskFilter = Builders<AgentTaskDocument>.Filter.Eq(x => x.AgentId, agentId);
         _dc.AgentTasks.DeleteMany(agentTaskFilter);
 
         var agentFilter = Builders<AgentDocument>.Filter.Eq(x => x.Id, agentId);
         _dc.Agents.DeleteOne(agentFilter);
         return true;
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, $"Error to delete agent {agentId}");
         return false;
     }
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the logic to delete AgentCodeScriptDocument was removed from the DeleteAgent method, which would lead to orphaned data. The proposed fix restores this critical cleanup logic.

Medium
Add null check to prevent crash

Add a null-conditional operator to request.States to prevent a
NullReferenceException when the States property is not included in the request.

src/Infrastructure/BotSharp.OpenAPI/Controllers/Instruct/InstructModeController.File.cs [15]

-request.States.ForEach(x => state.SetState(x.Key, x.Value, source: StateSource.External));
+request.States?.ForEach(x => state.SetState(x.Key, x.Value, source: StateSource.External));

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential NullReferenceException if request.States is null and provides a simple, correct fix that prevents a likely runtime crash.

Medium
Add null check for request object

Add a null check for the request object at the beginning of the
GetConversationChartData method to prevent potential downstream errors.

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.Visualization.cs [15-16]

-var chart = _services.GetServices<IChartProcessor>().FirstOrDefault(x => x.Provider == request?.ChartProvider);
+if (request == null) return null;
+var chart = _services.GetServices<IChartProcessor>().FirstOrDefault(x => x.Provider == request.ChartProvider);
 if (chart == null) return null;

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential edge case where a null request could lead to a downstream NullReferenceException and proposes a valid fix to improve code robustness.

Low
Learned
best practice
Stream file without buffering

Remove the unnecessary read-into-buffer and return the stream directly to avoid
extra allocations. This prevents large memory usage and is more efficient.

src/Infrastructure/BotSharp.OpenAPI/Controllers/Conversation/ConversationController.File.cs [109-114]

 var stream = System.IO.File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
-var bytes = new byte[stream.Length];
-stream.Read(bytes, 0, (int)stream.Length);
-stream.Position = 0;
-
 return new FileStreamResult(stream, contentType) { FileDownloadName = fName };

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate async/API usage semantics: avoid reading entire file into memory unnecessarily for downloads; stream files to clients to prevent large allocations and potential performance issues.

Low
Prevent null-return contract breakage

Either change the return type to nullable or return an empty object/throw
argument exception; alternatively guard at call sites. Prefer returning a
non-null instance or using ArgumentNullException.

src/Infrastructure/BotSharp.OpenAPI/ViewModels/Agents/View/AgentCodeScriptViewModel.cs [23-36]

 public static AgentCodeScriptViewModel From(AgentCodeScript model)
 {
-    if (model == null)
-    {
-        return null;
-    }
+    if (model == null) throw new ArgumentNullException(nameof(model));
 
     return new AgentCodeScriptViewModel
     {
         Name = model.Name,
         Content = model.Content,
         ScriptType = model.ScriptType
     };
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why:
Relevant best practice - Ensure nullability guards and safe defaults: avoid returning null from factory/conversion methods that advertise non-null return types to prevent unexpected null dereferences.

Low
General
Use enumeration for better performance

Replace Directory.GetFiles() with Directory.EnumerateFiles() for better
performance and consistency with the rest of the PR.

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.Agent.cs [868]

-var userAgentFile = Directory.GetFiles(userDir).FirstOrDefault(x => Path.GetFileName(x) == USER_AGENT_FILE);
+var userAgentFile = Directory.EnumerateFiles(userDir).FirstOrDefault(x => Path.GetFileName(x) == USER_AGENT_FILE);
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies an instance where Directory.GetFiles was missed during the PR's refactoring to Directory.EnumerateFiles, making the code consistent and improving performance.

Low
  • More

@iceljc iceljc merged commit 627e94b into SciSharp:master Oct 29, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant