
### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Program.cs

using System.Text;
using xLoggingService.DI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace xAiApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);            
            
            //
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            //            
            var result = Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging => 
                    logging.AddXTelemetryLogger())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .AddXTelemetry();

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Startup.cs

using System;
using System.IO;
using xAiApi.DI;
using System.Linq;
using xAiModels.DI;
using xAiService.DI;
using xTagService.DI;
using System.Net.Http;
using xAiApi.Database;
using xHttpService.DI;
using xPushService.DI;
using xFileService.DI;
using xDataService.DI;
using Newtonsoft.Json;
using System.Reflection;
using xAiApi.Extensions;
using xStringService.DI;
using xLoggingService.DI;
using xStorageService.DI;
using xIdentityService.DI;
using xDataService.Models;
using xCommons.Extensions;
using xAiModels.Constants;
using xPushService.Helpers;
using xCommons.Configurations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection;

namespace xAiApi
{
    public class Startup
    {
        //
        #region Props ...
        public IConfiguration Configuration { get; }
        private readonly List<XDatabaseDescriptor> databases;
        private readonly XAiApiDatabaseDescriptor apiDatabaseDescriptor;
        #endregion

        //
        #region Constructor(s) ...
        public Startup(IConfiguration configuration)
        {
            //
            Configuration = configuration;

            //
            // Create an Api Descriptor Class Instance ...
            apiDatabaseDescriptor = new XAiApiDatabaseDescriptor();
            databases = new List<XDatabaseDescriptor>
            {
                apiDatabaseDescriptor
            };
        }
        #endregion

        public void ConfigureServices(IServiceCollection services)
        {
            //
            // Register Validation Provider and all XCommons Module Services ...
            services.AddXCommons(Configuration);

            //
            // Register App Configuration ...
            services.AddXAppConfiguration(Configuration);
            var appConfiguration = services.GetRegisteredService<XAppConfiguration>();

            //
            // Register Logging Service ...
            services.AddXLoggingService(Configuration);

            //
            // Register Allowed Origins ...
            services.AddXCors(appConfiguration.AllowedOrigins);

            //
            // Register Swagger ...
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            services.AddXSwagger(Configuration, xmlFilePath: xmlPath);

            //
            // Register HttpService ...
            services.AddXHttpService(Configuration);

            //
            // Add Api V1 Versioning ...
            services.AddXApiV1Versioning();

            //
            // OAuthIntrospectin Http Client Handler ...
            // this is for handling SSLErrors ...
            services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    return new HttpClientHandler
                    {
                        ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
                    };
                });

            //
            // Register Authorizations ...
            services.AddXAuthorization();

            //
            services.AddControllers()
                .AddNewtonsoftJson(x =>
                {
                    x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

            //
            var lifeTime = ServiceLifetime.Scoped;
            var repositoryType = xDataService.Constants.XRepositoryType.EF;

            //
            // Register XIdentity Service ...
            services.AddXIdentityService(
                lifeTime: lifeTime,
                configuration: Configuration
            );

            //
            // Storage Service ...
            services.AddXStorageService(Configuration);

            //
            // Push Service ...
            services.AddXPushService(
                lifeTime: lifeTime,
                config: Configuration
            );

            //
            // Preparing DataBases ...
            if (databases.HasChild())
            {
                //
                databases
                    .ToList()
                    .ForEach(database =>
                    {
                        //
                        // Register DataBase ...
                        services.AddXDatabase(
                            lifeTime: lifeTime,
                            descriptor: database,
                            configuration: Configuration
                        );
                    });
            }

            //
            // Register String Service ...
            services.AddXStringService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register Tag Service ...
            services.AddXTagService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register File Service ...
            services.AddXFileService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register AiApi Data Service ...
            services.AddXAiDataService<XAiApiDbContext>(
                lifeTime: lifeTime,
                repositoryType: repositoryType
            );

            //
            // Register XAiApi Configuration ...
            services.AddXAiApiConfiguration(Configuration);

            //
            // Register MCP Server Provider ...
            services.AddXAiMcpServerProvider();

            //
            // Register File Content Extractor Services ...
            services.AddXAiFileContentExtractors();

            //
            // Register Text Chunker Service ...
            services.AddXAiTextChunker();

            //
            // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
            services.AddXAiChatWithDocuments();

            //
            // Register XAiMcpClient ...
            services.AddXAiMcpClient();

            //
            // Persistent RAG (Knowledge over XAiVector Table) ...
            services.AddXRagService();

            //
            // Register Default AI Services ...
            services.AddXAiServices();
        }

        public void Configure(
            IApplicationBuilder app, 
            IWebHostEnvironment env
        )
        {
            //
            // Configure the HTTP request pipeline.
            // Order: Exception Handling -> Https -> Static Files -> Swagger (Dev) -> Cors
            //        -> Model Proxy (Terminal for /{RoutePrefix}) -> Routing -> AuthN -> AuthZ -> Endpoints ...
            var isDevelopmentEnvironment = env.IsDevelopment();
            if (isDevelopmentEnvironment)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(XAiModelsConstants.XAiErrorRoute);
                app.UseHsts();
            }

            //
            // Setting Environment in App Confiuration ...
            app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);

            //
            // Force Https Redirection ...
            app.UseHttpsRedirection();

            //
            // Use Storage Service (Prepare Folders + Static Files) ...
            // Must be before Routing so Static Files Short Circuit Pipeline ...
            app.UseXStorageService();

            //
            // Use Swagger Middleware (Only in Development) ...
            if (isDevelopmentEnvironment)
            {
                app.UseXSwagger();
            }

            //
            // Using Cors (before Proxy so Browser Requests get CORS Headers) ...
            app.UseXCors();

            //
            // Enable Model Proxy (Handles its own Authentication) ...
            app.UseXAiModelProxy();

            //
            // Using Routing ...
            app.UseRouting();

            //
            // Using Request Logging ...
            if (!isDevelopmentEnvironment)
            {
                app.UseXRequestLogger();
            }

            //
            // Use xIdentityService (Authentication) ...
            app.UseXIdentityService();

            //
            // Use Authorization ...
            app.UseAuthorization();

            //
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //
            // Use PushService (Legacy UseSignalR -> Registers its own Router) ...
            var pushHelper = new XPushServiceHelper();
            app.UseXPushService(pushHelper);

            //
            // Using DataBase ...
            if (databases.HasChild())
            {
                //
                databases
                    .ToList()
                    .ForEach(database =>
                    {
                        //
                        app.UseXDatabase(
                            descriptor: database,
                            isDevelopmentEnvironment: isDevelopmentEnvironment
                        );
                    });
            }

            //
            // Using String Service ...
            app.UseXStringService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );

            //
            // Using XTag Service ...
            app.UseXTagService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );

            //
            // Using File Service ...
            app.UseXFileService(
                isDevelopmentEnvironment: isDevelopmentEnvironment
            );
        }
    }
}




### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Configurations\XAiApiConfiguration.cs

using xAiApi.Models;
using xAiModels.Models;

namespace xAiApi.Configurations
{
    public class XAiApiConfiguration
    {
        /// <summary>
        /// Allowed Models to Use ...
        /// </summary>
        public XAiModelDescriptor[] Models { get; set; } = [];

        /// <summary>
        /// Allowed Prompts to Use ...
        /// </summary>
        public XAiPromptDescriptor[] Prompts { get; set; } = [];

        /// <summary>
        /// OCR Configuration ...
        /// </summary>
        public XAiOCRDescriptor OCR { get; set; } = new();

        /// <summary>
        /// Transcript Configuration ...
        /// </summary>
        public XAiTransciptDescriptor Transcript { get; set; } = new();

        /// <summary>
        /// PDF To Image Configuration ...
        /// </summary>
        public XPDFToImageDescriptor PDFToImageDescriptor { get; set; } = new();

        /// <summary>
        /// Proxy Configuration ...
        /// </summary>
        /// <returns></returns>
        public XAiModelProxyConfiguration ProxyConfiguration { get; set; } = new();

        /// <summary>
        /// Text Chunker Configuration ...
        /// </summary>
        public XTextChunkerDescriptor TextChunker { get; set; } = new();

        /// <summary>
        /// RAG Configuration ...
        /// </summary>
        public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
        
        /// <summary>
        /// DateTime Configuration ...
        /// </summary>
        /// <returns></returns>
        public XDateTimeDescriptor DateTime { get; set; } = new();
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Constants\ConfigurationNodeNames.cs

namespace xAiApi.Constants
{
    public partial struct ConfigurationNodeNames
    {
        public const string AI_API_NODE = "AiApiConfiguration";
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Constants\XAiApiConstants.cs

namespace xAiApi.Constants
{
    public struct XAiApiConstants
    {
        //
        // Database Descriptor ...
        public const string XAiApiDbIdentifier = "xAiApiDb";
        public const string XAiApiMigrationsAssemblyIdentifier = "xAiApi";

        //
        public const string XDILogTag = "XAiApi";

        //
        public const string XAiApiRagPromptName = "ChatWithDocuments";
        public const string XAiApiIntroductionPromptName = "Introduction";
        public const string XAiApiContentExtractionPromptName = "ContentExtraction";

        //
        public const string XAiDefaultModelName = "Arion";
        public const string XAiEmbeddingModelName = "Embed";
        public const string XAiDefaultVisionModelName = "Qwen";
        public const string XAiDefaultThinkingModelName = "Qwen";
        public const string XAiEmbeddingPromptName = "Embedding";
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\AccountController.cs

using xCommons.Providers;
using xCommons.Configurations;
using xIdentityHelper.Controllers;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;

namespace xAiApi.Controllers
{
    public partial class AccountController : XAccountControllerBase
    {
        //
        #region Constructor ...
        public AccountController(
            ILogger<AccountController> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        { }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\ChatWithDocumentsController.cs

using System;
using System.Linq;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Providers;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xHttpService.Extensions;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using xAiApi.Interfaces.Extractors;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Chat With Documents (In-Memory RAG) Controller ...
    /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session
    /// </summary>
    [Authorize]
    public class ChatWithDocumentsController : XBaseIdentityApiV1Controller
    {
        /// <summary>
        /// Default AI Service ...
        /// </summary>
        private readonly IXAiService aiService;

        /// <summary>
        /// Text Chunker Service ...
        /// </summary>
        private readonly IXTextChunker textChunker;

        /// <summary>
        /// In Memory Vector Store ...
        /// </summary>
        private readonly IXInMemoryVectorStore vectorStore;

        /// <summary>
        /// XAiApi Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration apiConfiguration;

        /// <summary>
        /// Embedding Service ...
        /// </summary>
        private readonly IXAiEmbeddingService embeddingService;

        /// <summary>
        /// File Context Extractor Service ...
        /// </summary>
        private readonly IXFileContentExtractor fileContentExtractor;

        public ChatWithDocumentsController(
            IXAiService aiService,
            IXTextChunker textChunker,
            IXInMemoryVectorStore vectorStore,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XAiApiConfiguration apiConfiguration,
            IXAiEmbeddingService embeddingService,
            XValidationProvider validationProvider,
            ILogger<ChatWithDocumentsController> logger,
            IXFileContentExtractor fileContentExtractor
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            //
            this.aiService = aiService;
            this.textChunker = textChunker;
            this.vectorStore = vectorStore;
            this.apiConfiguration = apiConfiguration;
            this.embeddingService = embeddingService;
            this.fileContentExtractor = fileContentExtractor;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into a (new or existing) In-Memory Session:
        /// Extract -> Chunk -> Embed -> Store ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="sessionId">Optional: Add to an Existing Session</param>
        /// <param name="ttlMinutes">Optional: Session TTL in Minutes (only for new Session)</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ingest")]
        [Consumes("multipart/form-data")]
        public async Task<ActionResult<XAiDocumentIngestResult>> Ingest(
            [FromForm] IFormFileCollection files,
            [FromForm] Guid? sessionId = null,
            [FromForm] int? ttlMinutes = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!files.HasChild())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Resolve Target Session ...
                Guid targetSessionId;
                if (sessionId.HasValue && sessionId.Value != Guid.Empty)
                {
                    //
                    if (!vectorStore.TryGet(sessionId.Value, out _, ownerId))
                    {
                        XException.NotFound.Throw();
                    }
                    targetSessionId = sessionId.Value;
                }
                else
                {
                    //
                    var ttl = TimeSpan.FromMinutes(
                        ttlMinutes.HasValue && ttlMinutes.Value > 0
                            ? ttlMinutes.Value
                            : apiConfiguration.RAGDescriptor.DefaultTtlMinutes
                    );
                    targetSessionId = vectorStore.CreateSession(ownerId, ttl);
                }

                //
                var result = new XAiDocumentIngestResult
                {
                    SessionId = targetSessionId
                };

                //
                // Extract -> Chunk -> Embed ...
                var vectors = new List<XAiVectorDto>();
                foreach (var file in files)
                {
                    //
                    cancellationToken.ThrowIfCancellationRequested();

                    //
                    if (file.IsNull() || file.Length == 0)
                    {
                        result.SkippedFiles.Add(file?.FileName ?? "(null)");
                        continue;
                    }

                    //
                    var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
                    if (!fileContentExtractor.CanExtract(mimeType))
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var text = await ExtractText(file, mimeType, cancellationToken);
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var chunks = textChunker.Chunk(text, file.FileName);
                    if (!chunks.HasChild())
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    // Embed in Batches ...
                    var fileVectors = await EmbedChunks(
                        chunks: chunks,
                        fileName: file.FileName,
                        mimeType: mimeType,
                        cancellationToken: cancellationToken
                    );

                    //
                    vectors.AddRange(fileVectors);
                    result.FilesCount++;
                }

                //
                // Store ...
                if (vectors.HasChild() &&
                    !vectorStore.Add(targetSessionId, vectors, ownerId))
                {
                    XException.ActionFailed.Throw();
                }

                //
                // Fill Result ...
                result.ChunksCount = vectors.Count;
                if (vectorStore.TryGet(targetSessionId, out var session, ownerId))
                {
                    lock (session.SyncRoot)
                    {
                        result.TotalVectorsCount = session.Vectors.Count;
                    }
                    result.ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl);
                }

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Ask ...
        /// <summary>
        /// Ask a Question over Ingested Documents ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ask")]
        public async Task<ActionResult<XAiDocumentAnswer>> Ask(
            [FromBody] XAiDocumentAskRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Check Session ...
                if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
                {
                    XException.NotFound.Throw();
                }

                //
                // Retrieve ...
                var context = await Retrieve(request, ownerId, cancellationToken);

                //
                var result = new XAiDocumentAnswer
                {
                    SessionId = request.SessionId,
                    Sources = ToSources(context)
                };

                //
                if (!context.HasChild())
                {
                    result.NoContextFound = true;
                    return Ok(result);
                }

                //
                // Generate ...
                result.Answer = await aiService.AskTextByContextAsync(
                    context: context,
                    userInfo: userInfo,
                    prompt: request.Prompt,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask a Question over Ingested Documents and Stream Response (SSE) ...
        /// First Event Carries Sources, Next Events Carry Text Deltas, Last Event has IsFinal = true ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskStream")]
        public async Task AskStream(
            [FromBody] XAiDocumentAskRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                //
                Response.StatusCode = StatusCodes.Status400BadRequest;
                Response.ContentType = "application/json; charset=utf-8";
                await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var ownerId = userInfo.UserId;

                //
                // Check Session ...
                if (!vectorStore.TryGet(request.SessionId, out _, ownerId))
                {
                    XException.NotFound.Throw();
                }

                //
                // Retrieve ...
                var context = await Retrieve(request, ownerId, cancellationToken);

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                // First Event: Sources ...
                var hasContext = context.HasChild();
                await WriteChunk(new XAiDocumentAnswerChunk
                {
                    Text = string.Empty,
                    IsFinal = !hasContext,
                    NoContextFound = !hasContext,
                    Sources = ToSources(context)
                }, cancellationToken);

                //
                if (!hasContext)
                {
                    await Response.WriteSseDoneAsync(cancellationToken);
                    return;
                }

                //
                // Stream Deltas ...
                var enumerable = aiService.AskTextByContextAsEnumerable(
                    context: context,
                    userInfo: userInfo,
                    prompt: request.Prompt,
                    cancellationToken: cancellationToken
                );
                await foreach (var delta in enumerable)
                {
                    //
                    if (delta.IsNullOrEmpty())
                    {
                        continue;
                    }

                    //
                    await WriteChunk(new XAiDocumentAnswerChunk
                    {
                        Text = delta
                    }, cancellationToken);
                }

                //
                // Final Event ...
                await WriteChunk(new XAiDocumentAnswerChunk
                {
                    Text = string.Empty,
                    IsFinal = true
                }, cancellationToken);
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "ChatWithDocuments: AskStream Failed");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }
        #endregion

        //
        #region Session ...
        /// <summary>
        /// Retrieve Session Info (without Embeddings) ...
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Session/{id:guid}")]
        public async Task<ActionResult<XAiDocumentSessionInfo>> GetSession(Guid id)
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                if (!vectorStore.TryGet(id, out var session, userInfo.UserId))
                {
                    XException.NotFound.Throw();
                }

                //
                IList<XAiVectorDto> vectors;
                lock (session.SyncRoot)
                {
                    vectors = session.Vectors.ToList();
                }

                //
                var result = new XAiDocumentSessionInfo
                {
                    Id = session.Id,
                    Ttl = session.Ttl,
                    VectorsCount = vectors.Count,
                    CreatedAtUtc = session.CreatedAtUtc,
                    LastAccessAtUtc = session.LastAccessAtUtc,
                    ExpiresAtUtc = session.LastAccessAtUtc.Add(session.Ttl),
                    Files = [.. vectors
                        .Select(v => v.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName))
                        .Where(f => !f.IsNullOrEmpty())
                        .Distinct()]
                };

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove a Session and Free Memory ...
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Session/{id:guid}")]
        public async Task<ActionResult<bool>> DeleteSession(Guid id)
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                if (!vectorStore.Remove(id, userInfo.UserId))
                {
                    XException.NotFound.Throw();
                }

                //
                return Ok(true);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Private ...
        /// <summary>
        /// Extract Plain Text of a File (Text or Audio Transcript) ...
        /// </summary>
        private async Task<string> ExtractText(
            IFormFile file,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            try
            {
                //
                using var stream = file.OpenReadStream();
                var extraction = await fileContentExtractor.ExtractRichAsync(
                    fileStream: stream,
                    mimeType: mimeType,
                    fileName: file.FileName,
                    cancellationToken: cancellationToken
                );

                //
                var result = extraction?.Text;
                if (string.IsNullOrWhiteSpace(result))
                {
                    result = extraction?.AudioTranscript;
                }

                //
                return result;
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "ChatWithDocuments: Extraction Failed for {FileName}", file.FileName);
                return null;
            }
        }

        /// <summary>
        /// Embed Chunks in Batches and Build Vectors ...
        /// </summary>
        private async Task<IList<XAiVectorDto>> EmbedChunks(
            IList<XTextChunk> chunks,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new List<XAiVectorDto>(chunks.Count);
            var batchSize = apiConfiguration.RAGDescriptor.EmbeddingBatchSize;

            //
            for (var offset = 0; offset < chunks.Count; offset += batchSize)
            {
                //
                cancellationToken.ThrowIfCancellationRequested();

                //
                var batch = chunks.Skip(offset).Take(batchSize).ToList();
                var embeddings = await embeddingService.Embeddings(
                    batch: batch.Select(c => c.Text).ToArray(),
                    cancellationToken: cancellationToken
                );

                //
                if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
                {
                    XException.ActionFailed.Throw();
                }

                //
                for (var i = 0; i < batch.Count; i++)
                {
                    //
                    var chunk = batch[i];
                    result.Add(new XAiVectorDto
                    {
                        Id = Guid.NewGuid(),
                        Text = chunk.Text,
                        Embedding = embeddings[i],
                        Identifier = chunk.Identifier,
                        Metadata = new Dictionary<string, string>
                        {
                            [apiConfiguration.RAGDescriptor.MetadataFileName] = fileName,
                            [apiConfiguration.RAGDescriptor.MetadataMimeType] = mimeType,
                            [apiConfiguration.RAGDescriptor.MetadataChunkIndex] = chunk.Index.ToString()
                        }
                    });
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Embed Prompt and Search Session ...
        /// </summary>
        private async Task<IList<XAiVectorSearchResult>> Retrieve(
            XAiDocumentAskRequest request,
            string ownerId,
            CancellationToken cancellationToken
        )
        {
            //
            var topK = Math.Clamp(
                request.TopK ?? apiConfiguration.RAGDescriptor.DefaultTopK,
                1,
                apiConfiguration.RAGDescriptor.MaxTopK
            );
            var minScore = request.MinScore ?? apiConfiguration.RAGDescriptor.DefaultMinScore;

            //
            var queryEmbedding = await embeddingService.Embedding(
                content: request.Prompt,
                cancellationToken: cancellationToken
            );
            if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            var result = vectorStore.Search(
                topK: topK,
                ownerId: ownerId,
                minScore: minScore,
                sessionId: request.SessionId,
                queryEmbedding: queryEmbedding
            );

            //
            return result ?? [];
        }

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        private IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var result = (context ?? [])
                .Select(c =>
                {
                    //
                    var chunkIndexText = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataChunkIndex);
                    var text = c.Text ?? string.Empty;
                    var snippetLength = Math.Min(text.Length, apiConfiguration.RAGDescriptor.SourceSnippetLength);

                    //
                    return new XAiDocumentSource
                    {
                        Score = c.Score,
                        Identifier = c.Identifier,
                        Snippet = text.Substring(0, snippetLength),
                        ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null,
                        FileName = c.Metadata.GetMetadata(apiConfiguration.RAGDescriptor.MetadataFileName)
                    };
                })
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Write a SSE Event ...
        /// </summary>
        private Task WriteChunk(
            XAiDocumentAnswerChunk chunk,
            CancellationToken cancellationToken
        )
        {
            //
            return Response.WriteSseEventAsync(
                data: chunk,
                cancellationToken: cancellationToken
            );
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\KnowledgeController.cs

using System;
using xAiApi.Models;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Constants;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xHttpService.Extensions;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using xIdentityHelper;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Knowledge (Persistent RAG over XAiVector Table) Controller ...
    /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete
    /// </summary>
    [Authorize]
    public class KnowledgeController : XBaseIdentityApiV1Controller
    {
        /// <summary>
        /// Persistent RAG Service ...
        /// </summary>
        private readonly IXAiRAGService ragService;

        public KnowledgeController(
            IXAiRAGService ragService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            ILogger<KnowledgeController> logger,
            XValidationProvider validationProvider
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            this.ragService = ragService;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into a Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store in XAiVector Table ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope">Target Scope: User (default) / Project / Conversation / Global (Admin)</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="knowledgeType">Optional Knowledge Type / Domain</param>
        /// <param name="replaceExisting">Replace Previously Stored Vectors of Same File (default true)</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ingest")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<XAiKnowledgeIngestResult>> Ingest(
            [FromForm] IFormFileCollection files,
            [FromForm] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
            [FromForm] Guid? scopeId = null,
            [FromForm] string knowledgeType = null,
            [FromForm] bool replaceExisting = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!files.HasChild())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await ragService.IngestAsync(
                    files: files,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    replaceExisting: replaceExisting,
                    cancellationToken: cancellationToken,
                    scope: BuildScope(scope, scopeId, knowledgeType)
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Documents ...
        /// <summary>
        /// List Ingested Documents of a Knowledge Scope ...
        /// </summary>
        /// <param name="scope">User (default) / Project / Conversation / Global</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="knowledgeType">Optional Knowledge Type Filter</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Documents")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<IList<XAiKnowledgeDocumentInfo>>> Documents(
            [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
            [FromQuery] Guid? scopeId = null,
            [FromQuery] string knowledgeType = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var scopeIdentifier = BuildScope(scope, scopeId, knowledgeType);

                //
                var result = await ragService.LoadDocumentsAsync(
                    userInfo: userInfo,
                    scope: scopeIdentifier,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove All Vectors of a Document in a Knowledge Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope">User (default) / Project / Conversation / Global (Admin)</param>
        /// <param name="scopeId">ProjectId or ConversationId (Required for Project / Conversation)</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        [HttpDelete("Documents")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult<int>> DeleteDocument(
            [FromQuery] string fileName,
            [FromQuery] XAiKnowledgeScope? scope = XAiKnowledgeScope.Global,
            [FromQuery] Guid? scopeId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                ValidationProvider.NotEmpty(fileName);

                //
                var userInfo = await GetUserInfo();

                //
                var result = await ragService.RemoveDocumentAsync(
                    fileName: fileName,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken,
                    scope: BuildScope(scope, scopeId, null)
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Private ...
        /// <summary>
        /// Build Scope Descriptor from Request Params ...
        /// </summary>
        private XAiKnowledgeScopeDescriptor BuildScope(
            XAiKnowledgeScope? scope,
            Guid? scopeId,
            string knowledgeType
        )
        {
            //
            if (!scope.HasValue)
            {
                scope = XAiKnowledgeScope.Global;
            }

            //
            var result = new XAiKnowledgeScopeDescriptor
            {
                Scope = scope.Value,
                ScopeId = scopeId,
                Type = knowledgeType,
            };

            //
            return result;
        }

        /// <summary>
        /// Write a SSE Event ...
        /// </summary>
        private Task WriteChunk(
            XAiDocumentAnswerChunk chunk,
            CancellationToken cancellationToken
        )
        {
            //
            return Response.WriteSseEventAsync(
                data: chunk,
                cancellationToken: cancellationToken
            );
        }
        #endregion
    }
}


### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\McpServersController.cs

using System;
using xModels.Dtos;
using xIdentityHelper;
using System.Threading;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiModels.Models.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    public class McpServersController : XBaseIdentityApiV1Controller
    {
        private readonly IXAiMcpServerProvider mcpServerProvider;

        public McpServersController(
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            ILogger<McpServersController> logger,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        {
            this.mcpServerProvider = mcpServerProvider;
        }

        //
        #region Provider ...
        /// <summary>
        /// Retrieve Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> GetMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.GetMcpServer(
                    id: id,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Add MCP Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> AddMcpServer(
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.AddMcpServer(
                    item: item,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Update Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> UpdateMcpServer(
            [FromRoute] Guid id,
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (id.IsDefaultGuid() ||
                    !ModelState.IsValid || 
                    !item.IsValidForAddOrUpdate())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.UpdateMcpServer(
                    id: id,
                    item: item,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Remove Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XAiMcpServerDto>> RemoveMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.RemoveMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Enable Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Enable")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> EnableMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.EnableMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Disable Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Disable")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> DisableMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.DisableMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Toggle Specified MCP Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("{id}/Toggle")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<bool>> ToggleMcpServer(
            [FromRoute] Guid id,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid || id.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.ToggleMcpServer(
                    id: id,
                    userInfo: userInfo,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Get all Registered MCP Servers by handling Ownership ...
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> GetMcpServers(
            [FromQuery] bool forceOwner = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid)
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.GetAll(
                    userInfo: userInfo,
                    forceOwner: forceOwner,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Registered MCP Servers by handling Ownership ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Query")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> QueryMcpServers(
            [FromQuery] XQuery query,
            [FromQuery] bool forceOwner = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!ModelState.IsValid)
                {
                    XException.InvalidArgs.Throw();
                }
                await ValidationProvider
                    .GroupValidationBuilder()
                    .AddNotNull(query)
                    .ValidateGroupAsync();

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await mcpServerProvider.Query(
                    query: query,
                    userInfo: userInfo,
                    forceOwner: forceOwner,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result.ToDynamicObject());
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        /// <summary>
        /// Refresh MCP Servers ...
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Refresh")]
        [Authorize(Policy = XPolicies.EnabledAdmin)]
        public async Task<ActionResult> RefreshMcpServers(
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();

                //
                await mcpServerProvider.RefreshAsync(
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok();                
            } catch(Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\StartupController.cs

using xCommons.Providers;
using xCommons.Extensions;
using xCommons.Controllers;
using xExceptions.Constants;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    /// <summary>
    /// Runing when application start ...
    /// </summary>
    [Route("")]
    [AllowAnonymous]
    public class StartupController : XBaseController
    {

        public StartupController(
            ILogger<StartupController> logger,
            XAppConfiguration appConfiguration,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            validationProvider
        )
        { }

        /// <summary>
        /// Show Configured Welcome Message 
        /// </summary>
        /// <returns></returns>
        [HttpGet("")]
        [AllowAnonymous]
        public virtual ActionResult<string> Index()
        {
            //
            var controllerName = GetControllerName();
            var message = $"{AppConfiguration.WelcomeMessage}";

            //
            return Ok(message);
        }

        /// <summary>
        /// Global Exception Handler Endpoint (Production) ...
        /// Returns a Generic Error without Leaking Exception Details ...
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("error")]
        [ApiExplorerSettings(IgnoreApi = true)]
        public virtual ActionResult Error()
        {
            //
            var error = XException.ActionFailed.ToXError();
            return StatusCode(StatusCodes.Status500InternalServerError, error);
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\TestIdentity.cs

using xCommons.Providers;
using xCommons.Configurations;
using xIdentityService.Interfaces;
using xIdentityHelper.Controllers;
using Microsoft.Extensions.Logging;

namespace xAiApi.Controllers {
    /// <summary>
    /// Test all Authentication Policies ...
    /// </summary>
    public class TestIdentity : XTestIdentityControllerBase {
        public TestIdentity (
            ILogger<TestIdentity> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base (
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        ) { }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\XAiController.cs

using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Configurations;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    public class XAiController : XAiServiceControllerBase<IXAiService>
    {
        public XAiController(
            ILogger<XAiController> logger,
            IXAiService aiService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            aiService,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        { }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\XAiServiceControllerBase.cs

using System;
using xModels.Dtos;
using xIdentityHelper;
using System.Threading;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiModels.Models.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xHttpService.Extensions;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Controllers;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    public abstract class XAiServiceControllerBase<TAiService> : XBaseIdentityApiV1Controller
    where TAiService : IXAiServiceBase
    {
        private readonly TAiService aiService;

        protected XAiServiceControllerBase(
            ILogger logger,
            TAiService aiService,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base(
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        )
        {
            this.aiService = aiService;
        }

        //
        #region Actions ...
        /// <summary>
        /// Ask Question and Get Response ...
        /// </summary>
        /// <param name="question"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskText")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> AskText(
            [FromQuery] string question,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                ValidationProvider.NotEmpty(question);

                //
                var userInfo = await GetUserInfo();

                //
                var result = await aiService.AskTextAsync(
                    prompt: question,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask Question and Get Response Stream ...
        /// </summary>
        /// <param name="question"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskTextStream(
            [FromQuery] string question,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (question.IsNullOrEmpty())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var userInfo = await GetUserInfo();

                //
                var enumerable = aiService.AskTextAsEnumerable(
                    prompt: question,
                    userInfo: userInfo,
                    cancellationToken: cancellationToken
                );

                //
                // Format: data: {"text":"..."}\n\n
                await foreach (var chunk in enumerable)
                {
                    //
                    // Skip Empty Chunks ...
                    if (string.IsNullOrEmpty(chunk))
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: new { text = chunk },
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskTextStream Failed");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextFromKnowledge")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> AskTextFromKnowledge(
            [FromQuery] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.AskTextFromKnowledgeAsync(
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("AskTextFromKnowledgeStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskTextFromKnowledgeStream(
            [FromQuery] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var enumerable = aiService.AskTextFromKnowledgeAsEnumerable(
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    cancellationToken: cancellationToken
                );

                //
                // Format: data: {json}\n\n
                await foreach (var resp in enumerable)
                {
                    //
                    // Skip Empty Responses ...
                    if (resp.IsNullOrDefault())
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: resp,
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskStream Failed ...");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }

        /// <summary>
        /// Ask Question and Get Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Ask")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> Ask(
            [FromBody] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.AskAsync(
                    files: null,
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    connectionId: connectionId,
                    projectId: request.ProjectId,
                    cancellationToken: cancellationToken,
                    conversationId: request.ConversationId
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask Question and Get Response Stream ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskStream")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskStream(
            [FromBody] XAiResponseRequest request,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var enumerable = aiService.AskAsEnumerable(
                    files: null,
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    connectionId: connectionId,
                    projectId: request.ProjectId,
                    cancellationToken: cancellationToken,
                    conversationId: request.ConversationId
                );

                //
                // Format: data: {json}\n\n
                await foreach (var resp in enumerable)
                {
                    //
                    // Skip Empty Responses ...
                    if (resp.IsNullOrDefault())
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: resp,
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskStream Failed ...");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }

        /// <summary>
        /// Ask Question with Files and Get Response ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskWithFiles")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task<ActionResult<string>> AskWithFiles(
            [FromForm] XAiResponseRequest request,
            [FromForm] IFormFileCollection files,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!request.IsValid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.AskAsync(
                    files: files,
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    connectionId: connectionId,
                    projectId: request.ProjectId,
                    cancellationToken: cancellationToken,
                    conversationId: request.ConversationId
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Ask Question with Files and Get Response Stream ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("AskWithFilesStream")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public virtual async Task AskWithFilesStream(
            [FromForm] XAiResponseRequest request,
            [FromForm] IFormFileCollection files,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate (before Stream Starts -> Proper Http Error) ...
            if (!request.IsValid())
            {
                await WriteStreamValidationError();
                return;
            }

            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Configure SSE Response ...
                Response.PrepareSseResponse();

                //
                var enumerable = aiService.AskAsEnumerable(
                    files: files,
                    topK: request.TopK,
                    userInfo: userInfo,
                    type: request.Type,
                    prompt: request.Prompt,
                    minScore: request.MinScore,
                    connectionId: connectionId,
                    projectId: request.ProjectId,
                    cancellationToken: cancellationToken,
                    conversationId: request.ConversationId
                );

                //
                // Format: data: {json}\n\n
                await foreach (var resp in enumerable)
                {
                    //
                    // Skip Empty Responses ...
                    if (resp.IsNullOrDefault())
                    {
                        continue;
                    }

                    //
                    await Response.WriteSseEventAsync(
                        data: resp,
                        cancellationToken: cancellationToken
                    );
                }

                //
                await Response.WriteSseDoneAsync(cancellationToken);
            }
            catch (Exception ex) when (ex.IsClientCancellation(cancellationToken))
            {
                // Client Disconnected ...
            }
            catch (Exception ex)
            {
                //
                Logger.LogError(ex, "AskStream Failed ...");
                if (!Response.HasStarted)
                {
                    //
                    var result = GetExceptionActionResult(ex);
                    await result.ExecuteResultAsync(ControllerContext);
                    return;
                }

                //
                await Response.WriteSseErrorAsync(ex.Message);
            }
        }
        #endregion

        //
        #region Loaders ...
        /// <summary>
        /// Retrieve AI Projects ...
        /// </summary>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Projects")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<IEnumerable<XAiProjectDto>>> LoadProjects(
            [FromQuery] bool includeDefaults = false,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.LoadProjects(
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    includeDefaults: includeDefaults,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Project's Conversations ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Projects/{projectId}/Conversations")]
        public async Task<ActionResult<IEnumerable<XAiConversationDto>>> LoadConversations(
            [FromRoute] Guid projectId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (projectId.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.LoadConversations(
                    projectId: projectId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Retrieve Specified AI Conversation's Messages ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Conversations/{conversationId}/Messages")]
        public async Task<ActionResult<IEnumerable<XAiMessageDto>>> LoadMessages(
            [FromRoute] Guid conversationId,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (conversationId.IsDefaultGuid())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var result = await aiService.LoadMessages(
                    conversationId: conversationId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet("Projects/Query")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<XQueryResult<XAiProjectDto>>> QueryProjects(
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryProjects(
                    query: query,
                    ownerId: userInfo.UserId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Projects/{projectId}/Conversations/Query")]
        public async Task<ActionResult<XQueryResult<XAiConversationDto>>> QueryConversations(
            [FromRoute] Guid projectId,
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryConversations(
                    query: query,
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpGet("Conversations/{conversationId}/Messages/Query")]
        public async Task<ActionResult<XQueryResult<XAiMessageDto>>> QueryMessages(
            [FromRoute] Guid conversationId,
            [FromQuery] XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                var result = await aiService.QueryMessages(
                    query: query,
                    ownerId: userInfo.UserId,
                    conversationId: conversationId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Creators ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("Projects")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<XAiProjectDto>> CreateProject(
            [FromBody] XAiProjectDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Update Required Params ...
                item.OwnerId = userInfo.UserId;
                if (!item.IsValidForAddOrUpdate())
                {
                    XException.InvalidData.Throw();
                }

                //
                var result = await aiService.CreateProject(
                    item: item,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [Authorize(Policy = XPolicies.EnabledUser)]
        [HttpPost("Projects/{projectId}/Conversations")]
        public async Task<ActionResult<XAiConversationDto>> CreateConversation(
            [FromRoute] Guid projectId,
            [FromBody] XAiConversationDto item,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (projectId.IsDefaultGuid() ||
                    item.IsNullOrDefault())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                // Update Required Params ...
                item.OwnerId = userInfo.UserId;
                if (!item.IsValidForAddOrUpdate())
                {
                    XException.InvalidData.Throw();
                }

                //
                var result = await aiService.CreateConversation(
                    item: item,
                    projectId: projectId,
                    ownerId: userInfo.UserId,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                //
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Content Extraction ...
        /// <summary>
        /// Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("ExtractContent")]
        [Consumes("multipart/form-data")]
        [Authorize(Policy = XPolicies.EnabledUser)]
        public async Task<ActionResult<string>> ExtractContent(
            [FromForm] IFormFileCollection files,
            [FromForm] string extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Validate ...
                if (!files.HasChild())
                {
                    XException.InvalidArgs.Throw();
                }

                //
                var userInfo = await GetUserInfo();
                var connectionId = GetConnectionId();

                //
                string[] extractorArr = null;
                if (!extractors.IsNullOrEmpty())
                {
                    extractorArr = [.. extractors.ParseListString<string>()];
                }

                //
                var result = await aiService.ExtractContent(
                    files: files,
                    extractors: extractorArr,
                    cancellationToken: cancellationToken
                );

                //
                return Ok(result);
            }
            catch (Exception ex)
            {
                var result = GetExceptionActionResult(ex);
                return result;
            }
        }
        #endregion

        //
        #region Non Actions ...
        /// <summary>
        /// Write Validation Error for Streaming Endpoints (before Stream Starts) ...
        /// </summary>
        /// <returns></returns>
        [NonAction]
        protected async Task WriteStreamValidationError()
        {
            //
            Response.StatusCode = StatusCodes.Status400BadRequest;
            Response.ContentType = "application/json; charset=utf-8";
            await Response.WriteAsync(XException.InvalidArgs.ToXError().ToJSON());
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDatabaseDescriptor.cs

using xAiApi.Constants;
using xDataService.Interfaces;
using xDataService.Models;

namespace xAiApi.Database
{
    /// <summary>
    /// Ai Api Database Descriptor ... 
    /// </summary>
    public class XAiApiDatabaseDescriptor : XDatabaseDescriptor<XAiApiDbContext>, IXDatabaseDescriptor<XAiApiDbContext>
    {
        public XAiApiDatabaseDescriptor() : base(
            name: XAiApiConstants.XAiApiDbIdentifier,
            repositories: []
        )
        {
            OptionsBuilder = b => b.MigrationsAssembly(XAiApiConstants.XAiApiMigrationsAssemblyIdentifier);
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDbContext.cs

using xDataService.Db;
using xAiApi.Constants;
using xAiModels.Providers;
using xTagService.Providers;
using xDataService.Providers;
using xFileService.Providers;
using xStringService.Providers;
using xDataService.Configuration;
using Microsoft.EntityFrameworkCore;

namespace xAiApi.Database
{
    /// <summary>
    /// Db Context of AiApi ...
    /// </summary>
    public class XAiApiDbContext : XDbContext
    {
        //
        #region DbSets ...
        #endregion

        //
        #region Navigation Property Entities ...
        #endregion

        //
        #region Constructor ...
        public XAiApiDbContext(
            DbContextOptions options,
            XDataServiceConfiguration config,
            XEntityRegisterarHandlerService dynamicEntityHandlers
        ) : base(
            config: config,
            options: options,
            database: XAiApiConstants.XAiApiDbIdentifier,
            dynamicEntityHandlers: dynamicEntityHandlers,
            dynamicEntityRegisterarsNames: [
                nameof(XTagEntityRegisterar),
                nameof(XFileEntityRegisterar),
                nameof(XStringEntityRegisterar),
                nameof(XAiVectorEntityRegisterar),
                nameof(XAiMessageEntityRegisterar),
                nameof(XAiProjectEntityRegisterar),
                nameof(XAiMcpServerEntityRegisterar),
                nameof(XAiConversationEntityRegisterar),
            ]
        )
        { }
        #endregion

        //
        #region Overrides ...
        //
        public override void OnXModelCreating(ModelBuilder modelBuilder)
        { }

        //
        public override void OnXConfiguring(DbContextOptionsBuilder optionsBuilder)
        { }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\DI\XDIHelperExtension.cs

using System;
using xAiApi.Constants;
using xAiApi.Providers;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiApi.Middlewares;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiApi.Providers.Extractors;
using xAiApi.Interfaces.Extractors;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace xAiApi.DI
{
    public static partial class XDIHelperExtension
    {
        /// <summary>
        /// Extract AI Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiApiConfiguration GetXAiApiConfiguration(this IConfiguration source)
        {
            //
            XAiApiConfiguration result = null;

            //
            var section = source.GetSection(ConfigurationNodeNames.AI_API_NODE);
            if (!section.IsNull())
            {
                result = section.Get<XAiApiConfiguration>();
            }

            //
            return result;
        }

        /// <summary>
        /// Register AiApi Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiApiConfiguration(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var apiConfig = configuration.GetXAiApiConfiguration();
            source.AddXAiApiConfiguration(apiConfig);
        }

        /// <summary>
        /// Register AiApi Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiApiConfiguration(
            this IServiceCollection source,
            XAiApiConfiguration configuration
        )
        {
            //
            if (!configuration.IsValid())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            source.AddSingleton(configuration);
        }

        /// <summary>
        /// Register Rag Service ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXRagService(
            this IServiceCollection source
        )
        {
            //
            // Persistent RAG (Knowledge over XAiVector Table) ...
            source.AddScoped<IXAiEmbeddingService, XAiEmbeddingService>();         
            source.AddScoped<IXAiRAGService, XAiRAGService>();   
        }

        /// <summary>
        /// Register Ai Services ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiServices(
            this IServiceCollection source
        )
        {
            //
            source.AddScoped<IXAiService, XAiService>();
            source.AddScoped<IXDefaultThinkingAiService, XDefaultThinkingAiService>();
        }

        /// <summary>
        /// Register AiApi File Content Extractor Services ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiFileContentExtractors(
            this IServiceCollection source
        )
        {
            //
            // Register File Content Extractors ...
            source.AddSingleton<IXFileContentExtractorBase, XPdfFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XRtfFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XEpubFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XDocxFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XHtmlFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XCodeFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XImageFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XAudioFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XExcelFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XVisionFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XPlainTextFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XPowerPointFileContentExtractor>();
            source.AddSingleton<IXFileContentExtractorBase, XOpenDocumentFileContentExtractor>();

            //
            source.AddSingleton<IXFileContentExtractor, XFileContentExtractor>();
        }

        /// <summary>
        /// Register AiApi Text Chunker Service ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiTextChunker(
            this IServiceCollection source
        )
        {
            //
            // Stateless -> Singleton ...
            source.AddSingleton<IXTextChunker, XTextChunker>();
        }

        /// <summary>
        /// Register In-Memory Vector Store Service ...
        /// </summary>
        public static void AddXAiInMemoryVectorStore(this IServiceCollection source)
        {
            source.AddSingleton<IXInMemoryVectorStore, XInMemoryVectorStore>();
            source.AddHostedService<XInMemoryVectorStoreCleanupService>();
        }

        /// <summary>
        /// Register all Services Required for Chat With Documents (In-Memory RAG):
        /// Text Chunker + In-Memory Vector Store (+ Cleanup) ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiChatWithDocuments(this IServiceCollection source)
        {
            source.AddXAiInMemoryVectorStore();
        }

        /// <summary>
        /// Use Model Proxy Provider ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseXAiModelProxy(
            this IApplicationBuilder source
        )
        {
            return source.UseMiddleware<XAiModelProxyMiddleware>();
        }

        //
        #region Private ...
        /// <summary>
        /// a LogTag for Service ...
        /// </summary>
        private static string XLogTag = XAiApiConstants.XDILogTag;

        /// <summary>
        /// print a log in Console ...
        /// </summary>
        /// <param name="message"></param>
        private static void Log(string message)
        {
            Console.WriteLine($"{XLogTag} => {message}");
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XModelsExtensions.cs

using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using xAiApi.Models;
using System.Net.Http;
using xAiApi.Constants;
using xAiModels.Models;
using System.Threading;
using System.ClientModel;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using System.ClientModel.Primitives;

namespace xAiApi.Extensions
{
    public static class XModelsExtensions
    {
        /// <summary>
        /// Validate Configurations ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XAiApiConfiguration source)
        {
            //
            var result =
                !source.IsNullOrDefault() &&
                source.Models.HasChild() &&
                source.Models.All(m => m.IsValid()) &&
                source.Prompts.All(m => m.IsValid()) &&
                source.Prompts.Any(p => p.Name
                    .Equals(
                        XAiApiConstants.XAiApiIntroductionPromptName,
                        StringComparison.InvariantCultureIgnoreCase));

            //
            return result;
        }

        /// <summary>
        /// Check TextChunker Descriptor is Valid or not ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XTextChunkerDescriptor source)
        {
            //
            var result =
                source.ChunkSize > 0 &&
                source.ChunkOverlap >= 0 &&
                source.ChunkOverlap < source.ChunkSize &&
                source.MinChunkSize >= 0 &&
                source.MinChunkSize <= source.ChunkSize;

            //
            return result;
        }

        /// <summary>
        /// Check Document Ask Request is Valid or not ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsValid(this XAiDocumentAskRequest source)
        {
            //
            var result =
                !source.IsNullOrDefault() &&
                !source.Prompt.IsNullOrEmpty() &&
                !source.SessionId.IsDefaultGuid();

            //
            return result;
        }

        /// <summary>
        /// Extract Default Model Descriptor ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiModelDescriptor GetDefaultModel(this XAiApiConfiguration source)
        {
            //
            XAiModelDescriptor result = null;

            //
            if (source.IsValid())
            {
                result = source.Models[0];
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve Specified Model from Config ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static XAiModelDescriptor GetModel(
            this XAiApiConfiguration source,
            string name
        )
        {
            //
            XAiModelDescriptor result = null;

            //
            if (source.IsValid())
            {
                //
                if (name.IsNullOrEmpty())
                {
                    result = source.GetDefaultModel();
                }
                else
                {
                    result = source.Models
                        .FirstOrDefault(m => m.Name
                            .Equals(name, System.StringComparison.InvariantCultureIgnoreCase));
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve Introduction Prompt ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiPromptDescriptor GetIntroductionPrompt(this XAiApiConfiguration source)
        {
            //
            XAiPromptDescriptor result = null;

            //
            if (source.IsValid())
            {
                //
                result = source.Prompts
                    .FirstOrDefault(p => p.Name
                        .Equals(
                            XAiApiConstants.XAiApiIntroductionPromptName,
                            System.StringComparison.InvariantCultureIgnoreCase));
            }

            //
            return result;
        }

        /// <summary>
        /// Select Specified Prompts and Parse it's Template
        /// and Generate Message ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <param name="params"></param>
        /// <returns></returns>
        public static string GetPrompt(
            this XAiApiConfiguration source,
            string name = null,
            IDictionary<string, string> @params = null
        )
        {
            //
            var result = string.Empty;

            //
            // Normalize ...
            if (name.IsNullOrEmpty())
            {
                name = XAiApiConstants.XAiApiIntroductionPromptName;
            }

            //
            if (source.IsValid())
            {
                //
                var prompt = source.Prompts
                    .FirstOrDefault(p => p.Name
                        .Equals(
                            name,
                            System.StringComparison.InvariantCultureIgnoreCase
                        )
                    );
                if (!prompt.IsNullOrDefault())
                {
                    //
                    result = prompt.Template;

                    //
                    // Handle Params ...
                    if (!@params.IsNullOrDefault() && @params.HasChild())
                    {
                        //
                        // Select Params ...
                        var existsParams = prompt.Params
                            .Where(p => @params.Any(pr => pr.Key == p.Name))
                            .Distinct()
                            .ToList();

                        //
                        // Replace Selected Params ...
                        existsParams
                            .ForEach(pk =>
                            {
                                result = result.Replace(pk.Param, @params[pk.Name]);
                            });
                    }
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Provide HttpClient for Common Usages ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static HttpClient GetHttpClient(this string source)
        {
            //
            var result = new HttpClient
            {
                //
                // Disable timeout completely (not recommended for production)
                Timeout = Timeout.InfiniteTimeSpan,

                //
                BaseAddress = source.IsNullOrEmpty()
                    ? null
                    : new Uri(source),

                //
                // OR set a very long timeout (e.g., 30 minutes for large file uploads)
                // Timeout = TimeSpan.FromMinutes(30)
            };

            //
            return result;
        }

        /// <summary>
        /// Instance and Retrieve Chat Client ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IChatClient GetClient(this XAiModelDescriptor source)
        {
            //
            // Try to Initialize LLm ...
            var model = source.LLM;
            var apiKey = source.ApiKey;
            var url = new Uri(source.Url);
            var httpClient = source.Url.GetHttpClient();

            //
            IChatClient result = null;
            switch (source.Provider)
            {
                //
                case XAiModelProviderType.Ollama:
                    //
                    // Instance Ollama Client using Custom HttpCLient ...
                    var ollamaClient = new OllamaApiClient(httpClient, model);
                    result =
                        new ChatClientBuilder(ollamaClient)
                        .UseFunctionInvocation()
                        .Build();
                    break;

                //
                case XAiModelProviderType.OpenAI:
                    //
                    // Instance Ollama Client using Custom HttpCLient ...
                    var openAiClient = new OpenAIClient(
                        new ApiKeyCredential(apiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : apiKey),
                        new OpenAIClientOptions
                        {
                            Endpoint = url,
                            Transport = new HttpClientPipelineTransport(httpClient)
                        }
                    );
                    result =
                        new ChatClientBuilder(
                            openAiClient
                            .GetChatClient(model)
                        .AsIChatClient())
                        .UseFunctionInvocation()
                        .Build();
                    break;

                //
                case XAiModelProviderType.DeepSeek:
                    break;

                //
                case XAiModelProviderType.HuggingFace:
                    break;

                //
                default:
                    break;
            }

            //
            if (result.IsNullOrDefault())
            {
                XException.InvalidData.Throw();
            }

            //
            return result;
        }

        // public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
        // {
        //     //
        //     var result = new List<AITool>();

        //     //
        //     foreach (var tool in source)
        //     {
        //         //
        //         var declaration = AIFunctionFactory.CreateDeclaration(
        //             name: tool.Name,
        //             jsonSchema: tool.InputSchema,
        //             description: tool.Description
        //         );

        //         //
        //         result.Add(declaration);
        //     }

        //     //
        //     return result;            
        // }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs

using System.Linq;
using xIdentityHelper;
using xAiApi.Providers;
using xAiApi.Interfaces;
using xCommons.Extensions;
using xCommons.Authorization;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;

namespace xAiApi.Extensions
{
    public static class XProgramExtensions
    {
        /// <summary>
        /// Register MCP Server Provider ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiMcpServerProvider(
            this IServiceCollection source
        )
        {
            source.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();
        }

        /// <summary>
        /// Register Authorization Policies
        /// </summary>
        /// <param name="services"></param>
        /// <param name="policies"></param>
        public static void AddXAuthorization(
            this IServiceCollection services,
            IDictionary<string, AuthorizationPolicy> policies = null
        )
        {
            //
            var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
            services.AddAuthorization(options =>
            {
                //
                if (!policies.IsNull())
                {
                    //
                    // Fill Policies ...
                    using (var policiesEnumerator = policies.GetEnumerator())
                    {
                        while (policiesEnumerator.MoveNext())
                        {
                            var policyDescriptor = policiesEnumerator.Current;
                            options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);

                            //
                            // Add Policy to Policy Handler ...
                            if (!policyHandler.IsNull())
                            {
                                //
                                // Check Policy is RequiredRole Policy ...
                                var roleRequirements = policyDescriptor.Value.Requirements
                                    .OfType<RequiredRolesRequirement>()
                                    .FirstOrDefault();
                                if (!roleRequirements.IsNull() && 
                                    roleRequirements.Roles.HasChild())
                                {
                                    //
                                    policyHandler.AddPolicy(
                                        policy: policyDescriptor.Key.ToNormalString(),
                                        requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
                                    );
                                }
                            }
                        }
                    }
                }

                //
                var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies();
                if (!xPolicies.IsNull())
                {
                    //
                    // Fill Policies ...
                    using (var policiesEnumerator = xPolicies.GetEnumerator())
                    {
                        while (policiesEnumerator.MoveNext())
                        {
                            //
                            var policyDescriptor = policiesEnumerator.Current;

                            //
                            // Add Policy to Authorization ...
                            options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);

                            //
                            // Add Policy to Policy Handler ...
                            if (!policyHandler.IsNull())
                            {
                                //
                                // Check Policy is RequiredRole Policy ...
                                var roleRequirements = policyDescriptor.Value.Requirements
                                    .OfType<RequiredRolesRequirement>()
                                    .FirstOrDefault();
                                if (!roleRequirements.IsNull() && 
                                    roleRequirements.Roles.HasChild())
                                {
                                    //
                                    policyHandler.AddPolicy(
                                        policy: policyDescriptor.Key.ToNormalString(),
                                        requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
                                    );
                                }
                            }
                        }
                    }
                }
            });

            //
            services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>();
        }

        /// <summary>
        /// Use Forward Headers Options for resolving behind a proxy issues ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void UseXForwardOptions(this IApplicationBuilder source)
        {
            //
            var forwardOptions = new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                RequireHeaderSymmetry = false
            };

            //
            forwardOptions.KnownNetworks.Clear();
            forwardOptions.KnownProxies.Clear();

            //
            // ref: https://github.com/aspnet/Docs/issues/2384
            source.UseForwardedHeaders(forwardOptions);
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingService.cs

namespace xAiApi.Interfaces
{
    public interface IXAiEmbeddingService : IXAiEmbeddingServiceBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiEmbeddingServiceBase.cs

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Base Embedding Provider Service ...
    /// </summary>
    public interface IXAiEmbeddingServiceBase // : IXAiServiceBase
    {
        /// <summary>
        /// Embedding Specified String ...
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<float[]> Embedding(
            string content,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embedding Specified Batch ...
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IReadOnlyList<float[]>> Embeddings(
            string[] batch,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embedding Generator ...
        /// </summary>
        /// <returns></returns>
        IEmbeddingGenerator<string, Embedding<float>> GetEmbeddingGenerator();
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiMcpServerProvider.cs

using System;
using xModels.Dtos;
using System.Threading;
using xAiModels.Models.Dtos;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Linq.Expressions;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// MCP Manager / Provider ...
    /// </summary>
    public interface IXAiMcpServerProvider
    {
        //
        #region Manager ...
        /// <summary>
        /// Get a List Of Available Tools which Provided using registered Mcp Servers ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<AITool>> GetAvailableToolsAsync(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Test Specified Mcp Server ...
        /// </summary>
        /// <param name="server"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> TestServerAsync(
            XAiMcpServerDto server,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Force Refresh Mcp Servers ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task RefreshAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );        
        #endregion

        //
        #region Actions ...
        /// <summary>
        /// Add an Mcp Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> AddMcpServer(
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Get an Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> GetMcpServer(
            Guid id,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Update Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> UpdateMcpServer(
            Guid id,
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Remove Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> RemoveMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Disable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> DisableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Enable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> EnableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Toggle Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<bool> ToggleMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Retrieve all Mcp Server ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMcpServerDto>> GetAll(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Find Specified Mcp Server ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMcpServerDto> FindOne(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Find a Collection of Specified Mcp Servers ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMcpServerDto>> FindMany(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Registered Mcp Servers ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiMcpServerDto>> Query(
            XQuery query,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiRAGService.cs

using xAiApi.Models;
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Persistent RAG Service over XAiVector Table:
    /// Ingest (Extract -> Chunk -> Embed -> Store) and Ask (Embed -> Search -> Generate) ...
    /// Isolation is Scope Based (Conversation / Project / User / Global) ...
    /// </summary>
    public interface IXAiRAGService
    {
        /// <summary>
        /// Ingest Files into Specified Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store (XAiVector) ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="replaceExisting"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiKnowledgeIngestResult> IngestAsync(
            IFormFileCollection files,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            bool replaceExisting = true,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<XAiVectorSearchResult>> RetrieveAsync(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// List Ingested Documents of Specified Scope ...
        /// </summary>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Remove All Vectors of a Document in Specified Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope">Target Scope (Null = User Scope)</param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        Task<int> RemoveDocumentAsync(
            string fileName,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
        /// Idempotent: Returns 0 when Nothing Left to Migrate ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Migrated Vectors</returns>
        Task<int> MigrateLegacyVectorsAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        );
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiService.cs

namespace xAiApi.Interfaces
{
    public interface IXAiService : IXAiServiceBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiServiceBase.cs

using System;
using xModels.Dtos;
using System.Threading;
using xAiModels.Models;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.Extensions.AI;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// Describe a Base Service Actions of any Ai Based Services ...
    /// </summary>
    public interface IXAiServiceBase : IDisposable
    {
        /// <summary>
        /// Chat Options ...
        /// </summary>
        ChatOptions Options { get; }

        /// <summary>
        /// Descriptor of Models which used in Service ...
        /// </summary>
        XAiModelDescriptor Descriptor { get; }

        //
        #region Actions ...
        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextAsync(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextAsEnumerable(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Providing Vector Search Result ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextByContextAsync(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By By Providing Vector Search Result and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextByContextAsEnumerable(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> AskTextFromKnowledgeAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiMessageDto> AskAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Loaders ...
        /// <summary>
        /// Load AI Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiProjectDto>> LoadProjects(
            string ownerId,
            string connectionId = null,
            bool includeDefaults = false,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Load Conversations of Specified AI Project ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiConversationDto>> LoadConversations(
            Guid projectId,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Load Messages of Specified Conversation ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<XAiMessageDto>> LoadMessages(
            Guid conversationId,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiProjectDto>> QueryProjects(
            string ownerId,
            XQuery query,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiConversationDto>> QueryConversations(
            string ownerId,
            Guid projectId,
            XQuery query,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XQueryResult<XAiMessageDto>> QueryMessages(
            string ownerId,
            Guid conversationId,
            XQuery query,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Creators ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiProjectDto> CreateProject(
            string ownerId,
            XAiProjectDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XAiConversationDto> CreateConversation(
            string ownerId,
            Guid projectId,
            XAiConversationDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        );
        #endregion

        //
        #region Content Extraction ...
        /// <summary>
        /// Try to Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> ExtractContent(
            IFormFileCollection files,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXDefaultThinkingAiService.cs

namespace xAiApi.Interfaces
{
    public interface IXDefaultThinkingAiService: IXAiServiceBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXInMemoryVectorStore.cs

using System;
using xAiApi.Models;
using xAiModels.Models.Dtos;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    public interface IXInMemoryVectorStore
    {
        int Count { get; }
        int RemoveExpired();
        Guid CreateSession(
            string ownerId = null, 
            TimeSpan? ttl = null
        );
        Guid CreateSession(
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null, 
            TimeSpan? ttl = null
        );
        bool Replace(
            Guid sessionId, 
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null
        );
        bool Add(
            Guid sessionId, 
            IEnumerable<XAiVectorDto> vectors, 
            string ownerId = null
        );
        IList<XAiVectorSearchResult> Search(
            Guid sessionId, 
            ReadOnlyMemory<float> queryEmbedding, 
            int topK = 5, 
            float minScore = 0f, 
            string ownerId = null
        );
        bool TryGet(
            Guid sessionId, 
            out XAiDocumentSession session, 
            string ownerId = null
        );
        bool Remove(
            Guid sessionId, 
            string ownerId = null
        );
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXTextChunker.cs

using xAiApi.Models;
using System.Collections.Generic;

namespace xAiApi.Interfaces
{
    /// <summary>
    /// a Service for Splitting Long Texts into Overlapping Chunks
    /// which Suitable for Embedding ...
    /// </summary>
    public interface IXTextChunker
    {
        /// <summary>
        /// Split Text into Chunks ...
        /// </summary>
        /// <param name="text">Source Text</param>
        /// <param name="source">Source Name (e.g. File Name) used for Identifier</param>
        /// <returns></returns>
        IList<XTextChunk> Chunk(
            string text,
            string source = null
        );

        /// <summary>
        /// Split Text into Chunks and Return only Texts ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        IList<string> ChunkTexts(
            string text
        );
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXAudioFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXAudioFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXCodeFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary> 
    /// Extractor for source code files ...
    /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) 
    /// </summary> 
    public interface IXCodeFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXDocxFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXDocxFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXEpubFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for EPUB electronic publication format
    /// (application/epub+zip)
    /// </summary>
    public interface IXEpubFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXExcelFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXExcelFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXFileContentExtractor.cs

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using xAiModels.Models;

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// a Base Service for Extracting File Content ...
    /// </summary>
    public interface IXFileContentExtractorBase
    {
        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        bool CanExtract(string mimeType);

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        );
    }

    /// <summary>
    /// a Service for Extracting File Content ...
    /// </summary>
    public interface IXFileContentExtractor
    {
        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <returns></returns>
        bool CanExtract(
            string mimeType,
            string[] extractors = null
        );

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        );

    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXHtmlFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for HTML documents (text/html, application/xhtml+xml)
    /// </summary>
    public interface IXHtmlFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXImageFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXImageFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXOpenDocumentFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for OpenDocument Format (ODF) documents
    /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
    /// </summary>
    public interface IXOpenDocumentFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPdfFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXPdfFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPlainTextFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXPlainTextFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXPowerPointFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for all PowerPoint Presentation formats
    /// (OpenXML: pptx, ppsx, potx, pptm, ppsm, potm | Legacy Binary: ppt, pps, pot)
    /// </summary>
    public interface IXPowerPointFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXRtfFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    /// <summary>
    /// Extractor for Rich Text Format (RTF) documents
    /// (application/rtf, text/rtf)
    /// </summary>
    public interface IXRtfFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\Extractors\IXVisionFileContentExtractor.cs

namespace xAiApi.Interfaces.Extractors
{
    public interface IXVisionFileContentExtractor : IXFileContentExtractorBase
    { }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Middlewares\XAiModelProxyMiddleware.cs

using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading;
using xAiApi.Extensions;
using xCommons.Constants;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using xIdentityService.Constants;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using Microsoft.Extensions.Logging;
using xExceptions.Constants;
using xIdentityModels.Models;
using xIdentityModels.Constants;

namespace xAiApi.Middlewares
{
    public class XAiModelProxyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly XAiApiConfiguration configuration;
        private readonly IHttpClientFactory httpClientFactory;
        private readonly ILogger<XAiModelProxyMiddleware> logger;

        public XAiModelProxyMiddleware(
            RequestDelegate next,
            XAiApiConfiguration configuration,
            IHttpClientFactory httpClientFactory,
            ILogger<XAiModelProxyMiddleware> logger
        )
        {
            //
            this.next = next;
            this.logger = logger;
            this.configuration = configuration;
            this.httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// Handle Routing ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(
            HttpContext context,
            IXIdentityProvider identityProvider
        )
        {
            //
            // Validate ...
            var isValid =
                !configuration.IsNull() &&
                !configuration.ProxyConfiguration.IsNull() &&
                configuration.ProxyConfiguration.Enabled &&
                !configuration.ProxyConfiguration.RoutePrefix.IsNullOrEmpty() &&
                context.Request.Path.StartsWithSegments(configuration.ProxyConfiguration.RoutePrefix, out var remaining);
            if (!isValid)
            {
                //
                await next(context);
                return;
            }

            //
            // Validating Segment ...
            var rawSegments = remaining.Value?
                .Trim('/')
                .Split('/', StringSplitOptions.RemoveEmptyEntries);
            if (!rawSegments.HasChild())
            {
                //
                await next(context);
                return;
            }

            //
            // Extract Model Name and Retrieve Model Descriptor and do Validation ...
            var modelName = Uri.UnescapeDataString(rawSegments[0]);
            var descriptor = configuration.GetModel(modelName);
            if (!descriptor.IsValid())
            {
                //
                // Handle Error ...
                await context.Response.WriteJsonAsync(
                    status: HttpStatusCode.NotFound,
                    data: new
                    {
                        error = $"Model '{modelName}' is not configured."
                    }
                );
                return;
            }

            //
            var errorMessages = new string[] { };
            var apiKey = context.ExtractApiKey();
            var clientIP = context.Request.ExtractClientIP();
            var tokenModel = await context.RetrieveTokensAsXTokenResponse();
            var isAuthenticated =
                //
                (!apiKey.IsNullOrEmpty()) ||
                //
                (!tokenModel.IsNull() && !tokenModel.AccessToken.IsNullOrEmpty())
                ;
            if (isAuthenticated)
            {
                //
                // Handle Authentication ...
                if (!apiKey.IsNullOrEmpty())
                {
                    //
                    // Try to Validate Api Key ...
                    var validationResult = await identityProvider.ValidateApiKey(
                        request: new XApiKeyValidationRequest
                        {
                            ApiKey = apiKey,
                            ClientIP = clientIP,
                            RequiredScope = XApiKeyScope.Read.GetStringValue()
                        }
                    );
                    isAuthenticated = !validationResult.Errors.HasChild();
                    if (!isAuthenticated)
                    {
                        errorMessages = [.. errorMessages, .. validationResult.Errors];
                    }
                }
                else if (!tokenModel.IsNullOrDefault())
                {
                    //
                    // Try To Validate Token ...
                    var validationResult = await identityProvider.Validate(tokenModel);
                    isAuthenticated = !validationResult.IsError;
                    if (!isAuthenticated)
                    {
                        errorMessages = [..errorMessages, validationResult.Error];
                    }
                }
                else
                {
                    isAuthenticated = false;
                }
            }
            if (!isAuthenticated)
            {
                //
                var error = XException.NotAuthorized.ToXError();
                error.Message = $"{error.Message}: {errorMessages.ToListString(',')}";
                await context.Response.WriteJsonAsync(
                    status: HttpStatusCode.Unauthorized,
                    data: error
                );
                return;
            }

            //
            var suffixPath = Uri.UnescapeDataString(string.Join('/', rawSegments.Skip(1)));
            var targetUri = BuildTargetUri(
                descriptor.Url,
                suffixPath,
                context.Request.QueryString
            );

            //
            // Collect Headers which need to Except ...
            var exceptionHeaders = new string[]
            {
                XAuthorization.Header,
                XAuthorization.ExpiresAt,
                XAuthorization.XPoweredBy,
                XAuthorization.AccessToken,
                XAuthorization.RefreshToken,
                XHeader.ApiKey.GetStringValue(),
                XAuthorization.AccessTokenExpired,
                XHeader.ConnectionId.GetStringValue(),
                XHeader.ChecksumDigest.GetStringValue(),
            };

            //
            using var upstreamRequest = new HttpRequestMessage(
                new HttpMethod(context.Request.Method),
                targetUri
            );

            //
            context.CopyRequestHeaders(
                dest: upstreamRequest,
                exceptions: exceptionHeaders
            );

            //
            if (
                context.Request.ContentLength > 0 ||
                context.Request.Headers.ContainsKey(HeaderNames.TransferEncoding)
            )
            {
                //
                context.Request.EnableBuffering();
                using var reader = new StreamReader(
                    context.Request.Body,
                    Encoding.UTF8,
                    detectEncodingFromByteOrderMarks: true,
                    bufferSize: 1024,
                    leaveOpen: true
                );
                var bodyText = await reader.ReadToEndAsync();
                var actualLength = Encoding.UTF8.GetByteCount(bodyText);
                var declaredLength = context.Request.ContentLength;
                var contentType = context.Request.ContentType ?? "application/octet-stream";
                var mediaType = contentType.Split(';')[0].Trim();
                upstreamRequest.Content = new StringContent(
                    bodyText,
                    Encoding.UTF8,
                    mediaType
                );
                context.Request.Body.Position = 0;
                context.CopyRequestHeaders(
                    dest: upstreamRequest.Content,
                    exceptions: exceptionHeaders
                );
            }

            //
            // Handle Api Key of LLM ...
            descriptor.AddModelDescriptorApiKey(
                request: upstreamRequest
            );

            //
            try
            {
                //
                var client = httpClientFactory.CreateClient("XAiModelProxy");
                client.Timeout = Timeout.InfiniteTimeSpan;

                //
                using var upstreamResponse = await client.SendAsync(
                    upstreamRequest,
                    HttpCompletionOption.ResponseHeadersRead,
                    context.RequestAborted
                );

                //
                context.Response.StatusCode = (int)upstreamResponse.StatusCode;

                //
                upstreamResponse.CopyHeaders(
                    response: context.Response,
                    exceptions: exceptionHeaders
                );

                //
                await using var responseStream = await upstreamResponse.Content
                    .ReadAsStreamAsync();
                await responseStream.CopyToAsync(
                    context.Response.Body,
                    context.RequestAborted
                );
            }
            catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
            { }
            catch (Exception ex)
            {
                //
                logger.LogError(ex, "Proxy failed for model {ModelName}", modelName);
                if (!context.Response.HasStarted)
                {
                    //
                    // Handle Error ...
                    var error = XException.ActionFailed.ToXError();
                    error.Message = $"{error.Message}: {ex.Message}";
                    await context.Response.WriteJsonAsync(
                        status: HttpStatusCode.BadGateway,
                        data: error
                    );
                }
            }
        }

        //
        #region Private ...
        private static Uri BuildTargetUri(
            string baseUrl,
            string suffixPath,
            QueryString query
        )
        {
            //
            var baseUri = new Uri(baseUrl, UriKind.Absolute);
            var builder = new UriBuilder(baseUri);
            var basePath = builder.Path.TrimEnd('/');

            //
            builder.Path = suffixPath.IsNullOrEmpty()
                ? basePath
                : $"{basePath}/{suffixPath.TrimStart('/')}";

            //
            builder.Query = query.HasValue
                ? query.Value.TrimStart('?')
                : string.Empty;

            //
            return builder.Uri;
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.cs

using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace xAiApi.Migrations
{
    public partial class InitialMigrationAiApi : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "AiConversations",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Title = table.Column<string>(maxLength: 255, nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false),
                    ProjectId = table.Column<Guid>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiConversations", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiMcpServers",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Scope = table.Column<int>(nullable: false),
                    Name = table.Column<string>(maxLength: 255, nullable: false),
                    Description = table.Column<string>(maxLength: 1000, nullable: true),
                    Enabled = table.Column<bool>(nullable: false),
                    EnvironmentVariables = table.Column<string>(nullable: true),
                    Endpoint = table.Column<string>(maxLength: 1000, nullable: true),
                    Headers = table.Column<string>(nullable: true),
                    TimeoutSeconds = table.Column<int>(nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiMcpServers", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiMessages",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Content = table.Column<string>(nullable: false),
                    Role = table.Column<int>(nullable: false),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false),
                    ConversationId = table.Column<Guid>(maxLength: 255, nullable: false),
                    MetaDatas = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiMessages", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiProjects",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Title = table.Column<string>(maxLength: 255, nullable: false),
                    Description = table.Column<string>(maxLength: 1000, nullable: true),
                    Prompt = table.Column<string>(nullable: true),
                    CreatedOn = table.Column<DateTime>(nullable: false),
                    UpdatedAt = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiProjects", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AiVectors",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    Text = table.Column<string>(nullable: true),
                    Identifier = table.Column<string>(nullable: true),
                    Type = table.Column<string>(maxLength: 100, nullable: true),
                    Embedding = table.Column<string>(nullable: true),
                    Metadata = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AiVectors", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Files",
                columns: table => new
                {
                    Id = table.Column<Guid>(nullable: false),
                    Deleted = table.Column<bool>(nullable: false),
                    Type = table.Column<int>(nullable: false),
                    OwnerId = table.Column<string>(maxLength: 255, nullable: false),
                    Name = table.Column<string>(maxLength: 255, nullable: false),
                    Path = table.Column<string>(nullable: false),
                    Thumb = table.Column<string>(nullable: true),
                    ThumbPath = table.Column<string>(nullable: true),
                    UploadedOn = table.Column<DateTime>(nullable: false),
                    FileName = table.Column<string>(nullable: true),
                    References = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Files", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Strings",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Deleted = table.Column<bool>(nullable: false),
                    Language = table.Column<string>(maxLength: 10, nullable: false),
                    ResourceTitle = table.Column<string>(maxLength: 255, nullable: false),
                    TranslatedValue = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Strings", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Tags",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Deleted = table.Column<bool>(nullable: false),
                    Tag = table.Column<string>(maxLength: 255, nullable: false),
                    References = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Tags", x => x.Id);
                });

            migrationBuilder.CreateIndex(
                name: "IX_AiVectors_Identifier",
                table: "AiVectors",
                column: "Identifier");

            migrationBuilder.CreateIndex(
                name: "IX_AiVectors_Type",
                table: "AiVectors",
                column: "Type");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "AiConversations");

            migrationBuilder.DropTable(
                name: "AiMcpServers");

            migrationBuilder.DropTable(
                name: "AiMessages");

            migrationBuilder.DropTable(
                name: "AiProjects");

            migrationBuilder.DropTable(
                name: "AiVectors");

            migrationBuilder.DropTable(
                name: "Files");

            migrationBuilder.DropTable(
                name: "Strings");

            migrationBuilder.DropTable(
                name: "Tags");
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.Designer.cs

// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using xAiApi.Database;

namespace xAiApi.Migrations
{
    [DbContext(typeof(XAiApiDbContext))]
    [Migration("20261104052650_InitialMigrationAiApi")]
    partial class InitialMigrationAiApi
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.14");

            modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<Guid>("ProjectId")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiConversations");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<bool>("Enabled")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Endpoint")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("EnvironmentVariables")
                        .HasColumnType("TEXT");

                    b.Property<string>("Headers")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Scope")
                        .HasColumnType("INTEGER");

                    b.Property<int>("TimeoutSeconds")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMcpServers");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<string>("Content")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<Guid>("ConversationId")
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("MetaDatas")
                        .HasColumnType("TEXT");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Role")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMessages");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Prompt")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiProjects");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Embedding")
                        .HasColumnType("TEXT");

                    b.Property<string>("Identifier")
                        .HasColumnType("TEXT");

                    b.Property<string>("Metadata")
                        .HasColumnType("TEXT");

                    b.Property<string>("Text")
                        .HasColumnType("TEXT");

                    b.Property<string>("Type")
                        .HasColumnType("TEXT")
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.HasIndex("Identifier");

                    b.HasIndex("Type");

                    b.ToTable("AiVectors");
                });

            modelBuilder.Entity("xFileService.Models.Entities.XFile", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("FileName")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Path")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Thumb")
                        .HasColumnType("TEXT");

                    b.Property<string>("ThumbPath")
                        .HasColumnType("TEXT");

                    b.Property<int>("Type")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UploadedOn")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Files");
                });

            modelBuilder.Entity("xStringService.Models.Entities.XString", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Language")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(10);

                    b.Property<string>("ResourceTitle")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("TranslatedValue")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Strings");
                });

            modelBuilder.Entity("xTagService.Models.Entities.XTag", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Tag")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });
#pragma warning restore 612, 618
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\XAiApiDbContextModelSnapshot.cs

// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using xAiApi.Database;

namespace xAiApi.Migrations
{
    [DbContext(typeof(XAiApiDbContext))]
    partial class XAiApiDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.14");

            modelBuilder.Entity("xAiModels.Models.Entities.XAiConversation", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<Guid>("ProjectId")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiConversations");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<bool>("Enabled")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Endpoint")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("EnvironmentVariables")
                        .HasColumnType("TEXT");

                    b.Property<string>("Headers")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Scope")
                        .HasColumnType("INTEGER");

                    b.Property<int>("TimeoutSeconds")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMcpServers");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<string>("Content")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<Guid>("ConversationId")
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("MetaDatas")
                        .HasColumnType("TEXT");

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<int>("Role")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiMessages");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiProject", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<DateTime>("CreatedOn")
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Description")
                        .HasColumnType("TEXT")
                        .HasMaxLength(1000);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Prompt")
                        .HasColumnType("TEXT");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<DateTime>("UpdatedAt")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("AiProjects");
                });

            modelBuilder.Entity("xAiModels.Models.Entities.XAiVector", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Embedding")
                        .HasColumnType("TEXT");

                    b.Property<string>("Identifier")
                        .HasColumnType("TEXT");

                    b.Property<string>("Metadata")
                        .HasColumnType("TEXT");

                    b.Property<string>("Text")
                        .HasColumnType("TEXT");

                    b.Property<string>("Type")
                        .HasColumnType("TEXT")
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.HasIndex("Identifier");

                    b.HasIndex("Type");

                    b.ToTable("AiVectors");
                });

            modelBuilder.Entity("xFileService.Models.Entities.XFile", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("TEXT");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("FileName")
                        .HasColumnType("TEXT");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("OwnerId")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("Path")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Thumb")
                        .HasColumnType("TEXT");

                    b.Property<string>("ThumbPath")
                        .HasColumnType("TEXT");

                    b.Property<int>("Type")
                        .HasColumnType("INTEGER");

                    b.Property<DateTime>("UploadedOn")
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Files");
                });

            modelBuilder.Entity("xStringService.Models.Entities.XString", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("Language")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(10);

                    b.Property<string>("ResourceTitle")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.Property<string>("TranslatedValue")
                        .IsRequired()
                        .HasColumnType("TEXT");

                    b.HasKey("Id");

                    b.ToTable("Strings");
                });

            modelBuilder.Entity("xTagService.Models.Entities.XTag", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("INTEGER");

                    b.Property<bool>("Deleted")
                        .HasColumnType("INTEGER");

                    b.Property<string>("References")
                        .HasColumnType("TEXT");

                    b.Property<string>("Tag")
                        .IsRequired()
                        .HasColumnType("TEXT")
                        .HasMaxLength(255);

                    b.HasKey("Id");

                    b.ToTable("Tags");
                });
#pragma warning restore 612, 618
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentModels.cs

using System;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// Result of Ingesting Documents into an In-Memory Session ...
    /// </summary>
    public class XAiDocumentIngestResult
    {
        /// <summary>
        /// Session Identifier which must be used in Ask Requests ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// Count of Successfully Processed Files ...
        /// </summary>
        public int FilesCount { get; set; }

        /// <summary>
        /// Count of Chunks (Vectors) Added to Session ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Total Vectors Count in Session after Ingest ...
        /// </summary>
        public int TotalVectorsCount { get; set; }

        /// <summary>
        /// Files which Skipped (Unsupported / Empty / Failed) ...
        /// </summary>
        public IList<string> SkippedFiles { get; set; } = new List<string>();

        /// <summary>
        /// Session Expiration Time (UTC) based on Last Access ...
        /// </summary>
        public DateTime ExpiresAtUtc { get; set; }
    }

    /// <summary>
    /// Request for Asking a Question over Ingested Documents ...
    /// </summary>
    public class XAiDocumentAskRequest
    {
        /// <summary>
        /// Session Identifier ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// User Question ...
        /// </summary>
        public string Prompt { get; set; }

        /// <summary>
        /// Count of Top Chunks used as Context (Optional) ...
        /// </summary>
        public int? TopK { get; set; }

        /// <summary>
        /// Minimum Similarity Score of Chunks (Optional) ...
        /// </summary>
        public float? MinScore { get; set; }
    }

    /// <summary>
    /// a Source Chunk which used for Generating Answer ...
    /// </summary>
    public class XAiDocumentSource
    {
        /// <summary>
        /// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
        /// </summary>
        public string Identifier { get; set; }

        /// <summary>
        /// Source File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Chunk Index in Source File ...
        /// </summary>
        public int? ChunkIndex { get; set; }

        /// <summary>
        /// Similarity Score ...
        /// </summary>
        public float Score { get; set; }

        /// <summary>
        /// Short Snippet of Chunk Text ...
        /// </summary>
        public string Snippet { get; set; }

        /// <summary>
        /// Knowledge Scope the Chunk Retrieved from (Null for Session Based Documents) ...
        /// </summary>
        public string Scope { get; set; }

        /// <summary>
        /// Knowledge Type of the Chunk ...
        /// </summary>
        public string Type { get; set; }
    }

    /// <summary>
    /// Answer of a Chat With Documents Request ...
    /// </summary>
    public class XAiDocumentAnswer
    {
        /// <summary>
        /// Session Identifier ...
        /// </summary>
        public Guid SessionId { get; set; }

        /// <summary>
        /// Generated Answer ...
        /// </summary>
        public string Answer { get; set; }

        /// <summary>
        /// True when no Relevant Chunk Found in Session ...
        /// </summary>
        public bool NoContextFound { get; set; }

        /// <summary>
        /// Sources used for Generating Answer ...
        /// </summary>
        public IList<XAiDocumentSource> Sources { get; set; } = new List<XAiDocumentSource>();
    }

    /// <summary>
    /// Streaming Chunk of a Chat With Documents Answer ...
    /// </summary>
    public class XAiDocumentAnswerChunk
    {
        /// <summary>
        /// Text Delta ...
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// True for Last Chunk ...
        /// </summary>
        public bool IsFinal { get; set; }

        /// <summary>
        /// True when no Relevant Chunk Found in Session ...
        /// </summary>
        public bool NoContextFound { get; set; }

        /// <summary>
        /// Sources (Only Filled in First Chunk) ...
        /// </summary>
        public IList<XAiDocumentSource> Sources { get; set; }
    }

    /// <summary>
    /// Public Info of a Document Session (without Embeddings) ...
    /// </summary>
    public class XAiDocumentSessionInfo
    {
        public Guid Id { get; set; }
        public TimeSpan Ttl { get; set; }
        public int VectorsCount { get; set; }
        public DateTime CreatedAtUtc { get; set; }
        public DateTime LastAccessAtUtc { get; set; }
        public DateTime ExpiresAtUtc { get; set; }
        public IList<string> Files { get; set; } = new List<string>();
    }

    /// <summary>
    /// Document RAG Configuration ...
    /// </summary>
    public class XAiDocumentRAGDescriptor
    {
        public int MaxTopK { get; set; } = 20;
        public int DefaultTopK { get; set; } = 5;
        public int DefaultTtlMinutes { get; set; } = 30;
        public int EmbeddingBatchSize { get; set; } = 32;
        public int SourceSnippetLength { get; set; } = 200;
        public float DefaultMinScore { get; set; } = 0.35f;
        public string MetadataFileName { get; set; } = "fileName";
        public string MetadataMimeType { get; set; } = "mimeType";
        public string PromptName { get; set; } = "ChatWithDocuments";
        public string MetadataChunkIndex { get; set; } = "chunkIndex";

        //
        // Knowledge (Persistent RAG) Limits ...
        /// <summary>
        /// Max Files Accepted in a Single Ingest Request (0 = Unlimited) ...
        /// </summary>
        public int MaxFilesPerIngest { get; set; } = 20;

        /// <summary>
        /// Max Size of a Single File in Bytes (0 = Unlimited) ...
        /// </summary>
        public long MaxFileSizeBytes { get; set; } = 25 * 1024 * 1024;

        /// <summary>
        /// Max Distinct Documents Allowed in a Non-Global Scope (0 = Unlimited) ...
        /// </summary>
        public int MaxDocumentsPerScope { get; set; } = 50;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiDocumentSession.cs

using System;
using xAiModels.Models.Dtos;
using System.Collections.Generic;

namespace xAiApi.Models
{
    public class XAiDocumentSession
    {
        public Guid Id { get; set; }
        public TimeSpan Ttl { get; set; }
        public string OwnerId { get; set; }
        public DateTime CreatedAtUtc { get; set; }
        public DateTime LastAccessAtUtc { get; set; }
        internal object SyncRoot { get; } = new object();
        public IList<XAiVectorDto> Vectors { get; set; } = new List<XAiVectorDto>();
        public bool IsExpired(DateTime utcNow) { return utcNow - LastAccessAtUtc >= Ttl; }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiKnowledgeModels.cs

using System;
using xAiModels.Constants;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// Describes Target Knowledge Base Scope of an Operation ...
    /// </summary>
    public class XAiKnowledgeScopeDescriptor
    {
        /// <summary>
        /// Scope Kind ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; } = XAiKnowledgeScope.User;

        /// <summary>
        /// Scope Identifier (ProjectId / ConversationId) - Null for Global and User ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Optional Knowledge Type / Domain Filter ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Create User Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor User(
            string type = null
        ) => new()
        {
            //
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = null,
            Scope = XAiKnowledgeScope.User,
        };
        
        /// <summary>
        /// Create Global Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Global(
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = null,
            Scope = XAiKnowledgeScope.Global,
        };
        
        /// <summary>
        /// Create Project Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Project(
            Guid projectId, 
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = projectId,
            Scope = XAiKnowledgeScope.Project,
        };
        
        /// <summary>
        /// Create Conversational Scope Knowledge Descriptor ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static XAiKnowledgeScopeDescriptor Conversation(
            Guid conversationId, 
            string type = null
        ) => new()
        {
            Type = type ?? XAiModelsConstants.XAiDefaultKnowledgeType,
            ScopeId = conversationId,
            Scope = XAiKnowledgeScope.Conversation,
        };
    }

    /// <summary>
    /// Result of Ingesting Files into Persistent Knowledge Base (XAiVector Table) ...
    /// </summary>
    public class XAiKnowledgeIngestResult
    {
        /// <summary>
        /// Target Scope ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; }

        /// <summary>
        /// Target Scope Identifier (Null for Global) ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Knowledge Type of Ingested Vectors ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Count of Successfully Ingested Files ...
        /// </summary>
        public int FilesCount { get; set; }

        /// <summary>
        /// Count of Stored Chunks (Vectors) in this Request ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Count of Removed Stale Vectors (Re-Ingest) ...
        /// </summary>
        public int ReplacedCount { get; set; }

        /// <summary>
        /// Skipped Files (Empty, Unsupported or Extraction Failed) ...
        /// </summary>
        public IList<string> SkippedFiles { get; set; } = new List<string>();

        /// <summary>
        /// Ingested Documents Info ...
        /// </summary>
        public IList<XAiKnowledgeDocumentInfo> Documents { get; set; } = new List<XAiKnowledgeDocumentInfo>();
    }

    /// <summary>
    /// Ask Request over Persistent Knowledge Base ...
    /// Retrieval is Tiered: Conversation -> Project -> User -> Global (Each Tier Fills Remaining TopK) ...
    /// </summary>
    public class XAiKnowledgeAskRequest
    {
        /// <summary>
        /// Question ...
        /// </summary>
        public string Prompt { get; set; }

        /// <summary>
        /// Optional: Conversation Scope (Caller must be Conversation Owner) ...
        /// When Provided, Conversation's Project is used for Second Tier Automatically ...
        /// </summary>
        public Guid? ConversationId { get; set; }

        /// <summary>
        /// Optional: Project Scope (Caller must be Project Owner) ...
        /// </summary>
        public Guid? ProjectId { get; set; }

        /// <summary>
        /// Include Personal (User) Knowledge Tier (default true) ...
        /// </summary>
        public bool IncludeUser { get; set; } = true;

        /// <summary>
        /// Include Global Knowledge Tier (default true) ...
        /// </summary>
        public bool IncludeGlobal { get; set; } = true;

        /// <summary>
        /// Optional: Restrict Retrieval to a Knowledge Type / Domain ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Optional: Restrict Retrieval to a Specific File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Optional: Max Retrieved Chunks ...
        /// </summary>
        public int? TopK { get; set; }

        /// <summary>
        /// Optional: Minimum Cosine Similarity Score ...
        /// </summary>
        public float? MinScore { get; set; }
    }

    /// <summary>
    /// Ingested Document Info ...
    /// </summary>
    public class XAiKnowledgeDocumentInfo
    {
        /// <summary>
        /// Scope ...
        /// </summary>
        public XAiKnowledgeScope Scope { get; set; }

        /// <summary>
        /// Scope Identifier (Null for Global) ...
        /// </summary>
        public Guid? ScopeId { get; set; }

        /// <summary>
        /// Knowledge Type ...
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// File Name ...
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Mime Type ...
        /// </summary>
        public string MimeType { get; set; }

        /// <summary>
        /// Ingesting User Identifier ...
        /// </summary>
        public string OwnerId { get; set; }

        /// <summary>
        /// Count of Stored Chunks ...
        /// </summary>
        public int ChunksCount { get; set; }

        /// <summary>
        /// Ingestion Time (UTC) ...
        /// </summary>
        public DateTime? IngestedAtUtc { get; set; }
    }

    /// <summary>
    /// Public Vector Info (Export) ...
    /// </summary>
    public class XAiKnowledgeVectorInfo
    {
        public Guid Id { get; set; }
        public string Text { get; set; }
        public string Type { get; set; }
        public Guid? ScopeId { get; set; }
        public string FileName { get; set; }
        public int? ChunkIndex { get; set; }
        public string Identifier { get; set; }
        public XAiKnowledgeScope Scope { get; set; }
        public Dictionary<string, string> Metadata { get; set; }

        /// <summary>
        /// Embedding (Only Filled when Requested) ...
        /// </summary>
        public float[] Embedding { get; set; }
    }
}


### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Describe an Mcp Server for Seeding ...
    /// </summary>
    public class XAiMcpServerDescriptor
    {
        public string Name { get; set; }
        public string OwnerId { get; set; }
        public string Headers { get; set; }
        public string Endpoint { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; } = true;
        public int TimeoutSeconds { get; set; } = 30;
        public string EnvironmentVariables { get; set; }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs

namespace xAiApi.Models
{
    public class XAiModelProxyConfiguration
    {
        /// <summary>
        /// Enable Proxy or not ...
        /// </summary>
        /// <value></value>
        public bool Enabled { get; set; } = false;

        /// <summary>
        /// Proxy Prefix ...
        /// </summary>
        /// <value></value>
        public string RoutePrefix { get; set; } = "ai-model";
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiOCRDescriptor.cs

using Tesseract;

namespace xAiApi.Models
{
    public class XAiOCRDescriptor
    {
        /// <summary>
        /// Provides Trained Data Path ...
        /// </summary>
        public string DataPath { get; set; }

        /// <summary>
        /// The Engine for Doing OCR ...
        /// </summary>
        public EngineMode EngineMode { get; set; }

        /// <summary>
        /// Enable OCR Fallback using Model ...
        /// </summary>
        public bool EnableOcrFallback { get; set; }

        /// <summary>
        /// Default OCR Language ...
        /// </summary>
        public string DefaultLanguage { get; set; }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiTransciptDescriptor.cs

namespace xAiApi.Models
{
    public class XAiTransciptDescriptor
    {
        public string Language { get; set; }
        public string ModelsPath { get; set; }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XDateTimeDescriptor.cs

namespace xAiApi.Models
{
    public class XDateTimeDescriptor
    {
        /// <summary>
        /// Adding Current DateTime to Prompt ...
        /// </summary>
        public bool InjectIntoSystemPrompt { get; set; } = true;

        /// <summary>
        /// Time Zone ...
        /// </summary>
        public string DefaultTimezone { get; set; } = "Asia/Tehran";

        /// <summary>
        /// Georgian Date Format ...
        /// </summary>
        public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";

        /// <summary>
        /// Include Persian Calendar ...
        /// </summary>
        public bool IncludePersianCalendar { get; set; } = true;

        /// <summary>
        /// Include Day of Week ...
        /// </summary>
        public bool IncludeDayOfWeek { get; set; } = true;

        /// <summary>
        /// Include Unix Timestamp ...
        /// </summary>
        public bool IncludeUnixTimestamp { get; set; } = false;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs

namespace xAiApi.Models
{
    public class XPDFToImageDescriptor
    {
        public int Dpi { get; set; } = 300;
        public int Width { get; set; } = 0;
        public int Height { get; set; } = 0;
        public bool UseTiling { get; set; } = false;
        public bool WithFormFill { get; set; } = false;
        public bool WithAspectRatio { get; set; } = false;
        public bool WithAnnotations { get; set; } = false;
        public bool DpiRelativeToBounds { get; set; } = false;

        public int MaxImageWidth { get; set; } = 2000;
        public int MinTextLengthThreshold { get; set; } = 50;
        public int MaxPagesForImageFallback { get; set; } = 0;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XPreparedChatContext.cs

using xAiModels.Models.Dtos;
using Microsoft.Extensions.AI;
using System.Collections.Generic;

namespace xAiApi.Models
{
    /// <summary>
    /// a Shared Context Between Actions for Generation ... 
    /// </summary>
    public class XPreparedChatContext
    {
        /// <summary>
        /// Specified Related Project, if Exists ...
        /// </summary>
        public XAiProjectDto Project { get; set; } = null;

        /// <summary>
        /// Specified Related Conversation, if Exists ...
        /// </summary>
        public XAiConversationDto Conversation { get; set; } = null;

        /// <summary>
        /// Specified Message History, if Exists ...
        /// </summary>
        public IList<ChatMessage> History { get; set; } = [];

        /// <summary>
        /// Specified Vector Search Conext, if Exists ...
        /// </summary>
        public IList<XAiVectorSearchResult> Context { get; set; } = [];

        /// <summary>
        /// Specified Persisted Prompt, if Exists ...
        /// </summary>
        public XAiMessageDto PersistedPromptMessage { get; set; } = null;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunk.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Represents a Chunk of a Text which Produced by Text Chunker ...
    /// </summary>
    public class XTextChunk
    {
        /// <summary>
        /// Zero Based Index of Chunk in Source Text ...
        /// </summary>
        public int Index { get; set; }

        /// <summary>
        /// Chunk Text Content ...
        /// </summary>
        public string Text { get; set; } = string.Empty;

        /// <summary>
        /// Source Name (e.g. File Name) which Chunk Extracted From ...
        /// </summary>
        public string Source { get; set; }

        /// <summary>
        /// Doc and Chunk Identifier (e.g. "file.pdf#3") ...
        /// </summary>
        public string Identifier { get; set; }

        /// <summary>
        /// Start Offset of Chunk in Normalized Source Text ...
        /// </summary>
        public int StartOffset { get; set; }

        /// <summary>
        /// Length of Chunk Text ...
        /// </summary>
        public int Length => Text?.Length ?? 0;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XTextChunkerDescriptor.cs

namespace xAiApi.Models
{
    /// <summary>
    /// Text Chunker Descriptor ...
    /// </summary>
    public class XTextChunkerDescriptor
    {
        /// <summary>
        /// Maximum Characters Count of each Chunk ...
        /// </summary>
        public int ChunkSize { get; set; } = 800;

        /// <summary>
        /// Characters Count which Shared between two Consecutive Chunks ...
        /// </summary>
        public int ChunkOverlap { get; set; } = 150;

        /// <summary>
        /// Chunks Smaller than this Size will be Merged into Previous Chunk ...
        /// </summary>
        public int MinChunkSize { get; set; } = 50;

        /// <summary>
        /// Chunck Identifier Separator ...
        /// </summary>
        public string ChunkIdentifierSeparator { get; set; } = "#";

        /// <summary>
        /// Normalize Line Endings and Repeated Whitespaces before Chunking ...
        /// </summary>
        public bool NormalizeWhitespace { get; set; } = true;
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingService.cs

using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers
{
    public class XAiEmbeddingService : XAiEmbeddingServiceBase, IXAiEmbeddingService
    {
        public XAiEmbeddingService(
            IXAiDataProvider dataProvider,
            XAiApiConfiguration configuration,
            ILogger<XAiEmbeddingService> logger,
            XValidationProvider validationProvider,
            IXFileContentExtractor fileContentExtractor
        ) : base(
            dataProvider,
            configuration,
            validationProvider,
            logger,
            fileContentExtractor,
            XAiApiConstants.XAiEmbeddingModelName
        )
        { }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiEmbeddingServiceBase.cs

using System;
using OpenAI;
using System.Linq;
using OllamaSharp;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using System.ClientModel;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Extensions;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.ClientModel.Primitives;

namespace xAiApi.Providers
{
    /// <summary>
    /// Base Embedding Provider Service ...
    /// </summary>
    public abstract class XAiEmbeddingServiceBase : IXAiEmbeddingServiceBase
    {
        private readonly string embeddingModelName;
        private readonly XAiModelDescriptor descriptor;
        private readonly IXAiDataProvider dataProvider;
        private readonly XAiApiConfiguration configuration;
        private readonly XValidationProvider validationProvider;
        private readonly ILogger<XAiEmbeddingServiceBase> logger;
        private readonly IXFileContentExtractor fileContentExtractor;

        protected XAiEmbeddingServiceBase(
            IXAiDataProvider dataProvider,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            ILogger<XAiEmbeddingServiceBase> logger,
            IXFileContentExtractor fileContentExtractor,
            string embeddingModelName = XAiApiConstants.XAiEmbeddingModelName
        )
        {
            //
            // Prepare Embedding Model Descriptor ...
            descriptor = configuration.GetModel(embeddingModelName);
            if (!descriptor.IsValid())
            {
                XException.InvalidConfiguration.Throw();
            }

            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.validationProvider = validationProvider;

            //
            this.logger = logger;
            this.fileContentExtractor = fileContentExtractor;
            this.embeddingModelName = embeddingModelName;
        }

        /// <summary>
        /// Embedding Specified String ...
        /// </summary>
        /// <param name="content"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<float[]> Embedding(
            string content,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (content.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var generator = GetEmbeddingGenerator();

            //
            GeneratedEmbeddings<Embedding<float>> response = null;
            response = await generator.GenerateAsync(
                values: [content],
                cancellationToken: cancellationToken
            );

            //
            if (response.IsNullOrDefault())
            {
                XException.ActionFailed.Throw();
            }

            //
            // Generae Result ...
            var result = response
                .First()?
                .Vector
                .ToArray()
               ?? [];
            if (result.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            // Normalize ...
            VectorHelper.Normalize(result);

            //
            return result;
        }

        /// <summary>
        /// Embedding Specified Batch ...
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IReadOnlyList<float[]>> Embeddings(
            string[] batch,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!batch.HasChild() ||
                !batch.All(x => !x.IsNullOrEmpty())
            )
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var generator = GetEmbeddingGenerator();

            //
            GeneratedEmbeddings<Embedding<float>> response = null;
            response = await generator.GenerateAsync(
                values: [.. batch],
                cancellationToken: cancellationToken
            );

            //
            if (response.IsNullOrDefault())
            {
                XException.ActionFailed.Throw();
            }

            //
            var result = response
                .Select(e => e.Vector.ToArray())
                .ToList();

            //
            // Normalize ...
            foreach (var vector in result)
            {
                VectorHelper.Normalize(vector);
            }

            //
            return result;
        }

        /// <summary>
        /// Embedding Generator ...
        /// </summary>
        /// <returns></returns>
        public IEmbeddingGenerator<string, Embedding<float>> GetEmbeddingGenerator()
        {
            //
            IEmbeddingGenerator<string, Embedding<float>> result = null;

            //
            if (!descriptor.IsValid())
            {
                XException.InvalidData.Throw("Invalid Embedding Model ...");
            }

            //
            switch (descriptor.Provider)
            {
                //
                case XAiModelProviderType.OpenAI:
                    //
                    var openAiClient = new OpenAIClient(
                        new ApiKeyCredential(descriptor.ApiKey.IsNullOrEmpty() ? XAiModelsConstants.XOpenAINoKey : descriptor.ApiKey),
                        new OpenAIClientOptions
                        {
                            Endpoint = new Uri(descriptor.Url),
                            Transport = new HttpClientPipelineTransport(descriptor.Url.GetHttpClient())
                        }
                    );
                    result = openAiClient
                        .GetEmbeddingClient(descriptor.LLM)
                        .AsIEmbeddingGenerator();
                    break;

                //
                case XAiModelProviderType.Ollama:
                    //
                    var ollamaClient = new OllamaApiClient(new Uri(descriptor.Url));
                    result = ollamaClient;
                    break;
            }

            //
            if (result.IsNull())
            {
                XException.InvalidData.Throw("Invalid Embedding Model ...");
            }

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiMcpServerProvider.cs

using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using System.Text.Json;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiService.Services;
using xAiModels.Extensions;
using xAiService.Extensions;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Linq.Expressions;
using xCommons.Configurations;
using Microsoft.Extensions.AI;
using xAiModels.Providers.Hubs;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Dtos;
using xIdentityHelper.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;
using System.Collections.Concurrent;
using xAiModels.Interfaces.Enrichers;

namespace xAiApi.Providers
{
    /// <summary>
    /// MCP Manager / Provider ...
    /// </summary>
    public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
    {
        //
        private readonly XAiMcpSessionStore sessionStore;
        private readonly XAiMcpHttpTransport mcpTransport;

        //
        private readonly XAppConfiguration configuration;
        private readonly IHubContext<XAiDataProviderHub> hub;
        private readonly IXIdentityProvider identityProvider;
        private readonly ILogger<XAiMcpServerProvider> logger;
        private readonly XValidationProvider validationProvider;
        private readonly IXAiMcpServerEnricher mcpServerEnricher;
        private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
        private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;

        //
        private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
        private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
        private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
        private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();

        //
        private bool isInitialized = false;
        private readonly SemaphoreSlim initLock = new(1, 1);

        public XAiMcpServerProvider(
            XAiMcpSessionStore sessionStore,
            XAppConfiguration configuration,
            XAiMcpHttpTransport mcpTransport,
            IHubContext<XAiDataProviderHub> hub,
            IXIdentityProvider identityProvider,
            ILogger<XAiMcpServerProvider> logger,
            XValidationProvider validationProvider,
            IXAiMcpServerEnricher mcpServerEnricher,
            IXAiMcpServerServiceProvider mcpServerServiceProvider,
            IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
        )
        {
            this.configuration = configuration;
            //
            this.hub = hub;
            this.logger = logger;
            this.sessionStore = sessionStore;
            this.mcpTransport = mcpTransport;
            this.identityProvider = identityProvider;
            this.mcpServerEnricher = mcpServerEnricher;
            this.validationProvider = validationProvider;
            this.mcpServerServiceProvider = mcpServerServiceProvider;
            this.mcpServerRepositoryProvider = mcpServerRepositoryProvider;
        }

        public async ValueTask DisposeAsync()
        {
            //
            foreach (var client in clients.Values)
            {
                try
                {
                    await client.DisposeAsync();
                }
                catch { }
            }
            initLock.Dispose();
        }

        //
        #region Manager ...
        /// <summary>
        /// Get a List Of Available Tools which Provided using registered Mcp Servers ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<AITool>> GetAvailableToolsAsync(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (userInfo.IsNullOrDefault())
            {
                //
                logger.LogInformation("there isn't any McpServer for non authenticated user ...");
                return [];
            }

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            // Load Servers Metadata ...
            await EnsureServersLoadedAsync(cancellationToken);

            //
            // Extract Accessible Mcp Servers ...
            var accessibleServers = mcpServers.Values
                   .Where(s => s.OwnerId == userInfo.UserId ||
                               s.Scope == XAiMcpServerUsageScope.All)
                   .ToList();

            //
            // Create User Speciic Client Connection ...
            foreach (var server in accessibleServers)
            {
                //
                // Create User Specific Client Key ...
                var key = (server.Id, userInfo.UserId);

                //
                // Check Expiration ...
                if (clients.ContainsKey(key) &&
                    clientExpirations.TryGetValue(key, out var exp) &&
                    exp < DateTime.UtcNow)
                {
                    //
                    // Remove Expired Client and Tools ...
                    if (clients.TryRemove(key, out var old))
                    {
                        //
                        try
                        {
                            await old.DisposeAsync();
                        }
                        catch { }
                    }

                    //
                    tools.TryRemove(key, out _);
                    clientExpirations.TryRemove(key, out _);
                }

                //
                if (clients.ContainsKey(key))
                {
                    continue;
                }

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    if (!clients.ContainsKey(key))
                    {
                        //
                        await ConnectAndValidateAsync(
                            descriptor: server,
                            userInfo: userInfo,
                            cancellationToken: cancellationToken
                        );
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            // Extract User Specified Mcp Client Tools ...
            var result = tools
                .Where(kv => kv.Key.UserId == userInfo.UserId)
                .SelectMany(kv => kv.Value)
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Test Specified Mcp Server ...
        /// </summary>
        /// <param name="server"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> TestServerAsync(
            XAiMcpServerDto server,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));

                //
                var client = CreateClientAsync(server, connectionId, userInfo);
                // await client.PingAsync(cancellationToken: cts.Token);
                var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);

                //
                var names = string.Join(", ", serverTools.Select(t => t.Name));
                return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}";
            }
            catch (Exception ex)
            {
                //
                return $"✗ Error: {ex.Message} ...";
            }
        }

        /// <summary>
        /// Force Refresh Mcp Servers ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RefreshAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (!userInfo.IsAdmin())
            {
                XException.NotAllowed.Throw();
            }

            //
            logger.LogInformation("MCP: Reinitialize Mcp Servers ...");
            foreach (var client in clients.Values)
            {
                try
                {
                    await client.DisposeAsync();
                }
                catch { }
            }
            tools.Clear();
            clients.Clear();
            mcpServers.Clear();

            //
            isInitialized = false;
            await GetAvailableToolsAsync(
                userInfo: userInfo,
                cancellationToken: cancellationToken
            );
        }
        #endregion

        //
        #region Actions ...
        /// <summary>
        /// Add an Mcp Server ...
        /// </summary>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> AddMcpServer(
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(item)
                .AddNotNull(userInfo)
                .AddUrl(item.Endpoint)
                .AddNotEmpty(item.Endpoint)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Normalize Scope ...
            if (!userInfo.IsAdmin())
            {
                item.Scope = XAiMcpServerUsageScope.Owner;
            }
            item.OwnerId = userInfo.UserId;
            item.CreatedOn = DateTime.UtcNow;

            //
            // Normalizing Timeout ...
            if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds)
            {
                item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds;
            }

            //
            // Validate for Add ...
            if (!item.IsValidForAddOrUpdate())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await mcpServerServiceProvider
                .AddAsync(
                    item: item,
                    saveChanges: true,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerCreated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[result.Id] = result;
                    await ConnectAndValidateAsync(result, connectionId, userInfo);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Get an Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> GetMcpServer(
            Guid id,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var result = await mcpServerServiceProvider
                .GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Update Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> UpdateMcpServer(
            Guid id,
            XAiMcpServerDto item,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(item)
                .AddIsGuid(item.Id)
                .AddNotNull(userInfo)
                .AddUrl(item.Endpoint)
                .AddNotNull(item.CreatedOn)
                .AddNotEmpty(item.Endpoint)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Normalize Scope ...
            if (!userInfo.IsAdmin())
            {
                item.Scope = XAiMcpServerUsageScope.Owner;
            }
            item.UpdatedAt = DateTime.UtcNow;

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != item.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            // Normalizing Timeout ...
            if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds)
            {
                item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds;
            }

            //
            // Validate for Add ...
            if (!item.IsValidForAddOrUpdate())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await mcpServerServiceProvider
                .UpdateAsync(
                    id: id,
                    item: item,
                    saveChanges: true,
                    connectionId: connectionId,
                    cancellationToken: cancellationToken
                );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[result.Id] = result;

                    //
                    // Remove Exists ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == result.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var old))
                        {
                            try
                            {
                                await old.DisposeAsync();
                            }
                            catch { }
                        }
                        tools.TryRemove(key, out _);
                    }

                    //
                    // Reconnect ...
                    await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Remove Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> RemoveMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            var result = await mcpServerServiceProvider.RemoveAsync(
                id: id,
                softDelete: true,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );

                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: result.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    // Remove Server Descriptor ...
                    mcpServers.TryRemove(result.Id, out _);

                    //
                    // Disconnect all Connections ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == result.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var c))
                        {
                            //
                            try
                            {
                                await c.DisposeAsync();
                            }
                            catch { }
                        }

                        //
                        tools.TryRemove(key, out _);
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Disable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> DisableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (!exists.Enabled)
            {
                return false;
            }
            exists.Enabled = false;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault() && !exists.Enabled;

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    // Remove Server Descriptor ...
                    mcpServers.TryRemove(exists.Id, out _);

                    //
                    // Disconnect all Connections ...
                    var keysToRemove = clients.Keys
                        .Where(k => k.ServerId == exists.Id)
                        .ToList();
                    foreach (var key in keysToRemove)
                    {
                        //
                        if (clients.TryRemove(key, out var c))
                        {
                            //
                            try
                            {
                                await c.DisposeAsync();
                            }
                            catch { }
                        }

                        //
                        tools.TryRemove(key, out _);
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Enable Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> EnableMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            if (exists.Enabled)
            {
                return false;
            }
            exists.Enabled = true;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault() && exists.Enabled;

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    mcpServers[exists.Id] = exists;
                    await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Toggle Specified Mcp Server ...
        /// </summary>
        /// <param name="id"></param>
        /// <param name="connectionId"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> ToggleMcpServer(
            Guid id,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddIsGuid(id)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Check McpServer Exists ...
            var exists = await mcpServerServiceProvider.GetAsync(
                id: id,
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );
            if (exists.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Ownership ...
            if (!userInfo.IsAdmin() &&
                userInfo.UserId != exists.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            exists.Enabled = !exists.Enabled;

            //
            exists = await mcpServerServiceProvider.UpdateAsync(
                id: id,
                item: exists,
                saveChanges: true,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );
            var result = !exists.IsNullOrDefault();

            //
            if (result)
            {
                //
                // Sending Push ...
                await SendPush(
                    connectionId: connectionId,
                    cancellationToken: cancellationToken,
                    payLoad: exists.ToJSON(camelCase: true),
                    action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue()
                );

                //
                await initLock.WaitAsync(cancellationToken);
                try
                {
                    //
                    if (exists.Enabled)
                    {
                        //
                        mcpServers[exists.Id] = exists;
                        await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
                    }
                    else
                    {
                        //
                        // Remove Server Descriptor ...
                        mcpServers.TryRemove(exists.Id, out _);

                        //
                        // Disconnect all Connections ...
                        var keysToRemove = clients.Keys
                            .Where(k => k.ServerId == exists.Id)
                            .ToList();
                        foreach (var key in keysToRemove)
                        {
                            //
                            if (clients.TryRemove(key, out var c))
                            {
                                //
                                try
                                {
                                    await c.DisposeAsync();
                                }
                                catch { }
                            }

                            //
                            tools.TryRemove(key, out _);
                        }
                    }
                }
                finally
                {
                    initLock.Release();
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve all Mcp Server ...
        /// </summary>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IEnumerable<XAiMcpServerDto>> GetAll(
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            var result = Enumerable.Empty<XAiMcpServerDto>();
            Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> orderBuilder = x => x.OrderByDescending(y => y.CreatedOn);
            if (forceOwner)
            {
                //
                result = await mcpServerServiceProvider
                    .FindManyAsync(
                        predicate: x =>
                            x.OwnerId
                                .Equals(
                                    userInfo.UserId,
                                    StringComparison.InvariantCultureIgnoreCase
                                ),
                        includeBuilder: null,
                        ignoreSoftDeleteds: true,
                        orderBuilder: orderBuilder,
                        cancellationToken: cancellationToken
                    );
            }
            else
            {
                //
                result = await mcpServerServiceProvider
                    .GetAllAsync(
                        includeBuilder: null,
                        ignoreSoftDeleteds: true,
                        orderBuilder: orderBuilder,
                        cancellationToken: cancellationToken
                    );
            }

            //
            if (result.HasChild())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.EnrichRange(
                    sources: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Find Specified Mcp Server ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiMcpServerDto> FindOne(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    predicate.Compile()(x) &&
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }
            else
            {
                //
                predicator = x => predicate.Compile()(x);
            }

            //
            var result = await mcpServerServiceProvider.FindOneAsync(
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken
            );

            //
            if (!result.IsNullOrDefault())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.Enrich(
                    source: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Find a Collection of Specified Mcp Servers ...
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IEnumerable<XAiMcpServerDto>> FindMany(
            Expression<Func<XAiMcpServer, bool>> predicate,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    predicate.Compile()(x) &&
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }
            else
            {
                //
                predicator = x => predicate.Compile()(x);
            }

            //
            var result = await mcpServerServiceProvider.FindManyAsync(
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                orderBuilder: x => x.OrderByDescending(y => y.CreatedOn)
            );

            //
            if (result.HasChild())
            {
                //
                // Handle Enrichment ...
                result = await mcpServerEnricher.EnrichRange(
                    sources: result,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }

        /// <summary>
        /// Query Registered Mcp Servers ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="forceOwner"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XQueryResult<XAiMcpServerDto>> Query(
            XQuery query,
            bool forceOwner = false,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            if (!userInfo.IsAdmin())
            {
                forceOwner = true;
            }

            //
            Expression<Func<XAiMcpServer, bool>> predicator = null;
            if (forceOwner)
            {
                //
                predicator = x =>
                    x.OwnerId
                        .Equals(
                            userInfo.UserId,
                            StringComparison.InvariantCultureIgnoreCase
                        );
            }

            //
            var result = await mcpServerServiceProvider.QueryAsync(
                query: query,
                includeBuilder: null,
                predicate: predicator,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                orderBuilder: x => x.OrderByDescending(y => y.CreatedOn)
            );

            //
            if (!result.IsNullOrDefault() && result.Items.HasChild())
            {
                //
                // Handle Enrichment ...
                result.Items = await mcpServerEnricher.EnrichRange(
                    sources: result.Items,
                    cancellationToken: cancellationToken
                );
            }

            //
            return result;
        }
        #endregion

        //
        #region Private ...
        private static Dictionary<string, string> ParseJsonDict(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<Dictionary<string, string>>(json);

        private static List<string> ParseJsonList(string json)
            => json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize<List<string>>(json);

        private XAiMcpClient CreateClientAsync(
            XAiMcpServerDto descriptor,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null
        )
        {
            //
            var result = new XAiMcpClient(
                logger: logger,
                userInfo: userInfo,
                transport: mcpTransport,
                serverId: descriptor.Id,
                sessionStore: sessionStore,
                connectionId: connectionId,
                appConfiguration: configuration,
                endpoint: new Uri(descriptor.Endpoint)
            );

            //
            return result;
        }

        private async Task ConnectAndValidateAsync(
            XAiMcpServerDto descriptor,
            string connectionId = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Create Specified Cancellation Token ...
                using var cts = CancellationTokenSource
                    .CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));

                //
                var client = CreateClientAsync(
                    userInfo: userInfo, 
                    descriptor: descriptor, 
                    connectionId: connectionId
                );

                //
                await client.InitializeAsync(cts.Token);

                //
                var clientTools = await client.ListToolsAsync(cts.Token);
                var aiTools = clientTools.ToAITools(client);

                //
                // Key for Cache ...
                var key = (descriptor.Id, userInfo.UserId);

                //
                tools[key] = aiTools;
                clients[key] = client;
                mcpServers[descriptor.Id] = descriptor;
                clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);

                //
                logger.LogInformation(
                    "MCP '{Name}': {Count} Tools Detected for {UserId} ...",
                    descriptor.Name,
                    aiTools.Count,
                    userInfo.UserId
                );
            } catch(Exception ex)
            {
                //
                logger.LogWarning(ex,
                    "MCP '{Name}': Connection Established Failed, Ignored ...",
                    descriptor.Name
                );                
            }
        }

        private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken)
        {
            //
            if (isInitialized)
            {
                return;
            }

            //
            await initLock.WaitAsync(cancellationToken);
            try
            {
                //
                if (isInitialized)
                {
                    return;
                }

                //
                var servers = await mcpServerServiceProvider.FindManyAsync(
                    orderBuilder: null,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    predicate: x => x.Enabled,
                    cancellationToken: cancellationToken
                );

                //
                if (servers.HasChild())
                {
                    //
                    foreach (var s in servers)
                    {
                        //
                        mcpServers[s.Id] = s;
                    }
                }

                //
                isInitialized = true;
            }
            finally
            {
                initLock.Release();
            }
        }
        #endregion

        //
        #region Hub Actions ...
        /// <summary>
        /// Send Custom Push Message ...
        /// </summary>
        /// <param name="action"></param>
        /// <param name="payLoad"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendPush(
            string action,
            string payLoad,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            try
            {
                //
                // Collect Allowed Actions ...
                var actions = new List<string>
                {
                    XAiDataProviderHubActions.McpServerCreated.GetStringValue(),
                    XAiDataProviderHubActions.McpServerUpdated.GetStringValue(),
                    XAiDataProviderHubActions.McpServerRemoved.GetStringValue(),
                };

                //
                // Validate Args ...
                var isValid =
                    !action.IsNullOrEmpty() &&
                    actions.Contains(action);
                if (!isValid)
                {
                    return;
                }

                //
                // Retrieve Connection Id ...
                var clients = hub.Clients.All;
                if (!connectionId.IsNullOrEmpty())
                {
                    clients = hub.Clients.AllExcept(connectionId);
                }

                //
                await clients.SendAsync(
                    action,
                    payLoad,
                    connectionId,
                    cancellationToken
                );
            }
            catch { }
        }
        #endregion            
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiRAGService.cs

using System;
using System.IO;
using System.Linq;
using xAiApi.Models;
using xIdentityHelper;
using System.Threading;
using xAiApi.Interfaces;
using xAiModels.Constants;
using xCommons.Extensions;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xFileService.Interfaces;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using xFileService.Models.Dtos;

namespace xAiApi.Providers
{
    /// <summary>
    /// Persistent RAG Service over XAiVector Table ...
    /// Isolation (Identifier Layout):
    ///   Conversation: "conversation/{conversationId}/{fileName}#{i}"
    ///   Project     : "project/{projectId}/{fileName}#{i}"
    ///   User        : "user/{ownerId}/{fileName}#{i}"
    ///   Global      : "global/{fileName}#{i}"
    /// Retrieval is Tiered: Conversation -> Project -> User -> Global ...
    /// </summary>
    public class XAiRAGService : IXAiRAGService
    {
        private readonly IXTextChunker textChunker;
        private readonly IXFileProvider fileProvider;
        private readonly IXAiDataProvider dataProvider;
        private readonly ILogger<XAiRAGService> logger;
        private readonly XAiApiConfiguration configuration;
        private readonly IXAiEmbeddingService embeddingService;
        private readonly IXFileContentExtractor fileContentExtractor;

        /// <summary>
        /// Characters which are not Allowed in File Name Part of Identifier ...
        /// </summary>
        private static readonly char[] UnsafeFileNameChars = ['/', '\\', '#'];

        public XAiRAGService(
            IXTextChunker textChunker,
            IXFileProvider fileProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAiRAGService> logger,
            XAiApiConfiguration configuration,
            IXAiEmbeddingService embeddingService,
            IXFileContentExtractor fileContentExtractor
        )
        {
            //
            this.logger = logger;
            this.textChunker = textChunker;
            this.fileProvider = fileProvider;
            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.embeddingService = embeddingService;
            this.fileContentExtractor = fileContentExtractor;
        }

        //
        #region Ingest ...
        /// <summary>
        /// Ingest Files into Specified Knowledge Scope:
        /// Extract -> Chunk -> Embed -> Store (XAiVector) ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="replaceExisting"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XAiKnowledgeIngestResult> IngestAsync(
            IFormFileCollection files,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            bool replaceExisting = true,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!files.HasChild() || !IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            var rag = configuration.RAGDescriptor;
            if (rag.MaxFilesPerIngest > 0 && files.Count > rag.MaxFilesPerIngest)
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Write) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);

            //
            var knowledgeType = scope.Type.IsNullOrEmpty()
                ? XAiModelsConstants.XAiDefaultKnowledgeType
                : scope.Type;
            var scopePrefix = GetScopePrefix(scope, userInfo);

            //
            var result = new XAiKnowledgeIngestResult
            {
                Type = knowledgeType,
                Scope = scope.Scope,
                ScopeId = scope.ScopeId,
            };
            var ingestedAt = DateTime.UtcNow;
            var ingestedAtUtc = ingestedAt.ToString("O");

            //
            // Existing Documents (for MaxDocumentsPerScope Limit) ...
            var existingDocuments = await LoadDocumentNames(scopePrefix, cancellationToken);

            //
            // Loop through Files ...
            foreach (var file in files)
            {
                //
                XFileDto uploadedFile = null;

                //
                try
                {
                    //
                    cancellationToken.ThrowIfCancellationRequested();

                    //
                    if (file.IsNull() || file.Length == 0)
                    {
                        result.SkippedFiles.Add(file?.FileName ?? "(null)");
                        continue;
                    }

                    //
                    // Size Limit ...
                    if (rag.MaxFileSizeBytes > 0 && file.Length > rag.MaxFileSizeBytes)
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var fileName = NormalizeFileName(file.FileName);
                    if (fileName.IsNullOrEmpty())
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    // Documents per Scope Limit (Global Unlimited; Re-Ingest of Existing Doc Allowed) ...
                    var isNewDocument = !existingDocuments.Contains(fileName);
                    if (
                        isNewDocument &&
                        scope.Scope != XAiKnowledgeScope.Global &&
                        rag.MaxDocumentsPerScope > 0 &&
                        existingDocuments.Count >= rag.MaxDocumentsPerScope
                    )
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
                    if (!fileContentExtractor.CanExtract(mimeType))
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    var text = await ExtractText(file, mimeType, cancellationToken);
                    if (text.IsNullOrEmpty())
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    // Chunk with Scoped Source => Identifier = "{scopePrefix}{fileName}#{index}" ...
                    var chunks = textChunker.Chunk(text, $"{scopePrefix}{fileName}");
                    if (!chunks.HasChild())
                    {
                        result.SkippedFiles.Add(file.FileName);
                        continue;
                    }

                    //
                    // Handle File Save ...
                    uploadedFile = await fileProvider.Upload(
                        file: file,
                        userInfo: userInfo,
                        connectionId: connectionId,
                        cancellationToken: cancellationToken
                    );

                    //
                    // Add Reference File to Prompt Message ...
                    if (
                        !uploadedFile.IsNullOrDefault() &&
                        scope.ScopeId.HasValue &&
                        !uploadedFile.Id.IsDefaultGuid()
                    )
                    {
                        //
                        await fileProvider.AddReference(
                            userInfo: userInfo,
                            id: uploadedFile.Id,
                            connectionId: connectionId,
                            cancellationToken: cancellationToken,
                            providedFor: scope.Scope.GetStringValue(),
                            forProvidedId: scope.ScopeId.Value.ToString()
                        );
                    }

                    //
                    // Embed in Batches ...
                    var vectors = await EmbedChunks(
                        scope: scope,
                        chunks: chunks,
                        fileName: fileName,
                        mimeType: mimeType,
                        type: knowledgeType,
                        ownerId: userInfo.UserId,
                        ingestedAtUtc: ingestedAtUtc,
                        cancellationToken: cancellationToken
                    );

                    //
                    // Remove Stale Vectors of Same Document ...
                    if (replaceExisting)
                    {
                        //
                        result.ReplacedCount += await dataProvider.RemoveVectorsAsync(
                            cancellationToken: cancellationToken,
                            identifierPrefix: GetDocumentChunkPrefix(scopePrefix, fileName)
                        );
                    }

                    //
                    // Store ...
                    var storedCount = await dataProvider.UpsertVectorsAsync(
                        items: vectors,
                        cancellationToken: cancellationToken
                    );

                    //
                    existingDocuments.Add(fileName);
                    result.FilesCount++;
                    result.ChunksCount += storedCount;
                    result.Documents.Add(new XAiKnowledgeDocumentInfo
                    {
                        FileName = fileName,
                        MimeType = mimeType,
                        Type = knowledgeType,
                        Scope = scope.Scope,
                        ScopeId = scope.ScopeId,
                        ChunksCount = storedCount,
                        OwnerId = userInfo.UserId,
                        IngestedAtUtc = ingestedAt,
                    });

                    //
                    logger.LogInformation(
                        "Knowledge: Ingested {FileName} into {Scope}:{ScopeId} by {OwnerId} with {Chunks} Chunks",
                        fileName, scope.Scope, scope.ScopeId, userInfo.UserId, storedCount
                    );
                }
                catch (Exception ex)
                {
                    //
                    logger.LogError(ex, "Ingesting Failed ...");

                    //
                    // Removing Uploaded File if Chuncking Failed ...
                    if (!uploadedFile.IsNullOrDefault() &&
                        !uploadedFile.Id.IsDefaultGuid()
                    )
                    {
                        //
                        await fileProvider.Remove(
                            id: uploadedFile.Id,
                            userInfo: userInfo,
                            connectionId: connectionId,
                            cancellationToken: cancellationToken
                        );
                    }
                }
            }

            //
            return result;
        }
        #endregion

        //
        #region Ask ...
        /// <summary>
        /// Embed Prompt and Retrieve Relevant Chunks (Tiered: Conversation -> Project -> User -> Global) ...
        /// Each Tier Fills Remaining TopK; Duplicates are Removed ...
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<XAiVectorSearchResult>> RetrieveAsync(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (
                request.IsNullOrDefault() ||
                request.Prompt.IsNullOrEmpty() ||
                !IsValidUser(userInfo)
            )
            {
                XException.InvalidArgs.Throw();
            }

            //
            var rag = configuration.RAGDescriptor;
            var effectiveTopK = Math.Clamp(request.TopK ?? rag.DefaultTopK, 1, rag.MaxTopK);
            var effectiveMinScore = request.MinScore ?? rag.DefaultMinScore;

            //
            // Resolve Tiers (with Ownership Checks) before Embedding ...
            var tiers = await ResolveTiers(request, userInfo, cancellationToken);
            if (!tiers.HasChild())
            {
                return [];
            }

            //
            // Embed Question (Once) ...
            var queryEmbedding = await embeddingService.Embedding(
                content: request.Prompt,
                cancellationToken: cancellationToken
            );
            if (queryEmbedding.IsNullOrDefault() || queryEmbedding.Length == 0)
            {
                XException.ActionFailed.Throw();
            }

            //
            var fileName = NormalizeFileName(request.FileName);
            var result = new List<XAiVectorSearchResult>();
            var seen = new HashSet<string>(StringComparer.Ordinal);
            foreach (var tier in tiers)
            {
                //
                var remaining = effectiveTopK - result.Count;
                if (remaining <= 0)
                {
                    break;
                }

                //
                var scopePrefix = GetScopePrefix(tier, userInfo);
                var prefix = fileName.IsNullOrEmpty()
                    ? scopePrefix
                    : GetDocumentChunkPrefix(scopePrefix, fileName);

                //
                var searchResult = await dataProvider.SearchVectorsAsync(
                    topK: remaining,
                    type: request.Type,
                    identifierPrefix: prefix,
                    minScore: effectiveMinScore,
                    queryEmbedding: queryEmbedding,
                    cancellationToken: cancellationToken
                );

                //
                foreach (var item in searchResult ?? [])
                {
                    if (seen.Add(item.Identifier ?? item.Id.ToString()))
                    {
                        result.Add(item);
                    }
                }
            }

            //
            return result;
        }
        #endregion

        //
        #region Documents ...
        /// <summary>
        /// List Ingested Documents of Specified Scope ...
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IList<XAiKnowledgeDocumentInfo>> LoadDocumentsAsync(
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Read) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: false, cancellationToken);

            //
            var vectors = await dataProvider.LoadVectorsAsync(
                type: scope.Type,
                includeEmbedding: false,
                cancellationToken: cancellationToken,
                identifierPrefix: GetScopePrefix(scope, userInfo)
            );

            //
            var rag = configuration.RAGDescriptor;
            var result = (vectors ?? [])
                .GroupBy(v => v.Metadata.GetMetadata(rag.MetadataFileName).IsNullOrEmpty()
                    ? v.Identifier
                    : v.Metadata.GetMetadata(rag.MetadataFileName))
                .Select(g =>
                {
                    //
                    var first = g.First();
                    var ingestedText = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc);

                    //
                    return new XAiKnowledgeDocumentInfo
                    {
                        FileName = g.Key,
                        Type = first.Type,
                        Scope = scope.Scope,
                        ChunksCount = g.Count(),
                        ScopeId = scope.ScopeId,
                        MimeType = first.Metadata.GetMetadata(rag.MetadataMimeType),
                        OwnerId = first.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataOwnerId),
                        IngestedAtUtc = DateTime.TryParse(
                            ingestedText, null, System.Globalization.DateTimeStyles.RoundtripKind, out var dt
                        ) ? dt : null
                    };
                })
                .OrderBy(d => d.FileName)
                .ToList();

            //
            return result;
        }

        /// <summary>
        /// Remove All Vectors of a Document in Specified Scope ...
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="scope"></param>
        /// <param name="userInfo"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Removed Vectors</returns>
        public async Task<int> RemoveDocumentAsync(
            string fileName,
            XAiKnowledgeScopeDescriptor scope = null,
            XUserClaimsInfoDto userInfo = null,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            var normalizedFileName = NormalizeFileName(fileName);
            if (normalizedFileName.IsNullOrEmpty() || !IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Resolve & Authorize Scope (Write) ...
            scope = NormalizeScope(scope);
            await EnsureAccess(scope, userInfo, isWrite: true, cancellationToken);

            //
            var result = await dataProvider.RemoveVectorsAsync(
                cancellationToken: cancellationToken,
                identifierPrefix: GetDocumentChunkPrefix(GetScopePrefix(scope, userInfo), normalizedFileName)
            );
            if (result > 0)
            {
                //
                // Remove Files using ...
                var file = await fileProvider.FindOne(
                    x => x.FileName
                        .Equals(
                            fileName,
                            StringComparison.InvariantCultureIgnoreCase) &&
                        x.OwnerId
                            .Equals(
                                userInfo.UserId,
                                StringComparison.InvariantCultureIgnoreCase),
                    cancellationToken: cancellationToken
                );

                //
                if (!file.IsNullOrDefault())
                {
                    //
                    await fileProvider.Remove(
                        id: file.Id,
                        userInfo: userInfo,
                        connectionId: connectionId,
                        cancellationToken: cancellationToken
                    );
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Migrate Legacy Vectors of Owner ("{ownerId}/{fileName}#i") into User Scope ("user/{ownerId}/{fileName}#i") ...
        /// Store First then Remove Legacy (no Data Loss on Failure); Idempotent ...
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Count of Migrated Vectors</returns>
        public async Task<int> MigrateLegacyVectorsAsync(
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!IsValidUser(userInfo))
            {
                XException.InvalidArgs.Throw();
            }

            //
            var legacyPrefix = $"{userInfo.UserId}{XAiModelsConstants.XAiKnowledgeOwnerSeparator}";
            var legacyVectors = await dataProvider.LoadVectorsAsync(
                includeEmbedding: true,
                identifierPrefix: legacyPrefix,
                cancellationToken: cancellationToken
            );
            if (!legacyVectors.HasChild())
            {
                return 0;
            }

            //
            var scope = XAiKnowledgeScopeDescriptor.User();
            var scopePrefix = GetScopePrefix(scope, userInfo);
            var migrated = legacyVectors
                .Select(v =>
                {
                    //
                    var type = v.Type.IsNullOrEmpty() ? XAiModelsConstants.XAiDefaultKnowledgeType : v.Type;
                    var metadata = v.Metadata ?? new Dictionary<string, string>();
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataType] = type;
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataScopeId] = string.Empty;
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString();
                    metadata[XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = userInfo.UserId;

                    //
                    return new XAiVectorDto
                    {
                        Type = type,
                        Text = v.Text,
                        Metadata = metadata,
                        Embedding = v.Embedding,
                        Identifier = $"{scopePrefix}{v.Identifier.Substring(legacyPrefix.Length)}",
                    };
                })
                .ToList();

            //
            var result = await dataProvider.UpsertVectorsAsync(
                items: migrated,
                cancellationToken: cancellationToken
            );
            await dataProvider.RemoveVectorsAsync(
                identifierPrefix: legacyPrefix,
                cancellationToken: cancellationToken
            );

            //
            logger.LogInformation(
                "Knowledge: Migrated {Count} Legacy Vectors of {OwnerId} into User Scope",
                result, userInfo.UserId
            );

            //
            return result;
        }

        /// <summary>
        /// Map Search Results to Public Sources ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IList<XAiDocumentSource> ToSources(
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var rag = configuration.RAGDescriptor;
            var result = (context ?? [])
                .Select(c =>
                {
                    //
                    var text = c.Text ?? string.Empty;
                    var snippetLength = Math.Min(text.Length, rag.SourceSnippetLength);
                    var chunkIndexText = c.Metadata.GetMetadata(rag.MetadataChunkIndex);

                    //
                    return new XAiDocumentSource
                    {
                        Type = c.Type,
                        Score = c.Score,
                        Identifier = c.Identifier,
                        Snippet = text.Substring(0, snippetLength),
                        FileName = c.Metadata.GetMetadata(rag.MetadataFileName),
                        Scope = c.Metadata.GetMetadata(XAiModelsConstants.XAiKnowledgeMetadataScope),
                        ChunkIndex = int.TryParse(chunkIndexText, out var idx) ? idx : null
                    };
                })
                .ToList();

            //
            return result;
        }
        #endregion

        //
        #region Private ...
        /// <summary>
        /// Extract Plain Text of a File (Text or Audio Transcript) ...
        /// </summary>
        private async Task<string> ExtractText(
            IFormFile file,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            try
            {
                //
                using var stream = file.OpenReadStream();
                var extraction = await fileContentExtractor.ExtractRichAsync(
                    fileStream: stream,
                    mimeType: mimeType,
                    fileName: file.FileName,
                    cancellationToken: cancellationToken
                );

                //
                var result = extraction?.Text;
                if (string.IsNullOrWhiteSpace(result))
                {
                    result = extraction?.AudioTranscript;
                }

                //
                return result;
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex, "Knowledge: Extraction Failed for {FileName}", file.FileName);
                return null;
            }
        }

        /// <summary>
        /// Embed Chunks in Batches and Build Vectors (with Scope Metadata) ...
        /// </summary>
        private async Task<IList<XAiVectorDto>> EmbedChunks(
            XAiKnowledgeScopeDescriptor scope,
            IList<XTextChunk> chunks,
            string type,
            string ownerId,
            string fileName,
            string mimeType,
            string ingestedAtUtc,
            CancellationToken cancellationToken
        )
        {
            //
            var rag = configuration.RAGDescriptor;
            var batchSize = Math.Max(1, rag.EmbeddingBatchSize);
            var result = new List<XAiVectorDto>(chunks.Count);

            //
            for (var offset = 0; offset < chunks.Count; offset += batchSize)
            {
                //
                cancellationToken.ThrowIfCancellationRequested();

                //
                var batch = chunks.Skip(offset).Take(batchSize).ToList();
                var embeddings = await embeddingService.Embeddings(
                    batch: batch.Select(c => c.Text).ToArray(),
                    cancellationToken: cancellationToken
                );

                //
                if (embeddings.IsNullOrDefault() || embeddings.Count != batch.Count)
                {
                    XException.ActionFailed.Throw();
                }

                //
                for (var i = 0; i < batch.Count; i++)
                {
                    //
                    var chunk = batch[i];
                    result.Add(new XAiVectorDto
                    {
                        //
                        Type = type,
                        Text = chunk.Text,
                        Embedding = embeddings[i],
                        Identifier = chunk.Identifier,
                        Metadata = new Dictionary<string, string>
                        {
                            [rag.MetadataFileName] = fileName,
                            [rag.MetadataMimeType] = mimeType,
                            [rag.MetadataChunkIndex] = chunk.Index.ToString(),
                            [XAiModelsConstants.XAiKnowledgeMetadataType] = type,
                            [XAiModelsConstants.XAiKnowledgeMetadataOwnerId] = ownerId,
                            [XAiModelsConstants.XAiKnowledgeMetadataScope] = scope.Scope.ToString(),
                            [XAiModelsConstants.XAiKnowledgeMetadataScopeId] = scope.ScopeId?.ToString("D") ?? string.Empty,
                            [XAiModelsConstants.XAiKnowledgeMetadataIngestedAtUtc] = ingestedAtUtc
                        }
                    });
                }
            }

            //
            return result;
        }

        //
        #region Scope ...
        /// <summary>
        /// Normalize Scope (Null => User, Clear ScopeId for User/Global, Require ScopeId for Project/Conversation) ...
        /// </summary>
        private XAiKnowledgeScopeDescriptor NormalizeScope(XAiKnowledgeScopeDescriptor scope)
        {
            //
            var result = scope ?? XAiKnowledgeScopeDescriptor.User();
            switch (result.Scope)
            {
                case XAiKnowledgeScope.User:
                case XAiKnowledgeScope.Global:
                    result.ScopeId = null;
                    break;

                case XAiKnowledgeScope.Project:
                case XAiKnowledgeScope.Conversation:
                    if (!result.ScopeId.HasValue || result.ScopeId.Value == Guid.Empty)
                    {
                        XException.InvalidArgs.Throw();
                    }
                    break;

                default:
                    XException.InvalidArgs.Throw();
                    break;
            }

            //
            return result;
        }

        /// <summary>
        /// Ensure Caller has Access to Scope:
        ///   User: Own Data | Global: Read = Everyone, Write = Admin
        ///   Project / Conversation: Caller must be Owner ...
        /// </summary>
        private async Task EnsureAccess(
            XAiKnowledgeScopeDescriptor scope,
            XUserClaimsInfoDto userInfo,
            bool isWrite,
            CancellationToken cancellationToken
        )
        {
            //
            switch (scope.Scope)
            {
                case XAiKnowledgeScope.Global:
                    if (isWrite && !IsAdmin(userInfo))
                    {
                        XException.NotAuthorized.Throw();
                    }
                    break;

                case XAiKnowledgeScope.Project:
                    await EnsureProjectOwner(scope.ScopeId.Value, userInfo, cancellationToken);
                    break;

                case XAiKnowledgeScope.Conversation:
                    await EnsureConversationOwner(scope.ScopeId.Value, userInfo, cancellationToken);
                    break;
            }
        }

        /// <summary>
        /// Ensure Caller Owns Project ...
        /// </summary>
        private async Task<XAiProjectDto> EnsureProjectOwner(
            Guid projectId,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await dataProvider.GetProject(
                id: projectId,
                cancellationToken: cancellationToken
            );
            if (result.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }
            if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
            {
                XException.NotAuthorized.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Ensure Caller Owns Conversation ...
        /// </summary>
        private async Task<XAiConversationDto> EnsureConversationOwner(
            Guid conversationId,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await dataProvider.GetConversation(
                id: conversationId,
                cancellationToken: cancellationToken
            );
            if (result.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }
            if (!string.Equals(result.OwnerId, userInfo.UserId, StringComparison.Ordinal))
            {
                XException.NotAuthorized.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Resolve Retrieval Tiers (Ordered): Conversation -> Project -> User -> Global ...
        /// </summary>
        private async Task<IList<XAiKnowledgeScopeDescriptor>> ResolveTiers(
            XAiKnowledgeAskRequest request,
            XUserClaimsInfoDto userInfo,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new List<XAiKnowledgeScopeDescriptor>();
            Guid? projectId = request.ProjectId.HasValue && request.ProjectId.Value != Guid.Empty
                ? request.ProjectId
                : null;

            //
            // Conversation Tier (+ Implicit Project) ...
            if (request.ConversationId.HasValue && request.ConversationId.Value != Guid.Empty)
            {
                //
                var conversation = await EnsureConversationOwner(
                    request.ConversationId.Value, userInfo, cancellationToken
                );
                result.Add(XAiKnowledgeScopeDescriptor.Conversation(request.ConversationId.Value));

                //
                // Conversation must Belong to Requested Project ...
                if (
                    projectId.HasValue &&
                    conversation.ProjectId != Guid.Empty &&
                    projectId.Value != conversation.ProjectId
                )
                {
                    XException.InvalidArgs.Throw();
                }
                if (conversation.ProjectId != Guid.Empty)
                {
                    projectId = conversation.ProjectId;
                }
            }

            //
            // Project Tier ...
            if (projectId.HasValue)
            {
                await EnsureProjectOwner(projectId.Value, userInfo, cancellationToken);
                result.Add(XAiKnowledgeScopeDescriptor.Project(projectId.Value));
            }

            //
            // User / Global Tiers ...
            if (request.IncludeUser)
            {
                result.Add(XAiKnowledgeScopeDescriptor.User());
            }
            if (request.IncludeGlobal)
            {
                result.Add(XAiKnowledgeScopeDescriptor.Global());
            }

            //
            return result;
        }

        /// <summary>
        /// Scope Prefix (Always Ends with Separator so "a" never Matches "ab"):
        /// "conversation/{id}/" | "project/{id}/" | "user/{ownerId}/" | "global/" ...
        /// </summary>
        private static string GetScopePrefix(
            XAiKnowledgeScopeDescriptor scope,
            XUserClaimsInfoDto userInfo
        )
        {
            //
            var separator = XAiModelsConstants.XAiKnowledgeSeparator;
            var result = scope.Scope switch
            {
                XAiKnowledgeScope.Global => $"{XAiModelsConstants.XAiKnowledgeGlobalPrefix}{separator}",
                XAiKnowledgeScope.User => $"{XAiModelsConstants.XAiKnowledgeUserPrefix}{separator}{userInfo.UserId}{separator}",
                XAiKnowledgeScope.Project => $"{XAiModelsConstants.XAiKnowledgeProjectPrefix}{separator}{scope.ScopeId:D}{separator}",
                XAiKnowledgeScope.Conversation => $"{XAiModelsConstants.XAiKnowledgeConversationPrefix}{separator}{scope.ScopeId:D}{separator}",
                _ => null
            };
            if (result.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Document Chunk Prefix: "{scopePrefix}{fileName}#" ...
        /// Separator Suffix Prevents "a.pdf" from Matching "a.pdf.bak" ...
        /// </summary>
        private string GetDocumentChunkPrefix(
            string scopePrefix,
            string fileName
        )
        {
            return $"{scopePrefix}{fileName}{configuration.TextChunker.ChunkIdentifierSeparator}";
        }

        /// <summary>
        /// Normalize File Name for Identifier (Strip Client Path, Replace Separators) ...
        /// </summary>
        private string NormalizeFileName(string fileName)
        {
            //
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return null;
            }

            //
            // Strip Client Side Path (Both Separators) ...
            var name = Path.GetFileName(fileName.Replace('\\', '/'))?.Trim();
            if (name.IsNullOrEmpty())
            {
                return null;
            }

            //
            foreach (var c in UnsafeFileNameChars)
            {
                name = name.Replace(c, '_');
            }
            var chunkSeparator = configuration.TextChunker.ChunkIdentifierSeparator;
            if (!chunkSeparator.IsNullOrEmpty())
            {
                name = name.Replace(chunkSeparator, "_");
            }

            //
            return name;
        }

        /// <summary>
        /// Load Distinct Document Names of a Scope ...
        /// </summary>
        private async Task<HashSet<string>> LoadDocumentNames(
            string scopePrefix,
            CancellationToken cancellationToken
        )
        {
            //
            var vectors = await dataProvider.LoadVectorsAsync(
                includeEmbedding: false,
                identifierPrefix: scopePrefix,
                cancellationToken: cancellationToken
            );

            //
            var rag = configuration.RAGDescriptor;
            var result = new HashSet<string>(
                (vectors ?? [])
                    .Select(v => v.Metadata.GetMetadata(rag.MetadataFileName))
                    .Where(n => !n.IsNullOrEmpty()),
                StringComparer.Ordinal
            );

            //
            return result;
        }

        /// <summary>
        /// Is Valid User ...
        /// </summary>
        private static bool IsValidUser(XUserClaimsInfoDto userInfo)
        {
            return !userInfo.IsNullOrDefault() && !userInfo.UserId.IsNullOrEmpty();
        }

        /// <summary>
        /// Is Caller Admin ...
        /// </summary>
        private static bool IsAdmin(XUserClaimsInfoDto userInfo)
        {
            //
            var result =
                !userInfo.IsNullOrDefault() &&
                !userInfo.Roles.IsNullOrDefault() &&
                userInfo.Roles.Any(r => string.Equals(r, XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase));

            //
            return result;
        }
        #endregion        
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiService.cs

using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers
{
    public class XAiService : XAIServiceBase, IXAiService
    {
        public XAiService(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAiService> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor
        ) : base(
            ragProvider,
            dataProvider,
            logger,
            configuration,
            validationProvider,
            mcpServerProvider,
            fileContentExtractor,
            XAiApiConstants.XAiDefaultModelName
        )
        { }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAIServiceBase.cs

using System;
using System.Linq;
using System.Text;
using xModels.Dtos;
using xAiApi.Models;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using TimeZoneConverter;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Providers;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiModels.Interfaces;
using xAiModels.Extensions;
using System.Globalization;
using xAiApi.Configurations;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xAiService.Extensions;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.Extensions.AI;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices;

namespace xAiApi.Providers
{
    /// <summary>
    /// Base Ai Service ...
    /// </summary>
    public abstract class XAIServiceBase : IXAiServiceBase
    {
        /// <summary>
        /// Chat Options ...
        /// </summary>
        public ChatOptions Options { get; }

        /// <summary>
        /// Descriptor of Models which used in Service ...
        /// </summary>        
        public XAiModelDescriptor Descriptor { get; }

        private readonly IXAiRAGService ragProvider;
        private readonly IXAiDataProvider dataProvider;
        private readonly ILogger<XAIServiceBase> logger;
        private readonly XAiApiConfiguration configuration;
        private readonly XValidationProvider validationProvider;
        private readonly IXAiMcpServerProvider mcpServerProvider;
        private readonly IXFileContentExtractor fileContentExtractor;

        //
        private readonly bool useProvidedMcpServers;

        protected XAIServiceBase(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAIServiceBase> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor,
            string model = null,
            bool useProvidedMcpServers = true
        )
        {
            //
            this.logger = logger;
            this.ragProvider = ragProvider;
            this.dataProvider = dataProvider;
            this.configuration = configuration;
            this.mcpServerProvider = mcpServerProvider;
            this.validationProvider = validationProvider;
            this.fileContentExtractor = fileContentExtractor;
            this.useProvidedMcpServers = useProvidedMcpServers;

            //
            // Prepare Embedding Model Descriptor ...
            Descriptor = configuration.GetModel(model);
            if (!Descriptor.IsValid())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            // Prepare Chat Options based On Tools ...
            Options = new ChatOptions();
        }

        //
        #region Actions ...
        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextAsync(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Check Prompt Exists ...
            if (prompt.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools];
            }

            //
            var response = await client.GetResponseAsync(
                options: Options,
                messages: history,
                cancellationToken: cancellationToken
            );

            //
            // Validate Response ...
            if (!response.IsValid())
            {
                //
                // Dispose Client ...
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            // Retrieve Response Text ...
            var result = response.Text;

            //
            return result;
        }

        /// <summary>
        /// Base Method for Communicate with LLM ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextAsEnumerable(
            string prompt,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Check Prompt Exists ...
            if (prompt.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: Options,
                messages: history
            );

            //
            await foreach (var res in enumerable)
            {
                //
                // Cancellation Token ...
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question By Providing Vector Search Result ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextByContextAsync(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt, context);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //            
            var response = await client.GetResponseAsync(
                options: Options,
                messages: history,
                cancellationToken: cancellationToken
            );

            //
            // Validate Response ...
            if (!response.IsValid())
            {
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            var result = response.Text;

            //
            return result;
        }

        /// <summary>
        /// Ask a Question By By Providing Vector Search Result and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextByContextAsEnumerable(
            string prompt,
            IList<XAiVectorSearchResult> context = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            using var client = Descriptor.GetClient();
            var history = GetHistory(prompt, context);

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: Options,
                messages: history,
                cancellationToken: cancellationToken
            );

            //
            await foreach (var res in enumerable)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<string> AskTextFromKnowledgeAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                    .AddNotEmpty(prompt)
                    .AddNotNull(userInfo)
                    .AddNotEmpty(userInfo.UserId)
                    .ValidateGroup();

            //
            // Prepare Requirements ...
            var prep = await PrepareChatRequirementsAsync(
                topK: topK,
                type: type,
                files: null,
                prompt: prompt,
                projectId: null,
                minScore: minScore,
                userInfo: userInfo,
                connectionId: null,
                conversationId: null,
                persistPrompt: false,
                additionalContents: null,
                addFilesToKnowledge: false,
                resolveConversation: false,
                extractFileContents: false,
                cancellationToken: cancellationToken
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var response = await client
                .GetResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );
            if (!response.IsValid())
            {
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            return response.Text;
        }

        /// <summary>
        /// Ask a Question By Rag Retrive From Knowledge and Stream Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<string> AskTextFromKnowledgeAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validation ...
            validationProvider
                .GroupValidationBuilder()
                    .AddNotEmpty(prompt)
                    .AddNotNull(userInfo)
                    .AddNotEmpty(userInfo.UserId)
                    .ValidateGroup();

            //
            // Prepare Requirements ...
            var prep = await PrepareChatRequirementsAsync(
                topK: topK,
                type: type,
                files: null,
                prompt: prompt,
                projectId: null,
                minScore: minScore,
                userInfo: userInfo,
                connectionId: null,
                conversationId: null,
                persistPrompt: false,
                additionalContents: null,
                resolveConversation: false,
                addFilesToKnowledge: false,
                extractFileContents: false,
                cancellationToken: cancellationToken
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var stream = client
                .GetStreamingResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );
            await foreach (var res in stream)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiMessageDto> AskAsync(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var prep = await PrepareChatRequirementsAsync(
                type: type,
                topK: topK,
                files: files,
                prompt: prompt,
                minScore: minScore,
                userInfo: userInfo,
                persistPrompt: true,
                projectId: projectId,
                additionalContents: null,
                resolveConversation: true,
                connectionId: connectionId,
                conversationId: conversationId,
                cancellationToken: cancellationToken,
                extractFileContents: extractFileContents,
                addFilesToKnowledge: addFilesToKnowledge
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var response = await client.GetResponseAsync(
                options: Options,
                messages: prep.History,
                cancellationToken: cancellationToken
            );
            if (!response.IsValid())
            {
                //
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            var result = await dataProvider.AddMessage(
                item: new XAiMessageDto
                {
                    Content = response.Text,
                    OwnerId = userInfo.UserId,
                    CreatedOn = DateTime.UtcNow,
                    Role = XAiChatRole.Assistant,
                    ConversationId = prep.Conversation.Id,
                    ConversationTitle = prep.Conversation.Title,
                },
                connectionId: connectionId,
                conversationId: prep.Conversation.Id,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Ask a Question as Prompt and Retrieve Response as Async Enumerable ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="type"></param>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="conversationId"></param>
        /// <param name="connectionId"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async IAsyncEnumerable<XAiResonseMessage> AskAsEnumerable(
            string prompt,
            string type = null,
            int? topK = null,
            float? minScore = null,
            Guid? projectId = null,
            Guid? conversationId = null,
            string connectionId = null,
            bool extractFileContents = false,
            bool addFilesToKnowledge = true,
            IFormFileCollection files = null,
            XUserClaimsInfoDto userInfo = null,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            var prep = await PrepareChatRequirementsAsync(
                type: type,
                topK: topK,
                files: files,
                prompt: prompt,
                minScore: minScore,
                userInfo: userInfo,
                persistPrompt: true,
                projectId: projectId,
                additionalContents: null,
                resolveConversation: true,
                connectionId: connectionId,
                conversationId: conversationId,
                cancellationToken: cancellationToken,
                extractFileContents: extractFileContents,
                addFilesToKnowledge: addFilesToKnowledge
            );

            //
            using var client = Descriptor.GetClient();

            //
            // Handle Provided MCP Servers ...
            if (useProvidedMcpServers)
            {
                //
                var availableTools = await mcpServerProvider
                    .GetAvailableToolsAsync(
                        userInfo: userInfo,
                        cancellationToken: cancellationToken
                );

                //
                Options.Tools = [.. availableTools.Cast<AITool>()];
            }

            //
            var stream = client
                .GetStreamingResponseAsync(
                    options: Options,
                    messages: prep.History,
                    cancellationToken: cancellationToken
                );

            //
            var answer = new System.Text.StringBuilder();
            long sequence = 1;
            await foreach (var res in stream)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                answer.Append(res.Text);
                yield return new XAiResonseMessage
                {
                    Content = res.Text,
                    Sequence = sequence++,
                    OwnerId = userInfo.UserId,
                    Role = XAiChatRole.Assistant,
                    RespondedOn = DateTime.UtcNow,
                    RespondTo = prep.PersistedPromptMessage.Id,
                };
            }

            //
            // Adding Full Message ...
            await dataProvider.AddMessage(
                item: new XAiMessageDto
                {
                    OwnerId = userInfo.UserId,
                    Content = answer.ToString(),
                    CreatedOn = DateTime.UtcNow,
                    Role = XAiChatRole.Assistant,
                    ConversationId = prep.Conversation.Id,
                },
                connectionId: connectionId,
                conversationId: prep.Conversation.Id,
                cancellationToken: cancellationToken
            );
        }
        #endregion

        //
        #region Loaders ...
        /// <summary>
        /// Load AI Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="connectionId"></param>
        /// <param name="includeDefaults"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiProjectDto>> LoadProjects(
            string ownerId,
            string connectionId = null,
            bool includeDefaults = false,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            if (ownerId.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await dataProvider.LoadProjects(
                ownerId: ownerId,
                fillConversations: false,
                connectionId: connectionId,
                fillConversationMessages: false,
                cancellationToken: cancellationToken
            );

            //
            // Handle Defaults Including ...
            if (includeDefaults)
            {
                //
                // Here we have to fill Conversations of Default Project ...
                var defaultProjectId = result.GetDafaultProject(ownerId);
                var defaultProject = result.FirstOrDefault(x => x.Id == defaultProjectId);
                result = result.Where(x => x.Id != defaultProjectId);

                //
                // Reading Conversations of Specified Default Project ...
                var defaultProjectConversations = await dataProvider.LoadConversations(
                    fillMessages: false,
                    connectionId: connectionId,
                    projectId: defaultProjectId,
                    cancellationToken: cancellationToken
                );
                var defaultConversationId = defaultProjectConversations.GetDefaultConversation(
                    ownerId: ownerId,
                    projectId: defaultProjectId
                );
                var defaultConversation = defaultProjectConversations.First(x => x.Id == defaultConversationId);
                defaultProjectConversations = defaultProjectConversations.Where(x => x.Id != defaultConversationId);

                //
                // Reading Default Conversations Messages ...
                var defaultConversationMessages = await dataProvider.LoadMessages(
                    cancellationToken: cancellationToken,
                    conversationId: defaultConversationId
                );

                //
                defaultConversation.Messages = [.. defaultConversationMessages.OrderByDescending(m => m.CreatedOn)];
                defaultProjectConversations = [defaultConversation, .. defaultProjectConversations];
                defaultProject.Conversations = [.. defaultProjectConversations];
                result = [defaultProject, .. result];
            }

            //
            return result;
        }

        /// <summary>
        /// Load Conversations of Specified AI Project ...
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiConversationDto>> LoadConversations(
            Guid projectId,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            if (projectId.IsDefaultGuid())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await dataProvider.LoadConversations(
                fillMessages: false,
                projectId: projectId,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Load Messages of Specified Conversation ...
        /// </summary>
        /// <param name="conversationId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<XAiMessageDto>> LoadMessages(
            Guid conversationId,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            if (conversationId.IsDefaultGuid())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await dataProvider.LoadMessages(
                conversationId: conversationId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }
        #endregion

        //
        #region Queries ...
        /// <summary>
        /// Query Projects ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiProjectDto>> QueryProjects(
            string ownerId,
            XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (ownerId.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var result = await dataProvider.QueryProjects(
                query: query,
                ownerId: ownerId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Query Conversations ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiConversationDto>> QueryConversations(
            string ownerId,
            Guid projectId,
            XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (ownerId.IsNullOrEmpty() ||
                projectId.IsDefaultGuid())
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Retrieve Project ...
            var project = await dataProvider.GetProject(
                id: projectId,
                fillConversations: false,
                fillConversationMessages: false,
                cancellationToken: cancellationToken
            );
            if (project.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Owner ...
            if (ownerId != project.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            var result = await dataProvider.QueryConversations(
                query: query,
                ownerId: ownerId,
                projectId: projectId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Query Messages ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="conversationId"></param>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XQueryResult<XAiMessageDto>> QueryMessages(
            string ownerId,
            Guid conversationId,
            XQuery query,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (ownerId.IsNullOrEmpty() ||
                conversationId.IsDefaultGuid())
            {
                XException.InvalidArgs.Throw();
            }

            //
            // Retrieve Conversation ...
            var conversation = await dataProvider.GetConversation(
                id: conversationId,
                fillMessages: false,
                cancellationToken: cancellationToken
            );
            if (conversation.IsNullOrDefault())
            {
                XException.NotFound.Throw();
            }

            //
            // Validate Owner ...
            if (ownerId != conversation.OwnerId)
            {
                XException.NotAllowed.Throw();
            }

            //
            var result = await dataProvider.QueryMessages(
                query: query,
                ownerId: ownerId,
                conversationId: conversationId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }
        #endregion

        //
        #region Creators ...
        /// <summary>
        /// Create an AI Project ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiProjectDto> CreateProject(
            string ownerId,
            XAiProjectDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await dataProvider.CreateProject(
                item: item,
                ownerId: ownerId,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }

        /// <summary>
        /// Create an AI Conversation ...
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="projectId"></param>
        /// <param name="item"></param>
        /// <param name="connectionId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<XAiConversationDto> CreateConversation(
            string ownerId,
            Guid projectId,
            XAiConversationDto item,
            string connectionId = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await dataProvider.CreateConversation(
                item: item,
                ownerId: ownerId,
                projectId: projectId,
                connectionId: connectionId,
                cancellationToken: cancellationToken
            );

            //
            return result;
        }
        #endregion

        //
        #region Content Extraction ...
        /// <summary>
        /// Try to Extract Files Content ...
        /// </summary>
        /// <param name="files"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractContent(
            IFormFileCollection files,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (!files.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            var extractionResults = new List<XFileExtractionResult>();
            foreach (var file in files)
            {
                //
                if (file.IsNull() || file.Length == 0)
                {
                    continue;
                }

                //
                var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
                if (!fileContentExtractor.CanExtract(mimeType, extractors))
                {
                    continue;
                }

                //
                try
                {
                    //
                    using var stream = file.OpenReadStream();

                    //
                    var fr = await fileContentExtractor.ExtractRichAsync(
                        fileStream: stream,
                        mimeType: mimeType,
                        extractors: extractors,
                        fileName: file.FileName,
                        cancellationToken: cancellationToken
                    );

                    //
                    if (fr.IsValid())
                    {
                        extractionResults.Add(fr);
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch
                {
                    continue;
                }
            }

            //
            var result = string.Empty;
            if (extractionResults.HasChild())
            {
                //
                extractionResults.ForEach(er =>
                {
                    result += $"File {er.FileName} Content:{Environment.NewLine}{er.Text ?? er.AudioTranscript}{Environment.NewLine}----";
                });
            }

            //
            return result;
        }
        #endregion

        /// <summary>
        /// Base Dispose Action ...
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public virtual void Dispose()
        { }

        //
        #region Private ...
        /// <summary>
        /// Prepare a Message History List for LLM Communication based on Prompt ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="forcePrompt"></param>
        /// <returns></returns>
        private IList<ChatMessage> GetHistory(
            string prompt = null,
            bool forcePrompt = true
        )
        {
            //
            // Validate Args ...
            if (prompt.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }

            //
            // User Prompt ...
            var promptMessage = new ChatMessage(
                ChatRole.User,
                prompt
            );

            //
            // Preparing Introduction Prompt ...
            var introductionPrompt = new ChatMessage(
                ChatRole.System,
                configuration.GetPrompt()
            );

            //
            List<ChatMessage> result =
            [
                introductionPrompt,
            ];

            //
            // Prepare Datetime ...
            var datetimeContext = BuildDateTimeContext();
            if (!datetimeContext.IsNullOrEmpty())
            {
                //
                result.Add(new ChatMessage(
                    ChatRole.Assistant,
                    datetimeContext
                ));
            }

            //
            if (forcePrompt &&
                prompt is not null &&
                !prompt.IsNullOrEmpty())
            {
                result.Add(promptMessage);
            }

            //
            return result;
        }

        /// <summary>
        /// Build Chat History for RAG:
        /// [System: Introduction + ChatWithDocuments Prompt + Context Block] + [User: Prompt] ...
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private IList<ChatMessage> GetHistory(
            string prompt,
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var introductionPrompt = configuration.GetPrompt();
            var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
            if (ragPrompt.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            var datetimeContext = BuildDateTimeContext();
            var contextBlock = BuildContextBlock(context);
            var systemText = introductionPrompt;
            if (context.HasChild() &&
                !contextBlock.IsNullOrEmpty()
            )
            {
                //
                systemText =
                    $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}";

                //
                if (!datetimeContext.IsNullOrEmpty())
                {
                    //
                    systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
                }

                //
                systemText +=
                    $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
                    $"Context:{Environment.NewLine}{contextBlock}";
            }

            //
            List<ChatMessage> result =
            [
                new ChatMessage(ChatRole.System, systemText),
                new ChatMessage(ChatRole.User, prompt),
            ];

            //
            return result;
        }

        /// <summary>
        /// Implementing Memory Strategy here ...
        /// </summary>
        /// <param name="project"></param>
        /// <param name="messages"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<IList<ChatMessage>> PrepareMemory(
            XAiProjectDto project,
            IEnumerable<XAiMessageDto> messages,
            IEnumerable<XAiVectorSearchResult> context = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new List<ChatMessage>();

            //
            await Task.FromResult(true);

            //
            // Retrieve Introduction Prompt ...
            var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
            var introductionPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiIntroductionPromptName);
            if (ragPrompt.IsNullOrEmpty() ||
                introductionPrompt.IsNullOrEmpty()
            )
            {
                XException.InvalidData.Throw();
            }

            //
            var contextBlock = BuildContextBlock(context);
            var systemText = introductionPrompt;
            if (context.HasChild() &&
                !contextBlock.IsNullOrEmpty())
            {
                //
                systemText =
                    $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" +
                    $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" +
                    $"Context:{Environment.NewLine}{contextBlock}";
            }

            //
            // Prepare Datetime ...
            var datetimeContext = BuildDateTimeContext();
            if (!datetimeContext.IsNullOrEmpty())
            {
                //
                systemText +=
                    $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
            }

            //
            // Apply Project Prompt as System Text ...
            if (!project.IsNullOrDefault() &&
                !project.Prompt.IsNullOrEmpty())
            {
                systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}";
            }

            //
            // Add System Message ...
            result.Add(new ChatMessage(ChatRole.System, systemText));

            //
            // Attach Message ...
            if (messages.HasChild())
            {
                //
                // TODO: Here we can Implement Memory Management based on 
                // Last nth of Messages, or Summarization of Messages, etc ...
                result = [..result, ..messages
                    .OrderBy(m => m.CreatedOn)
                    .Select(m => m.ToChatMessages())];
            }

            //
            return result;
        }

        /// <summary>
        /// Convert Context Chunks to a Numbered Text Block ...
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string BuildContextBlock(
            IEnumerable<XAiVectorSearchResult> context
        )
        {
            //
            var result = "(no context)";

            //
            var items = context?
                .Where(c =>
                    !c.IsNullOrDefault() &&
                    !c.Text.IsNullOrEmpty()
                )
                .ToList() ?? [];
            if (!items.HasChild())
            {
                return result;
            }

            //
            var index = 1;
            var builder = new System.Text.StringBuilder();
            foreach (var item in items)
            {
                //
                var identifier = item.Identifier.IsNullOrEmpty()
                    ? item.Id.ToString()
                    : item.Identifier;

                //
                builder.AppendLine($"[{index}] Source: [{identifier}] (score: {item.Score:0.000})");
                builder.AppendLine(item.Text.Trim());
                builder.AppendLine("----");

                //
                index++;
            }

            //
            result = builder.ToString();

            //
            return result;
        }

        /// <summary>
        /// Normalizing Rag Params ...
        /// </summary>
        /// <param name="topK"></param>
        /// <param name="minScore"></param>
        /// <param name="type"></param>
        private void NormalizeRagParams(
            ref int? topK,
            ref float? minScore,
            ref string type
        )
        {
            //
            var rag = configuration.RAGDescriptor;

            //
            // TopK ...
            if (!topK.HasValue || topK.Value < 1)
            {
                topK = rag.DefaultTopK;
            }
            else if (topK.Value > rag.MaxTopK)
            {
                topK = rag.MaxTopK;
            }

            //
            // Min Score ...
            if (!minScore.HasValue || minScore.Value < 0 || minScore.Value > 1)
            {
                minScore = rag.DefaultMinScore;
            }

            //
            // Type ...
            if (type.IsNullOrEmpty())
            {
                type = XAiModelsConstants.XAiDefaultKnowledgeType;
            }
        }

        /// <summary>
        /// Retrieve Prepared Chat Context ...
        /// </summary>
        /// <param name="topK"></param>
        /// <param name="type"></param>
        /// <param name="prompt"></param>
        /// <param name="minScore"></param>
        /// <param name="projectId"></param>
        /// <param name="persistPrompt"></param>
        /// <param name="connectionId"></param>
        /// <param name="conversationId"></param>
        /// <param name="resolveConversation"></param>
        /// <param name="files"></param>
        /// <param name="userInfo"></param>
        /// <param name="extractFileContents"></param>
        /// <param name="addFilesToKnowledge"></param>
        /// <param name="additionalContents"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
            int? topK,
            string type,
            string prompt,
            float? minScore,
            Guid? projectId,
            bool persistPrompt,
            string connectionId,
            Guid? conversationId,
            bool resolveConversation,
            IFormFileCollection files,
            XUserClaimsInfoDto userInfo,
            bool extractFileContents = true,
            bool addFilesToKnowledge = false,
            IList<AIContent> additionalContents = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate Args ...
            validationProvider
                .GroupValidationBuilder()
                .AddNotEmpty(prompt)
                .AddNotNull(userInfo)
                .AddNotEmpty(userInfo.UserId)
                .ValidateGroup();

            //
            // Normalize ...
            NormalizeRagParams(
                topK: ref topK,
                type: ref type,
                minScore: ref minScore
            );

            // 
            // Resolve Project and Conversation ...
            XAiProjectDto project = null;
            XAiConversationDto conversation = null;
            if (resolveConversation)
            {
                //
                // Check Project ...
                if (!projectId.HasValue || projectId.Value.IsDefaultGuid())
                {
                    //
                    project = await dataProvider.GetDefaultProject(
                        ownerId: userInfo.UserId,
                        connectionId: connectionId,
                        cancellationToken: cancellationToken
                    );

                    //
                    projectId = project.Id;
                }
                else
                {
                    //
                    project = await dataProvider.GetProject(
                        id: projectId.Value,
                        fillConversations: false,
                        fillConversationMessages: false,
                        cancellationToken: cancellationToken
                    );
                }
                if (project.IsNullOrDefault())
                {
                    XException.NotFound.Throw();
                }

                //
                // Check Conversation ...
                if (!conversationId.HasValue || conversationId.Value.IsDefaultGuid())
                {
                    //
                    conversation = await dataProvider.GetDefaultConversation(
                        ownerId: userInfo.UserId,
                        projectId: projectId.Value,
                        connectionId: connectionId,
                        cancellationToken: cancellationToken
                    );

                    //
                    conversationId = conversation.Id;
                }
                else
                {
                    //
                    conversation = await dataProvider.GetConversation(
                        fillMessages: false,
                        id: conversationId.Value,
                        cancellationToken: cancellationToken
                    );
                }
                if (conversation.IsNullOrDefault())
                {
                    XException.NotFound.Throw();
                }
            }

            // 
            // Ingest Files if Provided and also Resolve Conversation Flagged ...
            if (
                files.HasChild() &&
                resolveConversation &&
                addFilesToKnowledge
            )
            {
                //
                try
                {
                    //
                    var ingestResult = await ragProvider
                        .IngestAsync(
                            files: files,
                            userInfo: userInfo,
                            replaceExisting: true,
                            connectionId: connectionId,
                            scope: XAiKnowledgeScopeDescriptor
                                .Conversation(
                                    type: type,
                                    conversationId: conversationId.Value
                                ),
                            cancellationToken: cancellationToken
                    );
                    if (ingestResult.SkippedFiles.HasChild())
                    {
                        //
                        logger.LogWarning(
                            "Ingest skipped {Count} file(s): {Files}",
                            ingestResult.SkippedFiles.Count,
                            string.Join(", ", ingestResult.SkippedFiles));
                    }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    // 
                    logger.LogError(ex,
                        "Ingest failed for prompt '{Prompt}'. Continuing without attachments.",
                        prompt
                    );
                }
            }

            //
            // If there isn't Files need to add Files to Knowledge ...
            if (files.HasChild() &&
                !addFilesToKnowledge
            )
            {
                //
                // Extract File Content and add them to Additional Contents ...
                foreach (var file in files)
                {
                    //
                    var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
                    if (mimeType.IsNullOrEmpty() ||
                    !fileContentExtractor.CanExtract(mimeType))
                    {
                        continue;
                    }

                    //
                    using var stream = file.OpenReadStream();

                    //
                    // Extract File Content if necessary ...
                    if (extractFileContents)
                    {
                        //
                        var content = await fileContentExtractor.ExtractAsync(
                            fileStream: stream,
                            mimeType: mimeType,
                            cancellationToken: cancellationToken
                        );
                        if (!content.IsNullOrEmpty())
                        {
                            //
                            var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
                            additionalContents = [.. additionalContents, fileContent];
                        }
                    }
                    else
                    {
                        //
                        var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
                        additionalContents = [.. additionalContents, fileContent];
                    }
                }
            }

            // 
            // Request Knowledge ...
            var knowledgeRequest = new XAiKnowledgeAskRequest
            {
                TopK = topK,
                Type = type,
                Prompt = prompt,
                IncludeUser = true,
                MinScore = minScore,
                IncludeGlobal = true,
                ProjectId = resolveConversation ? projectId : null,
                ConversationId = resolveConversation ? conversationId : null,
            };
            var context = await ragProvider
                .RetrieveAsync(
                    userInfo: userInfo,
                    request: knowledgeRequest,
                    cancellationToken: cancellationToken
            );

            //
            // Prepare History and Persisted Prompt Message ...
            IList<ChatMessage> history;
            XAiMessageDto persistedPromptMessage = null;
            if (persistPrompt)
            {
                //
                // Retrieve Conversation Message ...
                var messages = await dataProvider
                    .LoadMessages(
                        conversationId: conversationId.Value,
                        cancellationToken: cancellationToken
                );

                //
                // Prepare History based on Memory Strategies ...
                history = await PrepareMemory(
                    context: context,
                    project: project,
                    messages: messages,
                    cancellationToken: cancellationToken
                );

                //
                // Persist Prompt Message ...
                persistedPromptMessage = await dataProvider.AddMessage(
                    item: new XAiMessageDto
                    {
                        Content = prompt,
                        Role = XAiChatRole.User,
                        OwnerId = userInfo.UserId,
                        CreatedOn = DateTime.UtcNow,
                        ConversationId = conversationId.Value,
                        ConversationTitle = conversation.Title,
                    },
                    connectionId: connectionId,
                    conversationId: conversationId.Value,
                    cancellationToken: cancellationToken
                );

                //
                history
                    .Add(persistedPromptMessage
                        .ToChatMessages(additionalContents: additionalContents));
            }
            else
            {
                //
                history = GetHistory(prompt, context);
            }

            //
            // Prepare Result ...
            var result = new XPreparedChatContext
            {
                Project = project,
                Context = context,
                History = history,
                Conversation = conversation,
                PersistedPromptMessage = persistedPromptMessage,
            };

            //
            return result;
        }

        private string BuildDateTimeContext()
        {
            //
            var cfg = configuration.DateTime;
            if (cfg == null || !cfg.InjectIntoSystemPrompt)
            {
                return string.Empty;
            }

            //
            try
            {
                //
                var tz = ResolveTimezone(cfg.DefaultTimezone);
                var nowUtc = DateTime.UtcNow;
                var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);

                //
                var sb = new StringBuilder();
                sb.AppendLine("[CURRENT DATETIME — for your reference]");
                sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}");

                //
                if (cfg.IncludeDayOfWeek)
                {
                    sb.AppendLine($"Day of week: {nowLocal:dddd}");
                }

                //
                if (cfg.IncludePersianCalendar)
                {
                    //
                    var pc = new PersianCalendar();
                    sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
                }

                //
                if (cfg.IncludeUnixTimestamp)
                {
                    sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
                }

                //
                sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations.");
                return sb.ToString().TrimEnd();
            }
            catch
            {
                return string.Empty;
            }
        }

        private static TimeZoneInfo ResolveTimezone(string id)
        {
            //
            if (id.IsNullOrEmpty())
            {
                return TimeZoneInfo.Utc;
            }

            //
            try
            {
                return TZConvert.GetTimeZoneInfo(id);
            }
            catch
            {
                return TimeZoneInfo.Utc;
            }
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XDefaultThinkingAiService.cs

using xAiApi.Constants;
using xAiApi.Interfaces;
using xCommons.Providers;
using xAiModels.Interfaces;
using xAiApi.Configurations;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers
{
    public class XDefaultThinkingAiService : XAIServiceBase, IXDefaultThinkingAiService
    {
        public XDefaultThinkingAiService(
            IXAiRAGService ragProvider,
            IXAiDataProvider dataProvider,
            ILogger<XAIServiceBase> logger,
            XAiApiConfiguration configuration,
            XValidationProvider validationProvider,
            IXAiMcpServerProvider mcpServerProvider,
            IXFileContentExtractor fileContentExtractor,
            ReasoningEffort effort = ReasoningEffort.Medium,
            ReasoningOutput output = ReasoningOutput.Full
        ) : base(
            ragProvider,
            dataProvider,
            logger,
            configuration,
            validationProvider,
            mcpServerProvider,
            fileContentExtractor,
            XAiApiConstants.XAiDefaultThinkingModelName
        )
        {
            //
            // Preparing Reasoning ...
            Options.Reasoning = new ReasoningOptions
            {
                Output = output,
                Effort = effort,
            };
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStore.cs

using System;
using System.Linq;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiModels.Helpers;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace xAiApi.Providers
{
    public class XInMemoryVectorStore : IXInMemoryVectorStore
    {
        private const int DefaultTtlMinutes = 30;
        private readonly ConcurrentDictionary<Guid, XAiDocumentSession> sessions = new ConcurrentDictionary<Guid, XAiDocumentSession>();
        public int Count { get { RemoveExpired(); return sessions.Count; } }

        public Guid CreateSession(
            string ownerId = null,
            TimeSpan? ttl = null
        )
        {
            //
            var result = CreateSession(null, ownerId, ttl);
            return result;
        }

        public Guid CreateSession(
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null,
            TimeSpan? ttl = null
        )
        {
            //
            var now = DateTime.UtcNow;
            var session = new XAiDocumentSession
            {
                Id = Guid.NewGuid(),
                OwnerId = ownerId,
                CreatedAtUtc = now,
                LastAccessAtUtc = now,
                Ttl = NormalizeTtl(ttl),
                Vectors = Copy(vectors)
            };
            sessions[session.Id] = session;
            var result = session.Id;
            return result;
        }

        public bool Replace(
            Guid sessionId,
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return false;
            }

            //
            lock (session.SyncRoot)
            {
                session.Vectors = Copy(vectors);
                session.LastAccessAtUtc = DateTime.UtcNow;
            }

            //
            return true;
        }

        public bool Add(
            Guid sessionId,
            IEnumerable<XAiVectorDto> vectors,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return false;
            }
            var additions = Copy(vectors);
            lock (session.SyncRoot)
            {
                //
                foreach (var vector in additions)
                {
                    session.Vectors.Add(vector);
                }

                // 
                session.LastAccessAtUtc = DateTime.UtcNow;
            }
            return true;
        }

        public IList<XAiVectorSearchResult> Search(
            Guid sessionId,
            ReadOnlyMemory<float> queryEmbedding,
            int topK = 5,
            float minScore = 0f,
            string ownerId = null
        )
        {
            //
            var result = new List<XAiVectorSearchResult>();
            if (topK <= 0 || queryEmbedding.Length == 0)
            {
                return result;
            }

            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId))
            {
                return result;
            }

            //
            var query = queryEmbedding.ToArray();
            lock (session.SyncRoot)
            {
                //
                session.LastAccessAtUtc = DateTime.UtcNow;
                foreach (var vector in session.Vectors)
                {
                    //
                    if (vector == null || vector.Embedding.Length == 0)
                    {
                        continue;
                    }

                    //
                    var score = VectorHelper.CosineSimilarity(
                        query,
                        vector.Embedding.ToArray()
                    );

                    //
                    if (score >= minScore)
                    {
                        //
                        result.Add(new XAiVectorSearchResult
                        {
                            Score = score,
                            Id = vector.Id,
                            Text = vector.Text,
                            Metadata = vector.Metadata,
                            Identifier = vector.Identifier,
                        });
                    }
                }
            }

            //
            result = [.. result
                .OrderByDescending(x => x.Score)
                .Take(topK)];

            //
            return result;
        }

        public bool TryGet(
            Guid sessionId,
            out XAiDocumentSession session,
            string ownerId = null
        )
        {
            //
            session = null;
            XAiDocumentSession found;
            if (!sessions.TryGetValue(sessionId, out found))
            {
                return false;
            }

            //
            lock (found.SyncRoot)
            {
                //
                XAiDocumentSession current;
                if (!sessions.TryGetValue(sessionId, out current) ||
                    !ReferenceEquals(current, found))
                    return false;

                //
                if (!OwnerMatches(found, ownerId))
                    return false;

                //
                if (found.IsExpired(DateTime.UtcNow))
                {
                    //
                    sessions.TryRemove(sessionId, out found);
                    return false;
                }

                //
                found.LastAccessAtUtc = DateTime.UtcNow;
                session = found;
                return true;
            }
        }

        public bool Remove(
            Guid sessionId,
            string ownerId = null
        )
        {
            //
            XAiDocumentSession session;
            if (!TryGet(sessionId, out session, ownerId)) return false;
            return sessions.TryRemove(sessionId, out session);
        }

        public int RemoveExpired()
        {
            //
            var now = DateTime.UtcNow; var removed = 0;
            foreach (var pair in sessions) { if (pair.Value.IsExpired(now) && sessions.TryRemove(pair.Key, out _)) removed++; }
            return removed;
        }

        //
        #region Private ...
        private static bool OwnerMatches(
            XAiDocumentSession session,
            string ownerId
        )
        {
            return string.IsNullOrEmpty(session.OwnerId) || string.Equals(session.OwnerId, ownerId, StringComparison.Ordinal);
        }

        private static TimeSpan NormalizeTtl(
            TimeSpan? ttl
        )
        {
            return !ttl.HasValue || ttl.Value <= TimeSpan.Zero ? TimeSpan.FromMinutes(DefaultTtlMinutes) : ttl.Value;
        }

        private static IList<XAiVectorDto> Copy(
            IEnumerable<XAiVectorDto> vectors
        )
        {
            return vectors == null ? new List<XAiVectorDto>() : vectors.Where(x => x != null).ToList();
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XInMemoryVectorStoreCleanupService.cs

using System;
using System.Threading;
using xAiApi.Interfaces;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace xAiApi.Providers
{
    /// <summary>
    /// Periodically Removes Expired Document Sessions from In-Memory Vector Store ...
    /// </summary>
    public class XInMemoryVectorStoreCleanupService : BackgroundService
    {
        /// <summary>
        /// Default Cleanup Interval ...
        /// </summary>
        public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5);

        private readonly TimeSpan interval;
        private readonly IXInMemoryVectorStore vectorStore;
        private readonly ILogger<XInMemoryVectorStoreCleanupService> logger;

        public XInMemoryVectorStoreCleanupService(
            IXInMemoryVectorStore vectorStore,
            ILogger<XInMemoryVectorStoreCleanupService> logger
        )
        {
            this.logger = logger;
            this.vectorStore = vectorStore;
            this.interval = DefaultInterval;
        }

        /// <summary>
        /// Cleanup Loop ...
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //
            try
            {
                //
                while (!stoppingToken.IsCancellationRequested)
                {
                    //
                    await Task.Delay(interval, stoppingToken);

                    //
                    try
                    {
                        //
                        var removed = vectorStore.RemoveExpired();
                        if (removed > 0)
                        {
                            //
                            logger.LogInformation(
                                "InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining",
                                removed,
                                vectorStore.Count
                            );
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "InMemoryVectorStore Cleanup Failed");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // Shutdown ...
            }
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XTextChunker.cs

using System.Linq;
using System.Text;
using xAiApi.Models;
using xAiApi.Interfaces;
using xAiApi.Extensions;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace xAiApi.Providers
{
    /// <summary>
    /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy:
    /// Paragraphs -> Sentences -> Words -> Hard Cut ...
    /// </summary>
    public class XTextChunker : IXTextChunker
    {
        /// <summary>
        /// Default Options which used when no Options Provided ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        /// <summary>
        /// Matches Paragraph Boundaries (two or more Line Breaks) ...
        /// </summary>
        private static readonly Regex ParagraphSplitter = new(
            @"\n\s*\n+",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ...
        /// </summary>
        private static readonly Regex SentenceSplitter = new(
            @"(?<=[\.\!\?؟。！？])\s+|(?<=\n)",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Repeated Horizontal Whitespaces ...
        /// </summary>
        private static readonly Regex HorizontalWhitespace = new(
            @"[ \t\f\v\u00A0]{2,}",
            RegexOptions.Compiled
        );

        /// <summary>
        /// Matches Three or more Line Breaks ...
        /// </summary>
        private static readonly Regex ExcessiveLineBreaks = new(
            @"\n{3,}",
            RegexOptions.Compiled
        );

        public XTextChunker(
            XAiApiConfiguration configuration
        )
        {
            //
            // Validate Configuration ...
            if (
                !configuration.IsValid() ||
                !configuration.TextChunker.IsValid()
            )
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Split Text into Chunks ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public IList<XTextChunk> Chunk(
            string text,
            string source = null
        )
        {
            //
            var result = new List<XTextChunk>();
            if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text))
            {
                return result;
            }

            //
            // Normalize ...
            var normalized = configuration.TextChunker.NormalizeWhitespace
                ? Normalize(text)
                : text;

            //
            // Short Circuit for Small Texts ...
            if (normalized.Length <= configuration.TextChunker.ChunkSize)
            {
                //
                result.Add(CreateChunk(normalized, 0, 0, source));
                return result;
            }

            //
            // Build Atomic Units (never larger than ChunkSize) ...
            var units = BuildUnits(normalized);

            //
            // Accumulate Units into Chunks with Overlap ...
            var chunks = Accumulate(units);

            //
            // Merge too Small Tail Chunks ...
            chunks = MergeSmallChunks(chunks);

            //
            for (var i = 0; i < chunks.Count; i++)
            {
                result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source));
            }

            //
            return result;
        }

        /// <summary>
        /// Split Text into Chunks and Return only Texts ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public IList<string> ChunkTexts(string text)
        {
            //
            var result = Chunk(text, null)
                .Select(c => c.Text)
                .ToList();

            //
            return result;
        }

        //
        #region Private ...
        /// <summary>
        /// Internal Text Unit with its Offset in Normalized Source ...
        /// </summary>
        private readonly struct Unit
        {
            public Unit(string text, int offset)
            {
                Text = text;
                Offset = offset;
            }

            public string Text { get; }
            public int Offset { get; }
        }

        /// <summary>
        /// Normalize Line Endings and Whitespaces ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string Normalize(string text)
        {
            //
            var result = text
                .Replace("\r\n", "\n")
                .Replace('\r', '\n');

            //
            result = HorizontalWhitespace.Replace(result, " ");
            result = ExcessiveLineBreaks.Replace(result, "\n\n");

            //
            result = result.Trim();

            //
            return result;
        }

        /// <summary>
        /// Create Chunk Model ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="offset"></param>
        /// <param name="index"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        private XTextChunk CreateChunk(
            string text,
            int offset,
            int index,
            string source
        )
        {
            //
            var identifier = source.IsNullOrEmpty()
                ? index.ToString()
                : $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}";

            //
            var result = new XTextChunk
            {
                Text = text,
                Index = index,
                Source = source,
                StartOffset = offset,
                Identifier = identifier
            };

            //
            return result;
        }

        /// <summary>
        /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private List<Unit> BuildUnits(string text)
        {
            //
            var result = new List<Unit>();

            //
            foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0))
            {
                //
                if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize)
                {
                    //
                    result.Add(paragraph);
                    continue;
                }

                //
                // Paragraph too Long -> Sentences ...
                foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset))
                {
                    //
                    if (sentence.Text.Length <= configuration.TextChunker.ChunkSize)
                    {
                        //
                        result.Add(sentence);
                        continue;
                    }

                    //
                    // Sentence too Long -> Word Boundary Hard Cut ...
                    result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize));
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="splitter"></param>
        /// <param name="baseOffset"></param>
        /// <returns></returns>
        private IEnumerable<Unit> SplitWithOffsets(
            string text,
            Regex splitter,
            int baseOffset
        )
        {
            //
            var position = 0;
            foreach (Match match in splitter.Matches(text))
            {
                //
                var part = text.Substring(position, match.Index - position);
                var unit = TrimUnit(part, baseOffset + position);
                if (!unit.Text.IsNullOrEmpty())
                {
                    yield return unit;
                }

                //
                position = match.Index + match.Length;
            }

            //
            if (position < text.Length)
            {
                //
                var tail = TrimUnit(text.Substring(position), baseOffset + position);
                if (!tail.Text.IsNullOrEmpty())
                {
                    yield return tail;
                }
            }
        }

        /// <summary>
        /// Trim Unit Text while Adjusting its Offset ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        private Unit TrimUnit(
            string text,
            int offset
        )
        {
            //
            var start = 0;
            while (start < text.Length && char.IsWhiteSpace(text[start]))
            {
                start++;
            }

            //
            var end = text.Length;
            while (end > start && char.IsWhiteSpace(text[end - 1]))
            {
                end--;
            }

            //
            var result = new Unit(text.Substring(start, end - start), offset + start);

            //
            return result;
        }

        /// <summary>
        /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ...
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="maxSize"></param>
        /// <returns></returns>
        private IEnumerable<Unit> HardSplit(
            Unit unit,
            int maxSize
        )
        {
            //
            var text = unit.Text;
            var position = 0;

            //
            while (position < text.Length)
            {
                //
                var remaining = text.Length - position;
                if (remaining <= maxSize)
                {
                    //
                    yield return TrimUnit(text.Substring(position), unit.Offset + position);
                    yield break;
                }

                //
                // Find Last Whitespace within Window ...
                var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize);
                if (cut <= position)
                {
                    //
                    // No Whitespace -> Hard Cut ...
                    cut = position + maxSize;
                }

                //
                var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position);
                if (!piece.Text.IsNullOrEmpty())
                {
                    yield return piece;
                }

                //
                position = cut;
                while (position < text.Length && char.IsWhiteSpace(text[position]))
                {
                    position++;
                }
            }
        }

        /// <summary>
        /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ...
        /// </summary>
        /// <param name="units"></param>
        /// <returns></returns>
        private List<Unit> Accumulate(List<Unit> units)
        {
            //
            var result = new List<Unit>();
            if (!units.HasChild())
            {
                return result;
            }

            //
            var buffer = new StringBuilder();
            var buffered = new List<Unit>();
            var bufferOffset = -1;

            //
            foreach (var unit in units)
            {
                //
                var separator = buffer.Length > 0 ? " " : string.Empty;
                var projected = buffer.Length + separator.Length + unit.Text.Length;

                //
                if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0)
                {
                    //
                    // Close Current Chunk ...
                    var closed = buffer.ToString();
                    result.Add(new Unit(closed, bufferOffset));

                    //
                    // Seed Next Chunk with Overlap Tail (only if Unit still Fits) ...
                    var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap);
                    var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize;

                    //
                    buffer.Clear();
                    if (!overlap.IsNullOrEmpty() && fits)
                    {
                        //
                        bufferOffset = ComputeOverlapOffset(buffered, overlap.Length);
                        buffer.Append(overlap);
                        separator = " ";
                    }
                    else
                    {
                        //
                        bufferOffset = -1;
                        separator = string.Empty;
                    }

                    //
                    buffered.Clear();
                }

                //
                if (bufferOffset < 0)
                {
                    bufferOffset = unit.Offset;
                }

                //
                buffer.Append(separator).Append(unit.Text);
                buffered.Add(unit);
            }

            //
            if (buffer.Length > 0)
            {
                result.Add(new Unit(buffer.ToString(), bufferOffset));
            }

            //
            return result;
        }

        /// <summary>
        /// Map Trailing Overlap Length of Buffered Units back to Source Offset ...
        /// Units Joined by Single Space Separator in Buffer ...
        /// </summary>
        /// <param name="buffered"></param>
        /// <param name="overlapLength"></param>
        /// <returns></returns>
        private int ComputeOverlapOffset(
            List<Unit> buffered,
            int overlapLength
        )
        {
            //
            var result = 0;
            var remaining = overlapLength;
            for (var i = buffered.Count - 1; i >= 0; i--)
            {
                //
                var unit = buffered[i];
                if (remaining <= unit.Text.Length)
                {
                    //
                    result = unit.Offset + unit.Text.Length - remaining;
                    return result;
                }

                //
                // Consume Unit and its Leading Separator ...
                remaining -= unit.Text.Length + 1;
                if (remaining <= 0)
                {
                    //
                    result = unit.Offset;
                    return result;
                }
            }

            //
            result = buffered.Count > 0 ? buffered[0].Offset : 0;

            //
            return result;
        }

        /// <summary>
        /// Take Trailing Overlap from Text, Aligned to Word Boundary ...
        /// </summary>
        /// <param name="text"></param>
        /// <param name="overlap"></param>
        /// <returns></returns>
        private string TakeOverlap(
            string text,
            int overlap
        )
        {
            //
            if (overlap <= 0 || text.Length <= overlap)
            {
                return string.Empty;
            }

            //
            var start = text.Length - overlap;
            var boundary = text.IndexOfAny(WordBoundaries, start);
            if (boundary < 0 || boundary >= text.Length - 1)
            {
                //
                // No Boundary inside Window -> Skip Overlap ...
                return string.Empty;
            }

            //
            return text.Substring(boundary + 1).Trim();
        }

        /// <summary>
        /// Merge Chunks Smaller than MinChunkSize into their Predecessor ...
        /// </summary>
        /// <param name="chunks"></param>
        /// <returns></returns>
        private List<Unit> MergeSmallChunks(List<Unit> chunks)
        {
            //
            if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2)
            {
                return chunks;
            }

            //
            var result = new List<Unit>();
            foreach (var chunk in chunks)
            {
                //
                if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0)
                {
                    //
                    var previous = result[result.Count - 1];
                    var merged = $"{previous.Text} {chunk.Text}";
                    if (merged.Length <= configuration.TextChunker.ChunkSize)
                    {
                        result[result.Count - 1] = new Unit(merged, previous.Offset);
                        continue;
                    }
                }

                //
                result.Add(chunk);
            }

            //
            return result;
        }

        /// <summary>
        /// Characters Considered as Word Boundaries ...
        /// </summary>
        private readonly char[] WordBoundaries = [' ', '\n', '\t'];
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XAudioFileContentExtractor.cs

using System;
using System.IO;
using FFMpegCore;
using System.Linq;
using Whisper.net;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts text content from Audio files ...
    /// </summary>    
    public class XAudioFileContentExtractor : IXAudioFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "audio/mpeg",
            "audio/mp3",
            "audio/wav",
            "audio/wave",
            "audio/x-wav",
            "audio/ogg",
            "audio/m4a",
            "audio/mp4",
            "audio/aac",
            "audio/x-m4a",
            "audio/webm"
        ];

        private readonly XAiApiConfiguration configuration;

        public XAudioFileContentExtractor(
            XAiApiConfiguration configuration
        )
        {
            //
            if (configuration.Transcript.IsNullOrDefault() ||
                configuration.Transcript.ModelsPath.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "audio",
                mimeType,
                cancellationToken
            );

            //
            return result.AudioTranscript;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                using var memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream, cancellationToken);
                memoryStream.Position = 0;

                //
                using var wavStream = await ConvertToWavAsync(
                    mimeType: mimeType,
                    inputStream: memoryStream,
                    cancellationToken: cancellationToken
                );

                //
                using var factory = WhisperFactory.FromPath(configuration.Transcript.ModelsPath);
                using var processor = factory.CreateBuilder()
                    .WithLanguage(configuration.Transcript.Language)
                    .Build();

                //
                var segments = new System.Text.StringBuilder();
                await foreach (var segment in processor.ProcessAsync(wavStream, cancellationToken))
                {
                    segments.Append(segment.Text);
                }

                //
                result.AudioTranscript = segments.ToString().Trim();
                result.Text = result.AudioTranscript;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Audio extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        //
        #region Private ...
        /// <summary>
        /// Audio Format Converting to WAV 16kHz Mono 16-bit PCM ...
        /// </summary>
        private async Task<Stream> ConvertToWavAsync(
            Stream inputStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var tempInput = Path.Combine(
                Path.GetTempPath(),
                $"audio_in_{Guid.NewGuid()}{GetExtensionFromMime(mimeType)}"
            );
            var tempOutput = Path.Combine(
                Path.GetTempPath(),
                $"audio_out_{Guid.NewGuid()}.wav"
            );

            //
            MemoryStream result = null;
            try
            {
                //
                using var fs = File.Create(tempInput);
                await inputStream.CopyToAsync(fs, cancellationToken);
                await FFMpegArguments
                    .FromFileInput(tempInput)
                    .OutputToFile(tempOutput, overwrite: true, options => options
                        .WithAudioCodec("pcm_s16le")
                        .WithCustomArgument("-ar 16000")
                        .WithCustomArgument("-ac 1")
                        .ForceFormat("wav"))
                    .ProcessAsynchronously();

                //
                result = new();
                using var fsTmp = File.OpenRead(tempOutput);
                await fsTmp.CopyToAsync(result, cancellationToken);
                result.Position = 0;
            }
            catch
            {
                result = null;
            }
            finally
            {
                //
                // Remove Temparory Files ...
                if (File.Exists(tempInput)) File.Delete(tempInput);
                if (File.Exists(tempOutput)) File.Delete(tempOutput);
            }

            //
            if (result.IsNull())
            {
                XException.ActionFailed.Throw();
            }

            //
            return result;
        }

        /// <summary>
        /// Retrieve File Extension based on mime type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private string GetExtensionFromMime(string mimeType)
        {
            //
            return mimeType?.ToLowerInvariant() switch
            {
                "audio/mpeg" or "audio/mp3" => ".mp3",
                "audio/m4a" or "audio/mp4" or "audio/aac" or "audio/x-m4a" => ".m4a",
                "audio/ogg" => ".ogg",
                "audio/webm" => ".webm",
                "audio/wav" or "audio/wave" or "audio/x-wav" => ".wav",
                _ => ".tmp"
            };
        }
        #endregion
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XCodeFileContentExtractor.cs

using System;
using System.Linq;
using xCommons.Extensions;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using System.IO;
using System.Threading;
using xAiModels.Models;
using System.Text;

namespace xAiApi.Providers.Extractors
{
    /// <summary> 
    /// Extractor for source code files ...
    /// (C#, Python, JavaScript, TypeScript, Java, Go, Rust, ...) 
    /// </summary> 
    public class XCodeFileContentExtractor : IXCodeFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/x-c",
            "text/x-go",
            "text/yaml",
            "text/x-php",
            "text/x-c++",
            "text/x-sql",
            "text/x-java",
            "text/x-rust",
            "text/x-ruby",
            "text/x-csharp",
            "text/x-python",
            "text/javascript",
            "text/typescript",
            "text/x-java-source",
            "application/x-yaml",
            "application/x-csharp",
            "application/x-python",
            "application/javascript",
            "application/typescript",
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                string.Empty,
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            // Read entire source code as UTF-8 (with BOM detection) ...
            using var reader = new StreamReader(
                fileStream,
                Encoding.UTF8,
                leaveOpen: false,
                detectEncodingFromByteOrderMarks: true
            );

            //
            var content = await reader.ReadToEndAsync();

            //
            // Normalize line endings for consistent downstream processing ...
            content = content?
                .Replace("\r\n", "\n")
                .Replace("\r", "\n");

            //
            result.Text = content;

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XDocxFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts text content from DOCX files using DocumentFormat.OpenXml ...
    /// </summary>    
    public class XDocxFileContentExtractor : IXDocxFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var stringBuilder = new StringBuilder();

            //
            using (var wordDocument = WordprocessingDocument.Open(memoryStream, false))
            {
                //
                var body = wordDocument.MainDocumentPart?.Document?.Body;
                if (body != null)
                {
                    //
                    var paragraphs = body.Elements<Paragraph>();
                    foreach (var paragraph in paragraphs)
                    {
                        //
                        var text = paragraph.InnerText?.Trim();
                        if (!string.IsNullOrEmpty(text))
                        {
                            stringBuilder.AppendLine(text);
                        }
                    }
                }
            }

            //
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType,
                fileStream: fileStream,
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XEpubFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using VersOne.Epub;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for EPUB electronic publication format
    /// (application/epub+zip)
    /// </summary>    
    public class XEpubFileContentExtractor : IXEpubFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/epub+zip"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "book.epub",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                result.Text = await ExtractEpubAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"EPUB extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Epub Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractEpubAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            // Copy to MemoryStream (VersOne.Epub requires seekable stream) ...
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            // Load EPUB book ...
            EpubBook book = await EpubReader.ReadBookAsync(ms);
            var sb = new StringBuilder();

            //
            // Extract metadata ...

            //
            if (!book.Title.IsNullOrEmpty())
            {
                sb.AppendLine($"Title: {book.Title}");
            }

            //
            if (!book.Author.IsNullOrEmpty())
            {
                sb.AppendLine($"Author: {book.Author}");
            }

            //
            sb.AppendLine();

            //
            // Extract chapters in reading order ...
            var chapterIndex = 0;
            foreach (var textContentFile in book.ReadingOrder)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                chapterIndex++;
                sb.AppendLine($"[Chapter {chapterIndex}]");
                var plainText = ExtractTextFromHtml(
                    textContentFile.Content
                );
                if (!plainText.IsNullOrEmpty())
                {
                    sb.AppendLine(plainText);
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract Text Content from HTML ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string ExtractTextFromHtml(string html)
        {
            //
            var result = string.Empty;

            //
            if (html.IsNullOrEmpty())
            {
                return result;
            }

            //
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);

            //
            var sb = new StringBuilder();
            var textNodes = htmlDocument.DocumentNode
                .SelectNodes("//text()");

            //
            if (textNodes == null)
            {
                return result;
            }

            //
            foreach (var node in textNodes)
            {
                //
                var text = node.InnerText?.Trim();
                if (!text.IsNullOrEmpty())
                {
                    sb.AppendLine(text);
                }
            }

            //
            result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XExcelFileContentExtractor.cs

using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Text;
using ExcelDataReader;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    public class XExcelFileContentExtractor : IXExcelFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
            "application/vnd.ms-excel" // .xls        
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var stringBuilder = new StringBuilder();

            //
            using (var reader = ExcelReaderFactory.CreateReader(memoryStream))
            {
                //
                var result = reader.AsDataSet();
                foreach (DataTable table in result.Tables)
                {
                    //
                    stringBuilder.AppendLine($"--- Sheet: {table.TableName} ---");

                    //
                    var headers = new string[table.Columns.Count];
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        headers[i] = table.Columns[i].ColumnName;
                    }
                    stringBuilder.AppendLine(string.Join(" | ", headers));
                    stringBuilder.AppendLine(new string('-', 50));

                    //
                    foreach (DataRow row in table.Rows)
                    {
                        //
                        var rowValues = new string[row.ItemArray.Length];
                        for (int i = 0; i < row.ItemArray.Length; i++)
                        {
                            rowValues[i] = row.ItemArray[i]?.ToString()?.Trim() ?? string.Empty;
                        }
                        stringBuilder.AppendLine(string.Join(" | ", rowValues));
                    }
                    stringBuilder.AppendLine();
                }
            }

            //
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType, 
                fileStream: fileStream, 
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XFileContentExtractor.cs

using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Composite extractor that delegates to appropriate extractor 
    /// based on MIME type ...
    /// </summary>    
    public class XFileContentExtractor : IXFileContentExtractor
    {
        //
        private readonly IList<IXFileContentExtractorBase> _extractors = [];

        public XFileContentExtractor(
            IEnumerable<IXFileContentExtractorBase> availableExtractors
        )
        {
            //
            _extractors = [.. availableExtractors
                .Where(e => e.GetType() != typeof(XFileContentExtractor))];
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <returns></returns>
        public bool CanExtract(
            string mimeType,
            string[] extractors = null
        )
        {
            //
            return GetExtractors(extractors)
                .Any(e => e.CanExtract(mimeType));
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var extractor = GetExtractors(extractors)
                .FirstOrDefault(e => e.CanExtract(mimeType));
            if (extractor.IsNull())
            {
                //
                XException.NotAllowed.Throw(
                    $"Unsupported file type: {mimeType}"
                );
            }

            //
            var result = await extractor
                .ExtractAsync(
                    mimeType: mimeType,
                    fileStream: fileStream,
                    cancellationToken: cancellationToken
                );

            //
            return result;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="extractors"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            string[] extractors = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            var extractor = GetExtractors(extractors)
                .FirstOrDefault(e => e.CanExtract(mimeType));
            if (extractor.IsNull())
            {
                //
                XException.NotAllowed.Throw(
                    $"Unsupported file type: {mimeType}"
                );
            }

            //
            var result = await extractor
                .ExtractRichAsync(
                    mimeType: mimeType,
                    fileName: fileName,
                    fileStream: fileStream,
                    cancellationToken: cancellationToken
                );

            //
            return result;
        }

        /// <summary>
        /// Extract Provided Extractors ...
        /// </summary>
        /// <param name="extractors"></param>
        /// <returns></returns>
        private IList<IXFileContentExtractorBase> GetExtractors(string[] extractors = null)
        {
            //
            var result = new List<IXFileContentExtractorBase>();

            //
            if (extractors.IsNull() || !extractors.HasChild())
            {
                //
                result = [.. _extractors];
            }
            else
            {
                //
                result = [.. _extractors
                    .Where(e => extractors
                        .Any(ex => e.GetType().FullName.Contains(ex)))];
            }

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XHtmlFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for HTML documents (text/html, application/xhtml+xml)
    /// </summary>
    public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/html",
            "application/xhtml+xml"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.html",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                result.Text = await ExtractHtmlAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                result.ErrorMessage =
                    $"HTML extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Html Content as Text ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractHtmlAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            // Load HTML into HtmlDocument
            var html = new HtmlDocument();
            html.Load(fileStream);

            // Remove noise nodes (script, style, etc.)
            RemoveNoiseNodes(html);

            // Extract title
            var title = ExtractTitle(html);

            // Extract body text
            var body = html.DocumentNode
                .SelectSingleNode("//body");
            var bodyText = body?.InnerText ?? string.Empty;

            // Clean and normalize text
            var cleanedText = CleanText(bodyText);

            // Build structured output
            var sb = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(title))
            {
                sb.AppendLine($"Title: {title}");
                sb.AppendLine();
            }
            sb.AppendLine(cleanedText);

            return sb.ToString().TrimEnd();
        }

        /// <summary>
        /// Remove Noisy Nodes ...
        /// </summary>
        /// <param name="html"></param>
        private void RemoveNoiseNodes(HtmlDocument html)
        {
            //
            // Remove script and style tags ...
            var noiseTags = new[] { "script", "style", "noscript", "iframe" };
            foreach (var tag in noiseTags)
            {
                //
                var nodes = html.DocumentNode
                    .Descendants(tag)
                    .ToList();
                foreach (var node in nodes)
                {
                    node.Remove();
                }
            }
        }

        /// <summary>
        /// Extract Title ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string ExtractTitle(HtmlDocument html)
        {
            //
            var titleNode = html.DocumentNode
                .SelectSingleNode("//title");

            //
            var result = titleNode?.InnerText?.Trim() ?? string.Empty;

            //
            return result;
        }

        /// <summary>
        /// Clean Text ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string CleanText(string text)
        {
            //
            var result = string.Empty;

            //
            if (text.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Decode HTML entities ...
            text = System.Net.WebUtility.HtmlDecode(text);

            //
            // Normalize whitespace ...
            text = System.Text.RegularExpressions.Regex
                .Replace(text, @"\s+", " ")
                .Trim();

            //
            result = text;

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XImageFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using xAiApi.Configurations;
using xCommons.Extensions;
using xExceptions.Constants;
using Tesseract;

namespace xAiApi.Providers.Extractors
{
    public class XImageFileContentExtractor : IXImageFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/gif",
            "image/webp",
            "image/bmp"
        ];

        /// <summary>
        /// AI Api Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        public XImageFileContentExtractor(
            XAiApiConfiguration configuration
        )
        {
            //
            if (configuration.IsNullOrDefault() ||
                configuration.OCR.IsNullOrDefault() ||
                configuration.OCR.DataPath.IsNullOrEmpty() ||
                configuration.OCR.DefaultLanguage.IsNullOrEmpty())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "image",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            var imageBytes = memoryStream.ToArray();

            //
            result.Images.Add(new XExtractedImage
            {
                Bytes = imageBytes,
                MimeType = mimeType,
                Description = $"Attached image: {fileName}"
            });

            //
            // OCR Fallback ...
            if (configuration.OCR.EnableOcrFallback)
            {
                //
                try
                {
                    //
                    var ocrText = await PerformOcrAsync(imageBytes, cancellationToken);
                    if (!string.IsNullOrWhiteSpace(ocrText))
                    {
                        result.Text = ocrText;
                    }
                }
                catch
                {
                    // OCR failed, but image is still available for Vision
                }
            }

            //
            return result;
        }

        /// <summary>
        /// Do OCR on Image for Text Extraction ...
        /// </summary>
        private async Task<string> PerformOcrAsync(
            byte[] imageBytes,
            CancellationToken cancellationToken
        )
        {
            //
            return await Task.Run(() =>
            {
                //
                // Validate Path ...
                if (!Directory.Exists(configuration.OCR.DataPath))
                {
                    //
                    throw new DirectoryNotFoundException(
                        $"TessData directory not found at: {configuration.OCR.DataPath}. " +
                        "Please download traineddata files from https://github.com/tesseract-ocr/tessdata"
                    );
                }
            
                //
                using var engine = new TesseractEngine(
                    datapath: configuration.OCR.DataPath,
                    language: configuration.OCR.DefaultLanguage,
                    engineMode: configuration.OCR.EngineMode
                );

                //
                using var pix = Pix.LoadFromMemory(imageBytes);

                //
                cancellationToken.ThrowIfCancellationRequested();

                //
                using var page = engine.Process(pix);

                //
                var text = page.GetText();

                //
                text = text?.Trim();

                //
                return text ?? string.Empty;
            }, cancellationToken);
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XOpenDocumentFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using OfficeIMO.OpenDocument;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for OpenDocument Format (ODF) documents
    /// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
    /// </summary>    
    public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/vnd.oasis.opendocument.text",          // .odt
            "application/vnd.oasis.opendocument.spreadsheet",   // .ods
            "application/vnd.oasis.opendocument.presentation"   // .odp
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.rtf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            // 
            try
            {
                //
                if (IsOdt(mimeType))
                {
                    result.Text = await ExtractOdtAsync(fileStream, cancellationToken);
                }
                else if (IsOds(mimeType))
                {
                    result.Text = await ExtractOdsAsync(fileStream, cancellationToken);
                }
                else if (IsOdp(mimeType))
                {
                    result.Text = await ExtractOdpAsync(fileStream, cancellationToken);
                }
                else
                {
                    result.ErrorMessage =
                        $"Unsupported OpenDocument MIME type: {mimeType}";
                }
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"RTF extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOdt(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.text";

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOds(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet";

            //
            return result;
        }

        /// <summary>
        /// Check Mime Type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOdp(string mimeType)
        {
            //
            var result = mimeType?
                .ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation";

            //
            return result;
        }

        /// <summary>
        /// Extract ODT File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdtAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var document = OdtDocument.Load(ms);

            //
            var sb = new StringBuilder();
            foreach (var paragraph in document.Paragraphs)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                if (!paragraph.Text.IsNullOrEmpty())
                {
                    sb.AppendLine(paragraph.Text.Trim());
                }
            }

            //
            // 4. استخراج جداول
            var tableIndex = 0;
            foreach (var table in document.Tables)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                tableIndex++;
                sb.AppendLine();
                sb.AppendLine($"[Table {tableIndex}]");

                //
                foreach (var row in table.Rows)
                {
                    //
                    var cellTexts = new List<string>();
                    foreach (var cell in row.Cells)
                    {
                        //
                        var cellText = string.Join(
                            " ",
                            cell.Paragraphs
                                .Select(p => p.Text?.Trim())
                                .Where(t => !string.IsNullOrWhiteSpace(t))
                        );
                        cellTexts.Add(cellText);
                    }

                    //
                    sb.AppendLine($"  | {string.Join(" | ", cellTexts)} |");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract ODS File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdsAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var document = OdsDocument.Load(ms);
            var sb = new StringBuilder();
            var sheetIndex = 0;
            foreach (var sheet in document.Sheets)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                sheetIndex++;
                sb.AppendLine($"--- Sheet: {sheet.Name} ---");

                //
                for (long row = 0; row < sheet.RowCount; row++)
                {
                    //
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    //
                    var cellValues = new List<string>();
                    var columnCount = sheet.ColumnRuns.Sum(r => r.RepeatCount);
                    for (long col = 0; col < columnCount; col++)
                    {
                        //
                        var value = sheet.GetValue(row, col);
                        if (!value.IsNull())
                        {
                            var text = value.LexicalValue?.Trim() ?? string.Empty;
                            cellValues.Add(text);
                        }
                    }

                    //
                    if (cellValues.Any(v => !string.IsNullOrWhiteSpace(v)))
                    {
                        sb.AppendLine(string.Join(" | ", cellValues));
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract ODS File Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOdpAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            var presentation = OdpPresentation.Load(ms);
            var sb = new StringBuilder();
            var slideIndex = 0;
            foreach (var slide in presentation.Slides)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                //
                slideIndex++;
                sb.AppendLine($"[Slide {slideIndex}]");
                var textParts = new List<string>();

                //
                foreach (var shape in slide.Shapes)
                {
                    //
                    if (shape is OdpTextBox textBox)
                    {
                        //
                        foreach (var paragraph in textBox.Paragraphs)
                        {
                            //
                            if (!paragraph.Text.IsNullOrEmpty())
                            {
                                textParts.Add(paragraph.Text.Trim());
                            }
                        }
                    }
                    else if (shape is OdpShape odpShape)
                    {
                        //
                        foreach (var paragraph in odpShape.TextParagraphs)
                        {
                            //
                            if (!paragraph.Text.IsNullOrEmpty())
                            {
                                textParts.Add(paragraph.Text.Trim());
                            }
                        }
                    }
                }

                //
                if (textParts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in textParts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPdfFileContentExtractor.cs

using System;
using System.IO;
using SkiaSharp;
using PDFtoImage;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xAiApi.Configurations;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from PDF files using PdfPig ...
    /// </summary>    
    public class XPdfFileContentExtractor : IXPdfFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "application/pdf"
        ];

        /// <summary>
        /// Api Configuration ...
        /// </summary>
        private readonly XAiApiConfiguration configuration;

        public XPdfFileContentExtractor(XAiApiConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.pdf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream, cancellationToken);
            memoryStream.Position = 0;

            //
            var extractedText = await ExtractTextAsync(
                memoryStream,
                cancellationToken
            );
            if (IsTextSufficient(extractedText))
            {
                // PDF متنی است
                result.Text = extractedText;
            }
            else
            {
                // PDF اسکن‌شده است - Fallback به تصویر
                memoryStream.Position = 0;
                result = await FallbackToImageExtractionAsync(
                    memoryStream,
                    fileName,
                    mimeType,
                    cancellationToken
                );
                result.UsedImageFallback = true;
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Text From PDF Files using Common way ...
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractTextAsync(
            Stream pdfStream,
            CancellationToken cancellationToken
        )
        {
            //
            var result = await Task.Run(() =>
            {
                //
                var sb = new StringBuilder();
                using var document = UglyToad.PdfPig.PdfDocument.Open(pdfStream);
                foreach (var page in document.GetPages())
                {
                    //
                    var text = page.Text?.Trim();
                    if (!string.IsNullOrEmpty(text))
                    {
                        //
                        sb.AppendLine(text);
                        sb.AppendLine();
                    }
                }

                //
                return sb.ToString();
            }, cancellationToken);

            //
            return result;
        }

        /// <summary>
        /// Check Extracted Content is Sufficient or not ...
        /// if not try to Falling Back using Images ...
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private bool IsTextSufficient(string text)
        {
            //
            if (string.IsNullOrWhiteSpace(text))
            {
                return false;
            }

            //
            // حذف فاصله‌ها و بررسی طول
            var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());

            //
            var result = cleanText.Length >= configuration.PDFToImageDescriptor.MinTextLengthThreshold;

            //
            return result;
        }

        /// <summary>
        /// Fallback Converts PDF Pages to Images ...
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<XFileExtractionResult> FallbackToImageExtractionAsync(
            Stream pdfStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType,
                UsedImageFallback = true
            };

            //
            await Task.Run(() =>
            {
                //
                try
                {
                    //
                    // Calculating With ...
                    var width = configuration.PDFToImageDescriptor.Width;
                    if (width >= 0 && configuration.PDFToImageDescriptor.MaxImageWidth > 0)
                    {
                        //
                        width = Math.Min(
                            width,
                            configuration.PDFToImageDescriptor.MaxImageWidth
                        );
                    }

                    //
                    // Preparing Render Options ...
                    var renderOptions = new RenderOptions
                    {
                        Width = width,
                        Dpi = configuration.PDFToImageDescriptor.Dpi,
                        Height = configuration.PDFToImageDescriptor.Height,
                        UseTiling = configuration.PDFToImageDescriptor.UseTiling,
                        WithFormFill = configuration.PDFToImageDescriptor.WithFormFill,
                        WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio,
                        WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations,
                        DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds,
                    };

                    //
                    // Preparing Images to Fallback ...
                    var pagesCount = Conversion.GetPageCount(pdfStream);
                    pdfStream.Position = 0;

                    //
                    if (configuration.PDFToImageDescriptor.MaxPagesForImageFallback > 0)
                    {
                        //
                        pagesCount = Math.Min(
                            pagesCount,
                            configuration.PDFToImageDescriptor.MaxPagesForImageFallback
                        );
                    }

                    //                    
                    for (int pageIndex = 0; pageIndex < pagesCount; pageIndex++)
                    {
                        //
                        //  Check Cancellation Token ...
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        //
                        try
                        {
                            //
                            var skBitmap = Conversion.ToImage(
                                page: pageIndex,
                                pdfStream: pdfStream,
                                options: renderOptions
                            );
                            pdfStream.Position = 0;

                            //
                            using (skBitmap)
                            using (var image = SKImage.FromBitmap(skBitmap))
                            using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                            using (var ms = new MemoryStream())
                            {
                                //
                                data.SaveTo(ms);
                                result.Images.Add(new XExtractedImage
                                {
                                    Bytes = ms.ToArray(),
                                    MimeType = "image/png",
                                    Description = $"Page {pageIndex + 1}, rendered from {fileName}"
                                });
                            }
                        }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = $"PDF image extraction failed: {ex.Message}";
                }
            }, cancellationToken);

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPlainTextFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from plain text files (txt, md, csv, json, xml) ...
    /// </summary>    
    public class XPlainTextFileContentExtractor : IXPlainTextFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/plain",
            "text/markdown",
            "text/csv",
            "text/xml",
            "application/json",
            "application/xml"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            using var reader = new StreamReader(fileStream);
            return await reader.ReadToEndAsync();
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var content = await ExtractAsync(
                mimeType: mimeType,
                fileStream: fileStream,
                cancellationToken: cancellationToken
            );

            //
            var result = new XFileExtractionResult
            {
                Text = content,
                FileName = fileName,
                MimeType = mimeType
            };

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XPowerPointFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using OfficeIMO.PowerPoint;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Packaging;
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from all PowerPoint formats
    /// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
    /// </summary>    
    public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            // OpenXML Formats
            "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
            "application/vnd.openxmlformats-officedocument.presentationml.slideshow",    // .ppsx
            "application/vnd.openxmlformats-officedocument.presentationml.template",     // .potx
            "application/vnd.ms-powerpoint.presentation.macroEnabled.12",               // .pptm
            "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",                  // .ppsm
            "application/vnd.ms-powerpoint.template.macroEnabled.12",                   // .potm
            // Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
            "application/vnd.ms-powerpoint"
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream: fileStream,
                fileName: "presentation",
                mimeType: mimeType,
                cancellationToken: cancellationToken
            );
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                if (IsOpenXmlFormat(mimeType))
                {
                    //
                    result.Text = await ExtractOpenXmlAsync(
                        fileStream,
                        cancellationToken
                    );
                }
                else if (IsLegacyFormat(mimeType))
                {
                    //
                    result.Text = await ExtractLegacyAsync(
                        fileStream,
                        cancellationToken
                    );
                }
                else
                {
                    //
                    result.ErrorMessage =
                        $"Unsupported PowerPoint MIME type: {mimeType}";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage =
                    $"PowerPoint extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Check Open XML Format ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsOpenXmlFormat(string mimeType)
        {
            //
            var result = mimeType?.ToLowerInvariant() switch
            {
                "application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
                "application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
                "application/vnd.openxmlformats-officedocument.presentationml.template" => true,
                "application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
                "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
                "application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
                _ => false
            };

            //
            return result;
        }

        /// <summary>
        /// Check Legacy Format ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        private bool IsLegacyFormat(string mimeType)
        {
            //
            var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
            return result;
        }

        /// <summary>
        /// Extract an Slide Title ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private string GetSlideTitle(SlidePart slidePart)
        {
            //
            var result = string.Empty;

            //
            // Title placeholder has specific type
            var titleShape = slidePart.Slide
                .Descendants<DocumentFormat.OpenXml.Presentation.Shape>()
                .FirstOrDefault(s => s.NonVisualShapeProperties?
                    .NonVisualDrawingProperties?
                    .Name?.Value?
                    .StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
                );
            if (titleShape != null)
            {
                //
                var titleText = titleShape
                    .Descendants<DrawingText>()
                    .Select(t => t.Text?.Trim())
                    .Where(t => !string.IsNullOrWhiteSpace(t));
                result = string.Join(" ", titleText);
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Speaker Notes ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private string GetSpeakerNotes(SlidePart slidePart)
        {
            //
            var result = string.Empty;

            //
            var notesSlidePart = slidePart.NotesSlidePart;
            if (notesSlidePart?.NotesSlide == null)
            {
                return result;
            }

            //
            var notesTexts = notesSlidePart.NotesSlide
                .Descendants<DrawingText>()
                .Select(t => t.Text?.Trim())
                .Where(t => !string.IsNullOrWhiteSpace(t))
                .ToList();

            //
            result = notesTexts.Count > 0
                ? string.Join(Environment.NewLine, notesTexts)
                : null;

            //
            return result;
        }

        /// <summary>
        /// Extract OpenXML Tables ...
        /// </summary>
        /// <param name="slidePart"></param>
        /// <returns></returns>
        private static string ExtractOpenXmlTables(SlidePart slidePart)
        {
            //
            var sb = new StringBuilder();

            //
            var tableElements = slidePart.Slide
                .Descendants<DocumentFormat.OpenXml.Drawing.Table>();

            //
            var tableIndex = 0;
            foreach (var table in tableElements)
            {
                //
                tableIndex++;
                sb.AppendLine($"  Table {tableIndex}:");

                //
                foreach (var row in table
                    .Descendants<DocumentFormat.OpenXml.Drawing.TableRow>())
                {
                    //
                    var cells = row
                        .Descendants<DocumentFormat.OpenXml.Drawing.TableCell>()
                        .Select(c => string.Join(" ", c
                            .Descendants<DrawingText>()
                            .Select(t => t.Text?.Trim())
                            .Where(t => !string.IsNullOrWhiteSpace(t))))
                        .ToList();

                    //
                    if (cells.Count > 0)
                    {
                        sb.AppendLine($"    | {string.Join(" | ", cells)} |");
                    }
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString();

            //
            return result;
        }

        /// <summary>
        /// Extract Open XML Format ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractOpenXmlAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var sb = new StringBuilder();

            //
            // Copy to MemoryStream (OpenXml requires seekable stream)
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            using var presentationDocument = PresentationDocument.Open(ms, false);
            var presentationPart = presentationDocument.PresentationPart;
            if (presentationPart == null)
            {
                XException.InvalidData.Throw();
            }

            //
            var slideParts = presentationPart.SlideParts.ToList();
            var slideIndex = 0;
            foreach (var slidePart in slideParts)
            {
                //
                if (cancellationToken.IsCancellationRequested) break;
                slideIndex++;

                //
                sb.AppendLine($"[Slide {slideIndex}]");

                //
                // 1. Extract slide title
                var slideTitle = GetSlideTitle(slidePart);
                if (!string.IsNullOrWhiteSpace(slideTitle))
                {
                    sb.AppendLine($"Title: {slideTitle}");
                }

                //
                // 2. Extract body texts
                var bodyTexts = slidePart.Slide
                    .Descendants<DrawingText>()
                    .Select(t => t.Text?.Trim())
                    .Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
                    .ToList();
                if (bodyTexts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in bodyTexts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                // 3. Extract tables
                var tables = ExtractOpenXmlTables(slidePart);
                if (!string.IsNullOrWhiteSpace(tables))
                {
                    //
                    sb.AppendLine("[Tables]");
                    sb.AppendLine(tables);
                }

                //
                // 4. Extract speaker notes
                var notes = GetSpeakerNotes(slidePart);
                if (!string.IsNullOrWhiteSpace(notes))
                {
                    //
                    sb.AppendLine("[Speaker Notes]");
                    sb.AppendLine(notes);
                }

                //
                // 5. Image count metadata
                var imageCount = slidePart.ImageParts?.Count() ?? 0;
                if (imageCount > 0)
                {
                    sb.AppendLine($"[Images: {imageCount}]");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }

        /// <summary>
        /// Extract Legacy Format ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractLegacyAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var sb = new StringBuilder();

            //
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms, cancellationToken);
            ms.Position = 0;

            //
            using var presentation = PowerPointPresentation.Load(ms);
            var slideIndex = 0;
            foreach (var slide in presentation.Slides)
            {
                //
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }
                slideIndex++;

                //
                sb.AppendLine($"[Slide {slideIndex}]");

                //
                var textParts = new List<string>();
                var imageCount = 0;
                foreach (var shape in slide.Shapes)
                {
                    //
                    if (shape is PowerPointTextBox textBox)
                    {
                        //
                        if (!textBox.Text.IsNullOrEmpty())
                        {
                            textParts.Add(textBox.Text.Trim());
                        }
                    }
                    else if (shape is PowerPointAutoShape autoShape)
                    {
                        //
                        if (!autoShape.AltText.IsNullOrEmpty())
                        {
                            textParts.Add(autoShape.AltText.Trim());
                        }
                    }
                    else if (shape is PowerPointPicture picture)
                    {
                        imageCount++;
                    }
                }

                //
                if (textParts.Count > 0)
                {
                    //
                    sb.AppendLine("Content:");
                    foreach (var text in textParts)
                    {
                        sb.AppendLine($"  - {text}");
                    }
                }

                //
                if (imageCount > 0)
                {
                    sb.AppendLine($"[Images: {imageCount}]");
                }

                //
                sb.AppendLine();
            }

            //
            var result = sb.ToString().TrimEnd();

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XRtfFileContentExtractor.cs

using System;
using RtfPipe;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using System.Text.RegularExpressions;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extractor for Rich Text Format (RTF) documents
    /// (application/rtf, text/rtf)
    /// </summary>
    public class XRtfFileContentExtractor : IXRtfFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "text/rtf",
            "application/rtf",
        ];

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = await ExtractRichAsync(
                fileStream,
                "document.rtf",
                mimeType,
                cancellationToken
            );

            //
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            // 
            try
            {
                //
                result.Text = await ExtractRtfAsync(
                    fileStream,
                    cancellationToken
                );
            }
            catch (Exception ex)
            {
                //
                result.ErrorMessage =
                    $"RTF extraction failed: {ex.Message}";
            }

            //
            return result;
        }

        /// <summary>
        /// Extract RTF Content ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> ExtractRtfAsync(
            Stream fileStream,
            CancellationToken cancellationToken
        )
        {
            //
            var result = string.Empty;

            //
            // Read RTF content as string ...
            using var reader = new StreamReader(
                fileStream,
                Encoding.UTF8,
                detectEncodingFromByteOrderMarks: true,
                leaveOpen: true
            );
            var rtfContent = await reader.ReadToEndAsync();
            if (rtfContent.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Convert RTF to HTML using RtfPipe ...
            var html = Rtf.ToHtml(rtfContent);

            //
            // Convert HTML to plain text ...
            result = HtmlToPlainText(html);

            //
            return result;
        }

        /// <summary>
        /// Converts Html to Text ...
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string HtmlToPlainText(string html)
        {
            //
            var result = string.Empty;

            //
            if (html.IsNullOrEmpty())
            {
                result = string.Empty;
            }

            //
            // Remove HTML tags ...
            result = Regex.Replace(
                html,
                "<.*?>",
                string.Empty,
                RegexOptions.Singleline
            );

            //
            // Decode HTML entities ...
            result = System.Net.WebUtility.HtmlDecode(result);

            //
            // Normalize whitespace ...
            result = Regex.Replace(result, @"\s+", " ").Trim();

            //
            return result;
        }
    }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\Extractors\XVisionFileContentExtractor.cs

using System;
using System.IO;
using System.Linq;
using System.Threading;
using xAiApi.Constants;
using xAiModels.Models;
using xAiApi.Extensions;
using xAiApi.Interfaces;
using xCommons.Extensions;
using xAiModels.Extensions;
using xAiApi.Configurations;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices;

namespace xAiApi.Providers.Extractors
{
    /// <summary>
    /// Extracts content from files using Vision Model ...
    /// </summary>    
    public class XVisionFileContentExtractor : IXVisionFileContentExtractor
    {
        /// <summary>
        /// Supported MIME Types ...
        /// </summary>
        private static readonly string[] SupportedMimeTypes =
        [
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/webp",
            "image/bmp",
            "application/pdf",
        ];

        //
        private readonly string prompt;
        private readonly XAiModelDescriptor descriptor;

        public XVisionFileContentExtractor(
            XAiApiConfiguration configuration,
            string promptName = XAiApiConstants.XAiApiContentExtractionPromptName,
            string modelName = XAiApiConstants.XAiDefaultVisionModelName
        )
        {
            // 
            // Retrieve Descriptoir ...
            if (modelName.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }
            descriptor = configuration.GetModel(modelName);

            //
            // Retrieve Extraction Prompt ...
            if (promptName.IsNullOrEmpty())
            {
                XException.InvalidArgs.Throw();
            }
            prompt = configuration.GetPrompt(
                name: promptName,
                @params: null
            );

            //
            // Validate Requirements ...
            if (prompt.IsNullOrEmpty() || descriptor.IsNullOrDefault())
            {
                XException.InvalidData.Throw();
            }
        }

        /// <summary>
        /// Check if this extractor supports the specified MIME type ...
        /// </summary>
        public bool CanExtract(string mimeType)
        {
            //
            return SupportedMimeTypes.Contains(
                mimeType?.ToLowerInvariant() ?? string.Empty
            );
        }

        /// <summary>
        /// Extract text content from file stream ...
        /// </summary>
        public async Task<string> ExtractAsync(
            Stream fileStream,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            var result = await ExtractRichAsync(fileStream, "file", mimeType, cancellationToken);
            return result.Text;
        }

        /// <summary>
        /// Extract content from stream as Rich Result ...
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<XFileExtractionResult> ExtractRichAsync(
            Stream fileStream,
            string fileName,
            string mimeType,
            CancellationToken cancellationToken = default
        )
        {
            //
            var result = new XFileExtractionResult
            {
                FileName = fileName,
                MimeType = mimeType
            };

            //
            try
            {
                //
                using var memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream, cancellationToken);
                var imageBytes = memoryStream.ToArray();
                var messages = new[]
                {
                    //
                    new ChatMessage(ChatRole.User, new[]
                    {
                        new DataContent(imageBytes, mimeType)
                    })
                };

                //
                var extractedContent = await RequestOCRAsync(
                    messages: messages,
                    cancellationToken: cancellationToken
                );
                if (!extractedContent.IsNullOrEmpty())
                {
                    result.Text = extractedContent.Trim();
                }
                else
                {
                    result.ErrorMessage = "there is not any Extracted Content ...";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Error in Vision Extraction: {ex.Message} ...";
            }

            //
            return result;
        }
    
        //
        #region OCR ...
        /// <summary>
        /// Request for Doing OCR on Given Data Contents ...
        /// </summary>
        /// <param name="messages"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>        
        public virtual async Task<string> RequestOCRAsync(
            IList<ChatMessage> messages,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!messages.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = descriptor.GetClient();

            //
            // Preparing Extraction Prompt Message ...
            var pMessage = new ChatMessage(
                ChatRole.System,
                prompt
            );

            //
            messages = [pMessage, .. messages];

            //
            var response = await client.GetResponseAsync(
                messages: messages,
                cancellationToken: cancellationToken
            );

            //
            // Validate Response ...
            if (!response.IsValid())
            {
                //
                // Dispose Client ...
                client.Dispose();
                XException.ActionFailed.Throw();
            }

            //
            // Retrieve Response Text ...
            var result = response.Text;

            //
            return result;
        }

        /// <summary>
        /// Request for Doing OCR on Given Data Contents as Stream ...
        /// </summary>
        /// <param name="messages"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>        
        public virtual async IAsyncEnumerable<string> RequestOCRAsEnumerable(
            IList<ChatMessage> messages,
            [EnumeratorCancellation]
            CancellationToken cancellationToken = default
        )
        {
            //
            // Validate ...
            if (!messages.HasChild())
            {
                XException.InvalidArgs.Throw();
            }

            //
            using var client = descriptor.GetClient();

            //
            // Preparing Extraction Prompt Message ...
            var pMessage = new ChatMessage(
                ChatRole.System,
                prompt
            );

            //
            messages = [pMessage, .. messages];

            //
            var enumerable = client.GetStreamingResponseAsync(
                options: null,
                messages: messages
            );

            //
            await foreach (var res in enumerable)
            {
                //
                // Cancellation Token ...
                if (cancellationToken.IsCancellationRequested)
                {
                    yield break;
                }

                //
                yield return res.Text;
            }
        }
        #endregion    
     }
}

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_093cc96f-7927-40f4-a61b-2cc948412f09.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ثبت XAiMcpServer به عنوان Entity و مدیریت داینامیک | مستند فنی</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --code-bg: #1e293b;
    --code-text: #e2e8f0;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1100px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge { display: flex; align-items: center; gap: 12px; }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta { text-align: left; font-size: 12px; opacity: 0.9; }
  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 26px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 { font-size: 15px; font-weight: 400; opacity: 0.9; }

  .document-body { padding: 40px; }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section { margin-bottom: 45px; page-break-inside: avoid; }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }
  .section-title h3 { font-size: 19px; font-weight: 700; color: var(--primary); margin-bottom: 2px; }
  .section-title .subtitle { font-size: 12px; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; direction: ltr; text-align: right; }

  .section-content { padding-right: 10px; }
  .section-content p { margin-bottom: 12px; text-align: justify; text-indent: 20px; }
  .section-content p.no-indent { text-indent: 0; }

  .highlight-box, .info-box, .success-box, .warning-box, .danger-box {
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
  }
  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
  }

  .danger-box {
    background: linear-gradient(to left, #fff5f5, #fed7d7);
    border: 1px solid #fc8181;
    border-right: 4px solid var(--danger);
  }

  pre {
    background: var(--code-bg);
    color: var(--code-text);
    padding: 20px 22px;
    border-radius: 8px;
    overflow-x: auto;
    margin: 15px 0;
    font-family: 'JetBrains Mono', 'Courier New', monospace;
    font-size: 12.5px;
    line-height: 1.7;
    direction: ltr;
    text-align: left;
    border: 1px solid #334155;
    position: relative;
  }

  pre::before {
    content: attr(data-lang);
    position: absolute;
    top: 8px;
    right: 12px;
    font-size: 10px;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: 600;
  }

  code {
    font-family: 'JetBrains Mono', 'Courier New', monospace;
    background: #f1f5f9;
    color: #1e293b;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12.5px;
    direction: ltr;
    display: inline-block;
  }

  pre code { background: none; color: inherit; padding: 0; display: inline; }

  .file-path {
    background: #2c5282;
    color: #bee3f8;
    padding: 8px 14px;
    border-radius: 6px 6px 0 0;
    font-family: 'JetBrains Mono', monospace;
    font-size: 11.5px;
    direction: ltr;
    text-align: left;
    margin-top: 15px;
    margin-bottom: -15px;
    border-bottom: 2px solid #1a365d;
  }

  .file-path::before {
    content: '📄 ';
    margin-left: 4px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th { padding: 14px 16px; text-align: right; font-weight: 600; font-size: 13px; }
  .styled-table td { padding: 13px 16px; border-bottom: 1px solid var(--border); font-size: 13px; }
  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }
  .styled-table .highlight-row { background: #fffaf0 !important; font-weight: 600; }

  .file-tree {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 20px 25px;
    margin: 15px 0;
    font-family: 'JetBrains Mono', monospace;
    font-size: 12.5px;
    direction: ltr;
    text-align: left;
    line-height: 1.9;
    color: var(--text-muted);
  }
  .file-tree .folder { color: var(--primary); font-weight: 600; }
  .file-tree .new { color: var(--success); }
  .file-tree .modify { color: var(--warning); }

  .step-badge {
    display: inline-block;
    background: var(--accent);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 12px;
    font-weight: 600;
    margin-left: 8px;
  }

  .checklist { list-style: none; padding: 0; margin: 15px 0; }
  .checklist li {
    padding: 10px 15px;
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    margin-bottom: 8px;
    border-radius: 6px;
    font-size: 13.5px;
  }
  .checklist li::before {
    content: '✓';
    color: var(--success);
    font-weight: 700;
    margin-left: 10px;
    display: inline-block;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }
  .conclusion-box h3 { font-size: 22px; font-weight: 800; margin-bottom: 15px; color: var(--accent); }
  .conclusion-box p { font-size: 14px; line-height: 1.8; text-indent: 0 !important; margin-bottom: 15px; }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }
  .document-footer .footer-brand { font-weight: 700; color: var(--accent); margin-bottom: 5px; font-size: 14px; }
  .footer-divider { width: 60px; height: 2px; background: var(--accent); margin: 10px auto; }

  @media print { body { background: white; padding: 0; } .document-container { box-shadow: none; border-radius: 0; } .section { page-break-inside: avoid; } }
  @media (max-width: 768px) { .document-body { padding: 25px 20px; } .document-header { padding: 30px 20px; } .header-top { flex-direction: column; gap: 15px; } .doc-meta { text-align: center; } }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge"><div class="company-logo"></div></div>
      <div class="doc-meta">
        <div>شماره مستند: ARCH-MCP-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: آبان ۱۴۰۵</div>
        <div>طبقه‌بندی: فنی-داخلی</div>
      </div>
    </div>
    <div class="document-title">
      <span class="label">TECHNICAL DESIGN DOCUMENT</span>
      <h1>ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک</h1>
      <h2>Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>هدف مستند:</strong><br>
      این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول <code>xAiModels</code>، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از <code>appSettings</code>، کنترلرهای CRUD، و اتصال به <code>XMcpServerConnectionManager</code> را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند <code>XAiProject</code> و <code>XAiConversation</code>) پیاده‌سازی می‌شوند.
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 0: Architecture Overview -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۰</div>
        <div class="section-title">
          <h3>نمای کلی معماری و جریان داده</h3>
          <div class="subtitle">Architecture Overview</div>
        </div>
      </div>
      <div class="section-content">
        <p>جریان کلی سیستم به این شکل خواهد بود:</p>

<pre data-lang="flow">
┌─────────────────────────────────────────────────────────────────┐
│  appsettings.json → "McpServers:Servers[]"                      │
│         │                                                        │
│         ▼                                                        │
│  XMcpServerSeederService (IHostedService)                       │
│         │   (در Startup اجرا می‌شود)                              │
│         ▼                                                        │
│  IXAiMcpServerRepositoryService → AddAsync/UpdateAsync           │
│         │                                                        │
│         ▼                                                        │
│  [AiMcpServers] Table (SQL/Mongo/InMemory)                      │
│         │                                                        │
│         ├──→ McpServersController (CRUD API)                    │
│         │         │                                              │
│         │         ▼                                              │
│         │    XMcpServerConnectionManager.RefreshAsync()          │
│         │                                                        │
│         ▼                                                        │
│  XMcpServerConnectionManager                                    │
│         │   (Ping + ListTools + Cache)                          │
│         ▼                                                        │
│  ChatOptions.Tools → IXDefaultAiService                         │
└─────────────────────────────────────────────────────────────────┘
</pre>

        <div class="info-box">
          <strong>💡 نکته کلیدی:</strong> <code>appSettings</code> فقط نقش <strong>Seed اولیه</strong> را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به <code>appSettings</code> اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر <code>UpdateExisting = true</code> باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند.
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">ساختار فایل‌های جدید/تغییر یافته:</h4>
        <div class="file-tree">
<span class="folder">xSaherelmWorkspace/</span>
├── <span class="folder">Modules/xAiModels/</span>
│   ├── <span class="folder">Models/</span>
│   │   ├── <span class="folder">Entities/</span>
│   │   │   └── <span class="new">XAiMcpServer.cs</span>                          [NEW]
│   │   │   ├── <span class="folder">Dtos/</span>
│   │   │   │   └── <span class="new">XAiMcpServerDto.cs</span>                     [NEW]
│   │   │   └── <span class="new">XMcpServerDescriptor.cs</span>                  [NEW]
│   │   ├── <span class="folder">Configurations/</span>
│   │   │   ├── <span class="modify">XAiModelMappersProfile.cs</span>              [MODIFY]
│   │   │   └── <span class="folder">Entities/</span>
│   │   │       └── <span class="new">XAiMcpServerEntityConfiguration.cs</span>  [NEW]
│   │   ├── <span class="modify">Constants/XAiModelsConstants.cs</span>            [MODIFY]
│   │   ├── <span class="folder">Interfaces/</span>
│   │   │   ├── <span class="folder">Entities/</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerKeyGenerator.cs</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerRepository.cs</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerRepositoryEvents.cs</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerRepositoryProvider.cs</span>
│   │   │   │   └── <span class="new">IXAiMcpServerEntityHub.cs</span>
│   │   │   ├── <span class="folder">Dtos/</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerDtoHub.cs</span>
│   │   │   │   ├── <span class="new">IXAiMcpServerRepositoryService.cs</span>
│   │   │   │   └── <span class="new">IXAiMcpServerServiceProvider.cs</span>
│   │   │   └── <span class="folder">Enrichers/</span>
│   │   │       └── <span class="new">IXAiMcpServerEnricher.cs</span>
│   │   ├── <span class="folder">Providers/</span>
│   │   │   ├── <span class="folder">Entities/</span>
│   │   │   │   ├── <span class="new">XAiMcpServerEFRepository.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerInMemoryRepository.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerMongoRepository.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerKeyGenerator.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerRepositoryEvents.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerEntityHub.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerRepositoryProvider.cs</span>
│   │   │   │   └── <span class="new">XAiMcpServerSeederBase.cs</span>
│   │   │   ├── <span class="folder">Dtos/</span>
│   │   │   │   ├── <span class="new">XAiMcpServerDtoHub.cs</span>
│   │   │   │   ├── <span class="new">XAiMcpServerRepositoryService.cs</span>
│   │   │   │   └── <span class="new">XAiMcpServerServiceProvider.cs</span>
│   │   │   ├── <span class="folder">Enrichers/</span>
│   │   │   │   └── <span class="new">XAiMcpServerEnricher.cs</span>
│   │   │   └── <span class="new">XAiMcpServerEntityRegisterar.cs</span>
│   │   ├── <span class="modify">Helpers/XAiModelsHelper.cs</span>                [MODIFY]
│   │   └── <span class="modify">DI/XDIHelperExtension.cs</span>                  [MODIFY]
│   │
├── <span class="folder">xAiApi/</span>
│   ├── <span class="folder">Configurations/</span>
│   │   └── <span class="new">XMcpServersConfiguration.cs</span>                [NEW]
│   ├── <span class="folder">Services/</span>
│   │   ├── <span class="new">XMcpServerSeederService.cs</span>                 [NEW]
│   │   └── <span class="modify">XMcpServerConnectionManager.cs</span>             [MODIFY]
│   ├── <span class="folder">Controllers/</span>
│   │   └── <span class="new">McpServersController.cs</span>                    [NEW]
│   ├── <span class="modify">Database/XAiApiDbContext.cs</span>                  [MODIFY]
│   ├── <span class="modify">Startup.cs</span>                                    [MODIFY]
│   └── <span class="modify">appsettings.json</span>                              [MODIFY]
</div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 1: Entity -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>تعریف Entity در xAiModels</h3>
          <div class="subtitle">Entity Layer / Models/Entities/XAiMcpServer.cs</div>
        </div>
      </div>
      <div class="section-content">
        <p>ابتدا موجودیت اصلی را با الگوبرداری دقیق از <code>XAiProject</code> و <code>XAiVector</code> تعریف می‌کنیم. فیلدهای JSON (مانند <code>Arguments</code>، <code>Headers</code>، <code>EnvironmentVariables</code>) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.</p>

        <div class="file-path">xAiModels/Models/Entities/XAiMcpServer.cs</div>
<pre data-lang="csharp"><code>using System;
using xModels.Base;
using System.ComponentModel.DataAnnotations;

namespace xAiModels.Models.Entities
{
    /// &lt;summary&gt;
    /// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
    /// &lt;/summary&gt;
    public class XAiMcpServer : XBaseGuidIDEntity
    {
        /// &lt;summary&gt;
        /// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
        /// &lt;/summary&gt;
        [Required]
        [StringLength(255)]
        public string OwnerId { get; set; }

        /// &lt;summary&gt;
        /// نام یکتای سرور (برای هر Owner) ...
        /// &lt;/summary&gt;
        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        /// &lt;summary&gt;
        /// توضیحات ...
        /// &lt;/summary&gt;
        [StringLength(1000)]
        public string Description { get; set; }

        /// &lt;summary&gt;
        /// فعال/غیرفعال ...
        /// &lt;/summary&gt;
        public bool Enabled { get; set; } = true;

        /// &lt;summary&gt;
        /// نوع Transport: "stdio" یا "http" ...
        /// &lt;/summary&gt;
        [Required]
        [StringLength(50)]
        public string Transport { get; set; } = "stdio";

        // --- تنظیمات Stdio ---
        [StringLength(500)]
        public string Command { get; set; }

        /// &lt;summary&gt;
        /// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
        /// &lt;/summary&gt;
        public string Arguments { get; set; }

        [StringLength(1000)]
        public string WorkingDirectory { get; set; }

        /// &lt;summary&gt;
        /// متغیرهای محیطی به‌صورت JSON Object ...
        /// &lt;/summary&gt;
        public string EnvironmentVariables { get; set; }

        // --- تنظیمات HTTP ---
        [StringLength(1000)]
        public string Endpoint { get; set; }

        /// &lt;summary&gt;
        /// هدرهای HTTP به‌صورت JSON Object ...
        /// &lt;/summary&gt;
        public string Headers { get; set; }

        /// &lt;summary&gt;
        /// مهلت اتصال و اعتبارسنجی (ثانیه) ...
        /// &lt;/summary&gt;
        public int TimeoutSeconds { get; set; } = 30;

        // --- Audit ---
        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
}</code></pre>

        <div class="file-path">xAiModels/Models/Dtos/XAiMcpServerDto.cs</div>
<pre data-lang="csharp"><code>using System;
using xModels.Base;
using xModels.Dtos;

namespace xAiModels.Models.Dtos
{
    public class XAiMcpServerDto : XBaseGuidIDEntityDto
    {
        public string OwnerId { get; set; }
        public virtual XPersonDto Owner { get; set; } = null;

        public string Name { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; }
        public string Transport { get; set; }

        public string Command { get; set; }
        public string Arguments { get; set; }
        public string WorkingDirectory { get; set; }
        public string EnvironmentVariables { get; set; }

        public string Endpoint { get; set; }
        public string Headers { get; set; }

        public int TimeoutSeconds { get; set; }

        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedAt { get; set; }
    }
}</code></pre>

        <div class="file-path">xAiModels/Models/XMcpServerDescriptor.cs</div>
<pre data-lang="csharp"><code>using System.Collections.Generic;

namespace xAiModels.Models
{
    /// &lt;summary&gt;
    /// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
    /// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
    /// &lt;/summary&gt;
    public class XMcpServerDescriptor
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public bool Enabled { get; set; } = true;
        public string Transport { get; set; } = "stdio";
        public int TimeoutSeconds { get; set; } = 30;

        // Stdio
        public string Command { get; set; }
        public List&lt;string&gt; Arguments { get; set; } = new();
        public string WorkingDirectory { get; set; }
        public Dictionary&lt;string, string&gt; EnvironmentVariables { get; set; }

        // HTTP
        public string Endpoint { get; set; }
        public Dictionary&lt;string, string&gt; Headers { get; set; }
    }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 2: Constants + Configuration -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>ثابت‌ها و Configuration</h3>
          <div class="subtitle">Constants / EntityConfiguration</div>
        </div>
      </div>
      <div class="section-content">
        <p>ثابت‌های جدید را به <code>XAiModelsConstants</code> اضافه کنید (دقیقاً مطابق الگوی موجود):</p>

        <div class="file-path">xAiModels/Constants/XAiModelsConstants.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── اضافه کنید در struct XAiModelsConstants ──

// Table Mapping
public const string XAiMcpServerTable = "AiMcpServers";

// GraphQL Collection Mappings
public const string XAiMcpServerSingleName = "aiMcpServer";
public const string XAiMcpServerCollectionName = "aiMcpServers";

// Hubs
public const string XAiMcpServerDtoHub = "aiMcpServerDto";
public const string XAiMcpServerEntityHub = "aiMcpServerEntity";

// EF Repositories Helper Extensions
public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor";</code></pre>

        <div class="file-path">xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs</div>
<pre data-lang="csharp"><code>using System;
using xAiModels.Constants;
using xDataService.Providers;
using xAiModels.Models.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace xAiModels.Configurations.Entities
{
    public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration&lt;XAiMcpServer, Guid&gt;
    {
        public override void Configure(EntityTypeBuilder&lt;XAiMcpServer&gt; builder)
        {
            builder.ToTable(XAiModelsConstants.XAiMcpServerTable);

            // نام برای هر Owner یکتاست
            builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
        }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/XAiMcpServerEntityRegisterar.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Providers;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
using Microsoft.EntityFrameworkCore;
using xAiModels.Configurations.Entities;

namespace xAiModels.Providers
{
    public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
    {
        public XAiMcpServerEntityRegisterar()
        : base(nameof(XAiMcpServerEntityRegisterar))
        {
            AddEntity&lt;XAiMcpServer, Guid&gt;();
        }

        public override void ConfigureEntities(ModelBuilder modelBuilder)
        {
            modelBuilder
                .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);

            base.ConfigureEntities(modelBuilder);
        }
    }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 3: Interfaces -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>لایه Interfaces</h3>
          <div class="subtitle">Interfaces / Entities + Dtos + Enrichers</div>
        </div>
      </div>
      <div class="section-content">
        <p>مطابق الگوی <code>XAiProject</code>، تمام اینترفیس‌های مربوطه را در سه پوشه <code>Entities</code>، <code>Dtos</code> و <code>Enrichers</code> ایجاد کنید:</p>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">الف) Interfaces/Entities</h4>

        <div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerKeyGenerator : IXKeyGenerator&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepository : IXBaseRepository&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs</div>
<pre data-lang="csharp"><code>using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents&lt;XAiMcpServer&gt; { }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerEntityHub : IXBaseEntityHub&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;
using xAiModels.Providers.Entities;

namespace xAiModels.Interfaces.Entities
{
    public interface IXAiMcpServerRepositoryProvider
        : IXBaseEntityProvider&lt;XAiMcpServer, Guid, XAiMcpServerEntityHub&gt; { }
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) Interfaces/Dtos</h4>

        <div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xAiModels.Models.Dtos;
using xPushService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerDtoHub
        : IXBaseDtoHub&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt; { }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs</div>
<pre data-lang="csharp"><code>using System;
using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xDataService.Interfaces;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerRepositoryService
        : IXBaseRepositoryService&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;
    {
        /// &lt;summary&gt;
        /// یافتن سرور بر اساس OwnerId و Name ...
        /// &lt;/summary&gt;
        Task&lt;XAiMcpServerDto&gt; FindByNameAsync(
            string ownerId,
            string name,
            CancellationToken cancellationToken = default
        );
    }
}</code></pre>

        <div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs</div>
<pre data-lang="csharp"><code>using System;
using xAiModels.Models.Dtos;
using xPushService.Interfaces;
using xAiModels.Providers.Dtos;
using xAiModels.Models.Entities;

namespace xAiModels.Interfaces.Dtos
{
    public interface IXAiMcpServerServiceProvider
        : IXBaseDtoProvider&lt;XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub&gt; { }
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ج) Interfaces/Enrichers</h4>

        <div class="file-path">xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs</div>
<pre data-lang="csharp"><code>using System.Threading;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xAiModels.Models.Entities;
using System.Collections.Generic;

namespace xAiModels.Interfaces.Enrichers
{
    public interface IXAiMcpServerEnricher
    {
        Task&lt;XAiMcpServerDto&gt; Enrich(
            XAiMcpServer source,
            CancellationToken cancellationToken = default
        );

        Task&lt;XAiMcpServerDto&gt; Enrich(
            XAiMcpServerDto source,
            CancellationToken cancellationToken = default
        );

        Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
            IEnumerable&lt;XAiMcpServer&gt; sources,
            CancellationToken cancellationToken = default
        );

        Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
            IEnumerable&lt;XAiMcpServerDto&gt; sources,
            CancellationToken cancellationToken = default
        );
    }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 4: Repository Layer -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>لایه Repository</h3>
          <div class="subtitle">EF / Mongo / InMemory + KeyGenerator + Events + Hubs</div>
        </div>
      </div>
      <div class="section-content">
        <p>سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با <code>XAiProjectEFRepository</code> و <code>XAiProjectMongoRepository</code> بسازید:</p>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Db;
using xDataService.Providers;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerEFRepository&lt;TContext&gt;
        : XBaseEFRepository&lt;XAiMcpServer, Guid, TContext&gt;, IXAiMcpServerRepository
        where TContext : XDbContext
    {
        public XAiMcpServerEFRepository(
            IXUnitOfWorks&lt;TContext&gt; unitOfWorks,
            XDataServiceConfiguration configuration,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerMongoRepository
        : XBaseMongoRepository&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerRepository
    {
        public XAiMcpServerMongoRepository(
            XDataBaseConfiguration dbConfiguration,
            XDataServiceConfiguration configuration,
            string collectionName = null,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerInMemoryRepository
        : XBaseInMemoryRepository&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerRepository
    {
        public XAiMcpServerInMemoryRepository(
            XDataServiceConfiguration configuration,
            IXAiMcpServerKeyGenerator keyGenerator = null,
            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
        ) : base(configuration, keyGenerator, baseRepositoryEvents) { }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs</div>
<pre data-lang="csharp"><code>using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerKeyGenerator
        : XGuidKeyGenerator&lt;XAiMcpServer&gt;, IXAiMcpServerKeyGenerator { }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs</div>
<pre data-lang="csharp"><code>using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerRepositoryEvents
        : XBaseRepositoryEvents&lt;XAiMcpServer&gt;, IXAiMcpServerRepositoryEvents { }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Base;
using xAiModels.Models.Entities;
using Microsoft.Extensions.Logging;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerEntityHub
        : XBaseEntityHub&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerEntityHub
    {
        public XAiMcpServerEntityHub(ILogger&lt;XAiMcpServerEntityHub&gt; logger)
            : base(logger) { }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Base;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;

namespace xAiModels.Providers.Entities
{
    public class XAiMcpServerRepositoryProvider
        : XBaseEntityProvider&lt;XAiMcpServer, Guid, XAiMcpServerEntityHub&gt;, IXAiMcpServerRepositoryProvider
    {
        public XAiMcpServerRepositoryProvider(
            IHubContext&lt;XAiMcpServerEntityHub&gt; hub,
            IXAiMcpServerRepository repository,
            XDataServiceConfiguration dataConfiguration,
            IXIdentityProvider identityProvider = null
        ) : base(hub, repository, dataConfiguration, identityProvider) { }
    }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 5: DTO Service Layer -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>لایه Service (RepositoryService + ServiceProvider + Enricher)</h3>
          <div class="subtitle">Providers/Dtos + Enrichers</div>
        </div>
      </div>
      <div class="section-content">
        <div class="file-path">xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── درون سازنده XAiModelMappersProfile اضافه کنید ──

// XAiMcpServer
CreateMap&lt;XAiMcpServer, XAiMcpServerDto&gt;();
CreateMap&lt;XAiMcpServerDto, XAiMcpServer&gt;();</code></pre>

        <div class="file-path">xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs</div>
<pre data-lang="csharp"><code>using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using xAiModels.Interfaces.Enrichers;

namespace xAiModels.Providers.Enrichers
{
    public class XAiMcpServerEnricher : IXAiMcpServerEnricher
    {
        private readonly IXIdentityProvider identityProvider;

        public XAiMcpServerEnricher(IXIdentityProvider identityProvider)
        {
            this.identityProvider = identityProvider;
        }

        public virtual async Task&lt;XAiMcpServerDto&gt; Enrich(
            XAiMcpServer source,
            CancellationToken cancellationToken = default
        )
        {
            var result = source.MapConvert&lt;XAiMcpServerDto, XAiMcpServer&gt;();
            result = await Enrich(source: result, cancellationToken: cancellationToken);
            return result;
        }

        public virtual async Task&lt;XAiMcpServerDto&gt; Enrich(
            XAiMcpServerDto source,
            CancellationToken cancellationToken = default
        )
        {
            XPersonDto owner = null;
            if (!source.OwnerId.IsNullOrEmpty())
            {
                var device = identityProvider.GetDevice();
                var userInfo = await identityProvider.GetUserInfo(
                    device: device,
                    userSelectByParam: source.OwnerId
                );
                owner = userInfo.ToXPersonDto();
            }

            var result = source.MapConvert&lt;XAiMcpServerDto, XAiMcpServerDto&gt;();
            result.Owner = owner;
            return result;
        }

        public virtual async Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
            IEnumerable&lt;XAiMcpServer&gt; sources,
            CancellationToken cancellationToken = default
        )
        {
            var tasks = sources.Select(x => Enrich(x, cancellationToken));
            return await Task.WhenAll(tasks);
        }

        public virtual async Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
            IEnumerable&lt;XAiMcpServerDto&gt; sources,
            CancellationToken cancellationToken = default
        )
        {
            var tasks = sources.Select(x => Enrich(x, cancellationToken));
            return await Task.WhenAll(tasks);
        }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs</div>
<pre data-lang="csharp"><code>using System;
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Threading.Tasks;
using xDataService.Providers;
using xAiModels.Configurations;
using xAiModels.Interfaces.Dtos;
using xAiModels.Interfaces.Entities;
using xAiModels.Interfaces.Enrichers;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerRepositoryService
        : XBaseRepositoryService&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;, IXAiMcpServerRepositoryService
    {
        private readonly IXAiMcpServerEnricher enricher;
        private readonly IXAiMcpServerRepository repository;

        public XAiMcpServerRepositoryService(
            IXAiMcpServerRepository repository,
            IXAiMcpServerEnricher enricher
        ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()])
        {
            this.enricher = enricher;
            this.repository = repository;
        }

        /// &lt;summary&gt;
        /// یافتن سرور بر اساس OwnerId و Name ...
        /// &lt;/summary&gt;
        public virtual async Task&lt;XAiMcpServerDto&gt; FindByNameAsync(
            string ownerId,
            string name,
            CancellationToken cancellationToken = default
        )
        {
            // اعتبارسنجی ورودی‌ها
            if (ownerId.IsNullOrEmpty() || name.IsNullOrEmpty())
                return null;

            // جستجو در Repository
            var entity = await repository.FindOneAsync(
                includeBuilder: null,
                ignoreSoftDeleteds: true,
                cancellationToken: cancellationToken,
                predicate: x => x.OwnerId == ownerId && x.Name == name
            );

            // عدم یافتن → null
            if (entity.IsNullOrDefault())
                return null;

            // Enrich و بازگشت
            return await enricher.Enrich(source: entity, cancellationToken: cancellationToken);
        }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Base;
using xAiModels.Models.Dtos;
using xAiModels.Interfaces.Dtos;
using xAiModels.Models.Entities;
using Microsoft.Extensions.Logging;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerDtoHub
        : XBaseDtoHub&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;, IXAiMcpServerDtoHub
    {
        public XAiMcpServerDtoHub(ILogger&lt;XAiMcpServerDtoHub&gt; logger)
            : base(logger) { }
    }
}</code></pre>

        <div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Base;
using xAiModels.Models.Dtos;
using xAiModels.Interfaces.Dtos;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.SignalR;

namespace xAiModels.Providers.Dtos
{
    public class XAiMcpServerServiceProvider
        : XBaseDtoProvider&lt;XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub&gt;, IXAiMcpServerServiceProvider
    {
        public XAiMcpServerServiceProvider(
            IHubContext&lt;XAiMcpServerDtoHub&gt; hub,
            XDataServiceConfiguration dataConfiguration,
            IXAiMcpServerRepositoryService service,
            IXIdentityProvider identityProvider = null
        ) : base(hub, dataConfiguration, service, identityProvider) { }
    }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 6: Helper + DI -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>Helper و ثبت در DI</h3>
          <div class="subtitle">XAiModelsHelper + XDIHelperExtension</div>
        </div>
      </div>
      <div class="section-content">
        <p>مطابق الگوی موجود در <code>XAiModelsHelper</code>، سه متد برای ساخت Repository Descriptor اضافه کنید:</p>

        <div class="file-path">xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── درون کلاس XAiModelsHelper اضافه کنید ──

#region XAiMcpServer ...
// EF Repository Descriptor
public static XEFRepositoryDescriptor&lt;
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository,
    XAiMcpServerEFRepository&lt;TContext&gt;, TContext
&gt; GetXAiMcpServerEFRepositoryDescriptor&lt;TContext&gt;()
where TContext : XDbContext
{
    return new XEFRepositoryDescriptor&lt;...&gt;();  // پر کردن کامل نوع‌ها
}

// Mongo Repository Descriptor
public static XMongoRepositoryDescriptor&lt;
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository, XAiMcpServerMongoRepository
&gt; GetXAiMcpServerMongoRepositoryDescriptor()
{
    return new XMongoRepositoryDescriptor&lt;...&gt;();
}

// InMemory Repository Descriptor
public static XInMemoryRepositoryDescriptor&lt;
    XAiMcpServer, Guid,
    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
    XAiMcpServerGraphType, GuidGraphType,
    XAiMcpServerGraphQuery,
    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
    XAiMcpServerGraphSchema,
    IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
&gt; GetXAiMcpServerInMemoryRepositoryDescriptor()
{
    return new XInMemoryRepositoryDescriptor&lt;...&gt;();
}
#endregion</code></pre>

        <div class="warning-box">
          <strong>⚠️ توجه:</strong> برای سادگی، GraphQL types (مانند <code>XAiMcpServerGraphType</code>، <code>XAiMcpServerGraphQuery</code> و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با <code>null</code> جایگزین کنید یا با الگوگیری دقیق از <code>XAiProjectGraphType</code> و... آن‌ها را ایجاد نمایید.
        </div>

        <p>سپس در <code>XDIHelperExtension</code> پروژه <code>xAiModels</code>، ثبت‌ها را اضافه کنید:</p>

        <div class="file-path">xAiModels/DI/XDIHelperExtension.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── ۱) متغیر استاتیک جدید اضافه کنید ──
private static XRepositoryDescriptor aiMcpServerDescriptor = null;

// ── ۲) درون switch روی repositoryType، در بخش EF ──
aiMcpServerDescriptor = typeof(XAiModelsHelper)
    .InvokeGenericMethod&lt;XRepositoryDescriptor&gt;(
        args: null,
        runtimeType: contextType,
        methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor
    );

// ── ۳) درون switch، در بخش Mongo ──
aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor();

// ── ۴) درون switch، در بخش InMemory ──
aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor();

// ── ۵) درون region Register Repository Descriptor ──
if (!aiMcpServerDescriptor.IsNull())
{
    services.AddXRepository(lifeTime: lifeTime, descriptor: aiMcpServerDescriptor);
}

// ── ۶) درون region Register Services، یک region جدید اضافه کنید ──
#region AiMcpServer ...
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider),
                          typeof(XAiMcpServerServiceProvider), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService),
                          typeof(XAiMcpServerRepositoryService), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider),
                          typeof(XAiMcpServerRepositoryProvider), lifeTime)
);
services.Add(
    new ServiceDescriptor(typeof(IXAiMcpServerEnricher),
                          typeof(XAiMcpServerEnricher), lifeTime)
);
#endregion</code></pre>

        <p>همچنین در <code>UseXAiDataService</code> (همان فایل، برای Hubs):</p>

<pre data-lang="csharp"><code>// ── اضافه کنید ──
pushHelper.AddHub&lt;XAiMcpServerDtoHub&gt;(XAiModelsConstants.XAiMcpServerDtoHub);
pushHelper.AddHub&lt;XAiMcpServerEntityHub&gt;(XAiModelsConstants.XAiMcpServerEntityHub);

// در بخش Use Repository Descriptor
if (!aiMcpServerDescriptor.IsNull())
{
    app.UseXRepository(descriptor: aiMcpServerDescriptor,
                       isDevelopmentEnvironment: isDevelopmentEnvironment);
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 7: DbContext Integration -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>ثبت Registerar در DbContext</h3>
          <div class="subtitle">XAiApiDbContext.cs (MODIFY)</div>
        </div>
      </div>
      <div class="section-content">
        <p>در فایل <code>XAiApiDbContext.cs</code>، نام Registerar جدید را به لیست <code>dynamicEntityRegisterarsNames</code> اضافه کنید:</p>

        <div class="file-path">xAiApi/Database/XAiApiDbContext.cs (MODIFY)</div>
<pre data-lang="csharp"><code>dynamicEntityRegisterarsNames: [
    nameof(XTagEntityRegisterar),
    nameof(XFileEntityRegisterar),
    nameof(XStringEntityRegisterar),
    nameof(XAiMessageEntityRegisterar),
    nameof(XAiProjectEntityRegisterar),
    nameof(XAiConversationEntityRegisterar),
    nameof(XAiMcpServerEntityRegisterar),    // ← جدید
]</code></pre>

        <div class="info-box">
          <strong>💡 نکته:</strong> پس از این تغییر، یک Migration جدید برای جدول <code>AiMcpServers</code> بسازید:
          <br><br>
          <code>dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext</code>
          <br><br>
          سپس <code>dotnet ef database update</code>.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 8: Seeder from appSettings -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>Seeder از appSettings</h3>
          <div class="subtitle">XMcpServersConfiguration + XMcpServerSeederService</div>
        </div>
      </div>
      <div class="section-content">
        <p>این بخش هسته اصلی درخواست شماست: خواندن <code>McpServers</code> از <code>appSettings</code>، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت <code>IHostedService</code> در استارتاپ اجرا می‌شود.</p>

        <h4 style="color: var(--primary); font-size: 15px;">الف) مدل Configuration</h4>

        <div class="file-path">xAiApi/Configurations/XMcpServersConfiguration.cs</div>
<pre data-lang="csharp"><code>using System.Collections.Generic;
using xAiModels.Models;

namespace xAiApi.Configurations
{
    /// &lt;summary&gt;
    /// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
    /// &lt;/summary&gt;
    public class XMcpServersConfiguration
    {
        /// &lt;summary&gt;
        /// آیا Seeder در استارتاپ اجرا شود؟
        /// &lt;/summary&gt;
        public bool SyncOnStartup { get; set; } = true;

        /// &lt;summary&gt;
        /// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
        /// &lt;/summary&gt;
        public bool UpdateExisting { get; set; } = false;

        /// &lt;summary&gt;
        /// OwnerId پیش‌فرض برای سرورهای Seed شده ...
        /// (اگر خالی باشد از "system" استفاده می‌شود)
        /// &lt;/summary&gt;
        public string DefaultOwnerId { get; set; } = "system";

        /// &lt;summary&gt;
        /// لیست سرورهای MCP ...
        /// &lt;/summary&gt;
        public List&lt;XMcpServerDescriptor&gt; Servers { get; set; } = new();
    }
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) سرویس Seeder</h4>

        <div class="file-path">xAiApi/Services/XMcpServerSeederService.cs</div>
<pre data-lang="csharp"><code>using System;
using System.Linq;
using System.Text.Json;
using xAiModels.Models;
using System.Threading;
using System.Threading.Tasks;
using xCommons.Extensions;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using Microsoft.Extensions.Hosting;
using xAiApi.Configurations;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using xAiModels.Interfaces.Dtos;

namespace xAiApi.Services
{
    /// &lt;summary&gt;
    /// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
    /// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
    /// &lt;/summary&gt;
    public class XMcpServerSeederService : IHostedService
    {
        private readonly ILogger&lt;XMcpServerSeederService&gt; logger;
        private readonly XMcpServersConfiguration config;
        private readonly IXAiMcpServerRepositoryService repositoryService;

        public XMcpServerSeederService(
            ILogger&lt;XMcpServerSeederService&gt; logger,
            IOptions&lt;XMcpServersConfiguration&gt; config,
            IXAiMcpServerRepositoryService repositoryService
        )
        {
            this.logger = logger;
            this.config = config.Value;
            this.repositoryService = repositoryService;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // اگر Sync غیرفعال است، هیچ کاری نکن
            if (!config.SyncOnStartup)
            {
                logger.LogInformation(
                    "MCP Seed: SyncOnStartup=false، عملیات Seed اجرا نشد.");
                return;
            }

            // اگر لیست خالی است، خارج شو
            if (!config.Servers.HasChild())
            {
                logger.LogInformation(
                    "MCP Seed: هیچ سروری در appSettings تعریف نشده است.");
                return;
            }

            logger.LogInformation(
                "MCP Seed: شروع Seed برای {Count} سرور ...",
                config.Servers.Count);

            foreach (var descriptor in config.Servers)
            {
                // اعتبارسنجی حداقلی
                if (descriptor.IsNullOrDefault() ||
                    descriptor.Name.IsNullOrEmpty())
                {
                    logger.LogWarning("MCP Seed: یک Descriptor نامعتبر نادیده گرفته شد.");
                    continue;
                }

                await SeedOneAsync(descriptor, cancellationToken);
            }

            logger.LogInformation("MCP Seed: عملیات به پایان رسید.");
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

        // ────────────────────────────────────────────────────────
        // Seed یک Descriptor
        // ────────────────────────────────────────────────────────
        private async Task SeedOneAsync(
            XMcpServerDescriptor descriptor,
            CancellationToken cancellationToken)
        {
            try
            {
                var ownerId = config.DefaultOwnerId.IsNullOrEmpty()
                    ? "system"
                    : config.DefaultOwnerId;

                // بررسی وجود سرور با این نام و Owner
                var existing = await repositoryService.FindByNameAsync(
                    ownerId: ownerId,
                    name: descriptor.Name,
                    cancellationToken: cancellationToken
                );

                // ── حالت ایجاد ──
                if (existing.IsNullOrDefault())
                {
                    var item = MapToDto(descriptor, ownerId, id: null);
                    item.CreatedOn = DateTime.UtcNow;

                    await repositoryService.AddAsync(
                        item: item,
                        saveChanges: true,
                        cancellationToken: cancellationToken
                    );

                    logger.LogInformation(
                        "MCP Seed: سرور '{Name}' ایجاد شد.", descriptor.Name);
                    return;
                }

                // ── حالت به‌روزرسانی ──
                if (!config.UpdateExisting)
                {
                    logger.LogDebug(
                        "MCP Seed: سرور '{Name}' از قبل وجود دارد (UpdateExisting=false).",
                        descriptor.Name);
                    return;
                }

                var updateItem = MapToDto(descriptor, ownerId, id: existing.Id);
                updateItem.CreatedOn = existing.CreatedOn;
                updateItem.UpdatedAt = DateTime.UtcNow;

                await repositoryService.UpdateAsync(
                    item: updateItem,
                    id: existing.Id,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                logger.LogInformation(
                    "MCP Seed: سرور '{Name}' به‌روزرسانی شد.", descriptor.Name);
            }
            catch (Exception ex)
            {
                logger.LogError(ex,
                    "MCP Seed: خطا در Seed سرور '{Name}'. این سرور نادیده گرفته می‌شود.",
                    descriptor.Name);
            }
        }

        // ────────────────────────────────────────────────────────
        // تبدیل Descriptor به DTO
        // ────────────────────────────────────────────────────────
        private static XAiMcpServerDto MapToDto(
            XMcpServerDescriptor d,
            string ownerId,
            Guid? id)
        {
            var item = new XAiMcpServerDto
            {
                OwnerId = ownerId,
                Name = d.Name,
                Description = d.Description,
                Enabled = d.Enabled,
                Transport = d.Transport,
                Command = d.Command,
                Endpoint = d.Endpoint,
                TimeoutSeconds = d.TimeoutSeconds,
                WorkingDirectory = d.WorkingDirectory,

                // تبدیل لیست/دیکشنری به JSON برای ذخیره در DB
                Arguments = d.Arguments.HasChild()
                    ? JsonSerializer.Serialize(d.Arguments)
                    : null,
                EnvironmentVariables = d.EnvironmentVariables.HasChild()
                    ? JsonSerializer.Serialize(d.EnvironmentVariables)
                    : null,
                Headers = d.Headers.HasChild()
                    ? JsonSerializer.Serialize(d.Headers)
                    : null,
            };

            if (id.HasValue) item.Id = id.Value;

            return item;
        }
    }
}</code></pre>

        <div class="success-box">
          <strong>✓ رفتار Seeder:</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>اگر سروری در DB نیست → ایجاد می‌شود</li>
            <li>اگر هست و <code>UpdateExisting = false</code> → دست نمی‌خورد</li>
            <li>اگر هست و <code>UpdateExisting = true</code> → فیلدها به‌روزرسانی می‌شوند</li>
            <li>خطای یک سرور باعث توقف کل فرآیند نمی‌شود</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 9: Startup Registration -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>ثبت در Startup.cs</h3>
          <div class="subtitle">Startup.cs (MODIFY)</div>
        </div>
      </div>
      <div class="section-content">

<pre data-lang="csharp"><code>// ── در ConfigureServices، بعد از AddXAiServices ──

// ۱. ثبت XMcpServersConfiguration از appSettings
services.Configure&lt;XMcpServersConfiguration&gt;(
    Configuration.GetSection("McpServers"));

// ۲. ثبت Seeder به‌صورت HostedService
services.AddHostedService&lt;XMcpServerSeederService&gt;();

// ۳. ثبت Connection Manager (از مرحله قبل)
services.AddSingleton&lt;XMcpServerConnectionManager&gt;();

// ۴. ثبت Health Monitor
services.AddHostedService&lt;XMcpHealthMonitorService&gt;();</code></pre>

        <div class="warning-box">
          <strong>⚠️ ترتیب اجرا:</strong> Seeder به‌عنوان <code>IHostedService</code> پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به <code>IXAiMcpServerRepositoryService</code> دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول <code>xAiModels</code> پیش از اجرای Seeder کامل شده باشند.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 10: API Controller -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>کنترلر CRUD برای مدیریت از طریق API</h3>
          <div class="subtitle">Controllers/McpServersController.cs</div>
        </div>
      </div>
      <div class="section-content">

        <div class="file-path">xAiApi/Controllers/McpServersController.cs</div>
<pre data-lang="csharp"><code>using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Services;
using xCommons.Providers;
using xCommons.Extensions;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using xAiModels.Interfaces.Dtos;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

namespace xAiApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    public class McpServersController : XBaseIdentityApiV1Controller
    {
        private readonly IXAiMcpServerRepositoryService repositoryService;
        private readonly XMcpServerConnectionManager connectionManager;

        public McpServersController(
            ILogger&lt;McpServersController&gt; logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider,
            XMcpServerConnectionManager connectionManager,
            IXAiMcpServerRepositoryService repositoryService
        ) : base(logger, appConfiguration, identityProvider, validationProvider)
        {
            this.connectionManager = connectionManager;
            this.repositoryService = repositoryService;
        }

        #region Loaders ...
        /// &lt;summary&gt;
        /// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
        /// &lt;/summary&gt;
        [HttpGet("")]
        public async Task&lt;ActionResult&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt;&gt; LoadAll(
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var result = await repositoryService.FindManyAsync(
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken,
                    predicate: x =&gt; x.OwnerId == userInfo.UserId,
                    orderBuilder: x =&gt; x.OrderBy(y =&gt; y.Name)
                );

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }

        /// &lt;summary&gt;
        /// دریافت یک سرور بر اساس Id ...
        /// &lt;/summary&gt;
        [HttpGet("{id:guid}")]
        public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; GetById(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var item = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                return Ok(item);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Creators ...
        /// &lt;summary&gt;
        /// ایجاد سرور MCP جدید ...
        /// &lt;/summary&gt;
        [HttpPost("")]
        public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; Create(
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (item.IsNullOrDefault() || item.Name.IsNullOrEmpty())
                    XException.InvalidArgs.Throw();

                var userInfo = await GetUserInfo();

                // بررسی یکتایی نام برای این Owner
                var existing = await repositoryService.FindByNameAsync(
                    ownerId: userInfo.UserId,
                    name: item.Name,
                    cancellationToken: cancellationToken
                );

                if (!existing.IsNullOrDefault())
                    XException.InvalidArgs.Throw("این نام قبلاً استفاده شده است.");

                // پر کردن فیلدهای ضروری
                item.Id = Guid.Empty;  // اطمینان از اینکه Id جدید تولید می‌شود
                item.OwnerId = userInfo.UserId;
                item.CreatedOn = DateTime.UtcNow;
                item.UpdatedAt = DateTime.UtcNow;

                var result = await repositoryService.AddAsync(
                    item: item,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Updaters ...
        /// &lt;summary&gt;
        /// به‌روزرسانی سرور MCP ...
        /// &lt;/summary&gt;
        [HttpPut("{id:guid}")]
        public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; Update(
            Guid id,
            [FromBody] XAiMcpServerDto item,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (item.IsNullOrDefault() || id == Guid.Empty)
                    XException.InvalidArgs.Throw();

                var userInfo = await GetUserInfo();

                var existing = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                // پر کردن فیلدهای سیستم
                item.Id = id;
                item.OwnerId = existing.OwnerId;
                item.CreatedOn = existing.CreatedOn;
                item.UpdatedAt = DateTime.UtcNow;

                var result = await repositoryService.UpdateAsync(
                    item: item,
                    id: id,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(result);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Removers ...
        /// &lt;summary&gt;
        /// حذف نرم یک سرور MCP ...
        /// &lt;/summary&gt;
        [HttpDelete("{id:guid}")]
        public async Task&lt;ActionResult&lt;bool&gt;&gt; Remove(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var existing = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                await repositoryService.RemoveAsync(
                    id: id,
                    softDelete: true,
                    saveChanges: true,
                    cancellationToken: cancellationToken
                );

                // بازسازی اتصال‌ها
                await connectionManager.RefreshAsync();

                return Ok(true);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion

        #region Actions ...
        /// &lt;summary&gt;
        /// اعتبارسنجی و اتصال دستی به یک سرور ...
        /// &lt;/summary&gt;
        [HttpPost("{id:guid}/Test")]
        public async Task&lt;ActionResult&lt;string&gt;&gt; Test(
            Guid id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var userInfo = await GetUserInfo();

                var item = await repositoryService.GetAsync(
                    id: id,
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken
                );

                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
                    XException.NotFound.Throw();

                var message = await connectionManager.TestServerAsync(
                    item, cancellationToken);

                return Ok(message);
            }
            catch (Exception ex)
            {
                return GetExceptionActionResult(ex);
            }
        }
        #endregion
    }
}</code></pre>

        <div class="info-box">
          <strong>💡 مسیرهای API:</strong>
          <table class="styled-table" style="margin-top: 10px;">
            <thead><tr><th>متد</th><th>مسیر</th><th>توضیح</th></tr></thead>
            <tbody>
              <tr><td>GET</td><td>/McpServers</td><td>لیست تمام سرورهای کاربر</td></tr>
              <tr><td>GET</td><td>/McpServers/{id}</td><td>دریافت یک سرور</td></tr>
              <tr><td>POST</td><td>/McpServers</td><td>ایجاد سرور جدید</td></tr>
              <tr><td>PUT</td><td>/McpServers/{id}</td><td>به‌روزرسانی</td></tr>
              <tr><td>DELETE</td><td>/McpServers/{id}</td><td>حذف نرم</td></tr>
              <tr><td>POST</td><td>/McpServers/{id}/Test</td><td>اعتبارسنجی و تست اتصال</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 11: Update Connection Manager -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>به‌روزرسانی XMcpServerConnectionManager</h3>
          <div class="subtitle">حالا از DB می‌خواند، نه از IOptionsMonitor</div>
        </div>
      </div>
      <div class="section-content">
        <p>در نسخه قبل، Connection Manager مستقیماً از <code>IOptionsMonitor&lt;XMcpServersConfiguration&gt;</code> می‌خواند. اکنون باید از دیتابیس بخواند:</p>

        <div class="file-path">xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)</div>
<pre data-lang="csharp"><code>using System;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Constants;
using xAiModels.Models.Dtos;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
using xAiModels.Interfaces.Dtos;

namespace xAiApi.Services
{
    public class XMcpServerConnectionManager : IAsyncDisposable
    {
        private readonly ILogger&lt;XMcpServerConnectionManager&gt; logger;
        private readonly IXAiMcpServerRepositoryService repositoryService;
        private readonly Dictionary&lt;Guid, McpClient&gt; clients = new();
        private readonly Dictionary&lt;Guid, IList&lt;McpClientTool&gt;&gt; tools = new();
        private readonly SemaphoreSlim initLock = new(1, 1);
        private bool isInitialized = false;

        public XMcpServerConnectionManager(
            ILogger&lt;XMcpServerConnectionManager&gt; logger,
            IXAiMcpServerRepositoryService repositoryService)
        {
            this.logger = logger;
            this.repositoryService = repositoryService;
        }

        /// &lt;summary&gt;
        /// دریافت تمام ابزارهای موجود از سرورهای فعال ...
        /// &lt;/summary&gt;
        public async Task&lt;IList&lt;McpClientTool&gt;&gt; GetAvailableToolsAsync(
            CancellationToken cancellationToken = default)
        {
            if (isInitialized)
                return tools.Values.SelectMany(t =&gt; t).ToList();

            await initLock.WaitAsync(cancellationToken);
            try
            {
                if (isInitialized)
                    return tools.Values.SelectMany(t =&gt; t).ToList();

                // ← خواندن از DB به‌جای IOptions
                var servers = await repositoryService.FindManyAsync(
                    includeBuilder: null,
                    ignoreSoftDeleteds: true,
                    cancellationToken: cancellationToken,
                    predicate: x =&gt; x.Enabled
                );

                if (servers.HasChild())
                {
                    var tasks = servers.Select(s =&gt;
                        ConnectAndValidateAsync(s, cancellationToken));
                    await Task.WhenAll(tasks);
                }

                isInitialized = true;
                return tools.Values.SelectMany(t =&gt; t).ToList();
            }
            finally
            {
                initLock.Release();
            }
        }

        /// &lt;summary&gt;
        /// تست دستی یک سرور خاص ...
        /// &lt;/summary&gt;
        public async Task&lt;string&gt; TestServerAsync(
            XAiMcpServerDto server,
            CancellationToken cancellationToken)
        {
            try
            {
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));

                var client = await CreateClientAsync(server, cts.Token);
                await client.PingAsync(cts.Token);
                var serverTools = await client.ListToolsAsync(cts.Token);

                var names = string.Join(", ", serverTools.Select(t =&gt; t.Name));
                return $"✓ سرور '{server.Name}' پاسخگو است. {serverTools.Count} ابزار: {names}";
            }
            catch (Exception ex)
            {
                return $"✗ خطا: {ex.Message}";
            }
        }

        // ────────────────────────────────────────────────────────
        private async Task ConnectAndValidateAsync(
            XAiMcpServerDto descriptor,
            CancellationToken cancellationToken)
        {
            try
            {
                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));

                var client = await CreateClientAsync(descriptor, cts.Token);
                await client.PingAsync(cts.Token);
                var serverTools = await client.ListToolsAsync(cts.Token);

                clients[descriptor.Id] = client;
                tools[descriptor.Id] = serverTools;

                logger.LogInformation(
                    "MCP '{Name}': {Count} ابزار کشف شد.",
                    descriptor.Name, serverTools.Count);
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex,
                    "MCP '{Name}': اتصال برقرار نشد، نادیده گرفته شد.",
                    descriptor.Name);
            }
        }

        // ────────────────────────────────────────────────────────
        private static async Task&lt;McpClient&gt; CreateClientAsync(
            XAiMcpServerDto s,
            CancellationToken cancellationToken)
        {
            IClientTransport transport = s.Transport?.ToLowerInvariant() switch
            {
                "http" =&gt; new HttpClientTransport(new HttpClientTransportOptions
                {
                    Endpoint = new Uri(s.Endpoint!),
                    AdditionalHeaders = ParseJsonDict(s.Headers),
                    TransportMode = HttpTransportMode.AutoDetect
                }),
                _ =&gt; new StdioClientTransport(new StdioClientTransportOptions
                {
                    Command = s.Command ?? "dotnet",
                    Arguments = ParseJsonList(s.Arguments) ?? new List&lt;string&gt;(),
                    WorkingDirectory = s.WorkingDirectory,
                    EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
                        .ToDictionary(kv =&gt; kv.Key, kv =&gt; (string?)kv.Value),
                    Name = s.Name,
                    ShutdownTimeout = TimeSpan.FromSeconds(5)
                })
            };

            return await McpClient.CreateAsync(transport,
                cancellationToken: cancellationToken);
        }

        // ────────────────────────────────────────────────────────
        private static Dictionary&lt;string, string&gt; ParseJsonDict(string json)
            =&gt; json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize&lt;Dictionary&lt;string, string&gt;&gt;(json);

        private static List&lt;string&gt; ParseJsonList(string json)
            =&gt; json.IsNullOrEmpty() ? null
                : JsonSerializer.Deserialize&lt;List&lt;string&gt;&gt;(json);

        // ────────────────────────────────────────────────────────
        public async Task RefreshAsync()
        {
            logger.LogInformation("MCP: بازسازی اتصال‌ها ...");

            foreach (var client in clients.Values)
            {
                try { await client.DisposeAsync(); } catch { }
            }
            clients.Clear();
            tools.Clear();

            isInitialized = false;
            await GetAvailableToolsAsync(CancellationToken.None);
        }

        public async ValueTask DisposeAsync()
        {
            foreach (var client in clients.Values)
            {
                try { await client.DisposeAsync(); } catch { }
            }
            initLock.Dispose();
        }
    }
}</code></pre>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد <code>RefreshAsync()</code> فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. <code>appSettings</code> فقط منبع Seed اولیه است.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 12: appsettings.json sample -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۲</div>
        <div class="section-title">
          <h3>نمونه کامل appsettings.json</h3>
          <div class="subtitle">appsettings.json (MODIFY)</div>
        </div>
      </div>
      <div class="section-content">

<pre data-lang="json"><code>{
  "AiApiConfiguration": {
    "Models": [ /* ... مدل‌های موجود ... */ ],
    "Prompts": [ /* ... پرامپت‌های موجود ... */ ]
  },

  "McpServers": {
    "SyncOnStartup": true,
    "UpdateExisting": false,
    "DefaultOwnerId": "system",
    "Servers": [
      {
        "Name": "xai-knowledge",
        "Description": "سرور MCP جستجو در پایگاه دانش",
        "Enabled": true,
        "Transport": "stdio",
        "Command": "dotnet",
        "Arguments": [ "xAiMcpServer.dll" ],
        "TimeoutSeconds": 20
      },
      {
        "Name": "remote-tools",
        "Description": "ابزارهای تیمی از راه دور",
        "Enabled": true,
        "Transport": "http",
        "Endpoint": "https://tools.example.com/mcp",
        "Headers": {
          "X-API-Key": "your-key"
        },
        "TimeoutSeconds": 30
      },
      {
        "Name": "file-processor",
        "Description": "پردازش فایل با معیارهای سفارشی",
        "Enabled": false,
        "Transport": "stdio",
        "Command": "node",
        "Arguments": [ "file-processor.js", "--port", "3000" ],
        "EnvironmentVariables": {
          "LOG_LEVEL": "info"
        },
        "TimeoutSeconds": 15
      }
    ]
  },

  "ConnectionStrings": { /* ... */ },
  "Logging": { /* ... */ }
}</code></pre>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 13: Testing & Validation -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۳</div>
        <div class="section-title">
          <h3>تست و اعتبارسنجی</h3>
          <div class="subtitle">Testing & Validation</div>
        </div>
      </div>
      <div class="section-content">
        <h4 style="color: var(--primary); font-size: 15px;">جریان تست پیشنهادی:</h4>

        <ol style="padding-right: 20px; margin-top: 10px; font-size: 14px; line-height: 2;">
          <li><strong>Migration:</strong> پس از اعمال Migration، جدول <code>AiMcpServers</code> را در دیتابیس بررسی کنید.</li>
          <li><strong>اجرای اپلیکیشن:</strong> لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند <em>"MCP Seed: سرور 'xai-knowledge' ایجاد شد."</em> نمایش داده شود.</li>
          <li><strong>بررسی DB:</strong> با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.</li>
          <li><strong>تست API:</strong> با یک توکن معتبر، <code>GET /McpServers</code> را فراخوانی کنید و لیست سرورها را ببینید.</li>
          <li><strong>تست ایجاد:</strong> یک سرور جدید با <code>POST /McpServers</code> بسازید.</li>
          <li><strong>تست Connection:</strong> با <code>POST /McpServers/{id}/Test</code> اعتبارسنجی کنید.</li>
          <li><strong>تست Function Calling:</strong> از <code>/DefaultAi/AskText</code> استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.</li>
        </ol>

        <div class="danger-box">
          <strong>⚠️ نکات مهم:</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.</li>
            <li>هنگام اجرای <code>dotnet ef migrations add</code>، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.</li>
            <li>در محیط توسعه، پیشنهاد می‌شود <code>UpdateExisting = true</code> باشد تا تغییرات appSettings سریع اعمال شوند.</li>
            <li>در محیط عملیاتی، <code>UpdateExisting = false</code> باشد تا APIها بازنویسی نشوند.</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 14: Summary -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۴</div>
        <div class="section-title">
          <h3>جمع‌بندی و چک‌لیست نهایی</h3>
          <div class="subtitle">Summary & Checklist</div>
        </div>
      </div>
      <div class="section-content">
        <h4 style="color: var(--primary); font-size: 15px;">چک‌لیست فایل‌های جدید/تغییر یافته:</h4>

        <ul class="checklist">
          <li>Entity، DTO و Descriptor در <code>xAiModels/Models</code> ایجاد شد</li>
          <li>EntityConfiguration و EntityRegisterar اضافه شد</li>
          <li>Constants جدید در <code>XAiModelsConstants</code> افزوده شد</li>
          <li>تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد</li>
          <li>Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد</li>
          <li>RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد</li>
          <li>Helper (سه متد Descriptor) به <code>XAiModelsHelper</code> اضافه شد</li>
          <li>ثبت در <code>XDIHelperExtension</code> انجام شد</li>
          <li>Mapper Profile به‌روزرسانی شد</li>
          <li>Registerar در <code>XAiApiDbContext</code> ثبت شد</li>
          <li>Migration اجرا شد</li>
          <li><code>XMcpServersConfiguration</code> و <code>XMcpServerSeederService</code> ایجاد شد</li>
          <li><code>XMcpServerConnectionManager</code> برای خواندن از DB تغییر کرد</li>
          <li><code>McpServersController</code> با CRUD کامل اضافه شد</li>
          <li><code>Startup.cs</code> به‌روزرسانی شد (Configure + HostedServices)</li>
          <li><code>appsettings.json</code> با بخش <code>McpServers</code> تکمیل شد</li>
        </ul>

        <div class="conclusion-box">
          <h3>🎯 نتیجه نهایی</h3>
          <p>با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:</p>
          <p style="font-size: 13px; line-height: 2;">
            <strong>appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM</strong>
          </p>
          <p style="margin-top: 15px;">
            سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت.
          </p>
        </div>
      </div>
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و مستندسازی: تیم معماری xSaherelmWorkspace</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: فنی-داخلی</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0da0136c-9f49-439d-bc78-84aa19e17262.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>نقشه BPMN2 تعاملی | مولفه‌های معماری سامانه هوش مصنوعی سازمانی</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1100px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  /* ===== BPMN Diagram Styles ===== */
  .bpmn-toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
    justify-content: space-between;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 15px;
  }

  .bpmn-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 14px;
    align-items: center;
    font-size: 12px;
    color: var(--text-muted);
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .legend-swatch {
    width: 14px; height: 14px;
    border-radius: 3px;
    border: 1px solid rgba(0,0,0,0.15);
  }

  .bpmn-hint {
    font-size: 12px;
    color: var(--primary);
    background: rgba(201,169,97,0.15);
    border: 1px solid rgba(201,169,97,0.4);
    padding: 6px 12px;
    border-radius: 20px;
    font-weight: 600;
  }

  .bpmn-canvas-wrap {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 10px;
    overflow: auto;
    position: relative;
  }

  .bpmn-canvas-wrap svg {
    display: block;
    width: 100%;
    height: auto;
    min-width: 1000px;
  }

  /* BPMN element base */
  .bpmn-el {
    cursor: pointer;
    transition: filter 0.15s ease, transform 0.15s ease;
  }

  .bpmn-el:hover {
    filter: drop-shadow(0 0 6px rgba(201,169,97,0.9));
  }

  .bpmn-el:hover .bpmn-shape {
    stroke: var(--accent-dark) !important;
    stroke-width: 2.5 !important;
  }

  .bpmn-el:focus {
    outline: none;
  }

  .bpmn-el:focus .bpmn-shape {
    stroke: var(--accent) !important;
    stroke-width: 3 !important;
  }

  /* Lane styles */
  .lane-bg { fill: #ffffff; stroke: #cbd5e0; stroke-width: 1; }
  .lane-bg.alt { fill: #f8fafc; }
  .lane-sep { stroke: #cbd5e0; stroke-width: 1; }
  .lane-label-bg { fill: #edf2f7; stroke: #cbd5e0; stroke-width: 1; }
  .lane-label-text {
    font-size: 11px;
    font-weight: 700;
    fill: #1a365d;
    text-anchor: middle;
    font-family: 'Vazirmatn', Tahoma, sans-serif;
  }

  /* Task (component) styles */
  .bpmn-shape {
    fill: #ffffff;
    stroke: #2c5282;
    stroke-width: 1.6;
    transition: fill 0.15s ease;
  }

  .bpmn-el:hover .bpmn-shape { fill: #fffaf0; }

  .bpmn-el[data-layer="1"] .bpmn-shape { stroke: #b7791f; }
  .bpmn-el[data-layer="2"] .bpmn-shape { stroke: #2c5282; }
  .bpmn-el[data-layer="3"] .bpmn-shape { stroke: #1a365d; }
  .bpmn-el[data-layer="4"] .bpmn-shape { stroke: #2c5282; }
  .bpmn-el[data-layer="5"] .bpmn-shape { stroke: #4a5568; }
  .bpmn-el[data-layer="6"] .bpmn-shape { stroke: #b7791f; }
  .bpmn-el[data-layer="x"] .bpmn-shape { stroke: #c53030; stroke-dasharray: 5 3; }
  .bpmn-el[data-layer="y"] .bpmn-shape { stroke: #dd6b20; stroke-dasharray: 5 3; }

  .bpmn-el[data-layer="1"] .bpmn-shape { fill: #fffaf0; }
  .bpmn-el[data-layer="6"] .bpmn-shape { fill: #fffaf0; }
  .bpmn-el[data-layer="x"] .bpmn-shape { fill: #fff5f5; }
  .bpmn-el[data-layer="y"] .bpmn-shape { fill: #fffaf0; }

  .bpmn-label {
    font-size: 10.5px;
    font-weight: 600;
    fill: #1a202c;
    text-anchor: middle;
    pointer-events: none;
    font-family: 'Vazirmatn', Tahoma, sans-serif;
  }

  .bpmn-sub {
    font-size: 8.5px;
    fill: #4a5568;
    text-anchor: middle;
    pointer-events: none;
    font-family: 'Vazirmatn', Tahoma, sans-serif;
  }

  /* Gateway (diamond) */
  .bpmn-gateway {
    fill: #fffaf0;
    stroke: #b7791f;
    stroke-width: 1.8;
  }

  .bpmn-el:hover .bpmn-gateway { fill: #fef5e7; }

  /* Data object / store (for resources) */
  .bpmn-data {
    fill: #edf2f7;
    stroke: #4a5568;
    stroke-width: 1.4;
  }

  /* Connections */
  .bpmn-flow {
    fill: none;
    stroke: #4a5568;
    stroke-width: 1.4;
    marker-end: url(#arrow);
  }

  .bpmn-flow.dashed {
    stroke-dasharray: 5 4;
    stroke: #718096;
  }

  .bpmn-flow.accent {
    stroke: #b7791f;
    stroke-width: 1.8;
  }

  .bpmn-flow-label {
    font-size: 8.5px;
    fill: #4a5568;
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    pointer-events: none;
  }

  /* Modal */
  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(26,54,93,0.55);
    backdrop-filter: blur(3px);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 20px;
    animation: fadeIn 0.18s ease;
  }

  .modal-overlay.open { display: flex; }

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  .modal-card {
    background: #ffffff;
    border-radius: 14px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.35);
    max-width: 640px;
    width: 100%;
    max-height: 88vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    animation: slideUp 0.2s ease;
    border: 1px solid var(--border);
  }

  @keyframes slideUp {
    from { transform: translateY(18px); opacity: 0.6; }
    to { transform: translateY(0); opacity: 1; }
  }

  .modal-header {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px 24px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 15px;
    border-bottom: 3px solid var(--accent);
  }

  .modal-header h3 {
    font-size: 18px;
    font-weight: 800;
    margin-bottom: 4px;
    line-height: 1.5;
  }

  .modal-header .modal-sub {
    font-size: 12px;
    opacity: 0.85;
  }

  .modal-close {
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.3);
    color: white;
    width: 34px; height: 34px;
    border-radius: 8px;
    font-size: 18px;
    cursor: pointer;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.15s ease;
  }

  .modal-close:hover { background: rgba(255,255,255,0.3); }

  .modal-body {
    padding: 22px 24px;
    overflow-y: auto;
  }

  .modal-section {
    margin-bottom: 20px;
  }

  .modal-section:last-child { margin-bottom: 0; }

  .modal-section h4 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 10px;
    padding-bottom: 6px;
    border-bottom: 2px solid var(--border);
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .modal-section h4 .dot {
    width: 8px; height: 8px;
    border-radius: 50%;
    background: var(--accent);
    display: inline-block;
  }

  .modal-section p,
  .modal-section li {
    font-size: 13px;
    color: var(--text-muted);
    line-height: 1.85;
  }

  .modal-section ul {
    list-style: none;
    padding: 0;
  }

  .modal-section ul li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 8px 12px;
    margin-bottom: 6px;
    border-radius: 6px;
    font-size: 12.5px;
  }

  .io-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
  }

  .io-col h5 {
    font-size: 12px;
    font-weight: 700;
    margin-bottom: 8px;
    padding: 6px 10px;
    border-radius: 6px;
    text-align: center;
  }

  .io-col.input h5 {
    background: #ebf8ff;
    color: var(--primary);
    border: 1px solid #90cdf4;
  }

  .io-col.output h5 {
    background: #f0fff4;
    color: var(--success);
    border: 1px solid #9ae6b4;
  }

  .io-col ul { margin: 0; }

  .io-col.input ul li { border-right-color: var(--primary-light); }
  .io-col.output ul li { border-right-color: var(--success); }

  .chip {
    display: inline-block;
    background: #edf2f7;
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 2px 10px;
    font-size: 11px;
    color: var(--text-muted);
    margin: 2px 4px 2px 0;
  }

  .chip.accent {
    background: rgba(201,169,97,0.18);
    border-color: rgba(201,169,97,0.5);
    color: var(--accent-dark);
    font-weight: 600;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
    .modal-overlay { display: none !important; }
  }

  @media (max-width: 900px) {
    .bpmn-canvas-wrap svg { min-width: 900px; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
    .io-grid { grid-template-columns: 1fr; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: BPMN-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">BPMN 2.0 INTERACTIVE MAP</span>
      <h1>نقشه فرایندی تعاملی مولفه‌ها</h1>
      <h2>سامانه هوش مصنوعی سازمانی — بر اساس معماری کلان ARCH-1405-001</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه مدیریتی،</strong><br>
      این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را بر اساس <strong>استاندارد BPMN 2.0</strong> رسم می‌کند. مولفه‌ها در قالب <strong>Lane</strong> (لایه‌های معماری) سازمان‌دهی شده‌اند و روابط میان آنها با <strong>Sequence Flow</strong> نمایش داده می‌شود. با کلیک روی هر مولفه، مودالی شامل <strong>وظایف، ورودی‌ها و خروجی‌ها</strong> و ارتباطات آن نمایش داده می‌شود.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>راهنمای نقشه BPMN2</h3>
          <div class="subtitle">How to Read the Map</div>
        </div>
      </div>
      <div class="section-content">
        <p>نقشه زیر بر اساس استاندارد BPMN 2.0 ترسیم شده است. هر <strong>Lane</strong> نماینده یک لایه معماری است و هر <strong>Task</strong> (مستطیل) نماینده یک مولفه. فلش‌ها جریان درخواست/کنترل را نشان می‌دهند. <strong>روی هر مولفه کلیک کنید</strong> تا جزئیات آن را در مودال مشاهده کنید.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">۸</div>
            <div class="stat-label">Lane (لایه + محور عرضی)</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۲۵+</div>
            <div class="stat-label">مولفه قابل کلیک</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">BPMN 2.0</div>
            <div class="stat-label">استاندارد رسم</div>
          </div>
        </div>

        <div class="info-box">
          <strong>💡 نحوه استفاده:</strong> نشانگر ماوس را روی هر مستطیل ببرید تا هایلایت شود؛ سپس کلیک کنید تا مودال اطلاعات (وظایف، ورودی‌ها، خروجی‌ها و ارتباطات) باز شود. برای بستن مودال، کلید <strong>Esc</strong> را بزنید یا روی پس‌زمینه کلیک کنید.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>نقشه BPMN2 تعاملی</h3>
          <div class="subtitle">Interactive BPMN2 Process Map</div>
        </div>
      </div>
      <div class="section-content">

        <div class="bpmn-toolbar">
          <div class="bpmn-legend">
            <span class="legend-item"><span class="legend-swatch" style="background:#fffaf0;border-color:#b7791f;"></span> لایه تعامل/گزارش</span>
            <span class="legend-item"><span class="legend-swatch" style="background:#ffffff;border-color:#2c5282;"></span> لایه کنترل/هوش</span>
            <span class="legend-item"><span class="legend-swatch" style="background:#ffffff;border-color:#1a365d;"></span> لایه ارکستراسیون</span>
            <span class="legend-item"><span class="legend-swatch" style="background:#ffffff;border-color:#4a5568;"></span> لایه داده</span>
            <span class="legend-item"><span class="legend-swatch" style="background:#fff5f5;border-color:#c53030;border-style:dashed;"></span> محور حاکمیت</span>
            <span class="legend-item"><span class="legend-swatch" style="background:#fffaf0;border-color:#dd6b20;border-style:dashed;"></span> محور مشاهده‌پذیری</span>
          </div>
          <span class="bpmn-hint">👆 روی هر مولفه کلیک کنید</span>
        </div>

        <div class="bpmn-canvas-wrap">
          <svg viewBox="0 0 1080 1500" role="img" aria-label="نقشه BPMN2 مولفه‌های معماری">

            <defs>
              <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M 0 0 L 10 5 L 0 10 z" fill="#4a5568"></path>
              </marker>
              <marker id="arrow-accent" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
                <path d="M 0 0 L 10 5 L 0 10 z" fill="#b7791f"></path>
              </marker>
            </defs>

            <!-- ===================== LANES ===================== -->
            <!-- Lane 1: Interaction (L1) -->
            <g>
              <rect class="lane-bg" x="150" y="10" width="920" height="150" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="10" width="150" height="150" rx="6"></rect>
              <text class="lane-label-text" x="75" y="70">L1 — تعامل و تجربه</text>
              <text class="lane-label-text" x="75" y="86" style="font-size:9px;font-weight:400;">Interaction Layer</text>
              <line class="lane-sep" x1="150" y1="10" x2="150" y2="160"></line>
            </g>

            <!-- Lane 2: Access & Session (L2) -->
            <g>
              <rect class="lane-bg alt" x="150" y="160" width="920" height="150" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="160" width="150" height="150" rx="6"></rect>
              <text class="lane-label-text" x="75" y="220">L2 — کنترل دسترسی</text>
              <text class="lane-label-text" x="75" y="236" style="font-size:9px;font-weight:400;">Access & Session</text>
              <line class="lane-sep" x1="150" y1="160" x2="150" y2="310"></line>
            </g>

            <!-- Lane 3: Orchestration (L3) -->
            <g>
              <rect class="lane-bg" x="150" y="310" width="920" height="170" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="310" width="150" height="170" rx="6"></rect>
              <text class="lane-label-text" x="75" y="375">L3 — ارکستراسیون</text>
              <text class="lane-label-text" x="75" y="391" style="font-size:9px;font-weight:400;">Orchestration / Agent Core</text>
              <line class="lane-sep" x1="150" y1="310" x2="150" y2="480"></line>
            </g>

            <!-- Lane 4: Intelligence (L4) -->
            <g>
              <rect class="lane-bg alt" x="150" y="480" width="920" height="160" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="480" width="150" height="160" rx="6"></rect>
              <text class="lane-label-text" x="75" y="540">L4 — هوش و مدل‌ها</text>
              <text class="lane-label-text" x="75" y="556" style="font-size:9px;font-weight:400;">Intelligence Layer</text>
              <line class="lane-sep" x1="150" y1="480" x2="150" y2="640"></line>
            </g>

            <!-- Lane 5: Data & Resources (L5) -->
            <g>
              <rect class="lane-bg" x="150" y="640" width="920" height="160" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="640" width="150" height="160" rx="6"></rect>
              <text class="lane-label-text" x="75" y="700">L5 — داده و منابع</text>
              <text class="lane-label-text" x="75" y="716" style="font-size:9px;font-weight:400;">Data & Resources</text>
              <line class="lane-sep" x1="150" y1="640" x2="150" y2="800"></line>
            </g>

            <!-- Lane 6: Output & Reporting (L6) -->
            <g>
              <rect class="lane-bg alt" x="150" y="800" width="920" height="150" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="800" width="150" height="150" rx="6"></rect>
              <text class="lane-label-text" x="75" y="860">L6 — خروجی و گزارش</text>
              <text class="lane-label-text" x="75" y="876" style="font-size:9px;font-weight:400;">Output & Reporting</text>
              <line class="lane-sep" x1="150" y1="800" x2="150" y2="950"></line>
            </g>

            <!-- Lane X: Data Governance (cross-cutting) -->
            <g>
              <rect class="lane-bg alt" x="150" y="950" width="920" height="150" rx="6" style="fill:#fff5f5;"></rect>
              <rect class="lane-label-bg" x="0" y="950" width="150" height="150" rx="6" style="fill:#fff5f5;"></rect>
              <text class="lane-label-text" x="75" y="1010" style="fill:#c53030;">X — حاکمیت داده</text>
              <text class="lane-label-text" x="75" y="1026" style="font-size:9px;font-weight:400;fill:#c53030;">Data Governance (Cross-cutting)</text>
              <line class="lane-sep" x1="150" y1="950" x2="150" y2="1100"></line>
            </g>

            <!-- Lane Y: Observability (cross-cutting) -->
            <g>
              <rect class="lane-bg" x="150" y="1100" width="920" height="150" rx="6" style="fill:#fffaf0;"></rect>
              <rect class="lane-label-bg" x="0" y="1100" width="150" height="150" rx="6" style="fill:#fffaf0;"></rect>
              <text class="lane-label-text" x="75" y="1160" style="fill:#dd6b20;">Y — مشاهده‌پذیری</text>
              <text class="lane-label-text" x="75" y="1176" style="font-size:9px;font-weight:400;fill:#dd6b20;">Observability (Cross-cutting)</text>
              <line class="lane-sep" x1="150" y1="1100" x2="150" y2="1250"></line>
            </g>

            <!-- Lane 7: External Actor (User) -->
            <g>
              <rect class="lane-bg alt" x="150" y="1250" width="920" height="120" rx="6"></rect>
              <rect class="lane-label-bg" x="0" y="1250" width="150" height="120" rx="6"></rect>
              <text class="lane-label-text" x="75" y="1305">کاربر / Actor</text>
              <text class="lane-label-text" x="75" y="1321" style="font-size:9px;font-weight:400;">External Actor</text>
              <line class="lane-sep" x1="150" y1="1250" x2="150" y2="1370"></line>
            </g>

            <!-- ===================== LANE 1: Interaction ===================== -->
            <!-- L1.1 Web UI -->
            <g class="bpmn-el" data-layer="1" tabindex="0" role="button"
               data-title="رابط وب سازمانی"
               data-sub="L1 — تعامل و تجربه کاربری"
               data-task="دریافت درخواست کاربر از مرورگر، نمایش چت، آپلود فایل، مشاهده گزارش‌ها و داشبورد."
               data-input="درخواست کاربر | فایل آپلودی | انتخاب گزینه‌های رابط"
               data-output="درخواست ساختاریافته به لایه نشست | نمایش پاسخ نهایی به کاربر"
               data-conn="→ مدیریت نشست (L2) — ارسال درخواست و دریافت پاسخ"
               data-req="محور ۴ (رابط کاربری)">
              <rect class="bpmn-shape" x="185" y="55" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="85">رابط وب</text>
              <text class="bpmn-sub" x="260" y="102">Web UI</text>
            </g>

            <!-- L1.2 Desktop -->
            <g class="bpmn-el" data-layer="1" tabindex="0" role="button"
               data-title="نسخه دسکتاپ"
               data-sub="L1 — تعامل و تجربه کاربری"
               data-task="دسترسی به قابلیت‌های سامانه از طریق اپلیکیشن دسکتاپ با قابلیت دسترسی کنترل‌شده به فایل‌های محلی."
               data-input="دستور کاربر | مسیر فایل محلی (با مجوز)"
               data-output="درخواست ساختاریافته | فایل ارسالی برای تحلیل"
               data-conn="→ مدیریت نشست (L2) — ارسال درخواست و دریافت پاسخ"
               data-req="محور ۴ (رابط کاربری و دسکتاپ)">
              <rect class="bpmn-shape" x="360" y="55" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="435" y="85">نسخه دسکتاپ</text>
              <text class="bpmn-sub" x="435" y="102">Desktop App</text>
            </g>

            <!-- L1.3 API Gateway -->
            <g class="bpmn-el" data-layer="1" tabindex="0" role="button"
               data-title="درگاه API"
               data-sub="L1 — تعامل و تجربه کاربری"
               data-task="امکان یکپارچه‌سازی سیستم‌های سازمانی و استفاده از حساب/اعتبار اختصاصی سازمان."
               data-input="درخواست API با توکن | پارامترهای فراخوانی"
               data-output="پاسخ ساختاریافته JSON | کد وضعیت"
               data-conn="→ مدیریت نشست (L2) — ارسال درخواست و دریافت پاسخ"
               data-req="محور ۳ (API و اعتبار اختصاصی)">
              <rect class="bpmn-shape" x="535" y="55" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="610" y="85">درگاه API</text>
              <text class="bpmn-sub" x="610" y="102">API Gateway</text>
            </g>

            <!-- ===================== LANE 2: Access ===================== -->
            <!-- L2.1 Auth -->
            <g class="bpmn-el" data-layer="2" tabindex="0" role="button"
               data-title="احراز هویت"
               data-sub="L2 — کنترل دسترسی و نشست"
               data-task="تأیید هویت کاربران و یکپارچه‌سازی با سامانه هویت سازمانی."
               data-input="توکن/اعتبارنامه کاربر | درخواست ورود"
               data-output="هویت تأییدشده | شناسه کاربر به مدیریت نشست"
               data-conn="→ مدیریت نشست (L2) — اعلام هویت تأییدشده"
               data-req="محور ۲ (مدیریت کاربران)">
              <rect class="bpmn-shape" x="185" y="205" width="140" height="70" rx="6"></rect>
              <text class="bpmn-label" x="255" y="235">احراز هویت</text>
              <text class="bpmn-sub" x="255" y="252">Authentication</text>
            </g>

            <!-- L2.2 Session -->
            <g class="bpmn-el" data-layer="2" tabindex="0" role="button"
               data-title="مدیریت نشست"
               data-sub="L2 — کنترل دسترسی و نشست"
               data-task="حفظ زمینه کاربر، سطح دسترسی فعال و سیاست‌های نشست در طول تعامل."
               data-input="هویت تأییدشده | درخواست کاربر | سطح دسترسی"
               data-output="نشست فعال | زمینه کاربر به ارکستراسیون"
               data-conn="← احراز هویت (L2) | ← موتور مجوزها (L2) | → موتور ایجنت (L3)"
               data-req="محور ۲ (نشست و دسترسی)">
              <rect class="bpmn-shape" x="350" y="205" width="140" height="70" rx="6"></rect>
              <text class="bpmn-label" x="420" y="235">مدیریت نشست</text>
              <text class="bpmn-sub" x="420" y="252">Session Manager</text>
            </g>

            <!-- L2.3 Permission Engine -->
            <g class="bpmn-el" data-layer="2" tabindex="0" role="button"
               data-title="موتور مجوزها"
               data-sub="L2 — کنترل دسترسی و نشست"
               data-task="اعمال مجوزها در سطح مدل، منبع، ابزار و رکورد؛ تعیین فهرست مجاز مدل‌ها و ابزارها."
               data-input="نقش‌ها و مجوزهای کاربر | فهرست منابع و مدل‌ها"
               data-output="فهرست مجاز مدل/ابزار/منبع | محدودیت‌های دسترسی به ایجنت"
               data-conn="→ مدیریت نشست (L2) | → موتور ایجنت (L3) — ابلاغ محدودیت‌ها"
               data-req="محور ۲ (سطح دسترسی تا رکورد)">
              <rect class="bpmn-shape" x="515" y="205" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="590" y="235">موتور مجوزها</text>
              <text class="bpmn-sub" x="590" y="252">Permission Engine</text>
            </g>

            <!-- L2.4 Role Manager -->
            <g class="bpmn-el" data-layer="2" tabindex="0" role="button"
               data-title="مدیریت نقش‌ها"
               data-sub="L2 — کنترل دسترسی و نشست"
               data-task="تعریف و مدیریت نقش‌ها، کاربران و سطوح دسترسی واحدهای مختلف سازمان."
               data-input="تعریف نقش جدید | تخصیص کاربر به نقش"
               data-output="نقش‌ها و مجوزهای به‌روزشده"
               data-conn="→ موتور مجوزها (L2) — تأمین داده مجوز"
               data-req="محور ۲ (مدیریت کاربران)">
              <rect class="bpmn-shape" x="690" y="205" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="765" y="235">مدیریت نقش‌ها</text>
              <text class="bpmn-sub" x="765" y="252">Role Manager</text>
            </g>

            <!-- ===================== LANE 3: Orchestration ===================== -->
            <!-- L3.1 Agent Engine -->
            <g class="bpmn-el" data-layer="3" tabindex="0" role="button"
               data-title="موتور ایجنت"
               data-sub="L3 — ارکستراسیون (هسته ایجنت)"
               data-task="هسته تصمیم‌گیری؛ دریافت هدف، تولید برنامه، اجرا و اصلاح بر اساس نتیجه (حلقه Closed-loop)."
               data-input="هدف کاربر | زمینه نشست | فهرست مجاز ابزار/مدل/منبع"
               data-output="برنامه اجرایی | تصمیم فراخوانی ابزار/مدل | نتیجه نهایی"
               data-conn="← مدیریت نشست (L2) | ← موتور مجوزها (L2) | → برنامه‌ریز (L3) | → درگاه مدل (L4) | → تولید گزارش (L6)"
               data-req="محور ۱ (ایجنت قابل‌آزمون)">
              <rect class="bpmn-shape" x="185" y="350" width="150" height="80" rx="6"></rect>
              <text class="bpmn-label" x="260" y="382">موتور ایجنت</text>
              <text class="bpmn-sub" x="260" y="400">Agent Engine</text>
            </g>

            <!-- L3.2 Planner -->
            <g class="bpmn-el" data-layer="3" tabindex="0" role="button"
               data-title="برنامه‌ریز (Planner)"
               data-sub="L3 — ارکستراسیون (هسته ایجنت)"
               data-task="تبدیل هدف کاربر به مراحل اجرایی قابل پیگیری و قابل اصلاح."
               data-input="هدف کاربر | زمینه | محدودیت‌ها"
               data-output="برنامه چندمرحله‌ای | ترتیب مراحل"
               data-conn="← موتور ایجنت (L3) | → انتخاب‌گر ابزار (L3)"
               data-req="محور ۱ (تبدیل هدف به مراحل)">
              <rect class="bpmn-shape" x="360" y="350" width="140" height="80" rx="6"></rect>
              <text class="bpmn-label" x="430" y="382">برنامه‌ریز</text>
              <text class="bpmn-sub" x="430" y="400">Planner</text>
            </g>

            <!-- L3.3 Tool Selector -->
            <g class="bpmn-el" data-layer="3" tabindex="0" role="button"
               data-title="انتخاب‌گر ابزار"
               data-sub="L3 — ارکستراسیون (هسته ایجنت)"
               data-task="انتخاب ابزار یا منبع مناسب از میان فهرست مجاز کاربر برای هر مرحله."
               data-input="مرحله برنامه | فهرست ابزار مجاز"
               data-output="ابزار انتخاب‌شده | فراخوانی اجرا"
               data-conn="← برنامه‌ریز (L3) | → ابزارهای عملیاتی (L5)"
               data-req="محور ۱ و ۲ (انتخاب ابزار مجاز)">
              <rect class="bpmn-shape" x="525" y="350" width="150" height="80" rx="6"></rect>
              <text class="bpmn-label" x="600" y="382">انتخاب‌گر ابزار</text>
              <text class="bpmn-sub" x="600" y="400">Tool Selector</text>
            </g>

            <!-- L3.4 Flow Manager -->
            <g class="bpmn-el" data-layer="3" tabindex="0" role="button"
               data-title="مدیریت جریان"
               data-sub="L3 — ارکستراسیون (هسته ایجنت)"
               data-task="هدایت جریان اجرا، مدیریت حالت‌ها، واکنش به خطا و تغییر شرایط."
               data-input="نتیجه اجرای ابزار | وضعیت خطا | شرایط جدید"
               data-output="تصمیم ادامه/اصلاح/خاتمه | هشدار به ایجنت"
               data-conn="← ابزارهای عملیاتی (L5) | → موتور ایجنت (L3) | → نقاط تأیید انسانی (L3)"
               data-req="محور ۱ (واکنش به خطا و تغییر شرایط)">
              <rect class="bpmn-shape" x="700" y="350" width="150" height="80" rx="6"></rect>
              <text class="bpmn-label" x="775" y="382">مدیریت جریان</text>
              <text class="bpmn-sub" x="775" y="400">Flow Manager</text>
            </g>

            <!-- L3.5 Human-in-the-loop -->
            <g class="bpmn-el" data-layer="3" tabindex="0" role="button"
               data-title="نقاط تأیید انسانی"
               data-sub="L3 — ارکستراسیون (هسته ایجنت)"
               data-task="تعریف و اجرای نقاط Human-in-the-loop برای تأیید عملیات حساس."
               data-input="درخواست تأیید | زمینه عملیات"
               data-output="تأیید/رد انسان | ادامه یا توقف جریان"
               data-conn="← مدیریت جریان (L3) | → موتور ایجنت (L3) | → رابط کاربری (L1) برای نمایش"
               data-req="محور ۱ (Human-in-the-loop)">
              <rect class="bpmn-shape" x="875" y="350" width="150" height="80" rx="6"></rect>
              <text class="bpmn-label" x="950" y="382">تأیید انسانی</text>
              <text class="bpmn-sub" x="950" y="400">Human-in-the-loop</text>
            </g>

            <!-- ===================== LANE 4: Intelligence ===================== -->
            <!-- L4.1 Model Gateway -->
            <g class="bpmn-el" data-layer="4" tabindex="0" role="button"
               data-title="درگاه مدل‌ها"
               data-sub="L4 — هوش و مدل‌ها"
               data-task="لایه انتزاع دسترسی به مدل‌های مختلف (داخلی/خارجی) با سیاست‌های یکسان."
               data-input="درخواست استدلال/تولید | شناسه مدل مجاز"
               data-output="پاسخ مدل | مصرف توکن (برای گزارش)"
               data-conn="← موتور ایجنت (L3) | ← مدیریت مدل (L4) | → بازیابی و تقویت (L4)"
               data-req="محور ۱ و ۵ (مدل و استقرار)">
              <rect class="bpmn-shape" x="185" y="510" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="540">درگاه مدل‌ها</text>
              <text class="bpmn-sub" x="260" y="557">Model Gateway</text>
            </g>

            <!-- L4.2 Model Manager -->
            <g class="bpmn-el" data-layer="4" tabindex="0" role="button"
               data-title="مدیریت مدل"
               data-sub="L4 — هوش و مدل‌ها"
               data-task="فهرست مدل‌های مجاز، نسخه‌بندی، به‌روزرسانی و سیاست دسترسی به مدل‌های جدید."
               data-input="فهرست مدل‌ها | نسخه جدید | سیاست دسترسی"
               data-output="مدل مجاز فعال | زمان‌بندی دسترسی به نسخه جدید"
               data-conn="→ درگاه مدل‌ها (L4) — تأمین مدل مجاز"
               data-req="محور ۱ (مدل‌های قابل استفاده و به‌روزرسانی)">
              <rect class="bpmn-shape" x="360" y="510" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="435" y="540">مدیریت مدل</text>
              <text class="bpmn-sub" x="435" y="557">Model Manager</text>
            </g>

            <!-- L4.3 RAG -->
            <g class="bpmn-el" data-layer="4" tabindex="0" role="button"
               data-title="بازیابی و تقویت (RAG)"
               data-sub="L4 — هوش و مدل‌ها"
               data-task="بازیابی اطلاعات از منابع مجاز کاربر و تقویت پاسخ مدل با شواهد."
               data-input="پرسش | فهرست منابع مجاز | زمینه"
               data-output="شواهد بازیابی‌شده | پاسخ تقویت‌شده با ارجاع"
               data-conn="← درگاه مدل‌ها (L4) | → منابع دانش سازمانی (L5)"
               data-req="محور ۲ و ۴ (بازیابی با رعایت دسترسی)">
              <rect class="bpmn-shape" x="535" y="510" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="610" y="540">بازیابی و تقویت</text>
              <text class="bpmn-sub" x="610" y="557">RAG</text>
            </g>

            <!-- L4.4 Memory -->
            <g class="bpmn-el" data-layer="4" tabindex="0" role="button"
               data-title="حافظه و زمینه"
               data-sub="L4 — هوش و مدل‌ها"
               data-task="مدیریت زمینه مکالمه، حافظه کوتاه‌مدت و بلندمدت با رعایت سطح دسترسی."
               data-input="تاریخچه تعامل | زمینه نشست | مجوز دسترسی"
               data-output="زمینه فعال | حافظه به‌روزشده"
               data-conn="↔ درگاه مدل‌ها (L4) | ↔ موتور ایجنت (L3)"
               data-req="محور ۲ (حافظه با رعایت دسترسی)">
              <rect class="bpmn-shape" x="710" y="510" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="785" y="540">حافظه و زمینه</text>
              <text class="bpmn-sub" x="785" y="557">Memory & Context</text>
            </g>

            <!-- ===================== LANE 5: Data ===================== -->
            <!-- L5.1 Knowledge -->
            <g class="bpmn-el" data-layer="5" tabindex="0" role="button"
               data-title="منابع دانش سازمانی"
               data-sub="L5 — داده و منابع"
               data-task="مخازن دانش، اسناد، پایگاه‌های دانش و محتوای ساختاریافته/غیرساختاریافته."
               data-input="درخواست بازیابی (با مجوز)"
               data-output="اطلاعات مرتبط | شواهد"
               data-conn="← بازیابی و تقویت (L4) — تأمین شواهد"
               data-req="محور ۴ و ۵ (منابع دانش و حاکمیت)">
              <rect class="bpmn-shape" x="185" y="670" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="700">منابع دانش</text>
              <text class="bpmn-sub" x="260" y="717">Knowledge Sources</text>
            </g>

            <!-- L5.2 File -->
            <g class="bpmn-el" data-layer="5" tabindex="0" role="button"
               data-title="مدیریت فایل و پوشه"
               data-sub="L5 — داده و منابع"
               data-task="دسترسی کنترل‌شده به فایل‌های محلی/شبکه و تحلیل چند فایل."
               data-input="مسیر فایل (با مجوز) | درخواست تحلیل"
               data-output="محتوای فایل | تحلیل چندفایلی"
               data-conn="← انتخاب‌گر ابزار (L3) | → تولید گزارش (L6)"
               data-req="محور ۴ (دسترسی به فایل و تحلیل چند فایل)">
              <rect class="bpmn-shape" x="360" y="670" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="435" y="700">مدیریت فایل</text>
              <text class="bpmn-sub" x="435" y="717">File & Folder</text>
            </g>

            <!-- L5.3 External -->
            <g class="bpmn-el" data-layer="5" tabindex="0" role="button"
               data-title="سرویس‌های خارجی"
               data-sub="L5 — داده و منابع"
               data-task="اتصال به سرویس‌های ثالث از طریق API با سیاست‌های حاکمیت داده."
               data-input="درخواست API | سیاست انتقال داده"
               data-output="پاسخ سرویس | لاگ انتقال"
               data-conn="← درگاه مدل‌ها (L4) | → سیاست‌گذار داده (X)"
               data-req="محور ۵ (انتقال داده به ثالث)">
              <rect class="bpmn-shape" x="535" y="670" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="610" y="700">سرویس‌های خارجی</text>
              <text class="bpmn-sub" x="610" y="717">External Services</text>
            </g>

            <!-- L5.4 Tools -->
            <g class="bpmn-el" data-layer="5" tabindex="0" role="button"
               data-title="ابزارهای عملیاتی"
               data-sub="L5 — داده و منابع"
               data-task="مجموعه ابزارهای قابل فراخوانی توسط ایجنت (جستجو، محاسبه، ارسال، تبدیل و...)."
               data-input="فراخوانی ابزار | پارامترها"
               data-output="نتیجه اجرا | وضعیت خطا"
               data-conn="← انتخاب‌گر ابزار (L3) | → مدیریت جریان (L3)"
               data-req="محور ۱ (ابزارهای ایجنت)">
              <rect class="bpmn-shape" x="710" y="670" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="785" y="700">ابزارهای عملیاتی</text>
              <text class="bpmn-sub" x="785" y="717">Operational Tools</text>
            </g>

            <!-- ===================== LANE 6: Output ===================== -->
            <!-- L6.1 Report Gen -->
            <g class="bpmn-el" data-layer="6" tabindex="0" role="button"
               data-title="تولید گزارش"
               data-sub="L6 — خروجی و گزارش"
               data-task="تولید خروجی متنی، جدولی و نموداری با قابلیت ویرایش و ارجاع به منابع."
               data-input="نتیجه ایجنت | شواهد | درخواست خروجی"
               data-output="گزارش متنی/جدولی/نموداری | ارجاع به منابع"
               data-conn="← موتور ایجنت (L3) | → مبدل قالب (L6) | → رابط کاربری (L1)"
               data-req="محور ۴ (خروجی و ارجاع)">
              <rect class="bpmn-shape" x="185" y="830" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="860">تولید گزارش</text>
              <text class="bpmn-sub" x="260" y="877">Report Generator</text>
            </g>

            <!-- L6.2 Format Converter -->
            <g class="bpmn-el" data-layer="6" tabindex="0" role="button"
               data-title="مبدل قالب"
               data-sub="L6 — خروجی و گزارش"
               data-task="تبدیل خروجی به Word، Excel و سایر قالب‌های موردنیاز."
               data-input="گزارش تولیدشده | قالب هدف"
               data-output="فایل Word/Excel | فایل نهایی"
               data-conn="← تولید گزارش (L6) | → رابط کاربری (L1)"
               data-req="محور ۴ (خروجی Word و Excel)">
              <rect class="bpmn-shape" x="360" y="830" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="435" y="860">مبدل قالب</text>
              <text class="bpmn-sub" x="435" y="877">Format Converter</text>
            </g>

            <!-- L6.3 Dashboard -->
            <g class="bpmn-el" data-layer="6" tabindex="0" role="button"
               data-title="داشبورد مصرف"
               data-sub="L6 — خروجی و گزارش"
               data-task="نمایش مصرف و هزینه به تفکیک کاربر، مدل، ایجنت و ابزار."
               data-input="داده‌های متریک و ردیابی | مصرف توکن | هزینه"
               data-output="داشبورد تحلیلی | گزارش مصرف"
               data-conn="← متریک و ردیابی (Y) | → رابط کاربری (L1)"
               data-req="محور ۳ (گزارش مصرف و هزینه)">
              <rect class="bpmn-shape" x="535" y="830" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="610" y="860">داشبورد مصرف</text>
              <text class="bpmn-sub" x="610" y="877">Usage Dashboard</text>
            </g>

            <!-- ===================== LANE X: Data Governance ===================== -->
            <!-- X.1 Data Policy -->
            <g class="bpmn-el" data-layer="x" tabindex="0" role="button"
               data-title="سیاست‌گذار داده"
               data-sub="X — حاکمیت داده (Cross-cutting)"
               data-task="تعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدل."
               data-input="سیاست‌های سازمانی | الزامات محرمانگی"
               data-output="سیاست اعمال‌شده | محدودیت انتقال داده"
               data-conn="→ سرویس‌های خارجی (L5) | → درگاه مدل‌ها (L4) | → سنسور محرمانگی (X)"
               data-req="محور ۵ (سیاست داده و آموزش مدل)">
              <rect class="bpmn-shape" x="185" y="980" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="1010">سیاست‌گذار داده</text>
              <text class="bpmn-sub" x="260" y="1027">Data Policy</text>
            </g>

            <!-- X.2 Audit -->
            <g class="bpmn-el" data-layer="x" tabindex="0" role="button"
               data-title="ممیزی و لاگ"
               data-sub="X — حاکمیت داده (Cross-cutting)"
               data-task="ثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها برای ممیزی."
               data-input="رخدادهای سیستم | تصمیمات ایجنت | دسترسی‌ها"
               data-output="لاگ ممیزی | گزارش رخداد"
               data-conn="→ داشبورد مصرف (L6) | → متریک و ردیابی (Y)"
               data-req="محور ۲ و ۵ (ممیزی)">
              <rect class="bpmn-shape" x="360" y="980" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="435" y="1010">ممیزی و لاگ</text>
              <text class="bpmn-sub" x="435" y="1027">Audit & Log</text>
            </g>

            <!-- X.3 Confidentiality Sensor -->
            <g class="bpmn-el" data-layer="x" tabindex="0" role="button"
               data-title="سنسور محرمانگی"
               data-sub="X — حاکمیت داده (Cross-cutting)"
               data-task="شناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسی در پاسخ‌ها."
               data-input="پاسخ پیش از ارائه | سطح دسترسی کاربر"
               data-output="پاسخ فیلترشده | هشدار افشا"
               data-conn="← تولید گزارش (L6) | → رابط کاربری (L1) | ← سیاست‌گذار داده (X)"
               data-req="محور ۲ (جلوگیری از افشا — آزمون نفوذ)">
              <rect class="bpmn-shape" x="535" y="980" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="610" y="1010">سنسور محرمانگی</text>
              <text class="bpmn-sub" x="610" y="1027">Confidentiality Sensor</text>
            </g>

            <!-- ===================== LANE Y: Observability ===================== -->
            <!-- Y.1 Metrics -->
            <g class="bpmn-el" data-layer="y" tabindex="0" role="button"
               data-title="متریک و ردیابی"
               data-sub="Y — مشاهده‌پذیری (Cross-cutting)"
               data-task="اندازه‌گیری مصرف توکن، زمان پاسخ، نرخ خطا و شاخص‌های عملکرد."
               data-input="رخدادهای اجرا | مصرف توکن | زمان پاسخ"
               data-output="متریک‌ها | داده خام به داشبورد"
               data-conn="→ داشبورد مصرف (L6) | ← ممیزی و لاگ (X)"
               data-req="محور ۳ و ۷ (عملکرد و مصرف)">
              <rect class="bpmn-shape" x="185" y="1130" width="150" height="70" rx="6"></rect>
              <text class="bpmn-label" x="260" y="1160">متریک و ردیابی</text>
              <text class="bpmn-sub" x="260" y="1177">Metrics & Tracing</text>
            </g>

            <!-- ===================== LANE 7: Actor ===================== -->
            <!-- Actor: User -->
            <g class="bpmn-el" data-layer="1" tabindex="0" role="button"
               data-title="کاربر سازمانی"
               data-sub="Actor — کاربر نهایی"
               data-task="ارسال درخواست، تأیید عملیات حساس، دریافت پاسخ و گزارش."
               data-input="هدف/پرسش | تأیید/رد | فایل ورودی"
               data-output="درخواست به رابط کاربری | تأیید انسانی"
               data-conn="→ رابط وب/دسکتاپ/API (L1) | ← تأیید انسانی (L3) برای نمایش"
               data-req="محور ۱ (Human-in-the-loop) و ۴ (رابط)">
              <ellipse class="bpmn-shape" cx="600" cy="1310" rx="80" ry="38"></ellipse>
              <text class="bpmn-label" x="600" y="1306">کاربر سازمانی</text>
              <text class="bpmn-sub" x="600" y="1322">Actor / User</text>
            </g>

            <!-- ===================== FLOWS ===================== -->
            <!-- Actor → Web UI -->
            <path class="bpmn-flow" d="M 600 1272 C 600 1220, 260 200, 260 127"></path>
            <!-- Actor → Desktop -->
            <path class="bpmn-flow" d="M 620 1272 C 620 1220, 435 200, 435 127"></path>
            <!-- Actor → API -->
            <path class="bpmn-flow" d="M 640 1272 C 640 1220, 610 200, 610 127"></path>

            <!-- L1 → L2 (vertical connectors) -->
            <path class="bpmn-flow" d="M 260 127 L 260 203"></path>
            <path class="bpmn-flow" d="M 435 127 L 435 203"></path>
            <path class="bpmn-flow" d="M 610 127 L 610 203"></path>

            <!-- L2 internal -->
            <path class="bpmn-flow" d="M 325 240 L 348 240"></path>
            <path class="bpmn-flow" d="M 490 240 L 513 240"></path>
            <path class="bpmn-flow" d="M 665 240 L 688 240"></path>

            <!-- L2 → L3 -->
            <path class="bpmn-flow accent" d="M 420 275 L 420 300 L 260 300 L 260 348" marker-end="url(#arrow-accent)"></path>
            <path class="bpmn-flow dashed" d="M 590 275 L 590 300 L 300 300 L 300 348"></path>

            <!-- L3 internal -->
            <path class="bpmn-flow" d="M 335 390 L 358 390"></path>
            <path class="bpmn-flow" d="M 500 390 L 523 390"></path>
            <path class="bpmn-flow" d="M 675 390 L 698 390"></path>
            <path class="bpmn-flow dashed" d="M 850 390 L 873 390"></path>
            <path class="bpmn-flow dashed" d="M 950 430 L 950 460 L 260 460 L 260 430" ></path>

            <!-- L3 → L4 -->
            <path class="bpmn-flow" d="M 260 430 L 260 508"></path>
            <!-- L3 → L5 (tool selector to tools) -->
            <path class="bpmn-flow" d="M 600 430 L 600 470 L 785 470 L 785 668"></path>
            <!-- L3 → L6 (agent to report) -->
            <path class="bpmn-flow accent" d="M 220 430 L 220 480 L 260 480 L 260 828" marker-end="url(#arrow-accent)"></path>

            <!-- L4 internal -->
            <path class="bpmn-flow" d="M 335 545 L 358 545"></path>
            <path class="bpmn-flow" d="M 510 545 L 533 545"></path>
            <path class="bpmn-flow dashed" d="M 685 545 L 708 545"></path>

            <!-- L4 → L5 -->
            <path class="bpmn-flow" d="M 610 580 L 610 620 L 435 620 L 435 668"></path>
            <path class="bpmn-flow dashed" d="M 610 580 L 610 620 L 610 668"></path>

            <!-- L5 → L6 (file to report) -->
            <path class="bpmn-flow" d="M 435 740 L 435 780 L 260 780 L 260 828"></path>

            <!-- L6 internal -->
            <path class="bpmn-flow" d="M 335 865 L 358 865"></path>

            <!-- X → targets -->
            <path class="bpmn-flow dashed" d="M 260 980 L 260 780 L 535 780 L 535 828" style="stroke:#c53030;" marker-end="url(#arrow)"></path>
            <path class="bpmn-flow dashed" d="M 610 980 L 610 920 L 610 902" style="stroke:#c53030;"></path>
            <path class="bpmn-flow dashed" d="M 435 980 L 435 920 L 435 902" style="stroke:#c53030;"></path>

            <!-- X.1 → X.3 -->
            <path class="bpmn-flow dashed" d="M 335 1015 L 533 1015" style="stroke:#c53030;"></path>

            <!-- Y → L6 -->
            <path class="bpmn-flow dashed" d="M 260 1130 L 260 1080 L 610 1080 L 610 902" style="stroke:#dd6b20;"></path>

            <!-- Flow labels -->
            <text class="bpmn-flow-label" x="270" y="180">درخواست</text>
            <text class="bpmn-flow-label" x="445" y="180">درخواست</text>
            <text class="bpmn-flow-label" x="620" y="180">درخواست</text>
            <text class="bpmn-flow-label" x="430" y="320">زمینه</text>
            <text class="bpmn-flow-label" x="270" y="320">مجوزها</text>
            <text class="bpmn-flow-label" x="270" y="470">استدلال</text>
            <text class="bpmn-flow-label" x="795" y="460">ابزار</text>
            <text class="bpmn-flow-label" x="230" y="650">نتیجه</text>
            <text class="bpmn-flow-label" x="445" y="770">فایل</text>
            <text class="bpmn-flow-label" x="545" y="770">فیلتر</text>
            <text class="bpmn-flow-label" x="620" y="1085">متریک</text>

            <!-- Legend for BPMN symbols (bottom) -->
            <g transform="translate(150, 1400)">
              <text x="0" y="0" style="font-size:11px;font-weight:700;fill:#1a365d;font-family:'Vazirmatn';">راهنمای نمادها (BPMN 2.0):</text>
              <rect x="0" y="12" width="18" height="14" rx="2" fill="#fff" stroke="#2c5282" stroke-width="1.5"></rect>
              <text x="24" y="24" style="font-size:10px;fill:#4a5568;font-family:'Vazirmatn';">Task / مولفه</text>
              <path d="M 150 20 L 180 20" stroke="#4a5568" stroke-width="1.4" marker-end="url(#arrow)"></path>
              <text x="186" y="24" style="font-size:10px;fill:#4a5568;font-family:'Vazirmatn';">Sequence Flow</text>
              <path d="M 320 20 L 350 20" stroke="#718096" stroke-width="1.4" stroke-dasharray="5 4" marker-end="url(#arrow)"></path>
              <text x="356" y="24" style="font-size:10px;fill:#4a5568;font-family:'Vazirmatn';">Data / Control Flow</text>
              <ellipse cx="560" cy="19" rx="20" ry="10" fill="#fff" stroke="#2c5282" stroke-width="1.5"></ellipse>
              <text x="586" y="24" style="font-size:10px;fill:#4a5568;font-family:'Vazirmatn';">Actor</text>
            </g>

          </svg>
        </div>

        <div class="info-box" style="margin-top:18px;">
          <strong>💡 نکته:</strong> این نقشه بر اساس استاندارد BPMN 2.0 ترسیم شده است. <strong>Lane</strong>ها نماینده لایه‌های معماری (L1 تا L6) و محورهای عرضی (X و Y) هستند. فلش‌های ممتد نماینده <strong>Sequence Flow</strong> (جریان اصلی درخواست) و فلش‌های نقطه‌چین نماینده <strong>Data/Control Flow</strong> (جریان داده و کنترل عرضی) هستند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>جدول مولفه‌ها و ارتباطات</h3>
          <div class="subtitle">Component & Connection Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر خلاصه‌ای از تمام مولفه‌های نقشه و ارتباطات ورودی/خروجی آنهاست. برای جزئیات بیشتر، روی هر مولفه در نقشه کلیک کنید.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>Lane</th>
              <th>مولفه</th>
              <th>ورودی اصلی</th>
              <th>خروجی اصلی</th>
              <th>مقصد</th>
            </tr>
          </thead>
          <tbody>
            <tr><td>L1</td><td>رابط وب / دسکتاپ / API</td><td>درخواست کاربر</td><td>درخواست ساختاریافته</td><td>مدیریت نشست</td></tr>
            <tr><td>L2</td><td>احراز هویت</td><td>اعتبارنامه</td><td>هویت تأییدشده</td><td>مدیریت نشست</td></tr>
            <tr><td>L2</td><td>مدیریت نشست</td><td>هویت + درخواست</td><td>نشست فعال</td><td>موتور ایجنت</td></tr>
            <tr><td>L2</td><td>موتور مجوزها</td><td>نقش‌ها</td><td>فهرست مجاز</td><td>موتور ایجنت</td></tr>
            <tr><td>L2</td><td>مدیریت نقش‌ها</td><td>تعریف نقش</td><td>مجوزهای به‌روز</td><td>موتور مجوزها</td></tr>
            <tr><td>L3</td><td>موتور ایجنت</td><td>هدف + زمینه</td><td>برنامه / نتیجه</td><td>برنامه‌ریز / گزارش</td></tr>
            <tr><td>L3</td><td>برنامه‌ریز</td><td>هدف</td><td>مراحل اجرایی</td><td>انتخاب‌گر ابزار</td></tr>
            <tr><td>L3</td><td>انتخاب‌گر ابزار</td><td>مرحله</td><td>ابزار انتخاب‌شده</td><td>ابزارهای عملیاتی</td></tr>
            <tr><td>L3</td><td>مدیریت جریان</td><td>نتیجه اجرا</td><td>تصمیم ادامه/اصلاح</td><td>موتور ایجنت</td></tr>
            <tr><td>L3</td><td>تأیید انسانی</td><td>درخواست تأیید</td><td>تأیید/رد</td><td>موتور ایجنت</td></tr>
            <tr><td>L4</td><td>درگاه مدل‌ها</td><td>درخواست استدلال</td><td>پاسخ مدل</td><td>موتور ایجنت</td></tr>
            <tr><td>L4</td><td>مدیریت مدل</td><td>فهرست مدل</td><td>مدل مجاز</td><td>درگاه مدل‌ها</td></tr>
            <tr><td>L4</td><td>بازیابی و تقویت</td><td>پرسش</td><td>شواهد</td><td>درگاه مدل‌ها</td></tr>
            <tr><td>L4</td><td>حافظه و زمینه</td><td>تاریخچه</td><td>زمینه فعال</td><td>درگاه مدل‌ها</td></tr>
            <tr><td>L5</td><td>منابع دانش</td><td>درخواست بازیابی</td><td>اطلاعات مرتبط</td><td>بازیابی و تقویت</td></tr>
            <tr><td>L5</td><td>مدیریت فایل</td><td>مسیر فایل</td><td>محتوای فایل</td><td>تولید گزارش</td></tr>
            <tr><td>L5</td><td>سرویس‌های خارجی</td><td>درخواست API</td><td>پاسخ سرویس</td><td>درگاه مدل‌ها</td></tr>
            <tr><td>L5</td><td>ابزارهای عملیاتی</td><td>فراخوانی</td><td>نتیجه اجرا</td><td>مدیریت جریان</td></tr>
            <tr><td>L6</td><td>تولید گزارش</td><td>نتیجه ایجنت</td><td>گزارش</td><td>مبدل قالب</td></tr>
            <tr><td>L6</td><td>مبدل قالب</td><td>گزارش</td><td>Word/Excel</td><td>رابط کاربری</td></tr>
            <tr><td>L6</td><td>داشبورد مصرف</td><td>متریک</td><td>گزارش مصرف</td><td>رابط کاربری</td></tr>
            <tr><td>X</td><td>سیاست‌گذار داده</td><td>سیاست سازمانی</td><td>محدودیت انتقال</td><td>سرویس خارجی / درگاه مدل</td></tr>
            <tr><td>X</td><td>ممیزی و لاگ</td><td>رخدادها</td><td>لاگ ممیزی</td><td>داشبورد</td></tr>
            <tr><td>X</td><td>سنسور محرمانگی</td><td>پاسخ پیش از ارائه</td><td>پاسخ فیلترشده</td><td>رابط کاربری</td></tr>
            <tr><td>Y</td><td>متریک و ردیابی</td><td>رخداد اجرا</td><td>متریک</td><td>داشبورد مصرف</td></tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>جمع‌بندی</h3>
          <div class="subtitle">Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>این مستند، تمام مولفه‌های معماری کلان سامانه هوش مصنوعی سازمانی را بر اساس استاندارد BPMN 2.0 رسم کرده است. ویژگی‌های کلیدی این نقشه:</p>

        <ul style="list-style:none;padding:0;">
          <li style="background:#f8fafc;border-right:3px solid var(--primary-light);padding:12px 18px;margin-bottom:8px;border-radius:6px;font-size:13px;"><strong>۸ Lane:</strong> شش لایه معماری + دو محور عرضی (حاکمیت داده و مشاهده‌پذیری) + Actor</li>
          <li style="background:#f8fafc;border-right:3px solid var(--primary-light);padding:12px 18px;margin-bottom:8px;border-radius:6px;font-size:13px;"><strong>۲۵+ مولفه قابل کلیک:</strong> هر مولفه دارای مودال اطلاعاتی شامل وظایف، ورودی، خروجی و ارتباطات</li>
          <li style="background:#f8fafc;border-right:3px solid var(--primary-light);padding:12px 18px;margin-bottom:8px;border-radius:6px;font-size:13px;"><strong>دو نوع جریان:</strong> Sequence Flow (ممتد) برای جریان اصلی و Data/Control Flow (نقطه‌چین) برای جریان عرضی</li>
          <li style="background:#f8fafc;border-right:3px solid var(--primary-light);padding:12px 18px;margin-bottom:8px;border-radius:6px;font-size:13px;"><strong>رنگ‌بندی معنادار:</strong> هر لایه با رنگ مشخص، محورهای عرضی با خط‌چین و رنگ متمایز</li>
          <li style="background:#f8fafc;border-right:3px solid var(--primary-light);padding:12px 18px;margin-bottom:8px;border-radius:6px;font-size:13px;"><strong>نگاشت به نیازمندی‌ها:</strong> هر مولفه به محور نیازمندی مرتبط (REQ-1405-001) ارجاع داده شده است</li>
        </ul>

        <div class="highlight-box" style="margin-top:20px;">
          <strong>نکته کلیدی:</strong> این نقشه BPMN2، پل ارتباطی بین <strong>معماری کلان (ARCH-1405-001)</strong> و <strong>طراحی تفصیلی</strong> است. هر مولفه در این نقشه، در مرحله طراحی تفصیلی به یک یا چند سرویس/ماژول قابل پیاده‌سازی تبدیل خواهد شد.
        </div>
      </div>
    </div>

    <div class="conclusion-box">
      <h3>🎯 ارزش این مستند</h3>
      <p>نقشه BPMN2 تعاملی، امکان درک سریع و دقیق معماری را برای ذی‌نفعان فنی و غیرفنی فراهم می‌کند.</p>
      <p>هر مولفه با کلیک، اطلاعات کامل وظایف و ارتباطات ورودی/خروجی را نمایش می‌دهد و مبنای طراحی تفصیلی و پیاده‌سازی قرار می‌گیرد.</p>
      <div class="highlight">
        <strong>💎 ارزش پیشنهادی:</strong><br>
        استاندارد BPMN 2.0 + تعامل‌پذیری کامل + نگاشت به نیازمندی‌ها + مبنای طراحی تفصیلی
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

<!-- ===================== MODAL ===================== -->
<div class="modal-overlay" id="modalOverlay" aria-hidden="true">
  <div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
    <div class="modal-header">
      <div>
        <h3 id="modalTitle">عنوان مولفه</h3>
        <div class="modal-sub" id="modalSub">زیرعنوان</div>
      </div>
      <button class="modal-close" id="modalClose" aria-label="بستن">✕</button>
    </div>
    <div class="modal-body">
      <div class="modal-section">
        <h4><span class="dot"></span> وظایف</h4>
        <p id="modalTask"></p>
      </div>
      <div class="modal-section">
        <h4><span class="dot"></span> ورودی‌ها و خروجی‌ها</h4>
        <div class="io-grid">
          <div class="io-col input">
            <h5>⬅ ورودی‌ها</h5>
            <ul id="modalInput"></ul>
          </div>
          <div class="io-col output">
            <h5>➡ خروجی‌ها</h5>
            <ul id="modalOutput"></ul>
          </div>
        </div>
      </div>
      <div class="modal-section">
        <h4><span class="dot"></span> ارتباطات</h4>
        <ul id="modalConn"></ul>
      </div>
      <div class="modal-section">
        <h4><span class="dot"></span> نیازمندی مرتبط</h4>
        <p><span class="chip accent" id="modalReq"></span></p>
      </div>
    </div>
  </div>
</div>

<script>
  (function () {
    'use strict';

    var overlay = document.getElementById('modalOverlay');
    var modalTitle = document.getElementById('modalTitle');
    var modalSub = document.getElementById('modalSub');
    var modalTask = document.getElementById('modalTask');
    var modalInput = document.getElementById('modalInput');
    var modalOutput = document.getElementById('modalOutput');
    var modalConn = document.getElementById('modalConn');
    var modalReq = document.getElementById('modalReq');
    var closeBtn = document.getElementById('modalClose');

    var lastFocused = null;

    function splitItems(str) {
      if (!str) return [];
      return str.split('|').map(function (s) { return s.trim(); }).filter(Boolean);
    }

    function fillList(ul, items) {
      ul.innerHTML = '';
      if (!items.length) {
        var li = document.createElement('li');
        li.textContent = '—';
        ul.appendChild(li);
        return;
      }
      items.forEach(function (text) {
        var li = document.createElement('li');
        li.textContent = text;
        ul.appendChild(li);
      });
    }

    function openModal(el) {
      lastFocused = el;
      modalTitle.textContent = el.getAttribute('data-title') || 'مولفه';
      modalSub.textContent = el.getAttribute('data-sub') || '';
      modalTask.textContent = el.getAttribute('data-task') || '';
      fillList(modalInput, splitItems(el.getAttribute('data-input')));
      fillList(modalOutput, splitItems(el.getAttribute('data-output')));
      fillList(modalConn, splitItems(el.getAttribute('data-conn')));
      modalReq.textContent = el.getAttribute('data-req') || '—';

      overlay.classList.add('open');
      overlay.setAttribute('aria-hidden', 'false');
      closeBtn.focus();
    }

    function closeModal() {
      overlay.classList.remove('open');
      overlay.setAttribute('aria-hidden', 'true');
      if (lastFocused && typeof lastFocused.focus === 'function') {
        lastFocused.focus();
      }
    }

    // Bind all BPMN elements
    var elements = document.querySelectorAll('.bpmn-el');
    elements.forEach(function (el) {
      el.addEventListener('click', function () { openModal(el); });
      el.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          openModal(el);
        }
      });
    });

    // Close handlers
    closeBtn.addEventListener('click', closeModal);
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay) closeModal();
    });
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && overlay.classList.contains('open')) {
        closeModal();
      }
    });
  })();
</script>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_0e4bdfcb-39a4-4b1f-94fa-d8159119150e.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی | مستند فنی</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--info: #3182ce;
--purple: #805ad5;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 1050px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 250px; height: 250px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge {
display: flex;
align-items: center;
gap: 12px;
}
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.doc-meta {
text-align: left;
font-size: 12px;
opacity: 0.9;
}
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
font-weight: 400;
opacity: 0.9;
}
.document-body {
padding: 40px;
}
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section {
margin-bottom: 45px;
page-break-inside: avoid;
}
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 {
font-size: 19px;
font-weight: 700;
color: var(--primary);
margin-bottom: 2px;
}
.section-title .subtitle {
font-size: 12px;
color: var(--text-muted);
}
.section-content { padding-right: 10px; }
.section-content p {
margin-bottom: 12px;
text-align: justify;
text-indent: 20px;
}
.section-content h4 {
color: var(--primary);
font-size: 16px;
margin: 20px 0 12px;
padding-right: 10px;
border-right: 3px solid var(--accent);
}
.section-content ul, .section-content ol {
padding-right: 25px;
margin: 12px 0;
}
.section-content li {
margin-bottom: 8px;
text-align: justify;
}
.section-content li strong { color: var(--primary); }
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box strong { color: var(--accent-dark); }
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--info);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.danger-box {
background: linear-gradient(to left, #fff5f5, #fee);
border: 1px solid #feb2b2;
border-right: 4px solid var(--danger);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.purple-box {
background: linear-gradient(to left, #faf5ff, #f3e8ff);
border: 1px solid #d6bcfa;
border-right: 4px solid var(--purple);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
font-size: 13px;
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th {
padding: 14px 16px;
text-align: right;
font-weight: 600;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
}
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row {
background: #fffaf0 !important;
font-weight: 600;
}
.component-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 18px;
margin: 25px 0;
}
.component-card {
background: #f8fafc;
border: 2px solid var(--border);
border-radius: 10px;
padding: 18px;
transition: all 0.3s;
}
.component-card:hover {
border-color: var(--accent);
box-shadow: 0 4px 12px rgba(201,169,97,0.15);
transform: translateY(-2px);
}
.component-card .card-icon {
width: 40px; height: 40px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 800;
font-size: 18px;
margin-bottom: 12px;
}
.component-card h4 {
font-size: 15px;
font-weight: 700;
color: var(--primary);
margin-bottom: 8px;
}
.component-card p {
font-size: 12.5px;
color: var(--text-muted);
text-indent: 0 !important;
margin-bottom: 0 !important;
}
.layer-diagram {
background: linear-gradient(135deg, #f7fafc, #edf2f7);
border: 2px solid var(--border);
border-radius: 12px;
padding: 25px;
margin: 25px 0;
}
.layer-row {
background: white;
border: 2px solid var(--primary-light);
border-radius: 8px;
padding: 15px 20px;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 15px;
}
.layer-row:last-child { margin-bottom: 0; }
.layer-row .layer-label {
background: var(--primary);
color: white;
padding: 6px 14px;
border-radius: 6px;
font-weight: 700;
font-size: 13px;
min-width: 160px;
text-align: center;
}
.layer-row .layer-content {
flex: 1;
font-size: 13px;
color: var(--text-muted);
}
.layer-row.api { border-color: var(--accent); }
.layer-row.api .layer-label { background: var(--accent); color: var(--primary); }
.layer-row.service { border-color: var(--info); }
.layer-row.service .layer-label { background: var(--info); }
.layer-row.infra { border-color: var(--purple); }
.layer-row.infra .layer-label { background: var(--purple); }
.layer-row.base { border-color: var(--success); }
.layer-row.base .layer-label { background: var(--success); }
.code-block {
background: #1a202c;
color: #e2e8f0;
border-radius: 8px;
padding: 18px 22px;
margin: 15px 0;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.7;
overflow-x: auto;
direction: ltr;
text-align: left;
border-right: 4px solid var(--accent);
}
.code-block .comment { color: #68d391; }
.code-block .keyword { color: #f6ad55; }
.code-block .string { color: #90cdf4; }
.code-block .type { color: #d6bcfa; }
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 15px;
margin: 25px 0;
}
.stat-card {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 20px 15px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 12px rgba(26,54,93,0.2);
}
.stat-card .stat-value {
font-size: 28px;
font-weight: 800;
margin-bottom: 5px;
color: var(--accent);
line-height: 1.2;
}
.stat-card .stat-label {
font-size: 11.5px;
opacity: 0.9;
}
.flow-diagram {
background: linear-gradient(135deg, #f7fafc, #edf2f7);
border: 2px solid var(--border);
border-radius: 12px;
padding: 25px;
margin: 25px 0;
}
.flow-step {
background: white;
border: 2px solid var(--primary-light);
border-radius: 8px;
padding: 15px 20px;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 15px;
position: relative;
}
.flow-step::after {
content: '↓';
position: absolute;
bottom: -20px;
left: 50%;
transform: translateX(-50%);
font-size: 20px;
color: var(--accent);
font-weight: 800;
}
.flow-step:last-child::after { display: none; }
.flow-step .step-num {
width: 35px; height: 35px;
background: var(--primary);
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 15px;
flex-shrink: 0;
}
.flow-step .step-content {
flex: 1;
font-size: 13.5px;
}
.flow-step .step-content strong {
color: var(--primary);
display: block;
margin-bottom: 3px;
}
.toc {
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 10px;
padding: 25px;
margin: 25px 0;
}
.toc h4 {
color: var(--primary);
margin-bottom: 15px;
font-size: 16px;
border-bottom: 2px solid var(--accent);
padding-bottom: 8px;
}
.toc ol { padding-right: 25px; }
.toc ol li {
margin-bottom: 6px;
font-size: 13.5px;
}
.toc ol li a {
color: var(--primary-light);
text-decoration: none;
border-bottom: 1px dotted var(--primary-light);
}
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 {
font-size: 22px;
font-weight: 800;
margin-bottom: 15px;
color: var(--accent);
}
.conclusion-box p {
font-size: 14px;
line-height: 1.8;
text-indent: 0 !important;
margin-bottom: 15px;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand {
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
font-size: 14px;
}
.footer-divider {
width: 60px;
height: 2px;
background: var(--accent);
margin: 10px auto;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
@media print {
body { background: white; padding: 0; }
.document-container { box-shadow: none; border-radius: 0; }
.section { page-break-inside: avoid; }
}
@media (max-width: 768px) {
.document-body { padding: 25px 20px; }
.document-header { padding: 30px 20px; }
.component-grid { grid-template-columns: 1fr; }
.stats-grid { grid-template-columns: 1fr 1fr; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo"></div>
</div>
<div class="doc-meta">
<div>شماره مستند: ARCH-APIKEY-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: ۱۲ مهر ۱۴۰۵</div>
<div>تهیه‌کننده: هادی خزاعی اصل</div>
<div>طبقه‌بندی: محرمانه</div>
</div>
</div>
<div class="document-title">
<span class="label">API KEY MANAGEMENT SYSTEM</span>
<h1>طراحی قابلیت مدیریت ApiKey و برنامه‌های کاربردی</h1>
<h2>بررسی نیازمندی‌ها، معماری و پیاده‌سازی گام به گام</h2>
</div>
</header>

<div class="document-body">

<div class="intro-text">
<strong>توسعه‌دهنده گرامی،</strong><br>
این مستند به‌عنوان یک طرح جامع فنی، قابلیت ایجاد برنامه‌های کاربردی دارای ApiKey را با پیروی از الگوهای OAuth2 در پلتفرم xDashboard بررسی می‌کند. در این سند، علاوه بر نیازمندی‌های اعلام‌شده، نیازمندی‌های تکمیلی و پیشنهادات بهبودی نیز ارائه شده است تا یک راهکار کامل، امن و مقیاس‌پذیر طراحی گردد.
</div>

<!-- فهرست مطالب -->
<div class="toc">
<h4>📑 فهرست مطالب</h4>
<ol>
<li><a href="#s1">خلاصه اجرایی و آمار کلیدی</a></li>
<li><a href="#s2">بررسی نیازمندی‌های اعلام‌شده</a></li>
<li><a href="#s3">نیازمندی‌های تکمیلی و پیشنهادات بهبود</a></li>
<li><a href="#s4">طراحی معماری و مدل داده</a></li>
<li><a href="#s5">مرحله ۱: پیاده‌سازی در xIds</a></li>
<li><a href="#s6">مرحله ۲: سرویس اعتبارسنجی ApiKey</a></li>
<li><a href="#s7">مرحله ۳: سرویس احراز هویت مبتنی بر ApiKey</a></li>
<li><a href="#s8">مرحله ۴: API Endpoints</a></li>
<li><a href="#s9">جریان عملیات و سناریوها</a></li>
<li><a href="#s10">الگوهای امنیتی و ملاحظات</a></li>
<li><a href="#s11">جمع‌بندی و گام‌های بعدی</a></li>
</ol>
</div>

<!-- بخش 1 -->
<div class="section" id="s1">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی و آمار کلیدی</h3>
<div class="subtitle">Executive Summary & Key Statistics</div>
</div>
</div>
<div class="section-content">
<p>سیستم مدیریت ApiKey، یک لایه امنیتی جدید به پلتفرم xDashboard اضافه می‌کند که امکان ایجاد برنامه‌های کاربردی (Applications) با کلیدهای دسترسی موقت را فراهم می‌سازد. این سیستم بر پایه الگوهای OAuth2 Client Credentials طراحی شده و با زیرساخت IdentityServer4 موجود در xIds یکپارچه می‌گردد.</p>

<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">۳</div>
<div class="stat-label">لایه اصلی پیاده‌سازی</div>
</div>
<div class="stat-card">
<div class="stat-value">۵</div>
<div class="stat-label">Entity جدید</div>
</div>
<div class="stat-card">
<div class="stat-value">۱۲+</div>
<div class="stat-label">نیازمندی تکمیلی</div>
</div>
<div class="stat-card">
<div class="stat-value">۴</div>
<div class="stat-label">مرحله پیاده‌سازی</div>
</div>
</div>

<div class="highlight-box">
<strong>نکته کلیدی:</strong> این راهکار با حفظ سازگاری کامل با الگوهای موجود پروژه (مانند <code>XValidationProvider</code>، <code>XException</code>، <code>XPolicies</code> و <code>IXIdentityManager</code>)، قابلیت ادغام بدون اصطکاک با اکوسیستم فعلی را دارد.
</div>
</div>
</div>

<!-- بخش 2 -->
<div class="section" id="s2">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>بررسی نیازمندی‌های اعلام‌شده</h3>
<div class="subtitle">Analysis of Stated Requirements</div>
</div>
</div>
<div class="section-content">
<p>بر اساس درخواست اعلام‌شده، سه نیازمندی اصلی شناسایی شده‌اند:</p>

<table class="styled-table">
<thead>
<tr>
<th>#</th>
<th>نیازمندی</th>
<th>محل پیاده‌سازی</th>
<th>الگوی مرجع</th>
</tr>
</thead>
<tbody>
<tr>
<td>۱</td>
<td>ایجاد برنامه کاربردی و تولید ApiKey با مدت انقضای قابل تنظیم</td>
<td>xIds</td>
<td>OAuth2 Client Credentials</td>
</tr>
<tr>
<td>۲</td>
<td>اعتبارسنجی ApiKey در سرویس‌های مرتبط</td>
<td>xIdentityService</td>
<td>Token Introspection</td>
</tr>
<tr>
<td>۳</td>
<td>تعریف دسترسی بر اساس ApiKey در احراز هویت</td>
<td>xIds + xApi</td>
<td>Policy-based Authorization</td>
</tr>
</tbody>
</table>

<div class="info-box">
<strong>💡 تحلیل اولیه:</strong> این نیازمندی‌ها در واقع پیاده‌سازی یک <strong>OAuth2 Client</strong> کامل هستند که در آن هر "برنامه کاربردی" معادل یک <code>Client</code> در IdentityServer4 بوده و ApiKey معادل <code>ClientSecret</code> است. با این حال، برای مدیریت بهتر چرخه حیات، نیاز به یک لایه انتزاعی بالاتر داریم.
</div>
</div>
</div>

<!-- بخش 3 -->
<div class="section" id="s3">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>نیازمندی‌های تکمیلی و پیشنهادات بهبود</h3>
<div class="subtitle">Additional Requirements & Improvement Suggestions</div>
</div>
</div>
<div class="section-content">
<p>در بررسی دقیق‌تر، نیازمندی‌های زیر شناسایی شدند که در درخواست اولیه ذکر نشده‌اند اما برای یک پیاده‌سازی کامل و امن ضروری هستند:</p>

<h4>🔐 الف) نیازمندی‌های امنیتی</h4>
<div class="component-grid">
<div class="component-card">
<div class="card-icon">🔑</div>
<h4>۱. چرخش کلید (Key Rotation)</h4>
<p>امکان تولید کلید جدید بدون اختلال در سرویس‌های در حال اجرا، با پشتیبانی از همزیستی موقت کلید قدیم و جدید.</p>
</div>
<div class="component-card">
<div class="card-icon">🚫</div>
<h4>۲. ابطال فوری (Revocation)</h4>
<p>امکان Revoke کردن ApiKey قبل از انقضای طبیعی، برای موارد اضطراری مانند نشت کلید.</p>
</div>
<div class="component-card">
<div class="card-icon">🌐</div>
<h4>۳. IP Whitelist</h4>
<p>محدودسازی استفاده از ApiKey به IPهای مشخص برای کاهش ریسک سوءاستفاده در صورت نشت.</p>
</div>
<div class="component-card">
<div class="card-icon">🔒</div>
<h4>۴. Rate Limiting</h4>
<p>محدودیت تعداد درخواست در واحد زمان برای هر ApiKey جهت جلوگیری از سوءاستفاده و حملات DoS.</p>
</div>
</div>

<h4>📊 ب) نیازمندی‌های مدیریتی</h4>
<div class="component-grid">
<div class="component-card">
<div class="card-icon">📝</div>
<h4>۵. Metadata و توضیحات</h4>
<p>ذخیره نام برنامه، توضیحات، نام مالک و اطلاعات تماس برای هر ApiKey.</p>
</div>
<div class="component-card">
<div class="card-icon">👤</div>
<h4>۶. Owner Assignment</h4>
<p>تخصیص هر ApiKey به یک کاربر یا سازمان مشخص برای مدیریت متمرکز و حسابرسی.</p>
</div>
<div class="component-card">
<div class="card-icon">📈</div>
<h4>۷. Audit Log</h4>
<p>ثبت کامل لاگ استفاده از هر ApiKey شامل زمان، IP، Endpoint و نتیجه درخواست.</p>
</div>
<div class="component-card">
<div class="card-icon">🏷️</div>
<h4>۸. Scope Management</h4>
<p>تعریف دقیق Scopeهای مجاز برای هر ApiKey (مانند read, write, admin) مشابه OAuth2.</p>
</div>
</div>

<h4>⚙️ ج) نیازمندی‌های عملیاتی</h4>
<div class="component-grid">
<div class="component-card">
<div class="card-icon">🔔</div>
<h4>۹. Notification System</h4>
<p>اطلاع‌رسانی به مالک قبل از انقضای ApiKey (مثلاً ۷ روز قبل) از طریق Email/SMS.</p>
</div>
<div class="component-card">
<div class="card-icon">🔄</div>
<h4>۱۰. Auto-Extension</h4>
<p>امکان تمدید خودکار ApiKey در صورت فعال بودن برنامه (اختیاری).</p>
</div>
<div class="component-card">
<div class="card-icon">📦</div>
<h4>۱۱. Bulk Operations</h4>
<p>امکان ایجاد، ابطال یا تمدید دسته‌ای ApiKeyها برای مدیریت در مقیاس بزرگ.</p>
</div>
<div class="component-card">
<div class="card-icon">🗂️</div>
<h4>۱۲. Tagging & Categorization</h4>
<p>دسته‌بندی ApiKeyها بر اساس نوع برنامه (Mobile, Web, IoT, Third-party) برای گزارش‌گیری.</p>
</div>
</div>

<div class="warning-box">
<strong>⚠️ پیشنهاد مهم:</strong> پیاده‌سازی حداقل موارد <strong>۱ تا ۴</strong> (چرخش کلید، ابطال فوری، IP Whitelist، Rate Limiting) برای یک سیستم تولیدی (Production) <strong>الزامی</strong> است. سایر موارد بر اساس اولویت کسب‌وکار در فازهای بعدی قابل اضافه شدن هستند.
</div>
</div>
</div>

<!-- بخش 4 -->
<div class="section" id="s4">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>طراحی معماری و مدل داده</h3>
<div class="subtitle">Architecture Design & Data Model</div>
</div>
</div>
<div class="section-content">

<h4>🏗️ معماری کلی سیستم</h4>
<div class="layer-diagram">
<div class="layer-row api">
<div class="layer-label">لایه API</div>
<div class="layer-content"><strong>ApplicationController</strong> — مدیریت برنامه‌ها و ApiKeyها (CRUD)</div>
</div>
<div class="layer-row service">
<div class="layer-label">لایه سرویس</div>
<div class="layer-content"><strong>XApplicationManager</strong> — منطق تجاری، تولید کلید، مدیریت چرخه حیات</div>
</div>
<div class="layer-row infra">
<div class="layer-label">لایه زیرساخت</div>
<div class="layer-content"><strong>XApiKeyValidator</strong> + <strong>XApiKeyAuthProvider</strong> — اعتبارسنجی و احراز هویت</div>
</div>
<div class="layer-row base">
<div class="layer-label">لایه داده</div>
<div class="layer-content"><strong>XApplication</strong> + <strong>XApiKey</strong> + <strong>XApiKeyUsageLog</strong> — Entityهای جدید</div>
</div>
</div>

<h4>📋 مدل‌های داده پیشنهادی</h4>

<div class="code-block">
<span class="comment">// Entity: XApplication (برنامه کاربردی)</span><br>
<span class="keyword">public class</span> <span class="type">XApplication</span> : <span class="type">XBaseGuidIDEntity</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;[Required][StringLength(<span class="string">255</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> Name { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringLength(<span class="string">1000</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> Description { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[Required][StringLength(<span class="string">255</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> OwnerId { <span class="keyword">get</span>; <span class="keyword">set</span>; } <span class="comment">// XUser.Id</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">XApplicationType</span> Type { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public bool</span> IsActive { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="keyword">true</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span> CreatedOn { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span> UpdatedAt { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Navigation</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public virtual</span> <span class="type">ICollection</span>&lt;<span class="type">XApiKey</span>&gt; ApiKeys { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
}
</div>

<div class="code-block">
<span class="comment">// Entity: XApiKey (کلید دسترسی)</span><br>
<span class="keyword">public class</span> <span class="type">XApiKey</span> : <span class="type">XBaseGuidIDEntity</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;[Required]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">Guid</span> ApplicationId { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[Required][StringLength(<span class="string">512</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> KeyHash { <span class="keyword">get</span>; <span class="keyword">set</span>; } <span class="comment">// SHA256 of ApiKey</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringLength(<span class="string">100</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> KeyPrefix { <span class="keyword">get</span>; <span class="keyword">set</span>; } <span class="comment">// "xapp_abc123..."</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[Required]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span> ExpiresAt { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span> CreatedOn { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span>? LastUsedAt { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span>? RevokedAt { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> RevokedBy { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public bool</span> IsRevoked =&gt; RevokedAt.HasValue;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public bool</span> IsExpired =&gt; <span class="type">DateTime</span>.UtcNow &gt;= ExpiresAt;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public bool</span> IsActive =&gt; !IsRevoked &amp;&amp; !IsExpired;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Scope &amp; Restrictions</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringLength(<span class="string">1000</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> AllowedScopes { <span class="keyword">get</span>; <span class="keyword">set</span>; } <span class="comment">// JSON array</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringLength(<span class="string">2000</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> AllowedIPs { <span class="keyword">get</span>; <span class="keyword">set</span>; } <span class="comment">// Comma-separated</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> RateLimitPerMinute { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">60</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Navigation</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public virtual</span> <span class="type">XApplication</span> Application { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
}
</div>

<div class="code-block">
<span class="comment">// Entity: XApiKeyUsageLog (لاگ استفاده)</span><br>
<span class="keyword">public class</span> <span class="type">XApiKeyUsageLog</span> : <span class="type">XBaseLongIDEntity</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">Guid</span> ApiKeyId { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> Endpoint { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> HttpMethod { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public string</span> ClientIP { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> StatusCode { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DateTime</span> RequestedOn { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public long</span> ResponseTimeMs { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
}
</div>

<h4>🔢 Enumهای مورد نیاز</h4>
<div class="code-block">
<span class="keyword">public enum</span> <span class="type">XApplicationType</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;Web, Mobile, Desktop, IoT, ThirdParty, Service<br>
}<br>
<br>
<span class="keyword">public enum</span> <span class="type">XApiKeyScope</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringValue(<span class="string">"read"</span>)] Read,<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringValue(<span class="string">"write"</span>)] Write,<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringValue(<span class="string">"admin"</span>)] Admin,<br>
&nbsp;&nbsp;&nbsp;&nbsp;[StringValue(<span class="string">"manage"</span>)] Manage<br>
}
</div>
</div>
</div>

<!-- بخش 5 -->
<div class="section" id="s5">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>مرحله ۱: پیاده‌سازی در xIds</h3>
<div class="subtitle">Phase 1: Implementation in xIds Module</div>
</div>
</div>
<div class="section-content">

<h4>📌 گام ۱.۱: افزودن تنظیمات قابل پیکربندی</h4>
<p>در کلاس <code>XIdentityConfiguration</code> (موجود در xIdentityModels)، بخش جدید برای تنظیمات ApiKey اضافه می‌شود:</p>

<div class="code-block">
<span class="comment">// File: xIdentityModels/Configurations/XIdentityConfiguration.cs</span><br>
<span class="keyword">public class</span> <span class="type">XIdentityConfiguration</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// ... existing properties ...</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">XApiKeyConfiguration</span> ApiKey { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="keyword">new</span>();<br>
}<br>
<br>
<span class="keyword">public class</span> <span class="type">XApiKeyConfiguration</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Default expiration in minutes (e.g., 43200 = 30 days)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> DefaultExpirationMinutes { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">43200</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Maximum allowed expiration (e.g., 525600 = 1 year)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> MaxExpirationMinutes { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">525600</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Maximum ApiKeys per Application</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> MaxKeysPerApplication { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">10</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Notification before expiration (minutes)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> NotifyBeforeMinutes { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">10080</span>; <span class="comment">// 7 days</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Enable audit logging</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public bool</span> EnableAuditLog { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="keyword">true</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Default rate limit (requests per minute)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public int</span> DefaultRateLimit { <span class="keyword">get</span>; <span class="keyword">set</span>; } = <span class="string">60</span>;<br>
}
</div>

<h4>📌 گام ۱.۲: افزودن DbContext و Migration</h4>
<p>در <code>XIdentityDbContext</code>، DbSetهای جدید اضافه می‌شوند:</p>

<div class="code-block">
<span class="comment">// File: xIds/DbContext/XIdentityDbContext.cs</span><br>
<span class="keyword">public class</span> <span class="type">XIdentityDbContext</span> : <span class="type">IdentityDbContext</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// ... existing DbSets ...</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DbSet</span>&lt;<span class="type">XApplication</span>&gt; Applications { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DbSet</span>&lt;<span class="type">XApiKey</span>&gt; ApiKeys { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public</span> <span class="type">DbSet</span>&lt;<span class="type">XApiKeyUsageLog</span>&gt; ApiKeyUsageLogs { <span class="keyword">get</span>; <span class="keyword">set</span>; }<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">protected override void</span> <span class="type">OnModelCreating</span>(<span class="type">ModelBuilder</span> modelBuilder)<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">base</span>.OnModelCreating(modelBuilder);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Configure XApplication</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;modelBuilder.Entity&lt;<span class="type">XApplication</span>&gt;(e =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.HasIndex(a =&gt; a.Name).IsUnique();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.HasMany(a =&gt; a.ApiKeys)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.WithOne(k =&gt; k.Application)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.HasForeignKey(k =&gt; k.ApplicationId);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Configure XApiKey</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;modelBuilder.Entity&lt;<span class="type">XApiKey</span>&gt;(e =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.HasIndex(k =&gt; k.KeyHash).IsUnique();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e.HasIndex(k =&gt; k.ExpiresAt);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});<br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
}
</div>

<h4>📌 گام ۱.۳: پیاده‌سازی XApplicationManager</h4>
<p>یک کلاس جدید برای مدیریت برنامه‌ها و ApiKeyها مشابه الگوی <code>XIdentityManager</code> موجود:</p>

<div class="code-block">
<span class="comment">// File: xIds/Interfaces/IXApplicationManager.cs</span><br>
<span class="keyword">public interface</span> <span class="type">IXApplicationManager</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Application CRUD</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApplicationDto</span>&gt; CreateApplication(<span class="type">XApplicationDto</span> item, <span class="keyword">string</span> ownerId);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApplicationDto</span>&gt; UpdateApplication(<span class="type">Guid</span> id, <span class="type">XApplicationDto</span> item);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="keyword">bool</span>&gt; DeleteApplication(<span class="type">Guid</span> id);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApplicationDto</span>&gt; GetApplication(<span class="type">Guid</span> id);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">IEnumerable</span>&lt;<span class="type">XApplicationDto</span>&gt;&gt; GetOwnerApplications(<span class="keyword">string</span> ownerId);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// ApiKey Management</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApiKeyCreationResult</span>&gt; CreateApiKey(<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Guid</span> applicationId,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">TimeSpan</span>? expiration = <span class="keyword">null</span>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">IEnumerable</span>&lt;<span class="keyword">string</span>&gt; scopes = <span class="keyword">null</span>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">IEnumerable</span>&lt;<span class="keyword">string</span>&gt; allowedIPs = <span class="keyword">null</span>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">int</span>? rateLimit = <span class="keyword">null</span>);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="keyword">bool</span>&gt; RevokeApiKey(<span class="type">Guid</span> apiKeyId, <span class="keyword">string</span> revokedBy);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApiKeyDto</span>&gt; RotateApiKey(<span class="type">Guid</span> apiKeyId, <span class="type">TimeSpan</span>? newExpiration = <span class="keyword">null</span>);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">IEnumerable</span>&lt;<span class="type">XApiKeyDto</span>&gt;&gt; GetApplicationApiKeys(<span class="type">Guid</span> applicationId);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Validation</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Task</span>&lt;<span class="type">XApiKeyValidationResult</span>&gt; ValidateApiKey(<span class="keyword">string</span> apiKey, <span class="keyword">string</span> clientIP);<br>
}
</div>

<h4>📌 گام ۱.۴: تولید امن ApiKey</h4>
<p>الگوی تولید کلید باید از نظر رمزنگاری امن باشد:</p>

<div class="code-block">
<span class="comment">// File: xIds/Helpers/XApiKeyGenerator.cs</span><br>
<span class="keyword">public static class</span> <span class="type">XApiKeyGenerator</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public static</span> (<span class="keyword">string</span> plainKey, <span class="keyword">string</span> hash, <span class="keyword">string</span> prefix) <span class="type">Generate</span>()<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Generate 32 bytes of cryptographically secure random data</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> randomBytes = <span class="keyword">new byte</span>[<span class="string">32</span>];<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">using</span> (<span class="keyword">var</span> rng = <span class="type">RandomNumberGenerator</span>.Create())<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rng.GetBytes(randomBytes);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Format: xapp_{base64url}</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> plainKey = <span class="string">$"xapp_{Convert.ToBase64String(randomBytes)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="string">.Replace("+", "-").Replace("/", "_").TrimEnd('=')}"</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Hash with SHA256 for storage (never store plain key)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">using</span> (<span class="keyword">var</span> sha256 = <span class="type">SHA256</span>.Create())<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> hashBytes = sha256.ComputeHash(<span class="type">Encoding</span>.UTF8.GetBytes(plainKey));<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> hash = <span class="type">BitConverter</span>.ToString(hashBytes).Replace(<span class="string">"-"</span>, <span class="string">""</span>).ToLower();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Prefix for quick identification (first 12 chars)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> prefix = plainKey.Substring(<span class="string">0</span>, <span class="string">16</span>) + <span class="string">"..."</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> (plainKey, hash, prefix);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public static bool</span> <span class="type">Verify</span>(<span class="keyword">string</span> plainKey, <span class="keyword">string</span> storedHash)<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">using</span> (<span class="keyword">var</span> sha256 = <span class="type">SHA256</span>.Create())<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> hashBytes = sha256.ComputeHash(<span class="type">Encoding</span>.UTF8.GetBytes(plainKey));<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> computedHash = <span class="type">BitConverter</span>.ToString(hashBytes)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Replace(<span class="string">"-"</span>, <span class="string">""</span>).ToLower();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> computedHash == storedHash;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
}
</div>

<div class="success-box">
<strong>✅ ویژگی‌های امنیتی این طراحی:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>کلید ApiKey هرگز به‌صورت Plain Text ذخیره نمی‌شود (فقط Hash)</li>
<li>استفاده از <code>RandomNumberGenerator</code> برای تولید امن</li>
<li>پیشوند <code>xapp_</code> برای شناسایی سریع نوع کلید</li>
<li>Prefix کوتاه برای نمایش در UI بدون افشای کلید کامل</li>
</ul>
</div>
</div>
</div>

<!-- بخش 6 -->
<div class="section" id="s6">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>مرحله ۲: سرویس اعتبارسنجی ApiKey</h3>
<div class="subtitle">Phase 2: ApiKey Validation Service</div>
</div>
</div>
<div class="section-content">

<h4>📌 گام ۲.۱: طراحی XApiKeyValidator</h4>
<p>این سرویس مسئولیت اعتبارسنجی کامل ApiKey را بر عهده دارد:</p>

<div class="code-block">
<span class="comment">// File: xIds/Validators/XApiKeyValidator.cs</span><br>
<span class="keyword">public class</span> <span class="type">XApiKeyValidator</span> : <span class="type">IXApiKeyValidator</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">private readonly</span> <span class="type">XIdentityDbContext</span> _dbContext;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">private readonly</span> <span class="type">IXIdentityConfiguration</span> _config;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">private readonly</span> <span class="type">IMemoryCache</span> _cache; <span class="comment">// For rate limiting</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">XApiKeyValidationResult</span>&gt; <span class="type">ValidateAsync</span>(<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">string</span> apiKey, <span class="keyword">string</span> clientIP, <span class="keyword">string</span> requiredScope = <span class="keyword">null</span>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> result = <span class="keyword">new</span> <span class="type">XApiKeyValidationResult</span>();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 1: Compute hash of provided key</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> hash = <span class="type">XApiKeyGenerator</span>.ComputeHash(apiKey);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 2: Lookup in database</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> keyEntity = <span class="keyword">await</span> _dbContext.ApiKeys<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Include(k =&gt; k.Application)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.FirstOrDefaultAsync(k =&gt; k.KeyHash == hash);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (keyEntity == <span class="keyword">null</span>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.InvalidApiKey;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 3: Check expiration</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (keyEntity.IsExpired)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.ApiKeyExpired;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 4: Check revocation</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (keyEntity.IsRevoked)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.ApiKeyRevoked;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 5: Check application active</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!keyEntity.Application.IsActive)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.ApplicationDisabled;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 6: Check IP whitelist</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(keyEntity.AllowedIPs))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> allowedIPs = keyEntity.AllowedIPs.Split(<span class="string">','</span>);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!allowedIPs.Contains(clientIP))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.IPNotAllowed;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 7: Check rate limit</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!<span class="type">CheckRateLimit</span>(keyEntity.Id, keyEntity.RateLimitPerMinute))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.RateLimitExceeded;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 8: Check scope (if required)</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(requiredScope))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> scopes = <span class="type">JsonConvert</span>.DeserializeObject&lt;<span class="type">List</span>&lt;<span class="keyword">string</span>&gt;&gt;(keyEntity.AllowedScopes);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!scopes.Contains(requiredScope))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Error = <span class="type">XException</span>.InsufficientScope;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 9: Update LastUsedAt</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;keyEntity.LastUsedAt = <span class="type">DateTime</span>.UtcNow;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">await</span> _dbContext.SaveChangesAsync();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Step 10: Build success result</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.IsValid = <span class="keyword">true</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.ApplicationId = keyEntity.ApplicationId;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.OwnerId = keyEntity.Application.OwnerId;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.Scopes = <span class="type">JsonConvert</span>.DeserializeObject&lt;<span class="type">List</span>&lt;<span class="keyword">string</span>&gt;&gt;(keyEntity.AllowedScopes);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> result;<br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
}
</div>

<h4>📌 گام ۲.۲: پیاده‌سازی Rate Limiter</h4>
<div class="code-block">
<span class="keyword">private bool</span> <span class="type">CheckRateLimit</span>(<span class="type">Guid</span> apiKeyId, <span class="keyword">int</span> limitPerMinute)<br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> cacheKey = <span class="string">$"ratelimit:{apiKeyId}"</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> currentCount = _cache.GetOrCreate(cacheKey, entry =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;entry.SlidingExpiration = <span class="type">TimeSpan</span>.FromMinutes(<span class="string">1</span>);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> <span class="string">0</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;});<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (currentCount &gt;= limitPerMinute)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return false</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;_cache.Set(cacheKey, currentCount + <span class="string">1</span>, <span class="type">TimeSpan</span>.FromMinutes(<span class="string">1</span>));<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return true</span>;<br>
}
</div>
</div>
</div>

<!-- بخش 7 -->
<div class="section" id="s7">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>مرحله ۳: سرویس احراز هویت مبتنی بر ApiKey</h3>
<div class="subtitle">Phase 3: ApiKey Authentication Service</div>
</div>
</div>
<div class="section-content">

<h4>📌 گام ۳.۱: ایجاد Authentication Handler</h4>
<p>برای یکپارچگی با ASP.NET Core Authentication، یک Handler جدید ایجاد می‌کنیم:</p>

<div class="code-block">
<span class="comment">// File: xIdentityService/Authentication/XApiKeyAuthenticationHandler.cs</span><br>
<span class="keyword">public class</span> <span class="type">XApiKeyAuthenticationHandler</span> : <span class="type">AuthenticationHandler</span>&lt;<span class="type">XApiKeyAuthenticationOptions</span>&gt;<br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public const string</span> AuthenticationScheme = <span class="string">"XApiKey"</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public const string</span> HeaderName = <span class="string">"X-Api-Key"</span>;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">private readonly</span> <span class="type">IXApiKeyValidator</span> _validator;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">protected override async</span> <span class="type">Task</span>&lt;<span class="type">AuthenticateResult</span>&gt; <span class="type">HandleAuthenticateAsync</span>()<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Extract ApiKey from header</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!Request.Headers.ContainsKey(HeaderName))<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> <span class="type">AuthenticateResult</span>.NoResult();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> apiKey = Request.Headers[HeaderName].ToString();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Validate ApiKey</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> validationResult = <span class="keyword">await</span> _validator.ValidateAsync(apiKey, clientIP);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">if</span> (!validationResult.IsValid)<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> <span class="type">AuthenticateResult</span>.Fail(validationResult.Error.Message);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Build ClaimsPrincipal</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> claims = <span class="keyword">new</span>[]<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">new</span> <span class="type">Claim</span>(<span class="type">ClaimTypes</span>.Name, validationResult.OwnerId),<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"application_id"</span>, validationResult.ApplicationId.ToString()),<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"auth_type"</span>, <span class="string">"apikey"</span>),<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">new</span> <span class="type">Claim</span>(<span class="type">JwtClaimTypes</span>.Scope, <span class="string">"apikey"</span>),<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;};<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Add scope claims</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> scopeClaims = validationResult.Scopes<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(s =&gt; <span class="keyword">new</span> <span class="type">Claim</span>(<span class="type">JwtClaimTypes</span>.Scope, s));<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> identity = <span class="keyword">new</span> <span class="type">ClaimsIdentity</span>(claims.Union(scopeClaims), AuthenticationScheme);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> principal = <span class="keyword">new</span> <span class="type">ClaimsPrincipal</span>(identity);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> ticket = <span class="keyword">new</span> <span class="type">AuthenticationTicket</span>(principal, AuthenticationScheme);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">return</span> <span class="type">AuthenticateResult</span>.Success(ticket);<br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
}
</div>

<h4>📌 گام ۳.۲: ثبت در Startup</h4>
<div class="code-block">
<span class="comment">// File: xApi/Startup.cs - ConfigureServices</span><br>
services.AddAuthentication(options =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;options.DefaultScheme = <span class="type">JwtBearerDefaults</span>.AuthenticationScheme;<br>
})<br>
.AddJwtBearer(<span class="comment">/* existing config */</span>)<br>
.AddScheme&lt;<span class="type">XApiKeyAuthenticationOptions</span>, <span class="type">XApiKeyAuthenticationHandler</span>&gt;(<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">XApiKeyAuthenticationHandler</span>.AuthenticationScheme,<br>
&nbsp;&nbsp;&nbsp;&nbsp;options =&gt; { });<br>
<br>
<span class="comment">// Authorization policies for ApiKey</span><br>
services.AddAuthorization(options =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;options.AddPolicy(<span class="string">"ApiKeyAccess"</span>, policy =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;policy.AddAuthenticationSchemes(<span class="type">XApiKeyAuthenticationHandler</span>.AuthenticationScheme);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;policy.RequireAuthenticatedUser();<br>
&nbsp;&nbsp;&nbsp;&nbsp;});<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Scope-based policies</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;options.AddPolicy(<span class="string">"ApiKeyRead"</span>, policy =&gt; {<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;policy.AddAuthenticationSchemes(<span class="type">XApiKeyAuthenticationHandler</span>.AuthenticationScheme);<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;policy.RequireClaim(<span class="type">JwtClaimTypes</span>.Scope, <span class="string">"read"</span>, <span class="string">"write"</span>, <span class="string">"admin"</span>);<br>
&nbsp;&nbsp;&nbsp;&nbsp;});<br>
});
</div>

<h4>📌 گام ۳.۳: استفاده در Controllerها</h4>
<div class="code-block">
<span class="comment">// Example: Supporting both JWT and ApiKey authentication</span><br>
[Authorize(Policy = <span class="string">"ApiKeyRead"</span>)]<br>
<span class="keyword">public class</span> <span class="type">DataController</span> : <span class="type">ControllerBase</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpGet(<span class="string">"items"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&gt; GetItems()<br>
&nbsp;&nbsp;&nbsp;&nbsp;{<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Works with both JWT Bearer and X-Api-Key header</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">var</span> userId = User.Identity.Name;<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// ...</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;}<br>
}
</div>
</div>
</div>

<!-- بخش 8 -->
<div class="section" id="s8">
<div class="section-header">
<div class="section-number">۸</div>
<div class="section-title">
<h3>مرحله ۴: API Endpoints</h3>
<div class="subtitle">Phase 4: API Endpoints Design</div>
</div>
</div>
<div class="section-content">

<h4>📌 طراحی Controller</h4>
<div class="code-block">
<span class="comment">// File: xIds/Controllers/ApplicationController.cs</span><br>
[ApiController]<br>
[Route(<span class="string">"api/v1/applications"</span>)]<br>
[Authorize(Policy = XPolicies.EnabledUser)]<br>
<span class="keyword">public class</span> <span class="type">ApplicationController</span> : <span class="type">XIBaseController</span><br>
{<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// Application CRUD</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpPost]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XApplicationDto</span>&gt;&gt; Create(<span class="type">XApplicationDto</span> model);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpGet]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">IEnumerable</span>&lt;<span class="type">XApplicationDto</span>&gt;&gt;&gt; GetMyApplications();<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpPut(<span class="string">"{id}"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&gt; Update(<span class="type">Guid</span> id, <span class="type">XApplicationDto</span> model);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpDelete(<span class="string">"{id}"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&gt; Delete(<span class="type">Guid</span> id);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">// ApiKey Management</span><br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpPost(<span class="string">"{appId}/apikeys"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XApiKeyCreationResponse</span>&gt;&gt; CreateApiKey(<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="type">Guid</span> appId, <span class="type">XCreateApiKeyRequest</span> request);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpGet(<span class="string">"{appId}/apikeys"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">IEnumerable</span>&lt;<span class="type">XApiKeyDto</span>&gt;&gt;&gt; GetApiKeys(<span class="type">Guid</span> appId);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpPost(<span class="string">"apikeys/{id}/revoke"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&gt; RevokeApiKey(<span class="type">Guid</span> id);<br>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
&nbsp;&nbsp;&nbsp;&nbsp;[HttpPost(<span class="string">"apikeys/{id}/rotate"</span>)]<br>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XApiKeyCreationResponse</span>&gt;&gt; RotateApiKey(<span class="type">Guid</span> id);<br>
}
</div>

<h4>📋 DTOهای مورد نیاز</h4>
<table class="styled-table">
<thead>
<tr>
<th>DTO</th>
<th>کاربرد</th>
<th>فیلدهای کلیدی</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>XApplicationDto</code></td>
<td>نمایش برنامه</td>
<td>Id, Name, Description, Type, IsActive, CreatedOn</td>
</tr>
<tr>
<td><code>XCreateApplicationRequest</code></td>
<td>درخواست ساخت برنامه</td>
<td>Name, Description, Type</td>
</tr>
<tr>
<td><code>XApiKeyDto</code></td>
<td>نمایش ApiKey (بدون کلید کامل)</td>
<td>Id, KeyPrefix, ExpiresAt, LastUsedAt, Scopes, IsActive</td>
</tr>
<tr>
<td><code>XCreateApiKeyRequest</code></td>
<td>درخواست ساخت ApiKey</td>
<td>ExpirationMinutes, Scopes, AllowedIPs, RateLimit</td>
</tr>
<tr>
<td><code>XApiKeyCreationResponse</code></td>
<td>پاسخ ساخت (فقط یکبار کلید کامل)</td>
<td>ApiKey (plain), ExpiresAt, KeyPrefix</td>
</tr>
</tbody>
</table>

<div class="danger-box">
<strong>🔴 نکته امنیتی بسیار مهم:</strong> کلید ApiKey به‌صورت Plain Text <strong>فقط یکبار</strong> در پاسخ <code>XApiKeyCreationResponse</code> به کاربر نمایش داده می‌شود. پس از آن، فقط <code>KeyPrefix</code> قابل مشاهده است و کاربر در صورت فراموشی کلید، باید آن را Rotate کند.
</div>
</div>
</div>

<!-- بخش 9 -->
<div class="section" id="s9">
<div class="section-header">
<div class="section-number">۹</div>
<div class="section-title">
<h3>جریان عملیات و سناریوها</h3>
<div class="subtitle">Operational Flows & Scenarios</div>
</div>
</div>
<div class="section-content">

<h4>🔄 سناریوی ۱: ایجاد برنامه و دریافت ApiKey</h4>
<div class="flow-diagram">
<div class="flow-step">
<div class="step-num">۱</div>
<div class="step-content">
<strong>کاربر درخواست ایجاد برنامه را ارسال می‌کند</strong>
POST /api/v1/applications با payload شامل نام، توضیحات و نوع برنامه
</div>
</div>
<div class="flow-step">
<div class="step-num">۲</div>
<div class="step-content">
<strong>سیستم برنامه را ایجاد می‌کند</strong>
ذخیره XApplication با OwnerId = کاربر فعلی
</div>
</div>
<div class="flow-step">
<div class="step-num">۳</div>
<div class="step-content">
<strong>کاربر درخواست ApiKey می‌کند</strong>
POST /api/v1/applications/{appId}/apikeys با تنظیمات انقضا و scope
</div>
</div>
<div class="flow-step">
<div class="step-num">۴</div>
<div class="step-content">
<strong>سیستم ApiKey تولید و برمی‌گرداند</strong>
کلید Plain Text فقط یکبار نمایش داده می‌شود، Hash در DB ذخیره می‌شود
</div>
</div>
</div>

<h4>🔄 سناریوی ۲: استفاده از ApiKey در درخواست API</h4>
<div class="flow-diagram">
<div class="flow-step">
<div class="step-num">۱</div>
<div class="step-content">
<strong>کلاینت درخواست API را ارسال می‌کند</strong>
Header: <code>X-Api-Key: xapp_abc123...</code>
</div>
</div>
<div class="flow-step">
<div class="step-num">۲</div>
<div class="step-content">
<strong>Authentication Handler کلید را استخراج می‌کند</strong>
XApiKeyAuthenticationHandler فعال می‌شود
</div>
</div>
<div class="flow-step">
<div class="step-num">۳</div>
<div class="step-content">
<strong>اعتبارسنجی کامل انجام می‌شود</strong>
بررسی انقضا، ابطال، IP whitelist، rate limit، scope
</div>
</div>
<div class="flow-step">
<div class="step-num">۴</div>
<div class="step-content">
<strong>ClaimsPrincipal ساخته می‌شود</strong>
با OwnerId، ApplicationId و Scopes
</div>
</div>
<div class="flow-step">
<div class="step-num">۵</div>
<div class="step-content">
<strong>درخواست به Controller هدایت می‌شود</strong>
Authorization policy بررسی و پاسخ ارسال می‌گردد
</div>
</div>
</div>

<h4>🔄 سناریوی ۳: چرخش کلید (Key Rotation)</h4>
<div class="flow-diagram">
<div class="flow-step">
<div class="step-num">۱</div>
<div class="step-content">
<strong>کاربر درخواست چرخش کلید را می‌دهد</strong>
POST /api/v1/applications/apikeys/{id}/rotate
</div>
</div>
<div class="flow-step">
<div class="step-num">۲</div>
<div class="step-content">
<strong>کلید جدید تولید می‌شود</strong>
کلید قدیمی برای مدت grace period (مثلاً ۱ ساعت) فعال می‌ماند
</div>
</div>
<div class="flow-step">
<div class="step-num">۳</div>
<div class="step-content">
<strong>کلید جدید به کاربر داده می‌شود</strong>
کاربر کلید جدید را در برنامه خود جایگزین می‌کند
</div>
</div>
<div class="flow-step">
<div class="step-num">۴</div>
<div class="step-content">
<strong>پس از grace period، کلید قدیمی منقضی می‌شود</strong>
Background job کلیدهای قدیمی را غیرفعال می‌کند
</div>
</div>
</div>
</div>
</div>

<!-- بخش 10 -->
<div class="section" id="s10">
<div class="section-header">
<div class="section-number">۱۰</div>
<div class="section-title">
<h3>الگوهای امنیتی و ملاحظات</h3>
<div class="subtitle">Security Patterns & Considerations</div>
</div>
</div>
<div class="section-content">

<table class="styled-table">
<thead>
<tr>
<th>الگوی امنیتی</th>
<th>پیاده‌سازی</th>
<th>اهمیت</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Hashing کلید</strong></td>
<td>SHA256 - کلید Plain Text هرگز ذخیره نمی‌شود</td>
<td style="color: var(--danger); font-weight: 700;">حیاتی</td>
</tr>
<tr>
<td><strong>HTTPS Only</strong></td>
<td>ApiKey فقط از طریق HTTPS قابل ارسال است</td>
<td style="color: var(--danger); font-weight: 700;">حیاتی</td>
</tr>
<tr>
<td><strong>Rate Limiting</strong></td>
<td>بر اساس ApiKey و IP با MemoryCache</td>
<td style="color: var(--warning); font-weight: 700;">بالا</td>
</tr>
<tr>
<td><strong>IP Whitelist</strong></td>
<td>محدودسازی به IPهای مجاز</td>
<td style="color: var(--warning); font-weight: 700;">بالا</td>
</tr>
<tr>
<td><strong>Scope Management</strong></td>
<td>هر ApiKey scope مشخصی دارد</td>
<td style="color: var(--warning); font-weight: 700;">بالا</td>
</tr>
<tr>
<td><strong>Audit Logging</strong></td>
<td>ثبت تمام استفاده‌ها در XApiKeyUsageLog</td>
<td style="color: var(--info); font-weight: 700;">متوسط</td>
</tr>
<tr>
<td><strong>Expiration</strong></td>
<td>مدت زمان محدود با قابلیت تمدید</td>
<td style="color: var(--warning); font-weight: 700;">بالا</td>
</tr>
<tr>
<td><strong>Revocation</strong></td>
<td>امکان ابطال فوری در صورت نشت</td>
<td style="color: var(--danger); font-weight: 700;">حیاتی</td>
</tr>
<tr>
<td><strong>Key Rotation</strong></td>
<td>چرخش بدون downtime با grace period</td>
<td style="color: var(--info); font-weight: 700;">متوسط</td>
</tr>
<tr>
<td><strong>One-time Display</strong></td>
<td>کلید فقط یکبار به کاربر نمایش داده می‌شود</td>
<td style="color: var(--warning); font-weight: 700;">بالا</td>
</tr>
</tbody>
</table>

<div class="purple-box">
<strong>🎯 یکپارچگی با OAuth2:</strong> این طراحی با الگوی <strong>OAuth2 Client Credentials Grant</strong> همخوانی کامل دارد. در واقع هر Application معادل یک OAuth2 Client و هر ApiKey معادل یک Client Secret است. در آینده می‌توان به‌راحتی این سیستم را به IdentityServer4 متصل کرد و از token endpoint آن برای تبدیل ApiKey به JWT استفاده نمود.
</div>

<h4>🔐 ملاحظات امنیتی تکمیلی</h4>
<ul>
<li><strong>ذخیره‌سازی:</strong> کلید ApiKey هرگز در Log یا Response بعد از ساخت ذخیره نمی‌شود</li>
<li><strong>انتقال:</strong> فقط از طریق Header (<code>X-Api-Key</code>)، نه URL Query</li>
<li><strong>طول کلید:</strong> حداقل ۲۵۶ بیت (۳۲ بایت) entropy</li>
<li><strong>Brute Force Protection:</strong> پس از ۵ تلاش ناموفق، IP برای ۱۵ دقیقه block می‌شود</li>
<li><strong>CORS:</strong> برای Endpoints حساس، CORS باید به‌دقت پیکربندی شود</li>
</ul>
</div>
</div>

<!-- بخش 11 -->
<div class="section" id="s11">
<div class="section-header">
<div class="section-number">۱۱</div>
<div class="section-title">
<h3>جمع‌بندی و گام‌های بعدی</h3>
<div class="subtitle">Summary & Next Steps</div>
</div>
</div>
<div class="section-content">

<h4>✅ خلاصه طراحی</h4>
<p>این مستند یک راهکار کامل برای مدیریت ApiKey در پلتفرم xDashboard ارائه می‌دهد که شامل موارد زیر است:</p>
<ul>
<li>مدل داده کامل با ۳ Entity جدید (XApplication, XApiKey, XApiKeyUsageLog)</li>
<li>پیاده‌سازی امن تولید و ذخیره‌سازی کلید با SHA256</li>
<li>Authentication Handler یکپارچه با ASP.NET Core</li>
<li>سیستم Rate Limiting و IP Whitelist</li>
<li>امکان چرخش کلید بدون downtime</li>
<li>سیستم Audit Log کامل</li>
<li>یکپارچگی با OAuth2 برای توسعه آینده</li>
</ul>

<h4>📋 گام‌های اجرایی پیشنهادی</h4>
<table class="styled-table">
<thead>
<tr>
<th>فاز</th>
<th>فعالیت</th>
<th>زمان تخمینی</th>
</tr>
</thead>
<tbody>
<tr>
<td>۱</td>
<td>طراحی و تصویب مدل داده + Migration</td>
<td>۱ روز</td>
</tr>
<tr>
<td>۲</td>
<td>پیاده‌سازی XApplicationManager + XApiKeyGenerator</td>
<td>۲ روز</td>
</tr>
<tr>
<td>۳</td>
<td>پیاده‌سازی XApiKeyValidator + Rate Limiter</td>
<td>۱ روز</td>
</tr>
<tr>
<td>۴</td>
<td>پیاده‌سازی Authentication Handler</td>
<td>۱ روز</td>
</tr>
<tr>
<td>۵</td>
<td>طراحی و پیاده‌سازی API Endpoints</td>
<td>۲ روز</td>
</tr>
<tr>
<td>۶</td>
<td>تست امنیتی و Unit Test</td>
<td>۲ روز</td>
</tr>
<tr>
<td>۷</td>
<td>مستندسازی API و راهنمای کلاینت</td>
<td>۱ روز</td>
</tr>
<tr class="highlight-row">
<td colspan="2"><strong>مجموع زمان تخمینی</strong></td>
<td><strong>۱۰ روز کاری</strong></td>
</tr>
</tbody>
</table>

<div class="conclusion-box">
<h3>🎯 توصیه نهایی</h3>
<p>این طراحی با رعایت کامل اصول امنیتی و انطباق با الگوهای موجود پروژه (IdentityServer4, XPolicies, XValidationProvider) آماده پیاده‌سازی است. پیشنهاد می‌شود فاز اول با حداقل نیازمندی‌های امنیتی (Hashing, HTTPS, Expiration, Revocation) شروع شود و قابلیت‌های پیشرفته (IP Whitelist, Rate Limiting, Audit Log) در فازهای بعدی اضافه گردند.</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
امنیت سطح Enterprise + یکپارچگی کامل با OAuth2 + مقیاس‌پذیری بالا + قابلیت ردیابی و حسابرسی کامل
</div>
</div>

<div class="info-box">
<strong>📞 گام بعدی:</strong> در صورت تأیید این طراحی، می‌توانیم پیاده‌سازی را با فاز ۱ (مدل داده و Migration) شروع کنیم. کدها دقیقاً مطابق الگوهای موجود پروژه (Partial Classes برای Manager، Validation با GroupValidationBuilder، و Exception Handling با XException) نوشته خواهند شد.
</div>
</div>
</div>

<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت طراحی و پیاده‌سازی داخلی تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>

</div>

<footer class="document-footer">
<div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل | شرکت فن‌آوران ساحر علم</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: ۱۲ مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
</footer>

</div>
</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_28cb240e-d19e-453e-872d-b7ba14ecd418.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>معرفی ساختار محصول هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: PROD-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">PRODUCT ARCHITECTURE OVERVIEW</span>
      <h1>معرفی ساختار محصول هوش مصنوعی سازمانی</h1>
      <h2>محصول در دست توسعه — رایان پرداز کاوش | معرفی به شرکت پارسا پلیمر شریف</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>کارفرمای محترم، شرکت پارسا پلیمر شریف،</strong><br>
      این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش <strong>در دست توسعه</strong> است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌هایی مانند شرکت پارسا پلیمر پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی سازمان شما، مستلزم گفتگو و دریافت بازخورد از تیم فنی شماست و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>خلاصه اجرایی</h3>
          <div class="subtitle">Executive Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.</p>

        <p>این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی مانند شرکت پارسا پلیمر شریف که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های سازمان شما و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">معماری<br>شش‌لایه</div>
            <div class="stat-label">پایه طراحی محصول</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">MCP<br>محور</div>
            <div class="stat-label">توسعه‌پذیری نامحدود</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">مدل<br>لوکال</div>
            <div class="stat-label">حاکمیت داده و محرمانگی</div>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نکته کلیدی:</strong> این مستند، معرفی <strong>ساختار محصول در دست توسعه</strong> است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی شرکت پارسا پلیمر شریف قرار گیرند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>معماری محصول در دست توسعه</h3>
          <div class="subtitle">Product Architecture Under Development</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه معماری</th>
              <th>قابلیت‌های پیش‌بینی‌شده در محصول</th>
              <th>وضعیت توسعه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه تعامل</td>
              <td>رابط وب سازمانی، نسخه دسکتاپ، درگاه API</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه کنترل دسترسی</td>
              <td>احراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه ارکستراسیون (هسته ایجنت)</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه هوش و مدل‌ها</td>
              <td>درگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه داده و منابع</td>
              <td>منابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه خروجی و گزارش</td>
              <td>تولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>محور عرضی حاکمیت داده</td>
              <td>سیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>محور عرضی مشاهده‌پذیری</td>
              <td>متریک و ردیابی مصرف، زمان پاسخ، نرخ خطا</td>
              <td>در دست توسعه</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف، از جمله شرکت پارسا پلیمر شریف، را فراهم کند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>ساختار محصول: سامانه ایجنت‌محور سازمانی</h3>
          <div class="subtitle">Product Structure: Enterprise Agentic System</div>
        </div>
      </div>
      <div class="section-content">
        <p>هسته محصول در دست توسعه، یک <strong>موتور ایجنت</strong> است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه معماری</th>
              <th>قابلیت پیش‌بینی‌شده در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه تعامل</td>
              <td>رابط وب سازمانی، نسخه دسکتاپ، درگاه API</td>
            </tr>
            <tr>
              <td>لایه کنترل دسترسی</td>
              <td>احراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها</td>
            </tr>
            <tr>
              <td>لایه ارکستراسیون (هسته ایجنت)</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
            </tr>
            <tr>
              <td>لایه هوش و مدل‌ها</td>
              <td>درگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه</td>
            </tr>
            <tr>
              <td>لایه داده و منابع</td>
              <td>منابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی</td>
            </tr>
            <tr>
              <td>لایه خروجی و گزارش</td>
              <td>تولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف</td>
            </tr>
            <tr>
              <td>محور عرضی حاکمیت داده</td>
              <td>سیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی</td>
            </tr>
            <tr>
              <td>محور عرضی مشاهده‌پذیری</td>
              <td>متریک و ردیابی مصرف، زمان پاسخ، نرخ خطا</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی شرکت پارسا پلیمر شریف بررسی و با نیازمندی‌های سازمان شما تطبیق داده شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>توسعه‌پذیری از طریق MCP</h3>
          <div class="subtitle">Extensibility via MCP</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>MCP (Model Context Protocol)</strong> در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک <strong>MCP Server</strong> تعریف شود و به سامانه اضافه گردد.</p>

        <div class="highlight-box">
          <strong>تأکید معماری:</strong> از منظر ساختار محصول، <strong>محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد</strong>. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی، از جمله نیازهای محتمل شرکت پارسا پلیمر شریف، هم‌راستا شود.
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نمونه قابلیت‌های قابل افزودن با MCP:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>حوزه سازمانی</th>
              <th>نمونه MCP Server</th>
              <th>کاربرد بالقوه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>منابع انسانی</td>
              <td>HR MCP</td>
              <td>مرخصی، آموزش، اطلاعات پرسنلی</td>
            </tr>
            <tr>
              <td>مالی و بودجه</td>
              <td>Finance MCP</td>
              <td>بودجه، هزینه، فاکتور، مراکز هزینه</td>
            </tr>
            <tr>
              <td>تولید و انبار</td>
              <td>Production MCP</td>
              <td>موجودی، سفارش، فرمولاسیون</td>
            </tr>
            <tr>
              <td>مدیریت اسناد</td>
              <td>DMS MCP</td>
              <td>جستجو و بازیابی اسناد سازمانی</td>
            </tr>
            <tr>
              <td>پایگاه داده</td>
              <td>DB MCP</td>
              <td>پرسش کنترل‌شده از داده‌ها</td>
            </tr>
            <tr>
              <td>فایل و پوشه</td>
              <td>File MCP</td>
              <td>دسترسی کنترل‌شده به فایل‌های محلی/شبکه</td>
            </tr>
            <tr>
              <td>همکاری سازمانی</td>
              <td>Collaboration MCP</td>
              <td>ایمیل، تقویم، اعلان</td>
            </tr>
            <tr>
              <td>سامانه‌های سازمانی</td>
              <td>ERP/CRM MCP</td>
              <td>یکپارچه‌سازی فرایندهای سازمانی</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>حاکمیت داده و رویکرد مدل‌های لوکال</h3>
          <div class="subtitle">Data Governance & Local Model Approach</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، <strong>حاکمیت داده</strong> به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.</p>

        <div class="warning-box">
          <strong>⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس:</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>خروج داده‌های حساس از مرز سازمان</li>
            <li>عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی</li>
            <li>احتمال استفاده از داده برای آموزش مدل‌های بعدی</li>
            <li>وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس</li>
            <li>عدم انطباق با سیاست‌های محرمانگی سازمانی</li>
          </ul>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">رویکرد پیش‌بینی‌شده در ساختار محصول:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>تصمیم</th>
              <th>رویکرد در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>مدل پیش‌فرض</td>
              <td>مدل لوکال از طریق Model Gateway و Ollama/On-Prem</td>
            </tr>
            <tr>
              <td>داده حساس</td>
              <td>عدم خروج از مرز سازمان</td>
            </tr>
            <tr>
              <td>مدل آنلاین</td>
              <td>فقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا</td>
            </tr>
            <tr>
              <td>آموزش مدل</td>
              <td>عدم استفاده از داده سازمان برای آموزش مدل‌های خارجی</td>
            </tr>
            <tr>
              <td>استقرار</td>
              <td>On-Premise با امکان عملکرد در قطع اینترنت بین‌الملل</td>
            </tr>
            <tr>
              <td>ممیزی</td>
              <td>ثبت کامل مسیر داده و تصمیمات ایجنت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا، از جمله شرکت پارسا پلیمر شریف، مناسب باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده</h3>
          <div class="subtitle">Agent Access Control & Tool Restriction</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. <strong>موتور مجوزها</strong> پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به <strong>ایجنت تصمیم‌گیرنده</strong> ابلاغ می‌شود:</p>

        <div class="comparison-grid">
          <div class="comparison-card recommended">
            <span class="card-badge">در ساختار محصول ✓</span>
            <h4>فهرست مجاز کاربر</h4>
            <ul>
              <li><span>مدل‌های مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>منابع دانش مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>ابزارهای مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>سطح دسترسی</span> <span class="value">تا سطح رکورد</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">در ساختار محصول ✓</span>
            <h4>محدودسازی ایجنت</h4>
            <ul>
              <li><span>انتخاب‌گر ابزار</span> <span class="value">فقط از فهرست مجاز</span></li>
              <li><span>فراخوانی مدل</span> <span class="value">فقط مدل مجاز</span></li>
              <li><span>بازیابی RAG</span> <span class="value">فقط منابع مجاز</span></li>
              <li><span>نقاط تأیید</span> <span class="value">عملیات حساس</span></li>
            </ul>
          </div>
        </div>

        <p>این یعنی <strong>ایجنت تصمیم‌گیرنده</strong> نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط <strong>موتور مجوزها</strong> به ایجنت ابلاغ می‌گردد.</p>

        <div class="highlight-box">
          <strong>نکته حساس:</strong> ساختار محصول از ترکیب <strong>RBAC</strong> (نقش‌محور) و <strong>ABAC</strong> (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده، از جمله شرکت پارسا پلیمر شریف، مناسب باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>دفاع لایه‌ای برای حفظ محرمانگی</h3>
          <div class="subtitle">Layered Defense for Confidentiality</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، برای جلوگیری از افشای اطلاعات، <strong>دفاع لایه‌ای</strong> در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه</th>
              <th>کنترل</th>
              <th>هدف</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه ۱</td>
              <td>احراز هویت و نشست</td>
              <td>تأیید هویت و سطح دسترسی فعال</td>
            </tr>
            <tr>
              <td>لایه ۲</td>
              <td>موتور مجوزها</td>
              <td>محدودسازی مدل، ابزار و منبع پیش از اجرا</td>
            </tr>
            <tr>
              <td>لایه ۳</td>
              <td>فهرست مجاز ابزار ایجنت</td>
              <td>جلوگیری از انتخاب ابزار غیرمجاز</td>
            </tr>
            <tr>
              <td>لایه ۴</td>
              <td>فیلتر بازیابی RAG</td>
              <td>بازیابی فقط از منابع مجاز کاربر</td>
            </tr>
            <tr>
              <td>لایه ۵</td>
              <td>سنسور محرمانگی خروجی</td>
              <td>جلوگیری از افشای اطلاعات در پاسخ نهایی</td>
            </tr>
            <tr>
              <td>لایه ۶</td>
              <td>ممیزی و لاگ</td>
              <td>ثبت و ردیابی تمام تصمیمات و دسترسی‌ها</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته حیاتی:</strong> لایه‌های <strong>۲ (موتور مجوزها)</strong> و <strong>۵ (سنسور محرمانگی)</strong> مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود.
        </div>

        <div class="success-box">
          <strong>✓ رویکرد ساختاری:</strong> دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>مثال جریان کار: یک درخواست، دو ایجنت</h3>
          <div class="subtitle">Workflow Example: One Request, Two Agents</div>
        </div>
      </div>
      <div class="section-content">
        <p>برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:</p>

        <div class="quote-box">
          <p>«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»</p>
          <div class="source">— درخواست نمونه واحد کارمند</div>
        </div>

        <p>این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: <strong>منابع انسانی</strong> و <strong>مالی</strong>. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>مرحله</th>
              <th>مسئول</th>
              <th>اقدام</th>
              <th>کنترل دسترسی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td>ایجنت مسیریاب</td>
              <td>تشخیص نیاز به HR و Finance</td>
              <td>فقط ابزارهای مجاز کاربر</td>
            </tr>
            <tr>
              <td>۲</td>
              <td>ایجنت منابع انسانی</td>
              <td>بررسی مرخصی و شرایط آموزش</td>
              <td>فقط رکورد HR خود کارمند و سیاست آموزش</td>
            </tr>
            <tr>
              <td>۳</td>
              <td>ایجنت مالی</td>
              <td>بررسی بودجه و هزینه دوره</td>
              <td>فقط بودجه مرکز هزینه واحد کاربر</td>
            </tr>
            <tr>
              <td>۴</td>
              <td>ترکیب نتایج</td>
              <td>تولید پاسخ نهایی</td>
              <td>سنسور محرمانگی خروجی</td>
            </tr>
            <tr>
              <td>۵</td>
              <td>تأیید انسانی</td>
              <td>اگر هزینه از سقف بیشتر باشد</td>
              <td>توقف و دریافت تأیید</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نحوه اعمال کنترل دسترسی در این سناریو:</h4>

        <ul class="reference-list">
          <li>
            <strong>ایجنت منابع انسانی</strong>
            به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد.
          </li>
          <li>
            <strong>ایجنت مالی</strong>
            به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد.
          </li>
          <li>
            <strong>در صورت عدم مجوز مالی</strong>
            اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد.
          </li>
          <li>
            <strong>اتصال از طریق MCP</strong>
            هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود.
          </li>
          <li>
            <strong>ممیزی کامل</strong>
            تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است.
          </li>
        </ul>

        <div class="info-box">
          <strong>💡 نتیجه مثال:</strong> ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی</h3>
          <div class="subtitle">Product Capabilities vs. Common Organizational Needs</div>
        </div>
      </div>
      <div class="section-content">
        <p>ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، مستلزم گفتگوی فنی با تیم ارزیابی شماست.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>نیاز رایج سازمانی</th>
              <th>قابلیت پیش‌بینی‌شده در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>دستیار هوشمند و ایجنت تصمیم‌گیرنده</td>
              <td>موتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop</td>
            </tr>
            <tr>
              <td>مدیریت دسترسی کاربران و واحدهای سازمانی</td>
              <td>RBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای</td>
            </tr>
            <tr>
              <td>شفافیت مصرف و هزینه</td>
              <td>داشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API</td>
            </tr>
            <tr>
              <td>تعامل کاربری و تولید گزارش</td>
              <td>رابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع</td>
            </tr>
            <tr>
              <td>حاکمیت داده و محرمانگی اطلاعات</td>
              <td>مدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده</td>
            </tr>
            <tr>
              <td>پیاده‌سازی، آموزش و پشتیبانی</td>
              <td>نقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی</td>
            </tr>
            <tr>
              <td>عملکرد پایدار و تاب‌آوری</td>
              <td>عملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های شرکت پارسا پلیمر شریف، آماده دریافت و بررسی نیازمندی‌های تیم فنی شما هستیم.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>وضعیت توسعه محصول و گام بعدی</h3>
          <div class="subtitle">Development Status & Next Step</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>وضعیت فعلی:</strong> محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، <strong>در دست توسعه</strong> است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:</p>

        <div class="timeline">
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز A: هسته ایجنت و رابط پایه</h5>
              <p>درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز B: ابزارها، RAG و منابع دانش</h5>
              <p>Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز C: حاکمیت داده و کنترل دسترسی</h5>
              <p>موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری</h5>
              <p>تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز E: Cross-Platform و آماده‌سازی محصول</h5>
              <p>نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام بعدی پیشنهادی:</h4>

        <ul class="reference-list">
          <li>
            <strong>برگزاری جلسه معرفی و گفتگوی فنی</strong>
            معرفی ساختار محصول و دریافت بازخورد از تیم فنی شرکت پارسا پلیمر شریف
          </li>
          <li>
            <strong>دریافت نیازمندی‌های اختصاصی سازمان</strong>
            شناخت دقیق نیازهای شرکت پارسا پلیمر شریف برای تطبیق محصول
          </li>
          <li>
            <strong>ارائه سناریوی نمونه Agent</strong>
            نمایش ساختار ایجنت بر اساس معماری محصول
          </li>
          <li>
            <strong>بررسی امکان اجرای پایلوت محدود</strong>
            شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت
          </li>
          <li>
            <strong>ارائه پیشنهاد تجاری شفاف</strong>
            بر اساس دامنه همکاری و نیازمندی‌های سازمانی
          </li>
        </ul>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>جمع‌بندی و پیشنهاد نهایی</h3>
          <div class="subtitle">Final Summary & Recommendation</div>
        </div>
      </div>
      <div class="section-content">
        <p>این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ویژگی</th>
              <th>رویکرد ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>معماری پایه</td>
              <td style="color: var(--success); font-weight: 600;">شش لایه + دو محور عرضی</td>
            </tr>
            <tr>
              <td>توسعه‌پذیری MCP</td>
              <td style="color: var(--success); font-weight: 600;">بدون محدودیت معماری</td>
            </tr>
            <tr>
              <td>حاکمیت داده</td>
              <td style="color: var(--success); font-weight: 600;">مدل لوکال (حاکمیت کامل)</td>
            </tr>
            <tr>
              <td>کنترل دسترسی ایجنت</td>
              <td style="color: var(--success); font-weight: 600;">تا سطح ابزار و رکورد</td>
            </tr>
            <tr>
              <td>دفاع محرمانگی</td>
              <td style="color: var(--success); font-weight: 600;">شش لایه مستقل</td>
            </tr>
            <tr>
              <td>وضعیت توسعه</td>
              <td style="color: var(--success); font-weight: 600;">در دست توسعه</td>
            </tr>
          </tbody>
        </table>

        <div class="conclusion-box">
          <h3>🎯 پیشنهاد نهایی</h3>
          <p>ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.</p>
          <p>توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.</p>
          <div class="highlight">
            <strong>💎 ارزش پیشنهادی ساختار محصول:</strong><br>
            معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای
          </div>
        </div>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی شرکت پارسا پلیمر شریف و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود.
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2a48ed4e-5c7a-406a-97d7-044165d6365c.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>بررسی فنی و راهنمای جامع ابزار AirLLM</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 950px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge {
display: flex;
align-items: center;
gap: 12px;
}
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 800;
font-size: 10px;
text-align: center;
line-height: 1.2;
}
.doc-meta {
text-align: left;
font-size: 12px;
opacity: 0.9;
}
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
font-weight: 400;
opacity: 0.9;
}
.document-body {
padding: 40px;
}
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 {
font-size: 19px;
font-weight: 700;
color: var(--primary);
margin-bottom: 2px;
}
.section-title .subtitle {
font-size: 12px;
color: var(--text-muted);
}
.section-content {
padding-right: 10px;
}
.section-content p {
margin-bottom: 12px;
text-align: justify;
text-indent: 20px;
}
.section-content p.no-indent { text-indent: 0; }
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box strong {
color: var(--accent-dark);
}
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--primary-light);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th {
padding: 14px 16px;
text-align: right;
font-weight: 600;
font-size: 13px;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
font-size: 13px;
}
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row {
background: #fffaf0 !important;
font-weight: 600;
}
pre {
background-color: #1a202c;
color: #e2e8f0;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
direction: ltr;
text-align: left;
margin: 15px 0;
font-family: 'Courier New', Courier, monospace;
font-size: 13px;
line-height: 1.6;
border-right: 4px solid var(--accent);
}
code {
font-family: 'Courier New', Courier, monospace;
background-color: #edf2f7;
color: var(--danger);
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
direction: ltr;
display: inline-block;
}
pre code {
background-color: transparent;
color: inherit;
padding: 0;
}
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 {
font-size: 22px;
font-weight: 800;
margin-bottom: 15px;
color: var(--accent);
}
.conclusion-box p {
font-size: 14px;
line-height: 1.8;
text-indent: 0 !important;
margin-bottom: 15px;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand {
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
font-size: 14px;
}
.footer-divider {
width: 60px;
height: 2px;
background: var(--accent);
margin: 10px auto;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
@media print {
body { background: white; padding: 0; }
.document-container { box-shadow: none; border-radius: 0; }
.section { page-break-inside: avoid; }
}
@media (max-width: 768px) {
.document-body { padding: 25px 20px; }
.document-header { padding: 30px 20px; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo">فن آوران<br>ساحر علم</div>
</div>
<div class="doc-meta">
<div>شماره مستند: TECH-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: ۲۸ مهر ۱۴۰۵</div>
<div>طبقه‌بندی: داخلی / فنی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL REVIEW & GUIDE</span>
<h1>بررسی فنی و راهنمای جامع ابزار AirLLM</h1>
<h2>تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود</h2>
</div>
</header>

<div class="document-body">
<div class="intro-text">
<strong>همکاران و ذینفعان محترم،</strong><br>
این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار <strong>AirLLM</strong> را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است.
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی</h3>
<div class="subtitle">Executive Summary</div>
</div>
</div>
<div class="section-content">
<p>ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.</p>
<div class="highlight-box">
<strong>نتیجه کلیدی:</strong> با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>معماری و مکانیزم عملکرد</h3>
<div class="subtitle">Architecture & Mechanism</div>
</div>
</div>
<div class="section-content">
<p>مکانیزم اصلی AirLLM بر پایه تکنیک <strong>«بارگذاری لایه‌ای» (Layer-wise Loading)</strong> استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:</p>
<div class="info-box">
<strong>گام ۱: تجزیه و ذخیره‌سازی اولیه</strong><br>
در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود.
<br><br>
<strong>گام ۲: بارگذاری پویا در GPU</strong><br>
در حین فرآیند استنتاج، تنها <strong>یک لایه</strong> از مدل در هر لحظه روی GPU بارگذاری می‌شود.
<br><br>
<strong>گام ۳: محاسبه و انتقال حالت (State)</strong><br>
پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود.
</div>
<div class="success-box">
<strong>💡 نتیجه معماری:</strong> این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>مدل‌های پشتیبانی‌شده و مصرف حافظه</h3>
<div class="subtitle">Supported Models & VRAM Consumption</div>
</div>
</div>
<div class="section-content">
<p>این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:</p>
<table class="styled-table">
<thead>
<tr>
<th>نام مدل</th>
<th>اندازه تقریبی</th>
<th>حداقل VRAM مورد نیاز</th>
</tr>
</thead>
<tbody>
<tr>
<td>Qwen3 / Mistral / Phi</td>
<td>≈8B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۲ گیگابایت</td>
</tr>
<tr>
<td>Qwen3-30B / Mixtral (MoE)</td>
<td>30–47B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-27B (dense VL)</td>
<td>27B</td>
<td style="color: var(--success); font-weight: 600;">~۳.۳۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-Flash-Next (MoE + PLE)</td>
<td>~180B</td>
<td style="color: var(--success); font-weight: 600;">~۵.۹۵ گیگابایت</td>
</tr>
<tr>
<td>Llama 3.x 70B (full precision)</td>
<td>70B</td>
<td style="color: var(--success); font-weight: 600;">~۴ گیگابایت</td>
</tr>
<tr class="highlight-row">
<td>DeepSeek-V3</td>
<td>671B</td>
<td style="color: var(--accent-dark); font-weight: 700;">~۱۲ گیگابایت</td>
</tr>
</tbody>
</table>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>راهنمای گام‌به‌گام پیاده‌سازی</h3>
<div class="subtitle">Step-by-Step Implementation Guide</div>
</div>
</div>
<div class="section-content">
<p>برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:</p>
<div class="warning-box">
<strong>پیش‌نیاز حیاتی:</strong> اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا.
</div>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۱: نصب کتابخانه</h4>
<pre><code>pip install airllm</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۲: مقداردهی اولیه مدل</h4>
<pre><code>from airllm import AutoModel

# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
model = AutoModel.from_pretrained("Qwen/Qwen3-32B")

# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
# model = AutoModel.from_pretrained("model-name", compression='4bit')
</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۳: آماده‌سازی ورودی و اجرای استنتاج</h4>
<pre><code>MAX_LENGTH = 128
input_text = ['What is the capital of United States?']

input_tokens = model.tokenizer(
    input_text,
    return_tensors="pt",
    return_attention_mask=False,
    truncation=True,
    max_length=MAX_LENGTH,
    padding=False
)

generation_output = model.generate(
    input_tokens['input_ids'].cuda(),
    max_new_tokens=20,
    use_cache=True,
    return_dict_in_generate=True
)

output = model.tokenizer.decode(generation_output.sequences[0])
print(output)
</code></pre>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>جمع‌بندی و توصیه‌های فنی</h3>
<div class="subtitle">Conclusion & Technical Recommendations</div>
</div>
</div>
<div class="section-content">
<p>با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:</p>
<table class="styled-table">
<thead>
<tr>
<th>مزیت</th>
<th>روش سنتی (بارگذاری کامل)</th>
<th>روش AirLLM (لایه‌ای)</th>
</tr>
</thead>
<tbody>
<tr>
<td>مصرف VRAM</td>
<td style="color: var(--danger); font-weight: 600;">بسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)</td>
<td style="color: var(--success); font-weight: 600;">بهینه و متناسب با اندازه لایه</td>
</tr>
<tr>
<td>نیاز به کوانتیزاسیون</td>
<td>الزامی برای کاهش مصرف</td>
<td style="color: var(--success); font-weight: 600;">غیرالزامی (حفظ دقت کامل)</td>
</tr>
<tr>
<td>سرعت استنتاج (با فشرده‌سازی)</td>
<td>پایه</td>
<td style="color: var(--success); font-weight: 600;">تا ۳ برابر سریع‌تر (با 4bit/8bit)</td>
</tr>
<tr class="highlight-row">
<td><strong>ارزش خالص فنی</strong></td>
<td>—</td>
<td style="color: var(--success); font-weight: 700; font-size: 15px;">بسیار بالاتر</td>
</tr>
</tbody>
</table>

<div class="conclusion-box">
<h3>🎯 توصیه نهایی معماری</h3>
<p>با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.</p>
<p>این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face
</div>
</div>
</div>
</div>

<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>

<footer class="document-footer">
<div class="footer-brand">طراحی و تدوین: هادی خزاعی اصل | معمار ارشد و توسعه‌دهنده سامانه‌های نرم‌افزاری</div>
<div class="footer-divider"></div>
<div>شرکت: فن آوران ساحر علم &nbsp;|&nbsp; تاریخ تهیه: ۲۸ مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: داخلی / فنی</div>
</footer>
</div>
</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_2e627fe4-93a8-4d6f-8f18-38eb87b1587b.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>پروپوزال راهکار هوش مصنوعی سازمانی | شرکت پارسا پلیمر شریف</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: PROP-1405-002</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">PROPOSAL & SOLUTION</span>
      <h1>پروپوزال راهکار هوش مصنوعی سازمانی</h1>
      <h2>سامانه ایجنت‌محور با توسعه‌پذیری MCP و حاکمیت داده درون‌سازمانی</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>کارفرمای محترم، شرکت پارسا پلیمر شریف،</strong><br>
      این مستند در پاسخ به درخواست رسمی شما (REQ-1405-001) تهیه شده است و راهکار پیشنهادی ما را به‌عنوان محصولی که <strong>معماری کلان آن در سازمان ما طراحی و پیاده‌سازی شده است</strong> معرفی می‌نماید. تمرکز این پروپوزال بر چهار محور اساسی است: ایجنت قابل‌آزمون، توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت. هدف، ارائه شفافیت کامل و اثبات عملی قابلیت‌ها در جلسه دمو و پایلوت محدود است.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>خلاصه اجرایی</h3>
          <div class="subtitle">Executive Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است. تیم ارزیابی شما با مفاهیمی مانند Agent در برابر Assistant، Human-in-the-loop، RAG، مدیریت دسترسی تا سطح سند/رکورد و حاکمیت داده کاملاً آشناست. بنابراین، پیشنهاد ما بر «ادعا» استوار نیست؛ بر <strong>قابلیت اثبات عملی</strong> استوار است.</p>

        <p>محصول پیشنهادی، یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن <strong>در سازمان ما طراحی و پیاده‌سازی شده</strong> و آماده ارائه در جلسه دمو و اجرای پایلوت محدود است. این محصول با تمرکز بر چهار محور کلیدی طراحی شده است:</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">ایجنت<br>قابل‌آزمون</div>
            <div class="stat-label">برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">MCP<br>نامحدود</div>
            <div class="stat-label">توسعه‌پذیری بدون محدودیت معماری</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">مدل<br>لوکال</div>
            <div class="stat-label">حاکمیت داده و محرمانگی کامل</div>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نتیجه کلیدی:</strong> آنچه به سازمان شما ارائه می‌شود، نه یک طرح مفهومی، بلکه یک <strong>محصول عملیاتی</strong> است که معماری شش‌لایه + دو محور عرضی آن پیاده‌سازی شده و آماده اثبات در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) می‌باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>جایگاه پیشنهاد: محصول پیاده‌سازی‌شده، نه طرح مفهومی</h3>
          <div class="subtitle">Implemented Product vs. Conceptual Design</div>
        </div>
      </div>
      <div class="section-content">
        <p>نکته متمایز این پیشنهاد آن است که معماری مطرح‌شده در مستندات فنی شما (ARCH-1405-001)، <strong>در سازمان ما به‌عنوان یک محصول طراحی و پیاده‌سازی شده است</strong>. این یعنی:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>شاخص</th>
              <th>طرح مفهومی (رایج در بازار)</th>
              <th>محصول پیاده‌سازی‌شده (پیشنهاد ما)</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>وضعیت معماری</td>
              <td>روی کاغذ و در مرحله طراحی</td>
              <td style="color: var(--success); font-weight: 600;">طراحی و پیاده‌سازی شده</td>
            </tr>
            <tr>
              <td>قابلیت اثبات عملی</td>
              <td>محدود به ادعا و اسلاید</td>
              <td style="color: var(--success); font-weight: 600;">قابل نمایش در جلسه دمو</td>
            </tr>
            <tr>
              <td>ریسک پیاده‌سازی</td>
              <td>بالا (عدم اطمینان از تحقق)</td>
              <td style="color: var(--success); font-weight: 600;">حداقل (محصول موجود است)</td>
            </tr>
            <tr>
              <td>زمان تحویل</td>
              <td>طولانی (چرخه کامل توسعه)</td>
              <td style="color: var(--success); font-weight: 600;">کوتاه (سفارشی‌سازی و استقرار)</td>
            </tr>
            <tr class="highlight-row">
              <td><strong>نتیجه نهایی</strong></td>
              <td><strong>ریسک بالا و زمان طولانی</strong></td>
              <td style="color: var(--success); font-weight: 700;"><strong>اطمینان بالا و تحویل سریع</strong></td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ مزیت کلیدی:</strong> شما با یک محصول زنده و آزمون‌پذیر مواجه هستید، نه با وعده‌های آینده. تمام قابلیت‌های مطرح‌شده در این پروپوزال، امروز در سازمان ما قابل نمایش و آزمون هستند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>محصول پیشنهادی: سامانه ایجنت‌محور سازمانی</h3>
          <div class="subtitle">Proposed Product: Enterprise Agentic System</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول ما یک چت‌بات ساده نیست. هسته محصول، یک <strong>موتور ایجنت</strong> است که هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه معماری</th>
              <th>قابلیت در محصول پیشنهادی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه تعامل</td>
              <td>رابط وب سازمانی، نسخه دسکتاپ، درگاه API</td>
            </tr>
            <tr>
              <td>لایه کنترل دسترسی</td>
              <td>احراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها</td>
            </tr>
            <tr>
              <td>لایه ارکستراسیون (هسته ایجنت)</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
            </tr>
            <tr>
              <td>لایه هوش و مدل‌ها</td>
              <td>درگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه</td>
            </tr>
            <tr>
              <td>لایه داده و منابع</td>
              <td>منابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی</td>
            </tr>
            <tr>
              <td>لایه خروجی و گزارش</td>
              <td>تولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف</td>
            </tr>
            <tr>
              <td>محور عرضی حاکمیت داده</td>
              <td>سیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی</td>
            </tr>
            <tr>
              <td>محور عرضی مشاهده‌پذیری</td>
              <td>متریک و ردیابی مصرف، زمان پاسخ، نرخ خطا</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> تمام لایه‌های فوق در محصول ما پیاده‌سازی شده‌اند و در جلسه دمو به‌صورت عملی قابل نمایش هستند. این ادعا با اجرای سناریوی چندمرحله‌ای Agent و آزمون‌های دسترسی، اثبات خواهد شد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>توسعه‌پذیری نامحدود از طریق MCP</h3>
          <div class="subtitle">Unlimited Extensibility via MCP</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>MCP (Model Context Protocol)</strong> در محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع استفاده می‌شود. هر قابلیت جدید می‌تواند در قالب یک <strong>MCP Server</strong> تعریف شود و بدون تغییر در هسته محصول به سامانه اضافه گردد.</p>

        <div class="highlight-box">
          <strong>تأکید معماری:</strong> از منظر معماری محصول، <strong>هیچ محدودیتی برای افزودن قابلیت از طریق MCP وجود ندارد</strong>. محدودیت تنها از جنس سیاست سازمانی و مجوزهای دسترسی است، نه از جنس معماری. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد.
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نمونه قابلیت‌های قابل افزودن با MCP:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>حوزه سازمانی</th>
              <th>نمونه MCP Server</th>
              <th>کاربرد پیشنهادی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>منابع انسانی</td>
              <td>HR MCP</td>
              <td>مرخصی، آموزش، اطلاعات پرسنلی</td>
            </tr>
            <tr>
              <td>مالی و بودجه</td>
              <td>Finance MCP</td>
              <td>بودجه، هزینه، فاکتور، مراکز هزینه</td>
            </tr>
            <tr>
              <td>تولید و انبار</td>
              <td>Production MCP</td>
              <td>موجودی، سفارش، فرمولاسیون</td>
            </tr>
            <tr>
              <td>مدیریت اسناد</td>
              <td>DMS MCP</td>
              <td>جستجو و بازیابی اسناد سازمانی</td>
            </tr>
            <tr>
              <td>پایگاه داده</td>
              <td>DB MCP</td>
              <td>پرسش کنترل‌شده از داده‌ها</td>
            </tr>
            <tr>
              <td>فایل و پوشه</td>
              <td>File MCP</td>
              <td>دسترسی کنترل‌شده به فایل‌های محلی/شبکه</td>
            </tr>
            <tr>
              <td>همکاری سازمانی</td>
              <td>Collaboration MCP</td>
              <td>ایمیل، تقویم، اعلان</td>
            </tr>
            <tr>
              <td>سامانه‌های سازمانی</td>
              <td>ERP/CRM MCP</td>
              <td>یکپارچه‌سازی فرایندهای سازمانی</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> توسعه‌پذیری محصول از طریق MCP، <strong>عملاً نامحدود</strong> است. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود — بدون نیاز به تغییر در هسته محصول.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>حاکمیت داده و ضرورت مدل‌های لوکال</h3>
          <div class="subtitle">Data Governance & Local Model Necessity</div>
        </div>
      </div>
      <div class="section-content">
        <p>در سناریوی شرکت پارسا پلیمر شریف — با اطلاعات حساس فرمولاسیون، مشتریان، فرایندها و اسناد سازمانی — <strong>استفاده از مدل‌های آنلاین، ذاتاً با حاکمیت داده و محرمانگی در تناقض است</strong>. زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.</p>

        <div class="warning-box">
          <strong>⚠️ ریسک مدل‌های آنلاین:</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>خروج داده‌های حساس از مرز سازمان</li>
            <li>عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی</li>
            <li>احتمال استفاده از داده برای آموزش مدل‌های بعدی</li>
            <li>وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس</li>
            <li>عدم انطباق با سیاست‌های محرمانگی سازمانی</li>
          </ul>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">معماری پیشنهادی حاکمیت داده:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>تصمیم</th>
              <th>پیاده‌سازی در محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>مدل پیش‌فرض</td>
              <td>مدل لوکال از طریق Model Gateway و Ollama/On-Prem</td>
            </tr>
            <tr>
              <td>داده حساس</td>
              <td>هرگز از مرز سازمان خارج نمی‌شود</td>
            </tr>
            <tr>
              <td>مدل آنلاین</td>
              <td>فقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا</td>
            </tr>
            <tr>
              <td>آموزش مدل</td>
              <td>داده سازمان برای آموزش مدل‌های خارجی استفاده نمی‌شود</td>
            </tr>
            <tr>
              <td>استقرار</td>
              <td>On-Premise با امکان عملکرد در قطع اینترنت بین‌الملل</td>
            </tr>
            <tr>
              <td>ممیزی</td>
              <td>ثبت کامل مسیر داده و تصمیمات ایجنت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> در سناریوی پیشنهادی، حاکمیت داده نه یک ادعا، بلکه یک <strong>سیاست اجرایی</strong> در معماری محصول است. مدل لوکال، پیش‌فرض است و داده حساس سازمان هرگز از مرز آن خارج نمی‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده</h3>
          <div class="subtitle">Agent Access Control & Tool Restriction</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول ما کنترل دسترسی را تنها به رابط کاربری محدود نمی‌کند. <strong>موتور مجوزها</strong> پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به <strong>ایجنت تصمیم‌گیرنده</strong> ابلاغ می‌شود:</p>

        <div class="comparison-grid">
          <div class="comparison-card recommended">
            <span class="card-badge">پیاده‌سازی‌شده ✓</span>
            <h4>فهرست مجاز کاربر</h4>
            <ul>
              <li><span>مدل‌های مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>منابع دانش مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>ابزارهای مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>سطح دسترسی</span> <span class="value">تا سطح رکورد</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">پیاده‌سازی‌شده ✓</span>
            <h4>محدودسازی ایجنت</h4>
            <ul>
              <li><span>انتخاب‌گر ابزار</span> <span class="value">فقط از فهرست مجاز</span></li>
              <li><span>فراخوانی مدل</span> <span class="value">فقط مدل مجاز</span></li>
              <li><span>بازیابی RAG</span> <span class="value">فقط منابع مجاز</span></li>
              <li><span>نقاط تأیید</span> <span class="value">عملیات حساس</span></li>
            </ul>
          </div>
        </div>

        <p>این یعنی <strong>ایجنت تصمیم‌گیرنده</strong> نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط <strong>موتور مجوزها</strong> به ایجنت ابلاغ می‌گردد.</p>

        <div class="highlight-box">
          <strong>نکته حساس:</strong> پشتیبانی از ترکیب <strong>RBAC</strong> (نقش‌محور) و <strong>ABAC</strong> (ویژگی‌محور) در محصول ما، کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن می‌سازد. این دقیقاً پاسخ به نیازمندی محور ۲ RFP شماست.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>دفاع لایه‌ای برای حفظ محرمانگی</h3>
          <div class="subtitle">Layered Defense for Confidentiality</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول ما برای جلوگیری از افشای اطلاعات، <strong>دفاع لایه‌ای</strong> را پیاده‌سازی کرده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه</th>
              <th>کنترل</th>
              <th>هدف</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه ۱</td>
              <td>احراز هویت و نشست</td>
              <td>تأیید هویت و سطح دسترسی فعال</td>
            </tr>
            <tr>
              <td>لایه ۲</td>
              <td>موتور مجوزها</td>
              <td>محدودسازی مدل، ابزار و منبع پیش از اجرا</td>
            </tr>
            <tr>
              <td>لایه ۳</td>
              <td>فهرست مجاز ابزار ایجنت</td>
              <td>جلوگیری از انتخاب ابزار غیرمجاز</td>
            </tr>
            <tr>
              <td>لایه ۴</td>
              <td>فیلتر بازیابی RAG</td>
              <td>بازیابی فقط از منابع مجاز کاربر</td>
            </tr>
            <tr>
              <td>لایه ۵</td>
              <td>سنسور محرمانگی خروجی</td>
              <td>جلوگیری از افشای اطلاعات در پاسخ نهایی</td>
            </tr>
            <tr>
              <td>لایه ۶</td>
              <td>ممیزی و لاگ</td>
              <td>ثبت و ردیابی تمام تصمیمات و دسترسی‌ها</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته حیاتی:</strong> لایه‌های <strong>۲ (موتور مجوزها)</strong> و <strong>۵ (سنسور محرمانگی)</strong> مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این دقیقاً پاسخ به <strong>آزمون نفوذ دسترسی</strong> کارفرماست.
        </div>

        <div class="success-box">
          <strong>✓ قابلیت اثبات:</strong> در جلسه دمو، پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت مطرح خواهد شد تا نشان داده شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، مسدود خواهد شد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>مثال جریان کار: یک درخواست، دو ایجنت</h3>
          <div class="subtitle">Workflow Example: One Request, Two Agents</div>
        </div>
      </div>
      <div class="section-content">
        <p>برای روشن‌تر شدن کنترل دسترسی در محصول، یک سناریوی واقعی را بررسی می‌کنیم. کارمندی درخواست می‌دهد:</p>

        <div class="quote-box">
          <p>«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»</p>
          <div class="source">— درخواست واحد کارمند</div>
        </div>

        <p>این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: <strong>منابع انسانی</strong> و <strong>مالی</strong>. محصول ما این درخواست را به‌صورت زیر پردازش می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>مرحله</th>
              <th>مسئول</th>
              <th>اقدام</th>
              <th>کنترل دسترسی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td>ایجنت مسیریاب</td>
              <td>تشخیص نیاز به HR و Finance</td>
              <td>فقط ابزارهای مجاز کاربر</td>
            </tr>
            <tr>
              <td>۲</td>
              <td>ایجنت منابع انسانی</td>
              <td>بررسی مرخصی و شرایط آموزش</td>
              <td>فقط رکورد HR خود کارمند و سیاست آموزش</td>
            </tr>
            <tr>
              <td>۳</td>
              <td>ایجنت مالی</td>
              <td>بررسی بودجه و هزینه دوره</td>
              <td>فقط بودجه مرکز هزینه واحد کاربر</td>
            </tr>
            <tr>
              <td>۴</td>
              <td>ترکیب نتایج</td>
              <td>تولید پاسخ نهایی</td>
              <td>سنسور محرمانگی خروجی</td>
            </tr>
            <tr>
              <td>۵</td>
              <td>تأیید انسانی</td>
              <td>اگر هزینه از سقف بیشتر باشد</td>
              <td>توقف و دریافت تأیید</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نحوه اعمال کنترل دسترسی در این سناریو:</h4>

        <ul class="reference-list">
          <li>
            <strong>ایجنت منابع انسانی</strong>
            به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد.
          </li>
          <li>
            <strong>ایجنت مالی</strong>
            به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد.
          </li>
          <li>
            <strong>در صورت عدم مجوز مالی</strong>
            اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد.
          </li>
          <li>
            <strong>اتصال از طریق MCP</strong>
            هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود.
          </li>
          <li>
            <strong>ممیزی کامل</strong>
            تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است.
          </li>
        </ul>

        <div class="info-box">
          <strong>💡 نتیجه مثال:</strong> محصول ما می‌تواند یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>انطباق با محورهای RFP شرکت پارسا پلیمر شریف</h3>
          <div class="subtitle">Compliance with RFP Requirements</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر نشان می‌دهد محصول پیشنهادی، چگونه به هر یک از هفت محور RFP شما پاسخ می‌دهد:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>محور RFP</th>
              <th>پاسخ محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>محور ۱: ماهیت ایجنت</td>
              <td>موتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop</td>
            </tr>
            <tr>
              <td>محور ۲: دسترسی</td>
              <td>RBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای</td>
            </tr>
            <tr>
              <td>محور ۳: پلن و مصرف</td>
              <td>داشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، API</td>
            </tr>
            <tr>
              <td>محور ۴: رابط و گزارش</td>
              <td>رابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع</td>
            </tr>
            <tr>
              <td>محور ۵: حاکمیت داده</td>
              <td>مدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده</td>
            </tr>
            <tr>
              <td>محور ۶: پیاده‌سازی و آموزش</td>
              <td>نقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی</td>
            </tr>
            <tr>
              <td>محور ۷: عملکرد و تاب‌آوری</td>
              <td>عملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> محصول پیشنهادی، به‌صورت سیستماتیک به تمام هفت محور RFP شما پاسخ می‌دهد. این پاسخ‌ها نه ادعای مکتوب، بلکه قابلیت‌های پیاده‌سازی‌شده و قابل‌آزمون هستند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>وضعیت بلوغ محصول و گام بعدی</h3>
          <div class="subtitle">Product Maturity & Next Step</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>وضعیت فعلی:</strong> معماری مطرح‌شده در سازمان ما طراحی و پیاده‌سازی شده و به‌عنوان محصول قابل ارائه درآمده است. فازهای کلیدی محصول شامل موارد زیر است:</p>

        <div class="timeline">
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز A: هسته ایجنت و رابط پایه</h5>
              <p>درگاه مدل، موتور ایجنت، رابط Blazor، احراز هویت — پیاده‌سازی شده</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز B: ابزارها، RAG و منابع دانش</h5>
              <p>Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — پیاده‌سازی شده</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز C: حاکمیت داده و کنترل دسترسی</h5>
              <p>موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — پیاده‌سازی شده</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری</h5>
              <p>تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — پیاده‌سازی شده</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز E: Cross-Platform و آماده‌سازی محصول</h5>
              <p>نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — پیاده‌سازی شده</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام بعدی پیشنهادی:</h4>

        <ul class="reference-list">
          <li>
            <strong>برگزاری جلسه معرفی و دموی فنی</strong>
            نمایش عملی محصول و پاسخ به سؤالات فنی تیم ارزیابی
          </li>
          <li>
            <strong>اجرای سناریوی چندمرحله‌ای Agent</strong>
            در محیط آزمایشی، شامل ابزار، خطا و مداخله انسانی
          </li>
          <li>
            <strong>اجرای آزمون نفوذ دسترسی</strong>
            با حساب‌های متفاوت و تلاش برای دور زدن مجوزها
          </li>
          <li>
            <strong>ارائه برنامه پایلوت محدود</strong>
            شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت
          </li>
          <li>
            <strong>ارائه پیشنهاد تجاری شفاف</strong>
            بر اساس دامنه پایلوت و نیازمندی‌های سازمانی
          </li>
        </ul>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات محصول، اجرای دموی عملی و ارائه برنامه پایلوت محدود هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>جمع‌بندی و پیشنهاد نهایی</h3>
          <div class="subtitle">Final Summary & Recommendation</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول پیشنهادی ما برای شرکت پارسا پلیمر شریف، یک سامانه هوش مصنوعی سازمانی <strong>آماده ارائه</strong> است که معماری آن در سازمان ما طراحی و پیاده‌سازی شده است. ویژگی‌های متمایز این پیشنهاد:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ویژگی</th>
              <th>طرح مفهومی (رایج)</th>
              <th>محصول پیشنهادی ما</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>وضعیت پیاده‌سازی</td>
              <td>روی کاغذ</td>
              <td style="color: var(--success); font-weight: 600;">پیاده‌سازی شده</td>
            </tr>
            <tr>
              <td>توسعه‌پذیری MCP</td>
              <td>محدود یا نامشخص</td>
              <td style="color: var(--success); font-weight: 600;">نامحدود از منظر معماری</td>
            </tr>
            <tr>
              <td>حاکمیت داده</td>
              <td>مدل آنلاین (ریسک محرمانگی)</td>
              <td style="color: var(--success); font-weight: 600;">مدل لوکال (حاکمیت کامل)</td>
            </tr>
            <tr>
              <td>کنترل دسترسی ایجنت</td>
              <td>محدود به رابط کاربری</td>
              <td style="color: var(--success); font-weight: 600;">تا سطح ابزار و رکورد</td>
            </tr>
            <tr>
              <td>دفاع محرمانگی</td>
              <td>یک لایه</td>
              <td style="color: var(--success); font-weight: 600;">شش لایه مستقل</td>
            </tr>
            <tr>
              <td>قابلیت اثبات</td>
              <td>ادعای مکتوب</td>
              <td style="color: var(--success); font-weight: 600;">دموی عملی و آزمون‌پذیر</td>
            </tr>
            <tr class="highlight-row">
              <td><strong>ارزش خالص ایجاد شده</strong></td>
              <td>—</td>
              <td style="color: var(--success); font-weight: 700; font-size: 15px;">بسیار بالاتر</td>
            </tr>
          </tbody>
        </table>

        <div class="conclusion-box">
          <h3>🎯 پیشنهاد نهایی</h3>
          <p>با توجه به تحلیل‌های انجام‌شده، محصول پیشنهادی ما نه یک طرح مفهومی، بلکه یک <strong>سامانه پیاده‌سازی‌شده و آزمون‌پذیر</strong> است که به تمام محورهای RFP شما پاسخ می‌دهد.</p>
          <p>توسعه‌پذیری نامحدود از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این پیشنهاد هستند.</p>
          <div class="highlight">
            <strong>💎 ارزش پیشنهادی:</strong><br>
            ایجنت قابل‌آزمون + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای + آمادگی پایلوت
          </div>
        </div>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تأیید این پروپوزال، آماده ارائه نسخه تفصیلی پیشنهاد فنی و تجاری، سناریوی نمونه Agent برای جلسه دمو، و برنامه زمان‌بندی پایلوت هستم. جلسه فنی پیشنهادی در اسرع وقت قابل برگزاری است.
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_3096683f-c9d2-4ee3-aa17-f6d2100104f0.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>نگاشت نقشه راه دانش فنی به roadmap.sh | سامانه هوش مصنوعی سازمانی</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1000px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    vertical-align: top;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  /* ===== Mapping-specific styles ===== */
  .mapping-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 12px;
    margin: 20px 0;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .mapping-header {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 16px 22px;
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
  }

  .mapping-num {
    width: 44px; height: 44px;
    background: var(--accent);
    color: var(--primary);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 18px;
    flex-shrink: 0;
  }

  .mapping-title {
    flex: 1;
    min-width: 180px;
  }

  .mapping-title h4 {
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 2px;
  }

  .mapping-title .mapping-sub {
    font-size: 11px;
    opacity: 0.85;
  }

  .mapping-arrow {
    font-size: 22px;
    color: var(--accent);
    font-weight: 800;
  }

  .mapping-target {
    background: rgba(201,169,97,0.2);
    border: 1px solid rgba(201,169,97,0.5);
    border-radius: 8px;
    padding: 6px 14px;
    font-size: 12px;
    font-weight: 600;
    color: var(--accent);
  }

  .mapping-body {
    padding: 20px 22px;
  }

  .mapping-body p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 0 !important;
    font-size: 13.5px;
    color: var(--text-muted);
  }

  .topic-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin: 15px 0;
  }

  .topic-box {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-right: 3px solid var(--primary-light);
    border-radius: 8px;
    padding: 14px 16px;
  }

  .topic-box h5 {
    font-size: 13px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .topic-box ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .topic-box ul li {
    font-size: 12px;
    color: var(--text-muted);
    padding: 3px 0 3px 14px;
    position: relative;
  }

  .topic-box ul li::before {
    content: '▸';
    position: absolute;
    right: 0;
    color: var(--accent);
    font-weight: 700;
  }

  .standard-chip {
    display: inline-block;
    background: rgba(201,169,97,0.18);
    border: 1px solid rgba(201,169,97,0.5);
    border-radius: 20px;
    padding: 2px 10px;
    font-size: 11px;
    color: var(--accent-dark);
    font-weight: 600;
    margin: 2px 4px 2px 0;
  }

  .standard-chip.blue {
    background: rgba(44,82,130,0.12);
    border-color: rgba(44,82,130,0.4);
    color: var(--primary);
  }

  .standard-chip.green {
    background: rgba(56,161,105,0.12);
    border-color: rgba(56,161,105,0.4);
    color: var(--success);
  }

  .standard-chip.red {
    background: rgba(229,62,62,0.1);
    border-color: rgba(229,62,62,0.4);
    color: var(--danger);
  }

  .deliverable-list {
    list-style: none;
    padding: 0;
    margin: 15px 0 0;
  }

  .deliverable-list li {
    background: #f0fff4;
    border: 1px solid #9ae6b4;
    border-right: 3px solid var(--success);
    border-radius: 6px;
    padding: 10px 14px;
    margin-bottom: 8px;
    font-size: 12.5px;
    color: var(--text-muted);
  }

  .deliverable-list li strong {
    color: var(--success);
    font-weight: 700;
  }

  .gap-box {
    background: #fff5f5;
    border: 1px solid #feb2b2;
    border-right: 4px solid var(--danger);
    border-radius: 8px;
    padding: 14px 18px;
    margin: 15px 0;
    font-size: 13px;
  }

  .gap-box strong { color: var(--danger); }

  .approach-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 15px;
    margin: 20px 0;
  }

  .approach-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 18px;
    text-align: center;
  }

  .approach-card .approach-icon {
    width: 48px; height: 48px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: var(--accent);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: 800;
    margin: 0 auto 12px;
  }

  .approach-card h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .approach-card p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin: 0;
  }

  .roadmap-link {
    display: inline-block;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    text-decoration: none;
    padding: 8px 18px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    margin: 5px 5px 5px 0;
    transition: opacity 0.15s ease;
  }

  .roadmap-link:hover { opacity: 0.85; }

  .roadmap-link.accent {
    background: linear-gradient(135deg, var(--accent), var(--accent-dark));
    color: var(--primary);
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .topic-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: MAP-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: آذر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">ROADMAP.SH MAPPING</span>
      <h1>نگاشت نقشه راه دانش فنی به roadmap.sh</h1>
      <h2>سامانه هوش مصنوعی سازمانی — از معماری تا محصول</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه مدیریتی،</strong><br>
      این مستند، نگاشت نقشه راه دانش فنی سامانه هوش مصنوعی سازمانی (مستند ROAD-1405-001) به نقشه‌های راه موجود در سایت <strong>roadmap.sh</strong> را ارائه می‌دهد. هدف، استفاده از منابع آموزشی جامعه‌محور و شناخته‌شده این سایت به‌عنوان <strong>ستون فقرات آموزشی</strong> برای هر فاز نقشه راه است. در این نگاشت، مشخص می‌شود هر فاز از نقشه راه دانش فنی، با کدام نقشه(های) راه roadmap.sh پوشش داده می‌شود، چه شکاف‌هایی وجود دارد و چگونه باید تکمیل شود. رویکرد نگاشت، <strong>فارغ از سکو</strong> و مبتنی بر <strong>مفاهیم و الگوها</strong> است.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>معرفی roadmap.sh و رویکرد نگاشت</h3>
          <div class="subtitle">About roadmap.sh & Mapping Approach</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>roadmap.sh</strong> یکی از محبوب‌ترین منابع جامعه‌محور برای نقشه‌های راه مهارت‌های فنی است که توسط صدها هزار توسعه‌دهنده در ماه استفاده می‌شود. این سایت مجموعه‌ای از نقشه‌های راه برای نقش‌های مختلف (Backend، Frontend، DevOps، AI Engineer، Cyber Security، Software Architect و...) ارائه می‌دهد که هر یک شامل موضوعات، منابع و مسیر یادگیری است.</p>

        <div class="approach-grid">
          <div class="approach-card">
            <div class="approach-icon">◇</div>
            <h5>فارغ از سکو</h5>
            <p>در استفاده از نقشه‌های راه، تمرکز بر مفاهیم و الگوهاست، نه ابزارهای خاص.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">◈</div>
            <h5>ستون فقرات آموزشی</h5>
            <p>roadmap.sh چارچوب کلی می‌دهد؛ تکمیل با منابع تخصصی در بخش‌های دارای شکاف.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">▤</div>
            <h5>نگاشت فاز به نقشه</h5>
            <p>هر فاز از ROAD-1405-001 به یک یا چند نقشه راه roadmap.sh نگاشت می‌شود.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">✓</div>
            <h5>حفظ خروجی قابل‌آزمون</h5>
            <p>خروجی‌های قابل‌آزمون (Deliverable) هر فاز، مبنای ارزیابی پیشرفت باقی می‌مانند.</p>
          </div>
        </div>

        <div class="highlight-box">
          <strong>اصل حاکم:</strong> roadmap.sh به‌عنوان <strong>نقشه راه آموزشی</strong> استفاده می‌شود، نه به‌عنوان <strong>نقشه راه محصول</strong>. یعنی موضوعات آن برای کسب دانش فنی تیم به کار می‌رود، اما خروجی‌های قابل‌آزمون و الزامات کارفرما (REQ-1405-001) همچنان معیار اصلی پیشرفت هستند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>نمای کلی نگاشت</h3>
          <div class="subtitle">Mapping Overview</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر، نگاشت کلی هفت فاز نقشه راه دانش فنی به نقشه‌های راه roadmap.sh را نشان می‌دهد:</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">۷</div>
            <div class="stat-label">فاز نقشه راه</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۶</div>
            <div class="stat-label">نقشه راه roadmap.sh</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۱</div>
            <div class="stat-label">شکاف اصلی (ایجنت)</div>
          </div>
        </div>

        <table class="styled-table">
          <thead>
            <tr>
              <th>فاز ROAD-1405-001</th>
              <th>نقشه(های) راه roadmap.sh</th>
              <th>درجه پوشش</th>
              <th>نیاز به تکمیل</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>فاز ۱: مبانی سیستم‌ها و داده</td>
              <td>Backend Developer (بخش‌های ابتدایی)</td>
              <td><span class="standard-chip green">بالا</span></td>
              <td>جزئی (مدیریت کلید، رمزنگاری پیشرفته)</td>
            </tr>
            <tr>
              <td>فاز ۲: مبانی مهندسی نرم‌افزار</td>
              <td>Software Design and Architecture</td>
              <td><span class="standard-chip green">بالا</span></td>
              <td>جزئی (Hexagonal، آزمون‌پذیری)</td>
            </tr>
            <tr>
              <td>فاز ۳: مبانی هوش مصنوعی و مدل‌ها</td>
              <td>AI Engineer</td>
              <td><span class="standard-chip green">بالا</span></td>
              <td>متوسط (ارزیابی مدل، حاکمیت AI)</td>
            </tr>
            <tr>
              <td>فاز ۴: معماری سیستم‌های توزیع‌شده</td>
              <td>System Design</td>
              <td><span class="standard-chip green">بالا</span></td>
              <td>متوسط (BPMN 2.0، Event Sourcing)</td>
            </tr>
            <tr>
              <td>فاز ۵: معماری ایجنت و ارکستراسیون</td>
              <td>AI Engineer (پیشرفته) + Software Architect</td>
              <td><span class="standard-chip red">پایین</span></td>
              <td>قابل توجه (منابع تخصصی ایجنت)</td>
            </tr>
            <tr>
              <td>فاز ۶: امنیت، حاکمیت داده و انطباق</td>
              <td>Cyber Security</td>
              <td><span class="standard-chip green">بالا</span></td>
              <td>متوسط (OWASP LLM، ISO 42001)</td>
            </tr>
            <tr>
              <td>فاز ۷: معماری کلان، محصول و عملیات</td>
              <td>DevOps + Software Architect</td>
              <td><span class="standard-chip">متوسط</span></td>
              <td>متوسط (مدیریت محصول، ADR)</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> بیشترین شکاف در <strong>فاز ۵ (معماری ایجنت)</strong> است. roadmap.sh در نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>نگاشت تفصیلی فاز به نقشه راه</h3>
          <div class="subtitle">Detailed Phase-to-Roadmap Mapping</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ادامه، هر فاز به‌صورت تفصیلی نگاشت شده است؛ شامل موضوعات پوشش‌داده‌شده، شکاف‌ها و منابع تکمیلی پیشنهادی:</p>

        <!-- Phase 1 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۱</div>
            <div class="mapping-title">
              <h4>مبانی سیستم‌ها و داده</h4>
              <div class="mapping-sub">Phase 1 — Foundations of Systems & Data</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">Backend Developer</div>
          </div>
          <div class="mapping-body">
            <p>نقشه راه <strong>Backend Developer</strong> در roadmap.sh، مبانی اینترنت، پروتکل HTTP، پایگاه‌های داده، مدل داده و مبانی امنیت را پوشش می‌دهد که با فاز ۱ نقشه راه دانش فنی هم‌پوشانی بالایی دارد.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>مبانی اینترنت و DNS</li>
                  <li>HTTP/HTTPS و REST</li>
                  <li>پایگاه‌های داده رابطه‌ای و NoSQL</li>
                  <li>مدل‌سازی داده</li>
                  <li>مبانی احراز هویت</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>مدیریت کلید پیشرفته (NIST SP 800-57)</li>
                  <li>رمزنگاری نامتقارن و امضای دیجیتال</li>
                  <li>Data Lake و Data Warehouse</li>
                  <li>مدل تهدید پایه</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip blue">RFC 8446 (TLS 1.3)</span>
              <span class="standard-chip blue">NIST SP 800-57</span>
              <span class="standard-chip">ISO/IEC 27001 (مبانی)</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>نقشه مفهومی داده سازمان</strong> + <strong>سند مدل تهدید پایه</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 2 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۲</div>
            <div class="mapping-title">
              <h4>مبانی مهندسی نرم‌افزار</h4>
              <div class="mapping-sub">Phase 2 — Software Engineering Foundations</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">Software Design and Architecture</div>
          </div>
          <div class="mapping-body">
            <p>نقشه راه <strong>Software Design and Architecture</strong>، الگوهای طراحی، اصول SOLID، معماری تمیز و جداسازی دغدغه‌ها را پوشش می‌دهد که با فاز ۲ هم‌پوشانی بالایی دارد.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>اصول SOLID</li>
                  <li>الگوهای طراحی (GoF)</li>
                  <li>معماری لایه‌ای و MVC</li>
                  <li>Separation of Concerns</li>
                  <li>مبانی آزمون‌پذیری</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>معماری Hexagonal (Ports & Adapters)</li>
                  <li>Test Double (Mock، Stub، Fake)</li>
                  <li>Contract Testing</li>
                  <li>ADR (Architecture Decision Records)</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip">Clean Architecture (Robert C. Martin)</span>
              <span class="standard-chip">Hexagonal Architecture (Alistair Cockburn)</span>
              <span class="standard-chip blue">ISO/IEC 25010</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند اصول و الگوهای منتخب</strong> + <strong>نمونه اولیه ساختار Hexagonal</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 3 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۳</div>
            <div class="mapping-title">
              <h4>مبانی هوش مصنوعی و مدل‌ها</h4>
              <div class="mapping-sub">Phase 3 — AI & Model Foundations</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">AI Engineer</div>
          </div>
          <div class="mapping-body">
            <p>نقشه راه <strong>AI Engineer</strong> در roadmap.sh، مبانی LLM، Prompt Engineering، RAG، پایگاه‌های داده برداری و ارزیابی مدل‌ها را پوشش می‌دهد. این نقشه راه، هسته لایه هوش (L4) معماری را پوشش می‌دهد.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>مبانی مدل‌های زبانی</li>
                  <li>Prompt Engineering</li>
                  <li>RAG و Vector Database</li>
                  <li>Function Calling</li>
                  <li>ارزیابی کیفیت پاسخ</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>NIST AI RMF و ISO 42001</li>
                  <li>Hallucination Detection پیشرفته</li>
                  <li>Bias و Fairness</li>
                  <li>سیاست دسترسی به مدل‌های جدید</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip green">NIST AI RMF</span>
              <span class="standard-chip green">ISO/IEC 42001</span>
              <span class="standard-chip">Attention Is All You Need</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند ارزیابی مدل‌ها</strong> + <strong>نمونه اولیه RAG</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 4 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۴</div>
            <div class="mapping-title">
              <h4>معماری سیستم‌های توزیع‌شده</h4>
              <div class="mapping-sub">Phase 4 — Distributed Systems Architecture</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">System Design</div>
          </div>
          <div class="mapping-body">
            <p>نقشه راه <strong>System Design</strong>، مباحث مقیاس‌پذیری، دسترس‌پذیری، الگوهای توزیع‌شده (CQRS، Event-Driven) و trade-offها را پوشش می‌دهد که با فاز ۴ هم‌پوشانی بالایی دارد.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>مقیاس‌پذیری و Load Balancing</li>
                  <li>Caching Strategies</li>
                  <li>Event-Driven Architecture</li>
                  <li>CQRS و Event Sourcing (مفهومی)</li>
                  <li>Circuit Breaker و Retry</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>BPMN 2.0 (برای مدل‌سازی فرایند)</li>
                  <li>OpenTelemetry (مشاهده‌پذیری)</li>
                  <li>Saga Pattern پیشرفته</li>
                  <li>Idempotency و Distributed Locking</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip">Enterprise Integration Patterns</span>
              <span class="standard-chip">Release It! (Michael Nygard)</span>
              <span class="standard-chip blue">OpenTelemetry Spec</span>
              <span class="standard-chip blue">BPMN 2.0</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند الگوهای معماری منتخب</strong> + <strong>نقشه BPMN2 تکمیلی</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 5 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۵</div>
            <div class="mapping-title">
              <h4>معماری ایجنت و ارکستراسیون</h4>
              <div class="mapping-sub">Phase 5 — Agent Architecture & Orchestration</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">AI Engineer + Software Architect</div>
          </div>
          <div class="mapping-body">
            <p>این فاز، <strong>بیشترین شکاف</strong> را در roadmap.sh دارد. نقشه AI Engineer به AI Agents اشاره دارد، اما معماری عمیق ایجنت (برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، چند-ایجنت) را پوشش نمی‌دهد. نقشه Software Architect نیز دید کلان می‌دهد اما تخصصی ایجنت نیست.</p>

            <div class="gap-box">
              <strong>⚠️ شکاف اصلی:</strong> roadmap.sh معماری ایجنت (Agent Architecture) را به‌طور عمیق پوشش نمی‌دهد. این فاز نیازمند منابع تخصصی تکمیلی است: مقالات علمی (ReAct، Reflexion، Plan-and-Execute)، مستندات پروتکل‌ها (MCP)، و منابع تخصصی طراحی ایجنت.
            </div>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده (جزئی)</h5>
                <ul>
                  <li>مفاهیم پایه AI Agent</li>
                  <li>Function Calling</li>
                  <li>Tool Use (مقدماتی)</li>
                  <li>حافظه و زمینه</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند منابع تخصصی</h5>
                <ul>
                  <li>الگوهای برنامه‌ریزی (ReAct، Reflexion)</li>
                  <li>Tool Selection Strategies</li>
                  <li>Human-in-the-loop Patterns</li>
                  <li>Multi-Agent Orchestration</li>
                  <li>ارزیابی ایجنت (Task Success Rate)</li>
                  <li>Guardrails و Kill Switch</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip green">ReAct (Yao et al.)</span>
              <span class="standard-chip green">Reflexion (Shinn et al.)</span>
              <span class="standard-chip blue">Model Context Protocol (MCP)</span>
              <span class="standard-chip green">NIST AI RMF (کنترل)</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سناریوی نمونه Agent</strong> (قابل ارائه در جلسه دمو) + <strong>چارچوب ارزیابی ایجنت</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 6 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۶</div>
            <div class="mapping-title">
              <h4>امنیت، حاکمیت داده و انطباق</h4>
              <div class="mapping-sub">Phase 6 — Security, Data Governance & Compliance</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">Cyber Security</div>
          </div>
          <div class="mapping-body">
            <p>نقشه راه <strong>Cyber Security</strong> در roadmap.sh، مباحث IAM (Identity & Access Management)، رمزنگاری، امنیت وب و OWASP را پوشش می‌دهد که با فاز ۶ هم‌پوشانی بالایی دارد و مستقیماً به محور عرضی حاکمیت (X) مرتبط است.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>OAuth 2.0 و OpenID Connect</li>
                  <li>RBAC و ABAC</li>
                  <li>OWASP Top 10 و API Security</li>
                  <li>رمزنگاری و TLS</li>
                  <li>Audit Logging</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>OWASP LLM Top 10</li>
                  <li>Prompt Injection و Jailbreak</li>
                  <li>ISO/IEC 42001 (مدیریت AI)</li>
                  <li>NIST AI RMF (کنترل)</li>
                  <li>ReBAC و Fine-grained Access</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip blue">OAuth 2.0 (RFC 6749)</span>
              <span class="standard-chip blue">OpenID Connect Core</span>
              <span class="standard-chip blue">OWASP LLM Top 10</span>
              <span class="standard-chip green">ISO/IEC 27001</span>
              <span class="standard-chip green">ISO/IEC 42001</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند مدل دسترسی و حاکمیت داده</strong> + <strong>سناریوی آزمون نفوذ دسترسی</strong></li>
            </ul>
          </div>
        </div>

        <!-- Phase 7 -->
        <div class="mapping-card">
          <div class="mapping-header">
            <div class="mapping-num">۷</div>
            <div class="mapping-title">
              <h4>معماری کلان، محصول و عملیات</h4>
              <div class="mapping-sub">Phase 7 — Enterprise Architecture, Product & Operations</div>
            </div>
            <div class="mapping-arrow">←</div>
            <div class="mapping-target">DevOps + Software Architect</div>
          </div>
          <div class="mapping-body">
            <p>ترکیب دو نقشه راه <strong>DevOps</strong> (برای SRE، مشاهده‌پذیری و عملیات) و <strong>Software Architect</strong> (برای نگاشت معماری به محصول و مدیریت چرخه عمر) پوشش مناسبی برای فاز ۷ فراهم می‌کند.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>موضوعات پوشش‌داده‌شده</h5>
                <ul>
                  <li>SLI/SLO/SLA</li>
                  <li>مشاهده‌پذیری (Logging، Metrics، Tracing)</li>
                  <li>Incident Management</li>
                  <li>معماری سازمانی (TOGAF مفهومی)</li>
                  <li>Release Strategies</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>موضوعات نیازمند تکمیل</h5>
                <ul>
                  <li>مدیریت محصول (Product Vision، Roadmap)</li>
                  <li>Token Accounting و Cost Attribution</li>
                  <li>ADR (Architecture Decision Records)</li>
                  <li>Capability Mapping</li>
                  <li>Team Topologies (مفهومی)</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:12px;"><strong>منابع تکمیلی پیشنهادی:</strong></p>
            <div>
              <span class="standard-chip">TOGAF ADM</span>
              <span class="standard-chip">Google SRE Book</span>
              <span class="standard-chip blue">OpenAPI Specification</span>
              <span class="standard-chip blue">ADR</span>
              <span class="standard-chip green">ISO/IEC 20000</span>
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون (از ROAD-1405-001):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند معماری محصول</strong> + <strong>سند SLA و SLO</strong></li>
            </ul>
          </div>
        </div>

      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>شکاف‌های کلیدی و راهکار تکمیل</h3>
          <div class="subtitle">Key Gaps & Completion Strategy</div>
        </div>
      </div>
      <div class="section-content">
        <p>roadmap.sh به‌عنوان ستون فقرات آموزشی، پوشش خوبی برای فازهای ۱ تا ۴، ۶ و ۷ دارد. اما شکاف‌های زیر باید با منابع تخصصی تکمیل شوند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>شکاف</th>
              <th>فاز مرتبط</th>
              <th>راهکار تکمیل</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>معماری ایجنت (Agent Architecture)</strong></td>
              <td>فاز ۵</td>
              <td>مقالات ReAct، Reflexion، Plan-and-Execute + مستندات MCP + منابع تخصصی طراحی ایجنت</td>
            </tr>
            <tr>
              <td><strong>ارزیابی ایجنت</strong></td>
              <td>فاز ۵</td>
              <td>چارچوب‌های ارزیابی (Task Success Rate، Step Efficiency) + آزمون سناریومحور</td>
            </tr>
            <tr>
              <td><strong>امنیت LLM</strong></td>
              <td>فاز ۶</td>
              <td>OWASP LLM Top 10 + Prompt Injection + Jailbreak Detection</td>
            </tr>
            <tr>
              <td><strong>حاکمیت AI</strong></td>
              <td>فاز ۳، ۶</td>
              <td>NIST AI RMF + ISO/IEC 42001 + OECD AI Principles</td>
            </tr>
            <tr>
              <td><strong>BPMN 2.0</strong></td>
              <td>فاز ۴</td>
              <td>مستندات OMG BPMN 2.0 + الگوهای مدل‌سازی فرایند</td>
            </tr>
            <tr>
              <td><strong>مدیریت محصول</strong></td>
              <td>فاز ۷</td>
              <td>منابع تخصصی Product Management + Prioritization Frameworks</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته مهم:</strong> شکاف <strong>معماری ایجنت</strong> (فاز ۵) بحرانی‌ترین شکاف است، زیرا این فاز مستقیماً به <strong>محور ۱ نیازمندی‌های کارفرما</strong> (ایجنت قابل‌آزمون) و <strong>نقطه عطف M4</strong> (آمادگی برای جلسه دمو) مرتبط است. بنابراین، منابع تخصصی این فاز باید به‌صورت جدی و جداگانه دنبال شوند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>نقشه راه تلفیقی پیشنهادی</h3>
          <div class="subtitle">Recommended Integrated Roadmap</div>
        </div>
      </div>
      <div class="section-content">
        <p>بر اساس نگاشت فوق، نقشه راه تلفیقی زیر پیشنهاد می‌شود که roadmap.sh را با منابع تخصصی تکمیل می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>فاز</th>
              <th>منبع اصلی (roadmap.sh)</th>
              <th>منبع تکمیلی</th>
              <th>خروجی قابل‌آزمون</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td>Backend Developer</td>
              <td>NIST SP 800-57، RFC 8446</td>
              <td>نقشه داده + مدل تهدید</td>
            </tr>
            <tr>
              <td>۲</td>
              <td>Software Design & Architecture</td>
              <td>Clean Architecture، Hexagonal</td>
              <td>سند الگوها + نمونه Hexagonal</td>
            </tr>
            <tr>
              <td>۳</td>
              <td>AI Engineer</td>
              <td>NIST AI RMF، ISO 42001</td>
              <td>ارزیابی مدل + نمونه RAG</td>
            </tr>
            <tr>
              <td>۴</td>
              <td>System Design</td>
              <td>BPMN 2.0، OpenTelemetry، Release It!</td>
              <td>الگوهای معماری + BPMN2</td>
            </tr>
            <tr class="highlight-row">
              <td>۵</td>
              <td>AI Engineer + Software Architect</td>
              <td>ReAct، Reflexion، MCP، منابع تخصصی ایجنت</td>
              <td>سناریوی Agent + چارچوب ارزیابی</td>
            </tr>
            <tr>
              <td>۶</td>
              <td>Cyber Security</td>
              <td>OWASP LLM Top 10، ISO 27001/42001</td>
              <td>مدل دسترسی + آزمون نفوذ</td>
            </tr>
            <tr>
              <td>۷</td>
              <td>DevOps + Software Architect</td>
              <td>Google SRE، TOGAF، OpenAPI</td>
              <td>معماری محصول + SLA/SLO</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نکته کلیدی:</strong> نقطه عطف <strong>M4</strong> (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و به‌ویژه <strong>فاز ۵ با منابع تخصصی</strong> محقق می‌شود. roadmap.sh برای فازهای ۱ تا ۴ و ۶ ستون فقرات است، اما فاز ۵ نیازمند منابع تخصصی جداگانه است.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>لینک‌های مرجع roadmap.sh</h3>
          <div class="subtitle">roadmap.sh Reference Links</div>
        </div>
      </div>
      <div class="section-content">
        <p>لینک‌های مستقیم به نقشه‌های راه پیشنهادی در roadmap.sh:</p>

        <div class="reference-list">
          <li>
            <strong>Backend Developer</strong>
            <div class="ref-source"><a href="https://roadmap.sh/backend" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/backend</a></div>
          </li>
          <li>
            <strong>Software Design and Architecture</strong>
            <div class="ref-source"><a href="https://roadmap.sh/software-design-architecture" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/software-design-architecture</a></div>
          </li>
          <li>
            <strong>AI Engineer</strong>
            <div class="ref-source"><a href="https://roadmap.sh/ai-engineer" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/ai-engineer</a></div>
          </li>
          <li>
            <strong>System Design</strong>
            <div class="ref-source"><a href="https://roadmap.sh/system-design" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/system-design</a></div>
          </li>
          <li>
            <strong>Software Architect</strong>
            <div class="ref-source"><a href="https://roadmap.sh/software-architect" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/software-architect</a></div>
          </li>
          <li>
            <strong>Cyber Security</strong>
            <div class="ref-source"><a href="https://roadmap.sh/cyber-security" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/cyber-security</a></div>
          </li>
          <li>
            <strong>DevOps</strong>
            <div class="ref-source"><a href="https://roadmap.sh/devops" class="roadmap-link" target="_blank" rel="noopener">roadmap.sh/devops</a></div>
          </li>
        </div>

        <div class="info-box">
          <strong>💡 نکته:</strong> roadmap.sh به‌طور مداوم به‌روزرسانی می‌شود. توصیه می‌شود لینک‌ها و محتوای نقشه‌های راه به‌صورت دوره‌ای بازبینی شوند تا از آخرین تغییرات مطلع شوید.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>جمع‌بندی</h3>
          <div class="subtitle">Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>این مستند، نگاشت نقشه راه دانش فنی (ROAD-1405-001) به نقشه‌های راه roadmap.sh را ارائه داد. ویژگی‌های کلیدی:</p>

        <ul class="reference-list">
          <li>
            <strong>پوشش بالای فازهای ۱ تا ۴، ۶ و ۷</strong>
            با نقشه‌های راه Backend، Software Design، AI Engineer، System Design، Cyber Security، DevOps و Software Architect
          </li>
          <li>
            <strong>شکاف بحرانی در فاز ۵ (ایجنت)</strong>
            نیازمند منابع تخصصی تکمیلی (ReAct، Reflexion، MCP)
          </li>
          <li>
            <strong>حفظ خروجی‌های قابل‌آزمون</strong>
            هر فاز همچنان با Deliverable مشخص از ROAD-1405-001 ارزیابی می‌شود
          </li>
          <li>
            <strong>رویکرد فارغ از سکو</strong>
            استفاده از roadmap.sh برای مفاهیم و الگوها، نه ابزارهای خاص
          </li>
          <li>
            <strong>نقشه راه تلفیقی</strong>
            ترکیب roadmap.sh با منابع تخصصی برای پوشش کامل هفت فاز
          </li>
        </ul>

        <div class="highlight-box">
          <strong>توصیه نهایی:</strong> roadmap.sh به‌عنوان <strong>ستون فقرات آموزشی</strong> برای فازهای ۱ تا ۴، ۶ و ۷ استفاده شود. برای فاز ۵ (هسته تمایز محصول)، منابع تخصصی ایجنت (مقالات علمی و مستندات پروتکل‌ها) به‌صورت جداگانه دنبال شوند. نقطه عطف <strong>M4</strong> (آمادگی برای جلسه دمو) با تکمیل فازهای ۱ تا ۶ و منابع تخصصی فاز ۵ محقق می‌شود.
        </div>
      </div>
    </div>

    <div class="conclusion-box">
      <h3>🎯 ارزش این مستند</h3>
      <p>این مستند، پل ارتباطی بین نقشه راه دانش فنی داخلی و منابع آموزشی جامعه‌محور roadmap.sh را فراهم می‌کند.</p>
      <p>با این نگاشت، تیم فنی می‌تواند از منابع شناخته‌شده و به‌روز roadmap.sh برای فازهای مختلف استفاده کند و شکاف‌ها را با منابع تخصصی تکمیل نماید.</p>
      <div class="highlight">
        <strong>💎 ارزش پیشنهادی:</strong><br>
        ستون فقرات آموزشی roadmap.sh + منابع تخصصی تکمیلی + حفظ خروجی قابل‌آزمون + رویکرد فارغ از سکو + نقشه راه تلفیقی
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: آذر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_4c60f04d-bd98-4ec0-af18-7beb569dfb05.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>رفع مشکل تست XApiKey در Swagger | مستند فنی</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
        :root {
            --primary: #1a365d;
            --primary-light: #2c5282;
            --accent: #c9a961;
            --accent-dark: #a8893f;
            --bg: #faf9f6;
            --card-bg: #ffffff;
            --text: #1a202c;
            --text-muted: #4a5568;
            --border: #e2e8f0;
            --success: #38a169;
            --danger: #e53e3e;
            --warning: #dd6b20;
            --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
            --code-bg: #f7fafc;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Vazirmatn', Tahoma, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.9;
            font-size: 15px;
            padding: 30px 15px;
        }
        .document-container {
            max-width: 1000px;
            margin: 0 auto;
            background: var(--card-bg);
            box-shadow: var(--shadow);
            border-radius: 12px;
            overflow: hidden;
        }
        .document-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
            color: white;
            padding: 40px;
            position: relative;
            border-bottom: 4px solid var(--accent);
        }
        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .doc-meta {
            text-align: left;
            font-size: 12px;
            opacity: 0.9;
        }
        .doc-meta div { margin-bottom: 3px; }
        .document-title h1 {
            font-size: 26px;
            font-weight: 800;
            margin-bottom: 8px;
        }
        .document-title h2 {
            font-size: 16px;
            font-weight: 400;
            opacity: 0.9;
        }
        .document-body { padding: 40px; }
        .section {
            margin-bottom: 40px;
            page-break-inside: avoid;
        }
        .section-header {
            display: flex;
            align-items: center;
            gap: 15px;
            padding-bottom: 12px;
            border-bottom: 2px solid var(--border);
            margin-bottom: 20px;
        }
        .section-number {
            width: 45px; height: 45px;
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 800;
            font-size: 18px;
            flex-shrink: 0;
        }
        .section-title h3 {
            font-size: 19px;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 2px;
        }
        .section-title .subtitle {
            font-size: 12px;
            color: var(--text-muted);
        }
        .section-content p {
            margin-bottom: 12px;
            text-align: justify;
            text-indent: 20px;
        }
        .code-block {
            background: var(--code-bg);
            border: 1px solid var(--border);
            border-right: 4px solid var(--accent);
            border-radius: 6px;
            padding: 15px 20px;
            margin: 15px 0;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
            direction: ltr;
            text-align: left;
            line-height: 1.6;
            white-space: pre-wrap;
        }
        .code-block .comment { color: #6a737d; }
        .code-block .keyword { color: #d73a49; }
        .code-block .string { color: #032f62; }
        .highlight-box {
            background: linear-gradient(to left, #fffaf0, #fef5e7);
            border: 1px solid #f6e05e;
            border-right: 4px solid var(--accent);
            padding: 18px 22px;
            border-radius: 8px;
            margin: 20px 0;
            font-size: 14px;
        }
        .highlight-box strong { color: var(--accent-dark); }
        .warning-box {
            background: linear-gradient(to left, #fff5f5, #fffaf0);
            border: 1px solid #feb2b2;
            border-right: 4px solid var(--danger);
            padding: 18px 22px;
            border-radius: 8px;
            margin: 20px 0;
            font-size: 14px;
        }
        .warning-box strong { color: var(--danger); }
        .success-box {
            background: linear-gradient(to left, #f0fff4, #e6fffa);
            border: 1px solid #9ae6b4;
            border-right: 4px solid var(--success);
            padding: 18px 22px;
            border-radius: 8px;
            margin: 20px 0;
            font-size: 14px;
        }
        .success-box strong { color: var(--success); }
        .info-box {
            background: linear-gradient(to left, #ebf8ff, #e6f6ff);
            border: 1px solid #90cdf4;
            border-right: 4px solid var(--primary-light);
            padding: 18px 22px;
            border-radius: 8px;
            margin: 20px 0;
            font-size: 14px;
        }
        .flow-diagram {
            background: #f8fafc;
            border: 2px solid var(--border);
            border-radius: 10px;
            padding: 25px;
            margin: 20px 0;
            text-align: center;
        }
        .flow-step {
            display: inline-block;
            background: white;
            border: 2px solid var(--primary-light);
            border-radius: 8px;
            padding: 10px 18px;
            margin: 5px;
            font-size: 13px;
            font-weight: 600;
            color: var(--primary);
        }
        .flow-arrow {
            display: inline-block;
            color: var(--accent);
            font-size: 20px;
            margin: 0 8px;
            font-weight: bold;
        }
        .flow-step.error {
            border-color: var(--danger);
            color: var(--danger);
            background: #fff5f5;
        }
        .flow-step.success {
            border-color: var(--success);
            color: var(--success);
            background: #f0fff4;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        th, td {
            padding: 12px 16px;
            border: 1px solid var(--border);
            text-align: right;
            font-size: 13px;
        }
        th {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            font-weight: 600;
        }
        tr:nth-child(even) { background: #f8fafc; }
        .step-card {
            background: white;
            border: 2px solid var(--border);
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            position: relative;
        }
        .step-card.critical {
            border-color: var(--danger);
            background: #fff5f5;
        }
        .step-card.important {
            border-color: var(--accent);
            background: #fffaf0;
        }
        .step-badge {
            position: absolute;
            top: -12px;
            right: 20px;
            background: var(--primary);
            color: white;
            padding: 3px 14px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 700;
        }
        .step-badge.critical { background: var(--danger); }
        .step-badge.important { background: var(--accent); }
        .step-card h4 {
            font-size: 16px;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 12px;
            margin-top: 8px;
        }
        .document-footer {
            background: var(--primary);
            color: white;
            padding: 25px 40px;
            text-align: center;
            font-size: 12px;
        }
        .footer-brand {
            font-weight: 700;
            color: var(--accent);
            margin-bottom: 5px;
            font-size: 14px;
        }
        .footer-divider {
            width: 60px;
            height: 2px;
            background: var(--accent);
            margin: 10px auto;
        }
        ul.checklist {
            list-style: none;
            padding: 0;
            margin: 15px 0;
        }
        ul.checklist li {
            padding: 8px 0 8px 30px;
            position: relative;
            border-bottom: 1px solid var(--border);
        }
        ul.checklist li:before {
            content: "✓";
            position: absolute;
            right: 0;
            color: var(--success);
            font-weight: bold;
            font-size: 16px;
        }
        ul.checklist li.fail:before {
            content: "✗";
            color: var(--danger);
        }
    </style>
</head>
<body>
    <div class="document-container">
        <header class="document-header">
            <div class="header-top">
                <div class="doc-meta">
                    <div>شماره مستند: XIDS-SWAGGER-APIKEY-002</div>
                    <div>نسخه: ۲.۰</div>
                    <div>تاریخ تهیه: ۲۰ مهر ۱۴۰۵</div>
                    <div>طبقه‌بندی: داخلی — فنی</div>
                </div>
            </div>
            <div class="document-title">
                <h1>رفع مشکل تست XApiKey در Swagger UI</h1>
                <h2>تحلیل ریشه‌ای و راه‌حل گام‌به‌گام برای فعال‌سازی کامل</h2>
            </div>
        </header>

        <div class="document-body">

            <!-- بخش ۱: خلاصه مشکل -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۱</div>
                    <div class="section-title">
                        <h3>خلاصه مشکل شناسایی‌شده</h3>
                        <div class="subtitle">Problem Summary</div>
                    </div>
                </div>
                <div class="section-content">
                    <p>
                        پس از بررسی دقیق کدهای پروژه <code>xIds</code>، مشخص شد که اگرچه زیرساخت
                        <code>XApiKeyAuthenticationHandler</code> و Policyهای مربوطه به‌درستی پیاده‌سازی شده‌اند،
                        اما <strong>چهار مشکل معماری</strong> مانع از کارکرد صحیح احراز هویت با API Key در Swagger می‌شوند.
                    </p>

                    <div class="warning-box">
                        <strong>🔴 مشکلات شناسایی‌شده:</strong>
                        <ol style="padding-right: 20px; margin-top: 10px;">
                            <li><strong>ترتیب ثبت Schemeها:</strong> <code>XApiKey</code> اول ثبت شده و به‌عنوان DefaultScheme انتخاب می‌شود — در نتیجه درخواست‌های Bearer Token هم به آن حواله می‌شوند و شکست می‌خورند.</li>
                            <li><strong>عدم تنظیم DefaultScheme:</strong> در <code>AddAuthentication()</code> هیچ DefaultScheme مشخصی تعیین نشده است.</li>
                            <li><strong>محدودیت LocalApi Policy:</strong> Policy <code>IdentityServerConstants.LocalApi.PolicyName</code> فقط Scheme <code>IdentityServerAccessToken</code> را قبول می‌کند.</li>
                            <li><strong>عدم وجود PolicyScheme هوشمند:</strong> هیچ مکانیزمی برای انتخاب پویای Scheme بر اساس Header درخواست وجود ندارد.</li>
                        </ol>
                    </div>
                </div>
            </div>

            <!-- بخش ۲: جریان فعلی -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۲</div>
                    <div class="section-title">
                        <h3>تحلیل جریان فعلی احراز هویت</h3>
                        <div class="subtitle">Current Authentication Flow Analysis</div>
                    </div>
                </div>
                <div class="section-content">
                    <p>
                        در کد فعلی <code>XDIHelperExtension.AddXIdentityServerAuthentication</code>، ترتیب ثبت به این صورت است:
                    </p>

                    <div class="code-block"><span class="comment">// xIds/DI/XDIHelperExtension.cs — کد فعلی</span>
<span class="keyword">var</span> authBuilder = services.AddAuthentication();  <span class="comment">// ← DefaultScheme تنظیم نشده!</span>

<span class="comment">// ۱. ثبت XApiKey (اول)</span>
<span class="keyword">if</span> (addApiKeyAuthentication)
{
    authBuilder.AddScheme&lt;..., XApiKeyAuthenticationHandler&gt;(
        <span class="string">"XApiKey"</span>, options =&gt; { });
}

<span class="comment">// ۲. ثبت JwtBearer</span>
authBuilder.AddJwtBearer(options =&gt; {
    options.ForwardDefaultSelector = context =&gt; { ... };
})
<span class="comment">// ۳. ثبت LocalApi</span>
.AddLocalApi();</div>

                    <div class="highlight-box">
                        <strong>💡 نکته کلیدی:</strong>
                        وقتی <code>AddAuthentication()</code> بدون پارامتر فراخوانی می‌شود و سپس اولین Scheme (<code>XApiKey</code>) ثبت می‌گردد،
                        ASP.NET Core به‌صورت خودکار <code>XApiKey</code> را به‌عنوان <strong>DefaultScheme</strong> در نظر می‌گیرد.
                        این یعنی تمام درخواست‌ها (حتی آن‌هایی که Bearer Token دارند) ابتدا به <code>XApiKeyAuthenticationHandler</code> می‌روند
                        و چون Header <code>X-Api-Key</code> وجود ندارد، <code>NoResult</code> برمی‌گردانند.
                    </div>

                    <div class="flow-diagram">
                        <div style="margin-bottom: 15px; font-weight: 700; color: var(--primary);">جریان فعلی (معیوب):</div>
                        <span class="flow-step">درخواست با Bearer Token</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step error">DefaultScheme = XApiKey</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step error">NoResult (بدون Header)</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step error">401 Unauthorized ❌</span>
                    </div>

                    <div class="flow-diagram">
                        <div style="margin-bottom: 15px; font-weight: 700; color: var(--primary);">جریان مطلوب (پس از اصلاح):</div>
                        <span class="flow-step">درخواست</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step success">PolicyScheme (هوشمند)</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step">XApiKey یا LocalApi</span>
                        <span class="flow-arrow">→</span>
                        <span class="flow-step success">200 OK ✓</span>
                    </div>
                </div>
            </div>

            <!-- بخش ۳: راه‌حل گام ۱ -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۳</div>
                    <div class="section-title">
                        <h3>گام ۱ — اصلاح AddXIdentityServerAuthentication با PolicyScheme</h3>
                        <div class="subtitle">Step 1: Fix Authentication Registration with PolicyScheme</div>
                    </div>
                </div>
                <div class="section-content">
                    <div class="step-card critical">
                        <div class="step-badge critical">حیاتی — فایل: xIds/DI/XDIHelperExtension.cs</div>
                        <h4>توضیح:</h4>
                        <p>
                            باید از <code>AddPolicyScheme</code> استفاده کنیم تا یک Scheme هوشمند بسازیم که بر اساس
                            وجود Header <code>X-Api-Key</code> در درخواست، Scheme مناسب را انتخاب کند.
                            همچنین DefaultScheme و DefaultChallengeScheme باید به‌درستی تنظیم شوند.
                        </p>
                    </div>

                    <p><strong>کد اصلاح‌شده کامل:</strong></p>
                    <div class="code-block"><span class="comment">// xIds/DI/XDIHelperExtension.cs</span>
<span class="comment">// متد: AddXIdentityServerAuthentication</span>

<span class="keyword">public static void</span> AddXIdentityServerAuthentication(
    <span class="keyword">this</span> IServiceCollection services,
    IConfiguration configuration,
    <span class="keyword">bool</span> addApiKeyAuthentication = <span class="keyword">false</span>
)
{
    <span class="comment">// افزودنی‌های مورد نیاز</span>
    services.AddXIdentityResourceConfiguration(configuration);

    <span class="comment">// ═══════════════════════════════════════════════════════</span>
    <span class="comment">// ثبت XApiKey Scheme (قبل از هر چیز دیگر)</span>
    <span class="comment">// ═══════════════════════════════════════════════════════</span>
    <span class="keyword">if</span> (addApiKeyAuthentication)
    {
        services.AddAuthentication()
            .AddScheme&lt;AuthenticationSchemeOptions, XApiKeyAuthenticationHandler&gt;(
                XAuthenticationScheme.XApiKey.GetStringValue(),
                options =&gt; { });
    }

    <span class="comment">// ═══════════════════════════════════════════════════════</span>
    <span class="comment">// تعریف PolicyScheme هوشمند برای مسیریابی درخواست‌ها</span>
    <span class="comment">// ═══════════════════════════════════════════════════════</span>
    <span class="keyword">var</span> smartSchemeName = <span class="string">"SmartAuthScheme"</span>;

    services.AddAuthentication(options =&gt;
    {
        <span class="comment">// DefaultScheme = PolicyScheme هوشمند</span>
        options.DefaultScheme = smartSchemeName;
        options.DefaultAuthenticateScheme = smartSchemeName;
        options.DefaultChallengeScheme = smartSchemeName;
    })
    .AddPolicyScheme(smartSchemeName, <span class="string">"Smart Authentication Scheme"</span>, options =&gt;
    {
        options.ForwardDefaultSelector = context =&gt;
        {
            <span class="comment">// بررسی وجود Header X-Api-Key</span>
            <span class="keyword">var</span> apiKeyHeader = XHeader.ApiKey.GetStringValue();
            <span class="keyword">if</span> (context.Request.Headers.ContainsKey(apiKeyHeader))
            {
                <span class="keyword">return</span> XAuthenticationScheme.XApiKey.GetStringValue();
            }

            <span class="comment">// در غیر این صورت، از LocalApi (IdentityServer) استفاده کن</span>
            <span class="keyword">return</span> XAuthentication.IDENTITY_SERVER_LOCAL_API;
        };
    })
    .AddJwtBearer(XAuthenticationScheme.XToken.GetStringValue(), options =&gt;
    {
        options.Authority = configuration
            .GetSection(<span class="string">"IdentityResourceConfiguration:Authority"</span>).Value;
        options.TokenValidationParameters.ValidateAudience = <span class="keyword">false</span>;
        options.TokenValidationParameters.ValidTypes = <span class="keyword">new</span>[] { <span class="string">"at+jwt"</span> };
    })
    .AddOAuth2Introspection(XAuthenticationScheme.XIntrospection.GetStringValue(), options =&gt;
    {
        <span class="keyword">var</span> identityConfig = configuration.GetXIdentityResourceConfiguration();
        options.Authority = identityConfig.Authority;
        options.ClientId = identityConfig.ApiName;
        options.ClientSecret = identityConfig.ClientSecret;
    })
    .AddLocalApi();
}</div>

                    <div class="success-box">
                        <strong>✅ چرا این راه‌حل کار می‌کند؟</strong>
                        <ul style="padding-right: 20px; margin-top: 10px;">
                            <li><code>PolicyScheme</code> به‌عنوان DefaultScheme عمل می‌کند و بر اساس Header تصمیم می‌گیرد.</li>
                            <li>اگر <code>X-Api-Key</code> وجود داشته باشد → به <code>XApiKeyAuthenticationHandler</code> حواله می‌دهد.</li>
                            <li>در غیر این صورت → به <code>LocalApi</code> (IdentityServer) حواله می‌دهد.</li>
                            <li>هیچ‌گاه Scheme اشتباه انتخاب نمی‌شود.</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- بخش ۴: راه‌حل گام ۲ -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۴</div>
                    <div class="section-title">
                        <h3>گام ۲ — اصلاح LocalApi Policy برای پذیرش XApiKey</h3>
                        <div class="subtitle">Step 2: Fix LocalApi Policy to Accept XApiKey</div>
                    </div>
                </div>
                <div class="section-content">
                    <div class="step-card important">
                        <div class="step-badge important">مهم — فایل: xIds/DI/XDIHelperExtension.cs</div>
                        <h4>توضیح:</h4>
                        <p>
                            در متد <code>AddXAuthorization</code>، Policy <code>LocalApi.PolicyName</code>
                            فقط Scheme <code>IdentityServerAccessToken</code> را قبول می‌کند.
                            باید این Policy را اصلاح کنیم تا <code>XApiKey</code> را هم بپذیرد.
                        </p>
                    </div>

                    <div class="code-block"><span class="comment">// xIds/DI/XDIHelperExtension.cs</span>
<span class="comment">// متد: AddXAuthorization</span>

<span class="keyword">public static void</span> AddXAuthorization(
    <span class="keyword">this</span> IServiceCollection services,
    IDictionary&lt;<span class="keyword">string</span>, AuthorizationPolicy&gt; policies = <span class="keyword">null</span>
)
{
    services.AddAuthorization(options =&gt;
    {
        <span class="comment">// ... کدهای قبلی برای policies و xPolicies ...</span>

        <span class="comment">// ═══════════════════════════════════════════════════════</span>
        <span class="comment">// اصلاح LocalApi Policy برای پذیرش هر دو Scheme</span>
        <span class="comment">// ═══════════════════════════════════════════════════════</span>
        options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =&gt;
        {
            policy.AddAuthenticationSchemes(<span class="keyword">new</span>[]
            {
                IdentityServerConstants.LocalApi.AuthenticationScheme,
                XAuthenticationScheme.XApiKey.GetStringValue()  <span class="comment">// ← اضافه شد</span>
            });
            policy.RequireAuthenticatedUser();
        });
    });

    services.AddSingleton&lt;IAuthorizationHandler, RequiredRolesHandler&gt;();
}</div>

                    <div class="info-box">
                        <strong>💡 نکته:</strong>
                        با این اصلاح، Endpointهایی که <code>[Authorize(LocalApi.PolicyName)]</code> دارند،
                        هم با Bearer Token و هم با X-Api-Key قابل دسترسی خواهند بود.
                    </div>
                </div>
            </div>

            <!-- بخش ۵: راه‌حل گام ۳ -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۵</div>
                    <div class="section-title">
                        <h3>گام ۳ — بررسی و اصلاح Swagger Security Definition</h3>
                        <div class="subtitle">Step 3: Verify Swagger Security Configuration</div>
                    </div>
                </div>
                <div class="section-content">
                    <div class="step-card">
                        <div class="step-badge">بررسی — فایل: xCommons/Extensions/DIExtensions.cs</div>
                        <h4>توضیح:</h4>
                        <p>
                            در کد فعلی <code>AddXSwaggerGenOptions</code>، Security Definition برای XApiKey
                            به‌درستی تعریف شده است. اما باید مطمئن شویم که <code>addXApiKeyAuthorization</code>
                            در فراخوانی <code>AddXSwagger</code> مقدار <code>true</code> دارد.
                        </p>
                    </div>

                    <p><strong>بررسی Startup.cs:</strong></p>
                    <div class="code-block"><span class="comment">// xIds/Startup.cs — ConfigureServices</span>

<span class="comment">// ثبت Swagger — مطمئن شوید پارامترها درست هستند</span>
<span class="keyword">var</span> xmlFile = $<span class="string">"{Assembly.GetExecutingAssembly().GetName().Name}.xml"</span>;
<span class="keyword">var</span> xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

services.AddXSwagger(
    Configuration,
    xmlFilePath: xmlPath,
    addRequiredXPoweredFilter: <span class="keyword">true</span>,
    addXTokenAuthorization: <span class="keyword">true</span>,
    addXApiKeyAuthorization: <span class="keyword">true</span>,     <span class="comment">// ← باید true باشد</span>
    addDefaultValueFilter: <span class="keyword">true</span>
);</div>

                    <p><strong>خروجی مورد انتظار در Swagger UI:</strong></p>
                    <div class="highlight-box">
                        <strong>🔑 در Swagger UI باید دو دکمه "Authorize" ببینید:</strong>
                        <ul style="padding-right: 20px; margin-top: 10px;">
                            <li><strong>accessToken:</strong> برای Bearer Token (مقدار: <code>Bearer {token}</code>)</li>
                            <li><strong>X-Api-Key:</strong> برای API Key (مقدار: <code>xapp_xxxxxxxxxxxx</code>)</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- بخش ۶: راه‌حل گام ۴ -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۶</div>
                    <div class="section-title">
                        <h3>گام ۴ — اصلاح XApiKeyAuthenticationHandler</h3>
                        <div class="subtitle">Step 4: Verify XApiKeyAuthenticationHandler</div>
                    </div>
                </div>
                <div class="section-content">
                    <div class="step-card">
                        <div class="step-badge">بررسی — فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs</div>
                        <h4>توضیح:</h4>
                        <p>
                            Handler فعلی به‌درستی پیاده‌سازی شده است. فقط یک نکته مهم:
                            مطمئن شوید که <code>ValidateApiKey</code> در <code>XApplicationProvider</code>
                            مقدار <code>requiredScope</code> را به‌درستی بررسی می‌کند.
                        </p>
                    </div>

                    <p><strong>کد فعلی Handler (صحیح است):</strong></p>
                    <div class="code-block"><span class="comment">// xIds/Providers/XApiKeyAuthenticationHandler.cs</span>
<span class="keyword">protected override async</span> Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
{
    <span class="comment">// ۱. استخراج API Key از Header</span>
    <span class="keyword">var</span> apiKeyHeader = HeaderName;  <span class="comment">// "X-Api-Key"</span>
    <span class="keyword">if</span> (!Request.Headers.ContainsKey(apiKeyHeader))
        <span class="keyword">return</span> AuthenticateResult.NoResult();

    <span class="keyword">var</span> apiKey = Request.Headers[apiKeyHeader].ToString();
    <span class="keyword">if</span> (apiKey.IsNullOrEmpty())
        <span class="keyword">return</span> AuthenticateResult.NoResult();

    <span class="comment">// ۲. استخراج Client IP</span>
    <span class="keyword">var</span> clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();

    <span class="comment">// ۳. اعتبارسنجی API Key</span>
    <span class="keyword">var</span> validationResult = <span class="keyword">await</span> applicationProvider.ValidateApiKey(
        apiKey: apiKey,
        clientIP: clientIP
    );

    <span class="keyword">if</span> (validationResult.Errors.HasChild())
    {
        <span class="keyword">var</span> message = validationResult.Errors.ToListString(<span class="string">'\n'</span>);
        <span class="keyword">return</span> AuthenticateResult.Fail(message);
    }

    <span class="comment">// ۴. ساخت Claims</span>
    <span class="keyword">var</span> claims = <span class="keyword">new</span> List&lt;Claim&gt; {
        <span class="keyword">new</span>(ClaimTypes.Name, validationResult.OwnerId),
        <span class="keyword">new</span>(JwtClaimTypes.Subject, validationResult.OwnerId),
        <span class="keyword">new</span>(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
        <span class="keyword">new</span>(XCustomClaims.AuthType, <span class="string">"apikey"</span>),
    };

    <span class="comment">// ۵. اضافه کردن Scopeها</span>
    <span class="keyword">if</span> (validationResult.Scopes != <span class="keyword">null</span>)
    {
        <span class="keyword">foreach</span> (<span class="keyword">var</span> scope <span class="keyword">in</span> validationResult.Scopes)
        {
            claims.Add(<span class="keyword">new</span> Claim(JwtClaimTypes.Scope, scope));
        }
    }

    <span class="comment">// ۶. ساخت Principal و Ticket</span>
    <span class="keyword">var</span> identity = <span class="keyword">new</span> ClaimsIdentity(claims, Scheme.Name);
    <span class="keyword">var</span> principal = <span class="keyword">new</span> ClaimsPrincipal(identity);
    <span class="keyword">var</span> ticket = <span class="keyword">new</span> AuthenticationTicket(principal, Scheme.Name);

    <span class="keyword">return</span> AuthenticateResult.Success(ticket);
}</div>

                    <div class="success-box">
                        <strong>✅ وضعیت Handler:</strong>
                        کد فعلی Handler صحیح است و نیازی به تغییر ندارد.
                        فقط مطمئن شوید که <code>validationResult.Scopes</code> مقادیر صحیح
                        (<code>read</code>, <code>write</code>, <code>admin</code>, <code>manage</code>)
                        را برمی‌گرداند.
                    </div>
                </div>
            </div>

            <!-- بخش ۷: تست در Swagger -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۷</div>
                    <div class="section-title">
                        <h3>گام ۵ — راهنمای تست در Swagger UI</h3>
                        <div class="subtitle">Step 5: Testing Guide in Swagger UI</div>
                    </div>
                </div>
                <div class="section-content">
                    <p><strong>مراحل تست گام‌به‌گام:</strong></p>

                    <div class="step-card">
                        <div class="step-badge">تست ۱</div>
                        <h4>ساخت Application و API Key</h4>
                        <p>ابتدا یک Application بسازید و سپس یک API Key برای آن ایجاد کنید:</p>
                        <div class="code-block"><span class="comment"># ۱. ساخت Application (با Bearer Token احراز هویت کنید)</span>
POST /Applications
Content-Type: application/json
Authorization: Bearer {access_token}
X-PoweredBy: {xPoweredValue}

{
  "name": "TestApp",
  "description": "Test Application",
  "type": 0
}

<span class="comment"># ۲. ساخت API Key (با Bearer Token)</span>
POST /Applications/{applicationId}/ApiKeys/Create
Content-Type: application/json
Authorization: Bearer {access_token}
X-PoweredBy: {xPoweredValue}

{
  "scopes": ["read", "write", "manage"],
  "rateLimit": 60,
  "expirationMinutes": 43200,
  "allowedIPs": ["127.0.0.1", "::1"]
}

<span class="comment"># پاسخ شامل plainKey است — آن را ذخیره کنید!</span>
<span class="comment"># مثال: xapp_abc123def456...</span></div>
                    </div>

                    <div class="step-card">
                        <div class="step-badge">تست ۲</div>
                        <h4>استفاده از API Key در Swagger UI</h4>
                        <p>در Swagger UI:</p>
                        <ol style="padding-right: 20px; margin-top: 10px;">
                            <li>روی دکمه <strong>"Authorize"</strong> (بالا سمت راست) کلیک کنید.</li>
                            <li>در بخش <strong>"X-Api-Key"</strong>، کلید API دریافتی را وارد کنید.</li>
                            <li>روی <strong>"Authorize"</strong> و سپس <strong>"Close"</strong> کلیک کنید.</li>
                            <li>Endpoint <code>GET /Account/Test/HiApiKeyAccess</code> را پیدا کنید.</li>
                            <li>روی <strong>"Try it out"</strong> و سپس <strong>"Execute"</strong> کلیک کنید.</li>
                        </ol>
                    </div>

                    <div class="step-card">
                        <div class="step-badge">تست ۳</div>
                        <h4>نتایج مورد انتظار</h4>
                        <table>
                            <thead>
                                <tr>
                                    <th>سناریو</th>
                                    <th>پاسخ مورد انتظار</th>
                                    <th>وضعیت</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>API Key معتبر + Scope کافی</td>
                                    <td><code>200 OK</code> — "Hi ApiKey Access, is Passed ..."</td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                                <tr>
                                    <td>API Key نامعتبر</td>
                                    <td><code>401 Unauthorized</code> — "ApiKey not found"</td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                                <tr>
                                    <td>API Key منقضی‌شده</td>
                                    <td><code>401</code> — "ApiKey is Expired"</td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                                <tr>
                                    <td>Scope ناکافی</td>
                                    <td><code>403 Forbidden</code></td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                                <tr>
                                    <td>IP غیرمجاز</td>
                                    <td><code>401</code> — "Client IP not Allowed"</td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                                <tr>
                                    <td>Rate Limit رد شده</td>
                                    <td><code>401</code> — "ApiKey Rate Limit Reached"</td>
                                    <td style="color: var(--success); font-weight: 600;">✓ صحیح</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="step-card">
                        <div class="step-badge">تست ۴</div>
                        <h4>تست با cURL (برای اطمینان بیشتر)</h4>
                        <div class="code-block"><span class="comment"># تست مستقیم با cURL</span>
curl -X GET "https://localhost:5001/Account/Test/HiApiKeyAccess" \
  -H "X-Api-Key: xapp_your_api_key_here" \
  -H "X-PoweredBy: your_powered_value" \
  -k

<span class="comment"># پاسخ مورد انتظار:</span>
<span class="comment"># "Hi ApiKey Access, is Passed ..."</span></div>
                    </div>
                </div>
            </div>

            <!-- بخش ۸: چک‌لیست نهایی -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۸</div>
                    <div class="section-title">
                        <h3>چک‌لیست نهایی اصلاحات</h3>
                        <div class="subtitle">Final Checklist</div>
                    </div>
                </div>
                <div class="section-content">
                    <table>
                        <thead>
                            <tr>
                                <th>ردیف</th>
                                <th>فایل</th>
                                <th>تغییر</th>
                                <th>اولویت</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>۱</td>
                                <td><code>xIds/DI/XDIHelperExtension.cs</code></td>
                                <td>بازنویسی <code>AddXIdentityServerAuthentication</code> با <code>PolicyScheme</code></td>
                                <td style="color: var(--danger); font-weight: 700;">🔴 حیاتی</td>
                            </tr>
                            <tr>
                                <td>۲</td>
                                <td><code>xIds/DI/XDIHelperExtension.cs</code></td>
                                <td>اصلاح <code>AddXAuthorization</code> — افزودن XApiKey به LocalApi Policy</td>
                                <td style="color: var(--danger); font-weight: 700;">🔴 حیاتی</td>
                            </tr>
                            <tr>
                                <td>۳</td>
                                <td><code>xIds/Startup.cs</code></td>
                                <td>بررسی <code>addXApiKeyAuthorization: true</code> در <code>AddXSwagger</code></td>
                                <td style="color: var(--warning); font-weight: 700;">🟡 بررسی</td>
                            </tr>
                            <tr>
                                <td>۴</td>
                                <td><code>xIds/Providers/XApiKeyAuthenticationHandler.cs</code></td>
                                <td>تأیید صحت کد (نیاز به تغییر ندارد)</td>
                                <td style="color: var(--success); font-weight: 700;">🟢 تأیید</td>
                            </tr>
                            <tr>
                                <td>۵</td>
                                <td><code>xIdentityHelper/XAuthorizationHelper.cs</code></td>
                                <td>تأیید Policyهای ApiKey (نیاز به تغییر ندارد)</td>
                                <td style="color: var(--success); font-weight: 700;">🟢 تأیید</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- بخش ۹: جمع‌بندی -->
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۹</div>
                    <div class="section-title">
                        <h3>جمع‌بندی و نکات پایانی</h3>
                        <div class="subtitle">Conclusion</div>
                    </div>
                </div>
                <div class="section-content">
                    <p>
                        ریشه اصلی مشکل تست XApiKey در Swagger، <strong>نحوه ثبت Authentication Schemes</strong>
                        و <strong>عدم استفاده از PolicyScheme هوشمند</strong> بود. با اعمال اصلاحات گام ۱ و ۲،
                        سیستم احراز هویت به‌صورت خودکار بر اساس Header درخواست، Scheme مناسب را انتخاب می‌کند
                        و Swagger UI می‌تواند به‌درستی با API Key احراز هویت نماید.
                    </p>

                    <div class="success-box">
                        <strong>🎯 نتیجه نهایی:</strong>
                        <ul style="padding-right: 20px; margin-top: 10px;">
                            <li>درخواست‌های دارای Header <code>X-Api-Key</code> → به <code>XApiKeyAuthenticationHandler</code> هدایت می‌شوند.</li>
                            <li>درخواست‌های دارای Header <code>Authorization: Bearer</code> → به <code>LocalApi</code> (IdentityServer) هدایت می‌شوند.</li>
                            <li>Swagger UI هر دو روش احراز هویت را پشتیبانی می‌کند.</li>
                            <li>Policyهای <code>ApiKeyAccess</code>, <code>ApiKeyReadAccess</code> و غیره به‌درستی کار می‌کنند.</li>
                        </ul>
                    </div>

                    <div class="highlight-box">
                        <strong>⚠️ نکته مهم:</strong>
                        پس از اعمال تغییرات، حتماً پروژه را <strong>Clean</strong> و <strong>Rebuild</strong> کنید
                        و سپس Swagger UI را با <strong>Ctrl+F5</strong> رفرش نمایید تا تغییرات Security Definition
                        به‌درستی اعمال شوند.
                    </div>
                </div>
            </div>

        </div>

        <footer class="document-footer">
            <div class="footer-brand">تهیه شده توسط: هادی خزاعی اصل | شرکت فن آوران ساحر علم</div>
            <div class="footer-divider"></div>
            <div>تاریخ انتشار: ۲۰ مهر ۱۴۰۵ | نسخه: ۲.۰ | طبقه‌بندی: داخلی — فنی</div>
        </footer>
    </div>
</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_560a6d9a-eefe-4125-9b3d-6ce0264876cb.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>معرفی ساختار محصول هوش مصنوعی سازمانی | رایان پرداز کاوش</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: PROD-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">PRODUCT ARCHITECTURE OVERVIEW</span>
      <h1>معرفی ساختار محصول هوش مصنوعی سازمانی</h1>
      <h2>محصول در دست توسعه — رایان پرداز کاوش</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>کارفرمای محترم،</strong><br>
      این مستند به معرفی ساختار محصولی می‌پردازد که در شرکت رایان پرداز کاوش <strong>در دست توسعه</strong> است. تمرکز این مستند، معرفی قابلیت‌های محصول بر اساس معماری آن است. هدف، ارائه تصویری شفاف از ساختار محصول و قابلیت‌هایی است که می‌تواند به نیازهای سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. بدیهی است که شناخت دقیق نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگو و دریافت بازخورد از تیم فنی آن سازمان است و این مستند صرفاً نقطه شروع این گفتگو محسوب می‌شود.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>خلاصه اجرایی</h3>
          <div class="subtitle">Executive Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>شرکت رایان پرداز کاوش در حال توسعه یک سامانه هوش مصنوعی سازمانی ایجنت‌محور است که معماری آن بر پایه شش لایه اصلی و دو محور عرضی طراحی شده است. این محصول با تمرکز بر چهار محور کلیدی در حال توسعه است: ایجنت قابل‌آزمون، توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، و کنترل دسترسی لایه‌ای تا سطح ابزار ایجنت.</p>

        <p>این مستند قصد دارد ساختار محصول و قابلیت‌های پیش‌بینی‌شده در معماری آن را به‌صورت شفاف معرفی کند. سازمان‌هایی که با داده‌های حساس، اسناد سازمانی و فرایندهای پیچیده سروکار دارند، می‌توانند از این ساختار برای پاسخ به نیازهای خود بهره ببرند. شناخت دقیق نیازمندی‌های هر سازمان و تطبیق محصول با آن، گام بعدی این همکاری خواهد بود.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">معماری<br>شش‌لایه</div>
            <div class="stat-label">پایه طراحی محصول</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">MCP<br>محور</div>
            <div class="stat-label">توسعه‌پذیری نامحدود</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">مدل<br>لوکال</div>
            <div class="stat-label">حاکمیت داده و محرمانگی</div>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نکته کلیدی:</strong> این مستند، معرفی <strong>ساختار محصول در دست توسعه</strong> است. قابلیت‌های مطرح‌شده بر اساس معماری محصول تعریف شده‌اند و می‌توانند مبنای گفتگوی فنی با تیم ارزیابی کارفرما قرار گیرند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>معماری محصول در دست توسعه</h3>
          <div class="subtitle">Product Architecture Under Development</div>
        </div>
      </div>
      <div class="section-content">
        <p>محصول در دست توسعه رایان پرداز کاوش، بر پایه یک معماری لایه‌ای طراحی شده است که جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری را در تمام لایه‌ها تضمین می‌کند. این معماری، مبنای توسعه قابلیت‌های محصول قرار گرفته است.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه معماری</th>
              <th>قابلیت‌های پیش‌بینی‌شده در محصول</th>
              <th>وضعیت توسعه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه تعامل</td>
              <td>رابط وب سازمانی، نسخه دسکتاپ، درگاه API</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه کنترل دسترسی</td>
              <td>احراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه ارکستراسیون (هسته ایجنت)</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه هوش و مدل‌ها</td>
              <td>درگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه داده و منابع</td>
              <td>منابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>لایه خروجی و گزارش</td>
              <td>تولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>محور عرضی حاکمیت داده</td>
              <td>سیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی</td>
              <td>در دست توسعه</td>
            </tr>
            <tr>
              <td>محور عرضی مشاهده‌پذیری</td>
              <td>متریک و ردیابی مصرف، زمان پاسخ، نرخ خطا</td>
              <td>در دست توسعه</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> معماری فوق، مبنای توسعه محصول قرار گرفته است. قابلیت‌های هر لایه در حال پیاده‌سازی و تکمیل هستند و در جلسه فنی، جزئیات بیشتر و زمان‌بندی توسعه هر بخش قابل ارائه خواهد بود. این ساختار به‌گونه‌ای طراحی شده که امکان تطبیق با نیازمندی‌های سازمان‌های مختلف را فراهم کند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>ساختار محصول: سامانه ایجنت‌محور سازمانی</h3>
          <div class="subtitle">Product Structure: Enterprise Agentic System</div>
        </div>
      </div>
      <div class="section-content">
        <p>هسته محصول در دست توسعه، یک <strong>موتور ایجنت</strong> است که بر اساس معماری تعریف‌شده، هدف کاربر را به مراحل اجرایی تبدیل می‌کند، برای هر مرحله ابزار یا منبع مناسب را از میان فهرست مجاز انتخاب می‌کند، عملیات را اجرا می‌کند، نتیجه را ارزیابی کرده و در صورت نیاز مسیر را اصلاح می‌کند. این ساختار، محصول را از یک سیستم پرسش‌وپاسخ ساده متمایز می‌سازد و امکان پاسخ به نیازهای پیچیده سازمانی را فراهم می‌آورد.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه معماری</th>
              <th>قابلیت پیش‌بینی‌شده در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه تعامل</td>
              <td>رابط وب سازمانی، نسخه دسکتاپ، درگاه API</td>
            </tr>
            <tr>
              <td>لایه کنترل دسترسی</td>
              <td>احراز هویت، مدیریت نشست، موتور مجوزها، مدیریت نقش‌ها</td>
            </tr>
            <tr>
              <td>لایه ارکستراسیون (هسته ایجنت)</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
            </tr>
            <tr>
              <td>لایه هوش و مدل‌ها</td>
              <td>درگاه مدل‌ها، مدیریت مدل، بازیابی و تقویت (RAG)، حافظه و زمینه</td>
            </tr>
            <tr>
              <td>لایه داده و منابع</td>
              <td>منابع دانش، مدیریت فایل، سرویس‌های خارجی، ابزارهای عملیاتی</td>
            </tr>
            <tr>
              <td>لایه خروجی و گزارش</td>
              <td>تولید گزارش، مبدل قالب (Word/Excel)، داشبورد مصرف</td>
            </tr>
            <tr>
              <td>محور عرضی حاکمیت داده</td>
              <td>سیاست‌گذار داده، ممیزی و لاگ، سنسور محرمانگی</td>
            </tr>
            <tr>
              <td>محور عرضی مشاهده‌پذیری</td>
              <td>متریک و ردیابی مصرف، زمان پاسخ، نرخ خطا</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> قابلیت‌های فوق بر اساس معماری محصول تعریف شده‌اند و مبنای توسعه آن قرار گرفته‌اند. این ساختار می‌تواند در جلسه فنی با تیم ارزیابی کارفرما بررسی و با نیازمندی‌های سازمان تطبیق داده شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>توسعه‌پذیری از طریق MCP</h3>
          <div class="subtitle">Extensibility via MCP</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>MCP (Model Context Protocol)</strong> در ساختار محصول ما به‌عنوان لایه استاندارد اتصال ایجنت به ابزارها و منابع در نظر گرفته شده است. بر اساس این معماری، هر قابلیت جدید می‌تواند در قالب یک <strong>MCP Server</strong> تعریف شود و به سامانه اضافه گردد.</p>

        <div class="highlight-box">
          <strong>تأکید معماری:</strong> از منظر ساختار محصول، <strong>محدودیت معماری برای افزودن قابلیت از طریق MCP وجود ندارد</strong>. هر MCP Server جدید در Tool Registry ثبت می‌شود و در صورت وجود مجوز، در اختیار ایجنت قرار می‌گیرد. این رویکرد، محصول را قادر می‌سازد تا با نیازهای متنوع سازمانی هم‌راستا شود.
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نمونه قابلیت‌های قابل افزودن با MCP:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>حوزه سازمانی</th>
              <th>نمونه MCP Server</th>
              <th>کاربرد بالقوه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>منابع انسانی</td>
              <td>HR MCP</td>
              <td>مرخصی، آموزش، اطلاعات پرسنلی</td>
            </tr>
            <tr>
              <td>مالی و بودجه</td>
              <td>Finance MCP</td>
              <td>بودجه، هزینه، فاکتور، مراکز هزینه</td>
            </tr>
            <tr>
              <td>تولید و انبار</td>
              <td>Production MCP</td>
              <td>موجودی، سفارش، فرمولاسیون</td>
            </tr>
            <tr>
              <td>مدیریت اسناد</td>
              <td>DMS MCP</td>
              <td>جستجو و بازیابی اسناد سازمانی</td>
            </tr>
            <tr>
              <td>پایگاه داده</td>
              <td>DB MCP</td>
              <td>پرسش کنترل‌شده از داده‌ها</td>
            </tr>
            <tr>
              <td>فایل و پوشه</td>
              <td>File MCP</td>
              <td>دسترسی کنترل‌شده به فایل‌های محلی/شبکه</td>
            </tr>
            <tr>
              <td>همکاری سازمانی</td>
              <td>Collaboration MCP</td>
              <td>ایمیل، تقویم، اعلان</td>
            </tr>
            <tr>
              <td>سامانه‌های سازمانی</td>
              <td>ERP/CRM MCP</td>
              <td>یکپارچه‌سازی فرایندهای سازمانی</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> ساختار محصول از طریق MCP، امکان توسعه قابلیت‌ها را فراهم می‌کند. هر ابزار جدید، سرویس جدید یا منبع داده جدید، با تعریف یک MCP Server و ثبت در Tool Registry، به قابلیت‌های ایجنت اضافه می‌شود. این رویکرد می‌تواند پاسخگوی نیازهای متنوع سازمانی باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>حاکمیت داده و رویکرد مدل‌های لوکال</h3>
          <div class="subtitle">Data Governance & Local Model Approach</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، <strong>حاکمیت داده</strong> به‌عنوان یک محور عرضی در تمام لایه‌ها در نظر گرفته شده است. برای سازمان‌هایی که با داده‌های حساس مانند فرمولاسیون، اطلاعات مشتریان، فرایندهای تولید و اسناد سازمانی سروکار دارند، استفاده از مدل‌های آنلاین می‌تواند با حاکمیت داده و محرمانگی در تناقض باشد؛ زیرا داده از مرز سازمان خارج می‌شود و کنترل کامل بر ذخیره‌سازی، پردازش و استفاده ثانویه از آن وجود ندارد.</p>

        <div class="warning-box">
          <strong>⚠️ ریسک مدل‌های آنلاین برای داده‌های حساس:</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>خروج داده‌های حساس از مرز سازمان</li>
            <li>عدم کنترل بر ذخیره‌سازی داده در سرورهای خارجی</li>
            <li>احتمال استفاده از داده برای آموزش مدل‌های بعدی</li>
            <li>وابستگی به اینترنت بین‌الملل و ریسک قطع سرویس</li>
            <li>عدم انطباق با سیاست‌های محرمانگی سازمانی</li>
          </ul>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">رویکرد پیش‌بینی‌شده در ساختار محصول:</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>تصمیم</th>
              <th>رویکرد در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>مدل پیش‌فرض</td>
              <td>مدل لوکال از طریق Model Gateway و Ollama/On-Prem</td>
            </tr>
            <tr>
              <td>داده حساس</td>
              <td>عدم خروج از مرز سازمان</td>
            </tr>
            <tr>
              <td>مدل آنلاین</td>
              <td>فقط برای داده غیرحساس، با تأیید سیاست و به‌صورت استثنا</td>
            </tr>
            <tr>
              <td>آموزش مدل</td>
              <td>عدم استفاده از داده سازمان برای آموزش مدل‌های خارجی</td>
            </tr>
            <tr>
              <td>استقرار</td>
              <td>On-Premise با امکان عملکرد در قطع اینترنت بین‌الملل</td>
            </tr>
            <tr>
              <td>ممیزی</td>
              <td>ثبت کامل مسیر داده و تصمیمات ایجنت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> در ساختار محصول، حاکمیت داده به‌عنوان یک سیاست اجرایی در نظر گرفته شده است. مدل لوکال، پیش‌فرض است و داده حساس سازمان، از مرز آن خارج نمی‌شود. این رویکرد می‌تواند برای سازمان‌هایی با الزامات محرمانگی بالا مناسب باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>کنترل دسترسی ایجنت و محدودسازی ابزارهای تصمیم‌گیرنده</h3>
          <div class="subtitle">Agent Access Control & Tool Restriction</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، کنترل دسترسی تنها به رابط کاربری محدود نمی‌شود. <strong>موتور مجوزها</strong> پیش از فراخوانی ایجنت، فهرست مجاز کاربر را تعیین می‌کند و این فهرست به <strong>ایجنت تصمیم‌گیرنده</strong> ابلاغ می‌شود:</p>

        <div class="comparison-grid">
          <div class="comparison-card recommended">
            <span class="card-badge">در ساختار محصول ✓</span>
            <h4>فهرست مجاز کاربر</h4>
            <ul>
              <li><span>مدل‌های مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>منابع دانش مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>ابزارهای مجاز</span> <span class="value">تعریف‌شده</span></li>
              <li><span>سطح دسترسی</span> <span class="value">تا سطح رکورد</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">در ساختار محصول ✓</span>
            <h4>محدودسازی ایجنت</h4>
            <ul>
              <li><span>انتخاب‌گر ابزار</span> <span class="value">فقط از فهرست مجاز</span></li>
              <li><span>فراخوانی مدل</span> <span class="value">فقط مدل مجاز</span></li>
              <li><span>بازیابی RAG</span> <span class="value">فقط منابع مجاز</span></li>
              <li><span>نقاط تأیید</span> <span class="value">عملیات حساس</span></li>
            </ul>
          </div>
        </div>

        <p>این یعنی <strong>ایجنت تصمیم‌گیرنده</strong> نمی‌تواند ابزاری خارج از مجوز کاربر را فراخوانی کند، حتی اگر آن ابزار در Tool Registry ثبت شده باشد. این محدودسازی در سطح معماری اعمال می‌شود و توسط <strong>موتور مجوزها</strong> به ایجنت ابلاغ می‌گردد.</p>

        <div class="highlight-box">
          <strong>نکته حساس:</strong> ساختار محصول از ترکیب <strong>RBAC</strong> (نقش‌محور) و <strong>ABAC</strong> (ویژگی‌محور) پشتیبانی می‌کند تا کنترل دسترسی را تا سطح رکورد، سند، واحد سازمانی و حتی فیلد اطلاعاتی ممکن سازد. این رویکرد می‌تواند برای سازمان‌هایی با ساختار دسترسی پیچیده مناسب باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>دفاع لایه‌ای برای حفظ محرمانگی</h3>
          <div class="subtitle">Layered Defense for Confidentiality</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ساختار محصول، برای جلوگیری از افشای اطلاعات، <strong>دفاع لایه‌ای</strong> در نظر گرفته شده است. این دفاع شامل شش نقطه مستقل است که هر یک از منظری متفاوت، محرمانگی را تضمین می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه</th>
              <th>کنترل</th>
              <th>هدف</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>لایه ۱</td>
              <td>احراز هویت و نشست</td>
              <td>تأیید هویت و سطح دسترسی فعال</td>
            </tr>
            <tr>
              <td>لایه ۲</td>
              <td>موتور مجوزها</td>
              <td>محدودسازی مدل، ابزار و منبع پیش از اجرا</td>
            </tr>
            <tr>
              <td>لایه ۳</td>
              <td>فهرست مجاز ابزار ایجنت</td>
              <td>جلوگیری از انتخاب ابزار غیرمجاز</td>
            </tr>
            <tr>
              <td>لایه ۴</td>
              <td>فیلتر بازیابی RAG</td>
              <td>بازیابی فقط از منابع مجاز کاربر</td>
            </tr>
            <tr>
              <td>لایه ۵</td>
              <td>سنسور محرمانگی خروجی</td>
              <td>جلوگیری از افشای اطلاعات در پاسخ نهایی</td>
            </tr>
            <tr>
              <td>لایه ۶</td>
              <td>ممیزی و لاگ</td>
              <td>ثبت و ردیابی تمام تصمیمات و دسترسی‌ها</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته حیاتی:</strong> لایه‌های <strong>۲ (موتور مجوزها)</strong> و <strong>۵ (سنسور محرمانگی)</strong> مستقل از هم هستند. حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود می‌شود. این رویکرد دفاع لایه‌ای، در ساختار محصول پیش‌بینی شده است تا محرمانگی اطلاعات در سطوح دسترسی مختلف تضمین شود.
        </div>

        <div class="success-box">
          <strong>✓ رویکرد ساختاری:</strong> دفاع لایه‌ای در محصول به‌گونه‌ای طراحی شده که پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت، پاسخ‌های متفاوت و متناسب با سطح دسترسی هر کاربر دریافت کنند. همچنین تلاش برای دور زدن مجوزها از طریق پرسش مستقیم، غیرمستقیم یا خلاصه‌سازی، در دو نقطه مستقل مسدود می‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>مثال جریان کار: یک درخواست، دو ایجنت</h3>
          <div class="subtitle">Workflow Example: One Request, Two Agents</div>
        </div>
      </div>
      <div class="section-content">
        <p>برای روشن‌تر شدن ساختار کنترل دسترسی در محصول، یک سناریوی نمونه را بررسی می‌کنیم. کارمندی درخواست می‌دهد:</p>

        <div class="quote-box">
          <p>«می‌خواهم در دوره تخصصی پلیمر در آبان شرکت کنم؛ هزینه آن از بودجه واحد پرداخت شود و مرخصی آموزشی هم ثبت شود.»</p>
          <div class="source">— درخواست نمونه واحد کارمند</div>
        </div>

        <p>این یک درخواست واحد است، اما برای پاسخ به آن به دو حوزه نیاز است: <strong>منابع انسانی</strong> و <strong>مالی</strong>. ساختار محصول، این درخواست را به‌صورت زیر پردازش می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>مرحله</th>
              <th>مسئول</th>
              <th>اقدام</th>
              <th>کنترل دسترسی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td>ایجنت مسیریاب</td>
              <td>تشخیص نیاز به HR و Finance</td>
              <td>فقط ابزارهای مجاز کاربر</td>
            </tr>
            <tr>
              <td>۲</td>
              <td>ایجنت منابع انسانی</td>
              <td>بررسی مرخصی و شرایط آموزش</td>
              <td>فقط رکورد HR خود کارمند و سیاست آموزش</td>
            </tr>
            <tr>
              <td>۳</td>
              <td>ایجنت مالی</td>
              <td>بررسی بودجه و هزینه دوره</td>
              <td>فقط بودجه مرکز هزینه واحد کاربر</td>
            </tr>
            <tr>
              <td>۴</td>
              <td>ترکیب نتایج</td>
              <td>تولید پاسخ نهایی</td>
              <td>سنسور محرمانگی خروجی</td>
            </tr>
            <tr>
              <td>۵</td>
              <td>تأیید انسانی</td>
              <td>اگر هزینه از سقف بیشتر باشد</td>
              <td>توقف و دریافت تأیید</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">نحوه اعمال کنترل دسترسی در این سناریو:</h4>

        <ul class="reference-list">
          <li>
            <strong>ایجنت منابع انسانی</strong>
            به ابزارهای مرخصی و آموزش دسترسی دارد، اما به حقوق، ارزیابی عملکرد یا پرونده سایر کارکنان دسترسی ندارد.
          </li>
          <li>
            <strong>ایجنت مالی</strong>
            به بودجه مرکز هزینه واحد کاربر دسترسی دارد، اما به فیش حقوقی یا اطلاعات مالی سایر واحدها دسترسی ندارد.
          </li>
          <li>
            <strong>در صورت عدم مجوز مالی</strong>
            اگر کاربر مجوز مالی نداشته باشد، ایجنت مالی پاسخ «عدم دسترسی» یا خروجی تجمیعی غیرمحرمانه ارائه می‌دهد.
          </li>
          <li>
            <strong>اتصال از طریق MCP</strong>
            هر دو ایجنت از طریق MCP به ابزارهای مجاز متصل می‌شوند و فهرست ابزار مجاز توسط موتور مجوزها تعیین می‌شود.
          </li>
          <li>
            <strong>ممیزی کامل</strong>
            تمام مراحل در سیستم ممیزی ثبت می‌شود و قابل ردیابی است.
          </li>
        </ul>

        <div class="info-box">
          <strong>💡 نتیجه مثال:</strong> ساختار محصول به‌گونه‌ای طراحی شده که یک درخواست واحد را میان چند ایجنت توزیع کند، بدون اینکه مرزهای محرمانگی نقض شود. هر ایجنت فقط به ابزارها و منابعی دسترسی دارد که کاربر مجاز است، و این محدودسازی در سطح معماری محصول اعمال می‌شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>قابلیت‌های محصول در پاسخ به نیازهای رایج سازمانی</h3>
          <div class="subtitle">Product Capabilities vs. Common Organizational Needs</div>
        </div>
      </div>
      <div class="section-content">
        <p>ساختار محصول در دست توسعه، قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. جدول زیر، این قابلیت‌ها را در کنار نیازهای رایج سازمانی نشان می‌دهد. بدیهی است که تطبیق دقیق با نیازمندی‌های اختصاصی هر سازمان، مستلزم گفتگوی فنی با تیم ارزیابی آن سازمان است.</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>نیاز رایج سازمانی</th>
              <th>قابلیت پیش‌بینی‌شده در ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>دستیار هوشمند و ایجنت تصمیم‌گیرنده</td>
              <td>موتور ایجنت با برنامه‌ریزی، انتخاب ابزار، اجرا، اصلاح و Human-in-the-loop</td>
            </tr>
            <tr>
              <td>مدیریت دسترسی کاربران و واحدهای سازمانی</td>
              <td>RBAC/ABAC، کنترل تا سطح رکورد، فهرست مجاز ابزار، دفاع لایه‌ای</td>
            </tr>
            <tr>
              <td>شفافیت مصرف و هزینه</td>
              <td>داشبورد مصرف، گزارش هزینه به تفکیک کاربر/مدل/ایجنت، درگاه API</td>
            </tr>
            <tr>
              <td>تعامل کاربری و تولید گزارش</td>
              <td>رابط وب/دسکتاپ، تحلیل فایل، خروجی Word/Excel، ارجاع به منبع</td>
            </tr>
            <tr>
              <td>حاکمیت داده و محرمانگی اطلاعات</td>
              <td>مدل لوکال، On-Premise، عدم خروج داده حساس، MCP کنترل‌شده</td>
            </tr>
            <tr>
              <td>پیاده‌سازی، آموزش و پشتیبانی</td>
              <td>نقشه راه فازبندی‌شده، مستندسازی، آموزش و پشتیبانی</td>
            </tr>
            <tr>
              <td>عملکرد پایدار و تاب‌آوری</td>
              <td>عملکرد در قطع اینترنت با مدل لوکال، SLA قابل تعریف، آمادگی پایلوت</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نتیجه:</strong> ساختار محصول به‌گونه‌ای طراحی شده که بتواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد. برای بررسی تطابق دقیق با نیازمندی‌های اختصاصی کارفرما، آماده دریافت و بررسی نیازمندی‌های تیم فنی هستیم.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>وضعیت توسعه محصول و گام بعدی</h3>
          <div class="subtitle">Development Status & Next Step</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>وضعیت فعلی:</strong> محصول در شرکت رایان پرداز کاوش بر پایه معماری شش‌لایه + دو محور عرضی، <strong>در دست توسعه</strong> است. فازهای توسعه محصول به‌صورت زیر سازمان‌دهی شده‌اند:</p>

        <div class="timeline">
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز A: هسته ایجنت و رابط پایه</h5>
              <p>درگاه مدل، موتور ایجنت، رابط کاربری، احراز هویت — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز B: ابزارها، RAG و منابع دانش</h5>
              <p>Tool Registry، MCP Client، RAG با ارجاع، مدیریت فایل — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز C: حاکمیت داده و کنترل دسترسی</h5>
              <p>موتور مجوزها، سنسور محرمانگی، ممیزی، سیاست‌گذار داده — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز D: گزارش، تأیید انسانی و مشاهده‌پذیری</h5>
              <p>تولید گزارش، مبدل قالب، Human-in-the-loop، داشبورد مصرف — در دست توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
          <div class="timeline-item">
            <div class="timeline-content">
              <h5>فاز E: Cross-Platform و آماده‌سازی محصول</h5>
              <p>نسخه دسکتاپ، موبایل، مدیریت مدل، استقرار On-Premise — در برنامه توسعه</p>
            </div>
            <div class="timeline-dot"></div>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام بعدی پیشنهادی:</h4>

        <ul class="reference-list">
          <li>
            <strong>برگزاری جلسه معرفی و گفتگوی فنی</strong>
            معرفی ساختار محصول و دریافت بازخورد از تیم فنی کارفرما
          </li>
          <li>
            <strong>دریافت نیازمندی‌های اختصاصی سازمان</strong>
            شناخت دقیق نیازهای کارفرما برای تطبیق محصول
          </li>
          <li>
            <strong>ارائه سناریوی نمونه Agent</strong>
            نمایش ساختار ایجنت بر اساس معماری محصول
          </li>
          <li>
            <strong>بررسی امکان اجرای پایلوت محدود</strong>
            شامل زمان، هزینه، پیش‌نیازها و معیارهای موفقیت
          </li>
          <li>
            <strong>ارائه پیشنهاد تجاری شفاف</strong>
            بر اساس دامنه همکاری و نیازمندی‌های سازمانی
          </li>
        </ul>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>جمع‌بندی و پیشنهاد نهایی</h3>
          <div class="subtitle">Final Summary & Recommendation</div>
        </div>
      </div>
      <div class="section-content">
        <p>این مستند، ساختار محصول هوش مصنوعی سازمانی در دست توسعه رایان پرداز کاوش را معرفی کرد. ویژگی‌های متمایز این ساختار:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ویژگی</th>
              <th>رویکرد ساختار محصول</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>معماری پایه</td>
              <td style="color: var(--success); font-weight: 600;">شش لایه + دو محور عرضی</td>
            </tr>
            <tr>
              <td>توسعه‌پذیری MCP</td>
              <td style="color: var(--success); font-weight: 600;">بدون محدودیت معماری</td>
            </tr>
            <tr>
              <td>حاکمیت داده</td>
              <td style="color: var(--success); font-weight: 600;">مدل لوکال (حاکمیت کامل)</td>
            </tr>
            <tr>
              <td>کنترل دسترسی ایجنت</td>
              <td style="color: var(--success); font-weight: 600;">تا سطح ابزار و رکورد</td>
            </tr>
            <tr>
              <td>دفاع محرمانگی</td>
              <td style="color: var(--success); font-weight: 600;">شش لایه مستقل</td>
            </tr>
            <tr>
              <td>وضعیت توسعه</td>
              <td style="color: var(--success); font-weight: 600;">در دست توسعه</td>
            </tr>
          </tbody>
        </table>

        <div class="conclusion-box">
          <h3>🎯 پیشنهاد نهایی</h3>
          <p>ساختار محصول در دست توسعه رایان پرداز کاوش، بر پایه معماری شش‌لایه + دو محور عرضی طراحی شده و قابلیت‌هایی را پیش‌بینی کرده است که می‌تواند به نیازهای رایج سازمان‌های صنعتی و دانش‌بنیان پاسخ دهد.</p>
          <p>توسعه‌پذیری از طریق MCP، حاکمیت داده با مدل‌های لوکال، کنترل دسترسی تا سطح ابزار ایجنت، و دفاع لایه‌ای برای محرمانگی، چهار ستون اصلی این ساختار هستند.</p>
          <div class="highlight">
            <strong>💎 ارزش پیشنهادی ساختار محصول:</strong><br>
            معماری ایجنت‌محور + توسعه‌پذیری MCP + حاکمیت داده با مدل لوکال + کنترل دسترسی تا سطح ابزار + دفاع لایه‌ای
          </div>
        </div>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به ادامه گفتگو، آماده برگزاری جلسه فنی برای معرفی ساختار محصول، دریافت نیازمندی‌های اختصاصی کارفرما و بررسی امکان تطبیق محصول با آن نیازها هستم. این جلسه، نقطه شروع همکاری و شناخت متقابل خواهد بود.
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6aa5608b-7bb0-4fab-8eaa-c6345e801b03.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>راهنمای گام‌به‌گام ساخت MCP Server در C# .NET Standard 2.0</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --code-bg: #1e293b;
    --code-text: #e2e8f0;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1050px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge { display: flex; align-items: center; gap: 12px; }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta { text-align: left; font-size: 12px; opacity: 0.9; }
  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 27px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 { font-size: 15px; font-weight: 400; opacity: 0.9; }

  .document-body { padding: 40px; }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section { margin-bottom: 45px; page-break-inside: avoid; }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }
  .section-title h3 { font-size: 19px; font-weight: 700; color: var(--primary); margin-bottom: 2px; }
  .section-title .subtitle { font-size: 12px; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; direction: ltr; text-align: right; }

  .section-content { padding-right: 10px; }
  .section-content p { margin-bottom: 12px; text-align: justify; text-indent: 20px; }
  .section-content p.no-indent { text-indent: 0; }

  .highlight-box, .info-box, .success-box, .warning-box, .danger-box {
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
  }
  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
  }

  .danger-box {
    background: linear-gradient(to left, #fff5f5, #fed7d7);
    border: 1px solid #fc8181;
    border-right: 4px solid var(--danger);
  }

  pre {
    background: var(--code-bg);
    color: var(--code-text);
    padding: 20px 22px;
    border-radius: 8px;
    overflow-x: auto;
    margin: 15px 0;
    font-family: 'JetBrains Mono', 'Courier New', monospace;
    font-size: 12.5px;
    line-height: 1.7;
    direction: ltr;
    text-align: left;
    border: 1px solid #334155;
    position: relative;
  }

  pre::before {
    content: attr(data-lang);
    position: absolute;
    top: 8px;
    right: 12px;
    font-size: 10px;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: 600;
  }

  code {
    font-family: 'JetBrains Mono', 'Courier New', monospace;
    background: #f1f5f9;
    color: #1e293b;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12.5px;
    direction: ltr;
    display: inline-block;
  }

  pre code { background: none; color: inherit; padding: 0; display: inline; }

  .file-path {
    background: #2c5282;
    color: #bee3f8;
    padding: 8px 14px;
    border-radius: 6px 6px 0 0;
    font-family: 'JetBrains Mono', monospace;
    font-size: 11.5px;
    direction: ltr;
    text-align: left;
    margin-top: 15px;
    margin-bottom: -15px;
    border-bottom: 2px solid #1a365d;
  }

  .file-path::before { content: '📄 '; margin-left: 4px; }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th { padding: 14px 16px; text-align: right; font-weight: 600; font-size: 13px; }
  .styled-table td { padding: 13px 16px; border-bottom: 1px solid var(--border); font-size: 13px; }
  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }
  .styled-table .highlight-row { background: #fffaf0 !important; font-weight: 600; }

  .file-tree {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 20px 25px;
    margin: 15px 0;
    font-family: 'JetBrains Mono', monospace;
    font-size: 12.5px;
    direction: ltr;
    text-align: left;
    line-height: 1.9;
    color: var(--text-muted);
  }
  .file-tree .folder { color: var(--primary); font-weight: 600; }
  .file-tree .new { color: var(--success); }

  .step-badge {
    display: inline-block;
    background: var(--accent);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 12px;
    font-weight: 600;
    margin-left: 8px;
  }

  .checklist { list-style: none; padding: 0; margin: 15px 0; }
  .checklist li {
    padding: 10px 15px;
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    margin-bottom: 8px;
    border-radius: 6px;
    font-size: 13.5px;
  }
  .checklist li::before {
    content: '✓';
    color: var(--success);
    font-weight: 700;
    margin-left: 10px;
    display: inline-block;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }
  .conclusion-box h3 { font-size: 22px; font-weight: 800; margin-bottom: 15px; color: var(--accent); }
  .conclusion-box p { font-size: 14px; line-height: 1.8; text-indent: 0 !important; margin-bottom: 15px; }
  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }
  .document-footer .footer-brand { font-weight: 700; color: var(--accent); margin-bottom: 5px; font-size: 14px; }
  .footer-divider { width: 60px; height: 2px; background: var(--accent); margin: 10px auto; }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 20px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label { font-size: 12px; opacity: 0.9; }

  @media print { body { background: white; padding: 0; } .document-container { box-shadow: none; border-radius: 0; } .section { page-break-inside: avoid; } }
  @media (max-width: 768px) { .document-body { padding: 25px 20px; } .document-header { padding: 30px 20px; } .header-top { flex-direction: column; gap: 15px; } .doc-meta { text-align: center; } .stats-grid { grid-template-columns: 1fr; } }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge"><div class="company-logo"></div></div>
      <div class="doc-meta">
        <div>شماره مستند: GUIDE-MCP-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: آبان ۱۴۰۵</div>
        <div>طبقه‌بندی: آموزشی-فنی</div>
      </div>
    </div>
    <div class="document-title">
      <span class="label">STEP-BY-STEP TUTORIAL</span>
      <h1>راهنمای گام‌به‌گام ساخت MCP Server در C#</h1>
      <h2>پیاده‌سازی کامل با .NET Standard 2.0 و کتابخانه رسمی ModelContextProtocol</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>هدف مستند:</strong><br>
      این مستند، یک راهنمای عملی و گام‌به‌گام برای ساخت یک <strong>MCP Server</strong> (Model Context Protocol Server) با استفاده از زبان C# و کتابخانه رسمی <code>ModelContextProtocol</code> است. تمام مراحل با کدهای کامل و قابل اجرا ارائه شده و پروژه نهایی روی <strong>.NET Standard 2.0</strong> کامپایل می‌شود تا با طیف گسترده‌ای از فریم‌ورک‌ها (از جمله .NET Framework قدیمی‌تر) سازگار باشد. در پایان، سرور ما با کلاینت‌هایی مانند <strong>Claude Desktop</strong> یا <strong>GitHub Copilot</strong> قابل استفاده خواهد بود.
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 0: MCP چیست -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۰</div>
        <div class="section-title">
          <h3>MCP چیست و چرا اهمیت دارد؟</h3>
          <div class="subtitle">What is MCP? / Why it matters</div>
        </div>
      </div>
      <div class="section-content">
        <p><strong>Model Context Protocol (MCP)</strong> یک پروتکل باز و استاندارد است که توسط شرکت Anthropic معرفی شده و هدف آن، ایجاد یک زبان مشترک بین <strong>مدل‌های زبانی (LLM)</strong> و <strong>منابع خارجی</strong> (مانند دیتابیس، API، فایل‌سیستم، ابزارهای داخلی سازمان) است. به کمک MCP، مدل‌های زبانی می‌توانند به‌طور استاندارد و امن، به داده‌ها و قابلیت‌های خارجی دسترسی داشته باشند بدون آنکه نیاز به کدنویسی اختصاصی برای هر مدل باشد.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">استاندارد<br>باز</div>
            <div class="stat-label">پشتیبانی توسط Anthropic، Microsoft، و جامعه</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">سه<br>قابلیت</div>
            <div class="stat-label">Tools، Resources، Prompts</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">قابل<br>حمل</div>
            <div class="stat-label">یک سرور، چند کلاینت</div>
          </div>
        </div>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">سه قابلیت اصلی MCP:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>قابلیت</th>
              <th>توضیح</th>
              <th>مثال</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>Tools</strong></td>
              <td>توابع قابل فراخوانی توسط مدل (مانند Function Calling)</td>
              <td>جستجو در دیتابیس، ارسال ایمیل، محاسبه</td>
            </tr>
            <tr>
              <td><strong>Resources</strong></td>
              <td>داده‌های فقط‌خواندنی که مدل می‌تواند بخواند</td>
              <td>فایل، رکورد دیتابیس، تنظیمات</td>
            </tr>
            <tr>
              <td><strong>Prompts</strong></td>
              <td>قالب‌های آماده برای پرامپت‌ها</td>
              <td>الگوهای پاسخ، شخصیت‌ها، سناریوها</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> در این مستند، تمرکز ما بر روی <strong>Tools</strong> خواهد بود، چراکه پرکاربردترین قابلیت MCP است و اجازه می‌دهد منطق تجاری موجود در پروژه‌های C# خود را به‌راحتی در اختیار مدل‌های زبانی قرار دهید.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 1: Prerequisites -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>پیش‌نیازها و آماده‌سازی محیط</h3>
          <div class="subtitle">Prerequisites</div>
        </div>
      </div>
      <div class="section-content">
        <p>پیش از شروع، مطمئن شوید که موارد زیر روی سیستم شما نصب و آماده هستند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>پیش‌نیاز</th>
              <th>حداقل نسخه</th>
              <th>توضیح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>.NET SDK</strong></td>
              <td>8.0 یا بالاتر</td>
              <td>برای اجرا و Build پروژه (خود کتابخانه روی netstandard2.0 کار می‌کند)</td>
            </tr>
            <tr>
              <td><strong>IDE یا Editor</strong></td>
              <td>—</td>
              <td>Visual Studio 2022، VS Code، یا Rider</td>
            </tr>
            <tr>
              <td><strong>NuGet</strong></td>
              <td>—</td>
              <td>به‌طور خودکار همراه .NET SDK نصب می‌شود</td>
            </tr>
            <tr>
              <td><strong>کلاینت MCP (اختیاری)</strong></td>
              <td>—</td>
              <td>Claude Desktop، GitHub Copilot، یا هر MCP Client دیگر برای تست</td>
            </tr>
          </tbody>
        </table>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">بررسی نصب .NET SDK:</h4>
        <p class="no-indent">در ترمینال یا Command Prompt دستور زیر را اجرا کنید:</p>

<pre data-lang="bash"><code>dotnet --version</code></pre>

        <p class="no-indent">اگر نسخه ۸.۰ یا بالاتر نمایش داده شد، همه چیز آماده است. در غیر این صورت، از سایت رسمی <code>dotnet.microsoft.com/download</code> آخرین نسخه را دانلود و نصب کنید.</p>

        <div class="warning-box">
          <strong>⚠️ توجه به .NET Standard 2.0:</strong> اگرچه خود پروژه شما بر روی <code>netstandard2.0</code> کامپایل می‌شود، اما برای اجرای آن و ساخت DLL نیاز به یک SDK مدرن دارید. این SDK هنگام اجرا، پروژه شما را به یک باینری سازگار تبدیل می‌کند. کتابخانه <code>ModelContextProtocol</code> به‌طور رسمی از <code>netstandard2.0</code> پشتیبانی می‌کند.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 2: Create Project -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>ایجاد پروژه جدید</h3>
          <div class="subtitle">Create a New Project</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ترمینال، به مسیری که می‌خواهید پروژه در آن ساخته شود بروید و دستور زیر را اجرا کنید:</p>

<pre data-lang="bash"><code>dotnet new console -n SampleMcpServer
cd SampleMcpServer</code></pre>

        <p>این دستور یک پروژه کنسول ساده با نام <code>SampleMcpServer</code> ایجاد می‌کند و شما را به پوشه آن منتقل می‌کند.</p>

        <div class="file-tree">
<span class="folder">SampleMcpServer/</span>
├── <span class="new">Program.cs</span>
├── <span class="new">SampleMcpServer.csproj</span>
└── obj/
</div>

        <div class="info-box">
          <strong>💡 چرا Console؟</strong> سرورهای MCP اغلب به‌صورت پروسه‌های Console اجرا می‌شوند و از طریق <strong>stdin/stdout</strong> با کلاینت (مثلاً Claude Desktop) ارتباط برقرار می‌کنند. این نوع Transport که <strong>stdio</strong> نامیده می‌شود، ساده‌ترین و پرکاربردترین روش برای اتصال کلاینت و سرور در محیط دسکتاپ است.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 3: NuGet Packages -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>افزودن پکیج‌های NuGet</h3>
          <div class="subtitle">Add NuGet Packages</div>
        </div>
      </div>
      <div class="section-content">
        <p>دو پکیج اصلی نیاز دارید:</p>

<pre data-lang="bash"><code>dotnet add package ModelContextProtocol
dotnet add package Microsoft.Extensions.Hosting</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">توضیح پکیج‌ها:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>پکیج</th>
              <th>نقش</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><code>ModelContextProtocol</code></td>
              <td>هسته اصلی SDK — شامل سرور، کلاینت، Transportها (stdio/http)، و Attributeهای `[McpServerTool]`</td>
            </tr>
            <tr>
              <td><code>Microsoft.Extensions.Hosting</code></td>
              <td>زیرساخت Host و Dependency Injection — برای راه‌اندازی سرویس‌ها با الگوی مدرن .NET</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 تأیید نسخه:</strong> کتابخانه <code>ModelContextProtocol</code> به‌طور فعال توسط Microsoft و Anthropic توسعه داده می‌شود و نسخه آن مرتباً به‌روزرسانی می‌شود. برای دریافت آخرین نسخه از <code>nuget.org</code> استفاده کنید.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 4: csproj Configuration -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>پیکربندی فایل پروژه (.csproj)</h3>
          <div class="subtitle">Configure Project File</div>
        </div>
      </div>
      <div class="section-content">
        <p>فایل <code>SampleMcpServer.csproj</code> را باز کنید و مطمئن شوید که <code>TargetFramework</code> روی <code>netstandard2.0</code> تنظیم شده و پکیج‌ها به‌درستی اضافه شده‌اند:</p>

        <div class="file-path">SampleMcpServer.csproj</div>
<pre data-lang="xml"><code>&lt;Project Sdk="Microsoft.NET.Sdk"&gt;

  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;netstandard2.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;LangVersion&gt;latest&lt;/LangVersion&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include="ModelContextProtocol" Version="*" /&gt;
    &lt;PackageReference Include="Microsoft.Extensions.Hosting" Version="*" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">توضیح فیلدها:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>فیلد</th>
              <th>توضیح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><code>OutputType</code></td>
              <td><code>Exe</code> — پروژه یک برنامه اجرایی (console app) خواهد بود</td>
            </tr>
            <tr>
              <td><code>TargetFramework</code></td>
              <td><code>netstandard2.0</code> — سازگاری با .NET Framework 4.6.1+ و .NET Core 2.0+</td>
            </tr>
            <tr>
              <td><code>Nullable</code></td>
              <td><code>enable</code> — فعال‌سازی بررسی nullability (امنیت بیشتر)</td>
            </tr>
            <tr>
              <td><code>LangVersion</code></td>
              <td><code>latest</code> — استفاده از آخرین امکانات زبان C#</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته مهم:</strong> اگر از <code>Version="*"</code> استفاده می‌کنید، NuGet آخرین نسخه پایدار را نصب می‌کند. در محیط عملیاتی توصیه می‌شود نسخه دقیق (مانند <code>"0.4.0-preview"</code>) را مشخص کنید تا از تغییرات ناخواسته جلوگیری شود.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 5: Define a Tool -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>تعریف اولین Tool (ابزار MCP)</h3>
          <div class="subtitle">Define Your First MCP Tool</div>
        </div>
      </div>
      <div class="section-content">
        <p>در ریشه پروژه، فایل جدیدی به نام <code>EchoTool.cs</code> بسازید. در این فایل، یک کلاس ساده با متد <code>Echo</code> تعریف می‌کنیم که هر پیامی را به مدل بازمی‌گرداند:</p>

        <div class="file-path">EchoTool.cs</div>
<pre data-lang="csharp"><code>using System.ComponentModel;
using ModelContextProtocol.Server;

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) =&gt; $"hello {message}";
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">توضیح Attributeها و اجزا:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>جزء</th>
              <th>نقش</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><code>[McpServerToolType]</code></td>
              <td>به SDK اعلام می‌کند که این کلاس شامل Tool است و باید اسکن شود</td>
            </tr>
            <tr>
              <td><code>[McpServerTool]</code></td>
              <td>متد را به‌عنوان یک Tool قابل فراخوانی توسط LLM ثبت می‌کند</td>
            </tr>
            <tr>
              <td><code>[Description(...)]</code></td>
              <td>توضیح انسانی که به مدل زبانی داده می‌شود تا بداند این Tool چه کاری انجام می‌دهد</td>
            </tr>
            <tr>
              <td><code>string message</code></td>
              <td>پارامتر ورودی — SDK به‌طور خودکار JSON Schema را از این signature تولید می‌کند</td>
            </tr>
            <tr>
              <td><code>string</code> (return type)</td>
              <td>نوع بازگشتی — می‌تواند <code>string</code>، <code>Task&lt;string&gt;</code> یا هر شیء سریالایزپذیر باشد</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ چرا این سادگی مهم است؟</strong> شما نیازی به نوشتن JSON Schema دستی، یا پیاده‌سازی هندلرهای پیچیده ندارید. SDK از روی signature متد و Attributeها، به‌طور خودکار همه چیز را می‌سازد. این رویکرد «Attribute-Driven» کار را بسیار ساده می‌کند.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 6: Program.cs -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>پیکربندی و اجرای سرور در Program.cs</h3>
          <div class="subtitle">Configure and Run the Server</div>
        </div>
      </div>
      <div class="section-content">
        <p>محتوای فایل <code>Program.cs</code> را با کد زیر جایگزین کنید. این کد، Host را می‌سازد، لاگ‌ها را به stderr هدایت می‌کند، و سرور را با Transport از نوع stdio راه‌اندازی می‌نماید:</p>

        <div class="file-path">Program.cs</div>
<pre data-lang="csharp"><code>using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

var builder = Host.CreateApplicationBuilder(args);

builder.Logging.AddConsole(consoleLogOptions =&gt;
{
    // Configure all logs to go to stderr so they don't corrupt the MCP protocol stream.
    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});

builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">تشریح خط‌به‌خط:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>خط</th>
              <th>توضیح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><code>Host.CreateApplicationBuilder(args)</code></td>
              <td>ساخت Builder مدرن .NET با پشتیبانی از Configuration و DI</td>
            </tr>
            <tr>
              <td><code>AddConsole(...LogToStandardErrorThreshold...)</code></td>
              <td><strong>بحرانی:</strong> هدایت لاگ‌ها به stderr. اگر لاگ‌ها به stdout بروند، با پروتکل MCP تداخل می‌کنند و ارتباط قطع می‌شود</td>
            </tr>
            <tr>
              <td><code>AddMcpServer()</code></td>
              <td>ثبت سرویس‌های MCP در DI Container</td>
            </tr>
            <tr>
              <td><code>WithStdioServerTransport()</code></td>
              <td>استفاده از stdin/stdout برای ارتباط — برای کلاینت‌های دسکتاپ ایده‌آل است</td>
            </tr>
            <tr>
              <td><code>WithToolsFromAssembly()</code></td>
              <td>اسکن خودکار اسمبلی و ثبت هر کلاسی که با <code>[McpServerToolType]</code> علامت‌گذاری شده</td>
            </tr>
            <tr>
              <td><code>await builder.Build().RunAsync()</code></td>
              <td>ساخت Host و شروع به گوش دادن برای درخواست‌ها</td>
            </tr>
          </tbody>
        </table>

        <div class="danger-box">
          <strong>⚠️ هشدار بسیار مهم:</strong> در استفاده از stdio، <strong>هرگز</strong> از <code>Console.WriteLine</code> برای لاگ استفاده نکنید. این کار پیام‌های پروتکل را خراب می‌کند. تمام لاگ‌ها باید از طریق <code>ILogger</code> و با تنظیم <code>LogToStandardErrorThreshold</code> به stderr هدایت شوند. اگر این نکته رعایت نشود، سرور به‌ظاهر اجرا می‌شود اما کلاینت نمی‌تواند با آن ارتباط برقرار کند.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 7: Build & Run -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>ساخت و اجرا</h3>
          <div class="subtitle">Build &amp; Run</div>
        </div>
      </div>
      <div class="section-content">
        <p>در پوشه پروژه، دستور زیر را اجرا کنید:</p>

<pre data-lang="bash"><code>dotnet build
dotnet run</code></pre>

        <p>سرور شما اجرا خواهد شد و منتظر دریافت پیام‌ها از طریق stdin خواهد بود. در این حالت، سرور در حالت <strong>منفعل (Passive)</strong> است و تنها زمانی که کلاینت MCP به آن متصل شود، شروع به کار خواهد کرد.</p>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">چه اتفاقی در پس‌زمینه می‌افتد؟</h4>
        <ol style="padding-right: 20px; margin-top: 10px; font-size: 14px; line-height: 2;">
          <li><strong>SDK</strong> اسمبلی را اسکن کرده و کلاس <code>EchoTool</code> را کشف می‌کند.</li>
          <li>از روی متد <code>Echo</code>، یک Tool با پارامتر ورودی <code>message: string</code> و نوع بازگشتی <code>string</code> استخراج می‌کند.</li>
          <li>یک <strong>JSON Schema</strong> خودکار برای این Tool تولید می‌کند.</li>
          <li>سرور شروع به گوش دادن به stdin می‌کند.</li>
          <li>وقتی کلاینت متصل می‌شود، ابتدا یک پیام <code>initialize</code> می‌فرستد و سرور با معرفی خودش و ابزارهای موجود پاسخ می‌دهد.</li>
          <li>سپس کلاینت می‌تواند پیام‌های <code>tools/list</code> یا <code>tools/call</code> بفرستد.</li>
        </ol>

        <div class="info-box">
          <strong>💡 چه چیزی روی stdout می‌رود؟</strong> فقط پیام‌های JSON-RPC پروتکل MCP. هیچ خروجی اضافی مجاز نیست. اگر می‌خواهید تست کنید، فقط از طریق یک کلاینت MCP اقدام کنید.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 8: Test with Client -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>تست با کلاینت MCP</h3>
          <div class="subtitle">Testing with an MCP Client</div>
        </div>
      </div>
      <div class="section-content">
        <p>برای تست، می‌توانید از <strong>Claude Desktop</strong>، <strong>VS Code Copilot</strong> یا هر MCP Client دیگری استفاده کنید. در ادامه، نمونه پیکربندی برای دو کلاینت پرکاربرد ارائه شده است.</p>

        <h4 style="color: var(--primary); font-size: 15px;">الف) Claude Desktop</h4>
        <p class="no-indent">فایل پیکربندی <code>claude_desktop_config.json</code> را باز کنید (در ویندوز در مسیر <code>%APPDATA%\Claude\</code> و در macOS در <code>~/Library/Application Support/Claude/</code>) و بخش <code>mcpServers</code> را اضافه کنید:</p>

<pre data-lang="json"><code>{
  "mcpServers": {
    "sample-echo": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "C:\\Path\\To\\SampleMcpServer\\SampleMcpServer.csproj"
      ]
    }
  }
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) VS Code (Copilot + MCP)</h4>
        <p class="no-indent">در فایل <code>.vscode/mcp.json</code>:</p>

<pre data-lang="json"><code>{
  "servers": {
    "sample-echo": {
      "command": "dotnet",
      "args": [
        "run",
        "--project",
        "${workspaceFolder}/SampleMcpServer/SampleMcpServer.csproj"
      ]
    }
  }
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ج) تست دستی با JSON-RPC</h4>
        <p class="no-indent">اگر می‌خواهید بدون کلاینت تست کنید، می‌توانید مستقیماً پیام JSON-RPC بفرستید. در ترمینال سرور را اجرا کنید و سپس پیام‌های زیر را روی stdin آن بنویسید:</p>

<pre data-lang="json"><code>// درخواست initialize
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}

// دریافت لیست ابزارها
{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}

// فراخوانی ابزار Echo
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"Echo","arguments":{"message":"World"}}}</code></pre>

        <div class="success-box">
          <strong>✓ پاسخ مورد انتظار:</strong> پس از فراخوانی <code>Echo</code>، باید چیزی شبیه به این دریافت کنید:
          <br><br>
          <code>{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"hello World"}]}}</code>
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 9: Advanced Tools -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>افزودن Toolهای پیشرفته‌تر</h3>
          <div class="subtitle">Advanced Tools</div>
        </div>
      </div>
      <div class="section-content">
        <p>Toolهای MCP می‌توانند پیچیده‌تر از یک Echo ساده باشند. در ادامه، چند الگوی پیشرفته آورده شده است:</p>

        <h4 style="color: var(--primary); font-size: 15px;">الف) Tool با چند پارامتر و نوع‌های مختلف</h4>
<pre data-lang="csharp"><code>[McpServerTool, Description("Adds two numbers and returns the result.")]
public static int Add(
    [Description("First number")] int a,
    [Description("Second number")] int b
) =&gt; a + b;</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">ب) Tool با پارامتر اختیاری</h4>
<pre data-lang="csharp"><code>[McpServerTool, Description("Searches for a term, with optional limit.")]
public static string Search(
    [Description("The search query")] string query,
    [Description("Maximum results (default: 10)")] int limit = 10
) =&gt; $"Searching for '{query}' with limit {limit}";</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">ج) Tool Async با CancellationToken</h4>
<pre data-lang="csharp"><code>[McpServerTool, Description("Fetches data from a remote API.")]
public static async Task&lt;string&gt; FetchData(
    [Description("The resource identifier")] string id,
    CancellationToken cancellationToken = default
)
{
    using var http = new HttpClient();
    return await http.GetStringAsync($"https://api.example.com/{id}", cancellationToken);
}</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">د) Tool با Dependency Injection</h4>
<p class="no-indent">برای استفاده از سرویس‌های موجود، می‌توانید Tool را به‌صورت non-static تعریف کنید و سرویس‌ها را از طریق سازنده تزریق کنید:</p>

<pre data-lang="csharp"><code>[McpServerToolType]
public class DatabaseTool
{
    private readonly IMyRepository _repository;

    // DI automatically resolves the dependency
    public DatabaseTool(IMyRepository repository)
    {
        _repository = repository;
    }

    [McpServerTool, Description("Retrieves a record by ID.")]
    public async Task&lt;string&gt; GetRecord(string id, CancellationToken ct = default)
    {
        var record = await _repository.GetByIdAsync(id, ct);
        return record?.ToJson() ?? "Not found";
    }
}</code></pre>

        <div class="info-box">
          <strong>💡 نکته:</strong> برای ثبت سرویس‌های DI، پیش از <code>builder.Build()</code> آن‌ها را اضافه کنید:
          <br><br>
          <code>builder.Services.AddScoped&lt;IMyRepository, MyRepository&gt;();</code>
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 10: MCPSharp Alternative -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>روش جایگزین: استفاده از MCPSharp</h3>
          <div class="subtitle">Alternative: MCPSharp Community Library</div>
        </div>
      </div>
      <div class="section-content">
        <p>اگر به یک API ساده‌تر و مختصرتر علاقه‌مند هستید، می‌توانید از کتابخانه جامعه <strong>MCPSharp</strong> استفاده کنید. این کتابخانه نیز از <code>netstandard2.0</code> پشتیبانی می‌کند و با تعداد خطوط کمتر، همان قابلیت‌ها را ارائه می‌دهد.</p>

        <h4 style="color: var(--primary); font-size: 15px;">نصب:</h4>
<pre data-lang="bash"><code>dotnet add package MCPSharp</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">مثال کامل:</h4>
<pre data-lang="csharp"><code>using MCPSharp;

public class Calculator
{
    [McpTool("add", "Adds two numbers")]
    public static int Add(
        [McpParameter(true)] int a,
        [McpParameter(true)] int b
    ) =&gt; a + b;

    [McpTool("multiply", "Multiplies two numbers")]
    public static int Multiply(
        [McpParameter(true)] int a,
        [McpParameter(true)] int b
    ) =&gt; a * b;
}

await MCPServer.StartAsync("CalculatorServer", "1.0.0");</code></pre>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">مقایسه دو رویکرد:</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>ویژگی</th>
              <th>ModelContextProtocol (رسمی)</th>
              <th>MCPSharp (جامعه)</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>نگهداری</td>
              <td>Microsoft + Anthropic</td>
              <td>جامعه (Community)</td>
            </tr>
            <tr>
              <td>پشتیبانی از .NET Standard 2.0</td>
              <td style="color: var(--success); font-weight: 600;">✓</td>
              <td style="color: var(--success); font-weight: 600;">✓</td>
            </tr>
            <tr>
              <td>میزان کد Boilerplate</td>
              <td>متوسط</td>
              <td style="color: var(--success); font-weight: 600;">حداقل</td>
            </tr>
            <tr>
              <td>پشتیبانی از DI</td>
              <td style="color: var(--success); font-weight: 600;">✓ کامل</td>
              <td>محدود</td>
            </tr>
            <tr>
              <td>Transport HTTP</td>
              <td style="color: var(--success); font-weight: 600;">✓</td>
              <td>در حال توسعه</td>
            </tr>
            <tr class="highlight-row">
              <td><strong>توصیه برای پروژه‌های عملیاتی</strong></td>
              <td colspan="2" style="text-align: center; color: var(--success); font-weight: 700;">ModelContextProtocol (رسمی)</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ توصیه:</strong> برای پروژه‌های عملیاتی و سازمانی، استفاده از کتابخانه رسمی <code>ModelContextProtocol</code> توصیه می‌شود زیرا پشتیبانی بلندمدت، به‌روزرسانی‌های امنیتی، و سازگاری با آخرین تغییرات پروتکل MCP را تضمین می‌کند. MCPSharp برای پروژه‌های کوچک، یادگیری، یا Prototype مناسب است.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 11: HTTP Transport -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>گزینه پیشرفته: HTTP Transport</h3>
          <div class="subtitle">Optional: HTTP Transport</div>
        </div>
      </div>
      <div class="section-content">
        <p>اگر می‌خواهید سرور MCP شما از راه دور (Remote) قابل دسترسی باشد (مثلاً در یک کانتینر Docker یا روی یک سرور Cloud)، می‌توانید به‌جای <code>stdio</code> از <strong>HTTP Transport</strong> استفاده کنید.</p>

        <div class="info-box">
          <strong>💡 چه زمانی HTTP؟</strong>
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>چندین کلاینت به‌طور همزمان می‌خواهند وصل شوند</li>
            <li>سرور در محیطی جدا از کلاینت اجرا می‌شود (Docker، Kubernetes، Cloud)</li>
            <li>نیاز به احراز هویت مرکزی و Rate Limiting دارید</li>
          </ul>
        </div>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">تغییرات لازم در Program.cs:</h4>
<pre data-lang="csharp"><code>using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddMcpServer()
    .WithHttpTransport()       // ← به‌جای WithStdioServerTransport
    .WithToolsFromAssembly();

var app = builder.Build();

app.MapMcp();                   // ← مسیر /mcp را فعال می‌کند

app.Run();</code></pre>

        <p class="no-indent">همچنین باید پکیج <code>Microsoft.AspNetCore</code> را اضافه کنید و نوع پروژه را از <code>Microsoft.NET.Sdk</code> به <code>Microsoft.NET.Sdk.Web</code> تغییر دهید.</p>

        <div class="warning-box">
          <strong>⚠️ توجه:</strong> HTTP Transport در .NET Standard 2.0 به‌طور کامل پشتیبانی نمی‌شود. برای استفاده از این قابلیت، بهتر است پروژه را به <code>net8.0</code> یا بالاتر ارتقا دهید. اگر مجبور به استفاده از .NET Standard 2.0 هستید، از stdio استفاده کنید و یک پروسه فرزند بسازید.
        </div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 12: Best Practices -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۲</div>
        <div class="section-title">
          <h3>بهترین روش‌ها و نکات عملیاتی</h3>
          <div class="subtitle">Best Practices</div>
        </div>
      </div>
      <div class="section-content">
        <ul class="checklist">
          <li>هر Tool را با <code>[Description]</code> واضح و دقیق توصیف کنید — مدل از این توضیح برای تصمیم‌گیری استفاده می‌کند</li>
          <li>پارامترها را با نوع‌های مشخص (نه <code>object</code>) تعریف کنید تا JSON Schema دقیق‌تری تولید شود</li>
          <li>برای عملیات طولانی، از <code>Task</code> و <code>CancellationToken</code> استفاده کنید</li>
          <li>خطاها را با Exceptionهای واضح پرتاب کنید — SDK آن‌ها را به JSON-RPC Error تبدیل می‌کند</li>
          <li>ورودی‌ها را اعتبارسنجی کنید (Validation) — مدل ممکن است ورودی نامعتبر بفرستد</li>
          <li>لاگ‌ها را هرگز روی stdout ننویسید — از <code>ILogger</code> و stderr استفاده کنید</li>
          <li>از <code>[McpServerToolType]</code> روی کلاس‌های Helper استفاده کنید تا ابزارها در فایل‌های مختلف تقسیم شوند</li>
          <li>در محیط عملیاتی، Transport را بر اساس سناریو انتخاب کنید (stdio برای دسکتاپ، HTTP برای Cloud)</li>
          <li>ورژن پروتکل MCP را در نظر بگیرید — کلاینت و سرور باید سازگار باشند</li>
          <li>برای تست خودکار، از JSON-RPC خام در سناریوهای Integration Test استفاده کنید</li>
        </ul>

        <h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">الگوی پیشنهادی ساختار پروژه:</h4>
        <div class="file-tree">
<span class="folder">SampleMcpServer/</span>
├── <span class="folder">Tools/</span>
│   ├── EchoTool.cs
│   ├── CalculatorTool.cs
│   └── DatabaseTool.cs
├── <span class="folder">Services/</span>
│   ├── IMyRepository.cs
│   └── MyRepository.cs
├── <span class="folder">Models/</span>
│   └── RecordDto.cs
├── Program.cs
├── appsettings.json
└── SampleMcpServer.csproj
</div>
      </div>
    </div>

    <!-- ============================================================= -->
    <!-- SECTION 13: Summary -->
    <!-- ============================================================= -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۳</div>
        <div class="section-title">
          <h3>جمع‌بندی</h3>
          <div class="subtitle">Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>در این مستند، به‌صورت گام‌به‌گام، ساخت یک MCP Server با C# و .NET Standard 2.0 را بررسی کردیم. مراحلی که پشت سر گذاشتیم:</p>

        <ul class="checklist">
          <li>با مفهوم MCP و سه قابلیت اصلی آن (Tools، Resources، Prompts) آشنا شدیم</li>
          <li>پیش‌نیازها و محیط توسعه را آماده کردیم</li>
          <li>یک پروژه Console جدید با <code>dotnet new console</code> ساختیم</li>
          <li>پکیج‌های <code>ModelContextProtocol</code> و <code>Microsoft.Extensions.Hosting</code> را نصب کردیم</li>
          <li>فایل <code>.csproj</code> را برای <code>netstandard2.0</code> پیکربندی کردیم</li>
          <li>اولین Tool خود را با <code>[McpServerTool]</code> تعریف کردیم</li>
          <li>سرور را در <code>Program.cs</code> با stdio Transport راه‌اندازی کردیم</li>
          <li>نحوه تست با Claude Desktop و VS Code را فرا گرفتیم</li>
          <li>الگوهای پیشرفته‌تر (Async، DI، پارامترهای اختیاری) را بررسی کردیم</li>
          <li>با کتابخانه جایگزین MCPSharp آشنا شدیم</li>
          <li>روش استفاده از HTTP Transport برای سناریوهای Cloud را دیدیم</li>
          <li>بهترین روش‌های عملیاتی را مرور کردیم</li>
        </ul>

        <div class="conclusion-box">
          <h3>🎯 نتیجه نهایی</h3>
          <p>شما اکنون یک MCP Server کامل و عملیاتی در اختیار دارید که:</p>
          <p style="font-size: 13px; line-height: 2;">
            <strong>با استاندارد باز MCP سازگار است، از .NET Standard 2.0 پشتیبانی می‌کند، به‌راحتی با Claude Desktop و GitHub Copilot یکپارچه می‌شود، و منطق تجاری موجود شما را در دسترس مدل‌های زبانی قرار می‌دهد.</strong>
          </p>
          <div class="highlight">
            <strong>💎 ارزش پیشنهادی:</strong><br>
            یکپارچگی استاندارد با LLM + بدون تغییر ساختار موجود پروژه + قابلیت حمل بالا + سادگی توسعه
          </div>
        </div>

        <div class="info-box">
          <strong>📞 گام بعدی پیشنهادی:</strong> پس از ساخت این سرور ساده، می‌توانید:
          <ul style="padding-right: 20px; margin-top: 10px;">
            <li>سرویس‌های موجود خود را به‌عنوان Toolهای MCP ثبت کنید (مانند RAG، مدیریت مکالمه، پردازش فایل)</li>
            <li>سرور را در CI/CD قرار دهید و به‌صورت خودکار منتشر کنید</li>
            <li>با یک MCP Client متصل شوید و تست End-to-End انجام دهید</li>
            <li>در صورت نیاز، به سمت HTTP Transport و استقرار در کانتینر حرکت کنید</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">تهیه و تنظیم: تیم معماری xSaherelmWorkspace</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: آموزشی-فنی</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_6b96ea86-c4b1-49a2-b46a-df5be36b52e5.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>معماری کلان محصول | سامانه هوش مصنوعی سازمانی</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  /* Architecture-specific styles */
  .arch-diagram {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 30px 20px;
    margin: 25px 0;
    text-align: center;
  }

  .arch-layer {
    background: white;
    border: 2px solid var(--primary-light);
    border-radius: 10px;
    padding: 15px;
    margin: 10px 0;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
  }

  .arch-layer-title {
    font-weight: 700;
    color: var(--primary);
    font-size: 14px;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px dashed var(--border);
  }

  .arch-components {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: center;
  }

  .arch-component {
    background: linear-gradient(135deg, #edf2f7, #e2e8f0);
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 6px 12px;
    font-size: 12px;
    color: var(--text);
  }

  .arch-component.primary-comp {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-color: var(--primary);
  }

  .arch-component.accent-comp {
    background: linear-gradient(135deg, var(--accent), var(--accent-dark));
    color: white;
    border-color: var(--accent-dark);
  }

  .arch-arrow {
    font-size: 20px;
    color: var(--accent);
    margin: 5px 0;
  }

  .arch-row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    margin: 15px 0;
    flex-wrap: wrap;
  }

  .arch-box {
    background: white;
    border: 2px solid var(--primary-light);
    border-radius: 10px;
    padding: 15px 20px;
    min-width: 150px;
    text-align: center;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
  }

  .arch-box-title {
    font-weight: 700;
    color: var(--primary);
    font-size: 13px;
    margin-bottom: 5px;
  }

  .arch-box-desc {
    font-size: 11px;
    color: var(--text-muted);
  }

  .flow-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin: 20px 0;
  }

  .flow-card {
    background: white;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 18px;
    position: relative;
  }

  .flow-card .flow-number {
    position: absolute;
    top: -12px;
    right: 15px;
    width: 28px;
    height: 28px;
    background: var(--accent);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 13px;
  }

  .flow-card h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
    padding-bottom: 6px;
    border-bottom: 1px solid var(--border);
  }

  .flow-card p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .relation-table td {
    vertical-align: top;
  }

  .relation-table .from-cell {
    background: #ebf8ff;
    font-weight: 600;
    color: var(--primary);
  }

  .relation-table .to-cell {
    background: #f0fff4;
    font-weight: 600;
    color: var(--success);
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
    .arch-row { flex-direction: column; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: ARCH-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">HIGH-LEVEL ARCHITECTURE</span>
      <h1>معماری کلان محصول</h1>
      <h2>سامانه هوش مصنوعی سازمانی — پاسخ به نیازمندی‌های پارسا پلیمر شریف</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه مدیریتی،</strong><br>
      این مستند به توصیف معماری کلان سامانه هوش مصنوعی سازمانی می‌پردازد که بر اساس تحلیل نیازمندی‌های شرکت پارسا پلیمر شریف (مستند REQ-1405-001) تدوین شده است. رویکرد این معماری، <strong>تفکر سیستماتیک</strong> و <strong>فارغ از سکو و جزئیات پیاده‌سازی</strong> است. هدف، شناسایی اجزاء و مولفه‌های اصلی سامانه، روابط میان آنها، و جریان‌های اطلاعاتی و کنترلی است تا مبنای طراحی تفصیلی و پیاده‌سازی قرار گیرد.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>اصول حاکم بر معماری</h3>
          <div class="subtitle">Architectural Principles</div>
        </div>
      </div>
      <div class="section-content">
        <p>معماری این سامانه بر پایه اصول زیر شکل گرفته است که برگرفته از نیازمندی‌های صریح کارفرما و رویکرد تفکر سیستماتیک است:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>اصل</th>
              <th>توضیح</th>
              <th>مبنای نیازمندی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>جداسازی دغدغه‌ها</strong></td>
              <td>تفکیک لایه‌های تعامل، کنترل، هوش، داده و حاکمیت به‌گونه‌ای که تغییر در یک لایه، حداقل اثر را بر لایه‌های دیگر داشته باشد</td>
              <td>محور ۱، ۲، ۵</td>
            </tr>
            <tr>
              <td><strong>حاکمیت‌محوری</strong></td>
              <td>کنترل دسترسی، ممیزی و سیاست‌های داده به‌صورت عرضی (Cross-cutting) در تمام لایه‌ها اعمال می‌شود، نه به‌صورت جزیره‌ای</td>
              <td>محور ۲، ۵</td>
            </tr>
            <tr>
              <td><strong>ایجنت‌محوری قابل‌آزمون</strong></td>
              <td>موتور ایجنت به‌عنوان یک مولفه مستقل با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا و اصلاح، قابل مشاهده و آزمون باشد</td>
              <td>محور ۱</td>
            </tr>
            <tr>
              <td><strong>شفافیت مصرف</strong></td>
              <td>اندازه‌گیری و گزارش‌گیری مصرف در سطح کاربر، مدل، ایجنت و ابزار به‌صورت یکپارچه</td>
              <td>محور ۳</td>
            </tr>
            <tr>
              <td><strong>تاب‌آوری و استقرارپذیری</strong></td>
              <td>امکان استقرار درون‌سازمانی (On-Premise) و عملکرد در شرایط قطع اینترنت بین‌الملل</td>
              <td>محور ۵، ۷</td>
            </tr>
            <tr>
              <td><strong>توسعه‌پذیری و سفارشی‌سازی</strong></td>
              <td>امکان افزودن مدل‌ها، ابزارها، ایجنت‌ها و منابع داده جدید بدون تغییر در هسته</td>
              <td>محور ۱، ۶</td>
            </tr>
          </tbody>
        </table>

        <div class="highlight-box">
          <strong>اصل حاکم:</strong> معماری باید به‌گونه‌ای باشد که <strong>هر ادعای قابلیت، قابل اثبات و آزمون</strong> باشد. این یعنی هر مولفه باید دارای مرز مشخص، رابط تعریف‌شده و رفتار قابل مشاهده باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>نمای کلی سیستم</h3>
          <div class="subtitle">System Overview</div>
        </div>
      </div>
      <div class="section-content">
        <p>سامانه به‌صورت کلان از <strong>شش لایه اصلی</strong> و <strong>دو محور عرضی</strong> تشکیل شده است. این ساختار لایه‌ای، جداسازی دغدغه‌ها را تضمین می‌کند و محورهای عرضی، حاکمیت و امنیت را در تمام لایه‌ها اعمال می‌نمایند.</p>

        <div class="arch-diagram">
          <div class="arch-layer" style="border-color: var(--accent);">
            <div class="arch-layer-title">لایه ۱: تعامل و تجربه کاربری (Interaction Layer)</div>
            <div class="arch-components">
              <span class="arch-component accent-comp">رابط وب سازمانی</span>
              <span class="arch-component accent-comp">نسخه دسکتاپ</span>
              <span class="arch-component accent-comp">رابط API</span>
              <span class="arch-component accent-comp">کانال‌های ارتباطی</span>
            </div>
          </div>

          <div class="arch-arrow">▼</div>

          <div class="arch-layer">
            <div class="arch-layer-title">لایه ۲: کنترل دسترسی و نشست (Access & Session Layer)</div>
            <div class="arch-components">
              <span class="arch-component primary-comp">احراز هویت</span>
              <span class="arch-component primary-comp">مدیریت نشست</span>
              <span class="arch-component primary-comp">اعمال مجوزها</span>
              <span class="arch-component primary-comp">مدیریت نقش‌ها</span>
            </div>
          </div>

          <div class="arch-arrow">▼</div>

          <div class="arch-layer">
            <div class="arch-layer-title">لایه ۳: هماهنگی و ارکستراسیون (Orchestration Layer)</div>
            <div class="arch-components">
              <span class="arch-component primary-comp">موتور ایجنت</span>
              <span class="arch-component primary-comp">برنامه‌ریز</span>
              <span class="arch-component primary-comp">انتخاب‌گر ابزار</span>
              <span class="arch-component primary-comp">مدیریت جریان</span>
              <span class="arch-component primary-comp">نقاط تأیید انسانی</span>
            </div>
          </div>

          <div class="arch-arrow">▼</div>

          <div class="arch-layer">
            <div class="arch-layer-title">لایه ۴: هوش و مدل‌ها (Intelligence Layer)</div>
            <div class="arch-components">
              <span class="arch-component primary-comp">درگاه مدل‌ها</span>
              <span class="arch-component primary-comp">مدیریت مدل</span>
              <span class="arch-component primary-comp">بازیابی و تقویت (RAG)</span>
              <span class="arch-component primary-comp">حافظه و زمینه</span>
            </div>
          </div>

          <div class="arch-arrow">▼</div>

          <div class="arch-layer">
            <div class="arch-layer-title">لایه ۵: داده و منابع (Data & Resources Layer)</div>
            <div class="arch-components">
              <span class="arch-component">منابع دانش سازمانی</span>
              <span class="arch-component">فایل‌ها و پوشه‌ها</span>
              <span class="arch-component">پایگاه‌های داده</span>
              <span class="arch-component">سرویس‌های خارجی</span>
              <span class="arch-component">ابزارهای عملیاتی</span>
            </div>
          </div>

          <div class="arch-arrow">▼</div>

          <div class="arch-layer" style="border-color: var(--accent);">
            <div class="arch-layer-title">لایه ۶: خروجی و گزارش (Output & Reporting Layer)</div>
            <div class="arch-components">
              <span class="arch-component accent-comp">تولید گزارش</span>
              <span class="arch-component accent-comp">خروجی Word/Excel</span>
              <span class="arch-component accent-comp">ارجاع به منابع</span>
              <span class="arch-component accent-comp">داشبورد مصرف</span>
            </div>
          </div>
        </div>

        <div class="arch-row">
          <div class="arch-box" style="border-color: var(--danger);">
            <div class="arch-box-title" style="color: var(--danger);">محور عرضی ۱: حاکمیت داده و امنیت</div>
            <div class="arch-box-desc">سیاست‌های داده، ممیزی، محرمانگی، جلوگیری از افشا — اعمال در تمام لایه‌ها</div>
          </div>
          <div class="arch-box" style="border-color: var(--warning);">
            <div class="arch-box-title" style="color: var(--warning);">محور عرضی ۲: مشاهده‌پذیری و اندازه‌گیری</div>
            <div class="arch-box-desc">لاگ، متریک، ردیابی مصرف، گزارش هزینه — اعمال در تمام لایه‌ها</div>
          </div>
        </div>

        <div class="info-box">
          <strong>💡 نکته معماری:</strong> محورهای عرضی به‌صورت <strong>Cross-cutting Concerns</strong> طراحی شده‌اند؛ یعنی هر درخواست کاربر، در هر لایه‌ای که پردازش شود، از فیلتر حاکمیت و مشاهده‌پذیری عبور می‌کند. این تضمین می‌کند که نیازمندی‌های محور ۲ (دسترسی) و محور ۳ (مصرف) به‌صورت سیستماتیک و نه جزیره‌ای برآورده شوند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>اجزاء و مولفه‌های اصلی</h3>
          <div class="subtitle">Core Components</div>
        </div>
      </div>
      <div class="section-content">
        <p>هر لایه از مولفه‌هایی تشکیل شده است که مسئولیت مشخص و رابط تعریف‌شده دارند. در ادامه، مولفه‌های کلیدی هر لایه تشریح می‌شود:</p>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۱: تعامل و تجربه کاربری</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>رابط وب سازمانی</td>
              <td>تعامل کاربران با سامانه از طریق مرورگر، شامل چت، آپلود فایل، مشاهده گزارش</td>
              <td>محور ۴</td>
            </tr>
            <tr>
              <td>نسخه دسکتاپ</td>
              <td>دسترسی به قابلیت‌های سامانه از طریق اپلیکیشن دسکتاپ با قابلیت دسترسی به فایل‌های محلی</td>
              <td>محور ۴</td>
            </tr>
            <tr>
              <td>درگاه API</td>
              <td>امکان یکپارچه‌سازی سیستم‌های سازمانی و استفاده از اعتبار اختصاصی</td>
              <td>محور ۳</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۲: کنترل دسترسی و نشست</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>احراز هویت</td>
              <td>تأیید هویت کاربران و یکپارچه‌سازی با سامانه‌های هویت سازمانی</td>
              <td>محور ۲</td>
            </tr>
            <tr>
              <td>مدیریت نقش‌ها</td>
              <td>تعریف و مدیریت نقش‌ها، کاربران و سطوح دسترسی واحدهای مختلف</td>
              <td>محور ۲</td>
            </tr>
            <tr>
              <td>موتور مجوزها</td>
              <td>اعمال مجوزها در سطح مدل، منبع، ابزار و رکورد؛ فهرست مجاز مدل‌ها و ابزارها</td>
              <td>محور ۲</td>
            </tr>
            <tr>
              <td>مدیریت نشست</td>
              <td>حفظ زمینه کاربر، سطح دسترسی فعال و سیاست‌های نشست</td>
              <td>محور ۲</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۳: هماهنگی و ارکستراسیون (هسته ایجنت)</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>موتور ایجنت</td>
              <td>هسته اصلی تصمیم‌گیری؛ دریافت هدف، تولید برنامه، اجرا و اصلاح بر اساس نتیجه</td>
              <td>محور ۱</td>
            </tr>
            <tr>
              <td>برنامه‌ریز (Planner)</td>
              <td>تبدیل هدف به مراحل اجرایی قابل پیگیری</td>
              <td>محور ۱</td>
            </tr>
            <tr>
              <td>انتخاب‌گر ابزار (Tool Selector)</td>
              <td>انتخاب ابزار یا منبع مناسب از میان فهرست مجاز کاربر</td>
              <td>محور ۱، ۲</td>
            </tr>
            <tr>
              <td>مدیریت جریان (Flow Manager)</td>
              <td>هدایت جریان اجرا، مدیریت حالت‌ها، واکنش به خطا و تغییر شرایط</td>
              <td>محور ۱</td>
            </tr>
            <tr>
              <td>نقاط تأیید انسانی</td>
              <td>تعریف و اجرای نقاط Human-in-the-loop برای تأیید عملیات حساس</td>
              <td>محور ۱</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۴: هوش و مدل‌ها</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>درگاه مدل‌ها (Model Gateway)</td>
              <td>لایه انتزاع دسترسی به مدل‌های مختلف (داخلی/خارجی) با سیاست‌های یکسان</td>
              <td>محور ۱، ۵</td>
            </tr>
            <tr>
              <td>مدیریت مدل</td>
              <td>فهرست مدل‌های مجاز، نسخه‌بندی، به‌روزرسانی و سیاست دسترسی به مدل‌های جدید</td>
              <td>محور ۱</td>
            </tr>
            <tr>
              <td>بازیابی و تقویت (RAG)</td>
              <td>بازیابی اطلاعات از منابع مجاز کاربر و تقویت پاسخ مدل با شواهد</td>
              <td>محور ۲، ۴</td>
            </tr>
            <tr>
              <td>حافظه و زمینه</td>
              <td>مدیریت زمینه مکالمه، حافظه کوتاه‌مدت و بلندمدت با رعایت سطح دسترسی</td>
              <td>محور ۲</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۵: داده و منابع</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>منابع دانش سازمانی</td>
              <td>مخازن دانش، اسناد، پایگاه‌های دانش و محتوای ساختاریافته/غیرساختاریافته</td>
              <td>محور ۴، ۵</td>
            </tr>
            <tr>
              <td>مدیریت فایل و پوشه</td>
              <td>دسترسی کنترل‌شده به فایل‌های محلی/شبکه و تحلیل چند فایل</td>
              <td>محور ۴</td>
            </tr>
            <tr>
              <td>سرویس‌های خارجی</td>
              <td>اتصال به سرویس‌های ثالث از طریق API با سیاست‌های حاکمیت داده</td>
              <td>محور ۵</td>
            </tr>
            <tr>
              <td>ابزارهای عملیاتی</td>
              <td>مجموعه ابزارهای قابل فراخوانی توسط ایجنت (جستجو، محاسبه، ارسال، تبدیل و...)</td>
              <td>محور ۱</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">لایه ۶: خروجی و گزارش</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>تولید گزارش</td>
              <td>تولید خروجی متنی، جدولی و نموداری با قابلیت ویرایش و ارجاع به منابع</td>
              <td>محور ۴</td>
            </tr>
            <tr>
              <td>مبدل قالب</td>
              <td>تبدیل خروجی به Word، Excel و سایر قالب‌های موردنیاز</td>
              <td>محور ۴</td>
            </tr>
            <tr>
              <td>داشبورد مصرف</td>
              <td>نمایش مصرف و هزینه به تفکیک کاربر، مدل، ایجنت و ابزار</td>
              <td>محور ۳</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">محورهای عرضی</h4>
        <table class="styled-table">
          <thead>
            <tr>
              <th>مولفه</th>
              <th>مسئولیت</th>
              <th>نیازمندی مرتبط</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>سیاست‌گذار داده</td>
              <td>تعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدل</td>
              <td>محور ۵</td>
            </tr>
            <tr>
              <td>ممیزی و لاگ</td>
              <td>ثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها برای ممیزی</td>
              <td>محور ۲، ۵</td>
            </tr>
            <tr>
              <td>سنسور محرمانگی</td>
              <td>شناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسی در پاسخ‌ها</td>
              <td>محور ۲</td>
            </tr>
            <tr>
              <td>متریک و ردیابی</td>
              <td>اندازه‌گیری مصرف توکن، زمان پاسخ، نرخ خطا و شاخص‌های عملکرد</td>
              <td>محور ۳، ۷</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>روابط میان مولفه‌ها</h3>
          <div class="subtitle">Component Relationships</div>
        </div>
      </div>
      <div class="section-content">
        <p>روابط میان مولفه‌ها بر اساس <strong>جریان درخواست</strong> و <strong>جریان کنترل</strong> تعریف می‌شود. هر درخواست کاربر از لایه تعامل وارد شده و پس از عبور از لایه‌های کنترل، ارکستراسیون و هوش، به منابع داده دسترسی پیدا کرده و خروجی از لایه گزارش بازمی‌گردد.</p>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">جریان اصلی درخواست (Request Flow)</h4>
        <div class="flow-grid">
          <div class="flow-card">
            <div class="flow-number">۱</div>
            <h5>ورود درخواست</h5>
            <p>کاربر از طریق رابط وب/دسکتاپ/API درخواست را ارسال می‌کند.</p>
          </div>
          <div class="flow-card">
            <div class="flow-number">۲</div>
            <h5>احراز و مجوز</h5>
            <p>لایه کنترل، هویت کاربر را تأیید و سطح دسترسی فعال را تعیین می‌کند.</p>
          </div>
          <div class="flow-card">
            <div class="flow-number">۳</div>
            <h5>تصمیم ارکستراسیون</h5>
            <p>موتور ایجنت نوع درخواست (پاسخ ساده / برنامه‌ریزی چندمرحله‌ای) را تشخیص می‌دهد.</p>
          </div>
          <div class="flow-card">
            <div class="flow-number">۴</div>
            <h5>بازیابی و استدلال</h5>
            <p>لایه هوش با رعایت مجوزها، اطلاعات را بازیابی و مدل مناسب را فراخوانی می‌کند.</p>
          </div>
          <div class="flow-card">
            <div class="flow-number">۵</div>
            <h5>اجرای ابزار</h5>
            <p>در صورت نیاز، ایجنت ابزار مجاز را انتخاب و عملیات را اجرا می‌کند.</p>
          </div>
          <div class="flow-card">
            <div class="flow-number">۶</div>
            <h5>تولید خروجی</h5>
            <p>لایه گزارش، پاسخ یا گزارش نهایی را با ارجاع به منابع تولید می‌کند.</p>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">جدول روابط کلیدی میان مولفه‌ها</h4>
        <table class="styled-table relation-table">
          <thead>
            <tr>
              <th>از مولفه</th>
              <th>به مولفه</th>
              <th>نوع رابطه</th>
              <th>توضیح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td class="from-cell">رابط کاربری</td>
              <td class="to-cell">مدیریت نشست</td>
              <td>درخواست/پاسخ</td>
              <td>هر تعامل کاربر از این مسیر وارد و نشست فعال می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">مدیریت نشست</td>
              <td class="to-cell">موتور مجوزها</td>
              <td>پرس‌وجو</td>
              <td>سطح دسترسی و فهرست مجاز کاربر استعلام می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">موتور مجوزها</td>
              <td class="to-cell">موتور ایجنت</td>
              <td>اعمال محدودیت</td>
              <td>فهرست ابزارها، مدل‌ها و منابع مجاز به ایجنت ابلاغ می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">موتور ایجنت</td>
              <td class="to-cell">برنامه‌ریز</td>
              <td>فراخوانی</td>
              <td>هدف کاربر برای تولید برنامه اجرایی ارسال می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">برنامه‌ریز</td>
              <td class="to-cell">انتخاب‌گر ابزار</td>
              <td>درخواست انتخاب</td>
              <td>برای هر مرحله، ابزار مناسب از فهرست مجاز انتخاب می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">انتخاب‌گر ابزار</td>
              <td class="to-cell">ابزارهای عملیاتی</td>
              <td>فراخوانی</td>
              <td>ابزار انتخاب‌شده اجرا و نتیجه بازمی‌گردد</td>
            </tr>
            <tr>
              <td class="from-cell">موتور ایجنت</td>
              <td class="to-cell">نقاط تأیید انسانی</td>
              <td>توقف/تأیید</td>
              <td>در عملیات حساس، اجرا متوقف و منتظر تأیید انسان می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">موتور ایجنت</td>
              <td class="to-cell">درگاه مدل‌ها</td>
              <td>فراخوانی مدل</td>
              <td>برای استدلال، تولید متن یا تصمیم‌گیری، مدل مناسب فراخوانی می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">درگاه مدل‌ها</td>
              <td class="to-cell">مدیریت مدل</td>
              <td>استعلام</td>
              <td>مدل مجاز و نسخه فعال برای کاربر بررسی می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">بازیابی و تقویت</td>
              <td class="to-cell">منابع دانش سازمانی</td>
              <td>بازیابی</td>
              <td>اطلاعات مرتبط با رعایت سطح دسترسی بازیابی می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">سنسور محرمانگی</td>
              <td class="to-cell">تولید گزارش</td>
              <td>فیلتر</td>
              <td>پاسخ نهایی پیش از ارائه، از نظر افشای اطلاعات بررسی می‌شود</td>
            </tr>
            <tr>
              <td class="from-cell">متریک و ردیابی</td>
              <td class="to-cell">داشبورد مصرف</td>
              <td>تغذیه داده</td>
              <td>داده‌های مصرف و هزینه برای گزارش‌گیری ارسال می‌شود</td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✓ نکته کلیدی درباره روابط:</strong> مسیر <strong>موتور مجوزها ← موتور ایجنت</strong> و <strong>سنسور محرمانگی ← تولید گزارش</strong> دو مسیر حیاتی برای پاسخ به آزمون نفوذ دسترسی کارفرما هستند. این دو مسیر تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مستقل مسدود شود (دفاع لایه‌ای).
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>جریان‌های کلیدی سیستم</h3>
          <div class="subtitle">Key System Flows</div>
        </div>
      </div>
      <div class="section-content">
        <p>سه جریان اصلی در سامانه وجود دارد که هر یک از منظر تفکر سیستماتیک، رفتار متفاوتی از خود نشان می‌دهند:</p>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">جریان ۱: پاسخ ساده (Simple Response)</h4>
        <p>درخواست کاربر مستقیماً به لایه هوش رفته، مدل پاسخ تولید می‌کند و پس از فیلتر محرمانگی، به کاربر بازمی‌گردد. این جریان برای پرسش‌های ساده و بدون نیاز به ابزار یا چند مرحله است.</p>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">جریان ۲: پاسخ مبتنی بر بازیابی (RAG Flow)</h4>
        <p>درخواست کاربر ابتدا به بازیابی اطلاعات از منابع مجاز می‌رود، شواهد بازیابی‌شده به مدل تزریق می‌شود و پاسخ با ارجاع به منابع تولید می‌گردد. این جریان برای پرسش‌های دانش‌محور و تحلیل اسناد است.</p>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">جریان ۳: اجرای چندمرحله‌ای ایجنت (Agentic Flow)</h4>
        <p>این جریان، هسته تمایز سامانه است و مستقیماً پاسخ به محور ۱ نیازمندی‌هاست:</p>

        <div class="arch-diagram">
          <div class="arch-row">
            <div class="arch-box">
              <div class="arch-box-title">۱. دریافت هدف</div>
              <div class="arch-box-desc">هدف کاربر در موتور ایجنت ثبت می‌شود</div>
            </div>
            <div class="arch-arrow">←</div>
            <div class="arch-box">
              <div class="arch-box-title">۲. تولید برنامه</div>
              <div class="arch-box-desc">برنامه‌ریز مراحل اجرایی را تولید می‌کند</div>
            </div>
          </div>
          <div class="arch-row">
            <div class="arch-box">
              <div class="arch-box-title">۳. انتخاب ابزار</div>
              <div class="arch-box-desc">برای هر مرحله ابزار مجاز انتخاب می‌شود</div>
            </div>
            <div class="arch-arrow">←</div>
            <div class="arch-box">
              <div class="arch-box-title">۴. اجرا</div>
              <div class="arch-box-desc">ابزار اجرا و نتیجه دریافت می‌شود</div>
            </div>
          </div>
          <div class="arch-row">
            <div class="arch-box">
              <div class="arch-box-title">۵. ارزیابی نتیجه</div>
              <div class="arch-box-desc">نتیجه با هدف مقایسه می‌شود</div>
            </div>
            <div class="arch-arrow">←</div>
            <div class="arch-box">
              <div class="arch-box-title">۶. اصلاح یا خاتمه</div>
              <div class="arch-box-desc">در صورت نیاز، برنامه اصلاح و ادامه می‌یابد</div>
            </div>
          </div>
          <div class="arch-row">
            <div class="arch-box" style="border-color: var(--warning);">
              <div class="arch-box-title" style="color: var(--warning);">نقاط تأیید انسانی</div>
              <div class="arch-box-desc">در عملیات حساس، اجرا متوقف و منتظر تأیید می‌شود</div>
            </div>
            <div class="arch-box" style="border-color: var(--danger);">
              <div class="arch-box-title" style="color: var(--danger);">مدیریت خطا</div>
              <div class="arch-box-desc">در صورت خطا، برنامه بازنگری یا به کاربر اعلام می‌شود</div>
            </div>
          </div>
        </div>

        <div class="info-box">
          <strong>💡 تمایز ایجنت از Assistant:</strong> در جریان ۳، سامانه <strong>هدف را به مراحل اجرایی تبدیل می‌کند، ابزار انتخاب می‌کند، عملیات را اجرا می‌کند و بر اساس نتیجه، مراحل بعدی را تعیین یا اصلاح می‌کند</strong>. این رفتار حلقه‌ای (Closed-loop) است، در حالی که Assistant صرفاً به یک درخواست پاسخ می‌دهد. این تمایز، دقیقاً همان چیزی است که کارفرما در محور ۱ به‌عنوان قابلیت قابل‌آزمون درخواست کرده است.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>نگاشت نیازمندی‌ها به مولفه‌های معماری</h3>
          <div class="subtitle">Requirements-to-Architecture Mapping</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر نشان می‌دهد هر محور از نیازمندی‌های کارفرما، توسط کدام لایه‌ها و مولفه‌های معماری پوشش داده می‌شود:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>محور نیازمندی</th>
              <th>لایه‌های درگیر</th>
              <th>مولفه‌های کلیدی</th>
              <th>نحوه پوشش</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><strong>محور ۱: ماهیت و ایجنت</strong></td>
              <td>لایه ۳، ۴</td>
              <td>موتور ایجنت، برنامه‌ریز، انتخاب‌گر ابزار، مدیریت جریان، نقاط تأیید انسانی</td>
              <td>جریان ۳ به‌صورت حلقه‌ای و قابل‌آزمون</td>
            </tr>
            <tr>
              <td><strong>محور ۲: دسترسی</strong></td>
              <td>لایه ۲ + محور عرضی</td>
              <td>مدیریت نقش‌ها، موتور مجوزها، سنسور محرمانگی، ممیزی</td>
              <td>دفاع لایه‌ای در دو نقطه مستقل</td>
            </tr>
            <tr>
              <td><strong>محور ۳: پلن و مصرف</strong></td>
              <td>محور عرضی + لایه ۶</td>
              <td>متریک و ردیابی، داشبورد مصرف، درگاه API</td>
              <td>اندازه‌گیری در سطح کاربر/مدل/ایجنت</td>
            </tr>
            <tr>
              <td><strong>محور ۴: رابط و گزارش</strong></td>
              <td>لایه ۱، ۵، ۶</td>
              <td>رابط وب، نسخه دسکتاپ، مدیریت فایل، تولید گزارش، مبدل قالب</td>
              <td>پوشش کامل تعامل و خروجی</td>
            </tr>
            <tr>
              <td><strong>محور ۵: حاکمیت داده</strong></td>
              <td>محور عرضی + لایه ۵</td>
              <td>سیاست‌گذار داده، ممیزی، درگاه مدل‌ها، مدیریت منابع</td>
              <td>اعمال عرضی در تمام لایه‌ها</td>
            </tr>
            <tr>
              <td><strong>محور ۶: پیاده‌سازی و آموزش</strong></td>
              <td>همه لایه‌ها</td>
              <td>توسعه‌پذیری مولفه‌ها، رابط‌های تعریف‌شده</td>
              <td>امکان سفارشی‌سازی لایه‌ای</td>
            </tr>
            <tr>
              <td><strong>محور ۷: عملکرد و تاب‌آوری</strong></td>
              <td>محور عرضی + لایه ۴، ۵</td>
              <td>متریک و ردیابی، درگاه مدل‌ها، مدیریت منابع</td>
              <td>امکان استقرار درون‌سازمانی</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>ویژگی‌های کیفی معماری</h3>
          <div class="subtitle">Architectural Quality Attributes</div>
        </div>
      </div>
      <div class="section-content">
        <p>معماری کلان باید ویژگی‌های کیفی زیر را تضمین کند که مستقیماً از نیازمندی‌های کارفرما استخراج شده‌اند:</p>

        <div class="comparison-grid">
          <div class="comparison-card recommended">
            <span class="card-badge">حیاتی ✓</span>
            <h4>امنیت و محرمانگی</h4>
            <ul>
              <li><span>دفاع لایه‌ای</span> <span class="value">دو نقطه مستقل</span></li>
              <li><span>ممیزی</span> <span class="value">کامل</span></li>
              <li><span>فیلتر خروجی</span> <span class="value">سنسور محرمانگی</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">حیاتی ✓</span>
            <h4>قابلیت آزمون</h4>
            <ul>
              <li><span>ایجنت</span> <span class="value">رفتار قابل مشاهده</span></li>
              <li><span>دسترسی</span> <span class="value">آزمون نفوذپذیر</span></li>
              <li><span>مصرف</span> <span class="value">قابل اندازه‌گیری</span></li>
            </ul>
          </div>
        </div>

        <div class="comparison-grid">
          <div class="comparison-card">
            <h4>تاب‌آوری</h4>
            <ul>
              <li><span>استقرار</span> <span class="value">درون‌سازمانی</span></li>
              <li><span>قطع اینترنت</span> <span class="value">عملکرد محلی</span></li>
              <li><span>مدل‌ها</span> <span class="value">چندگانه</span></li>
            </ul>
          </div>
          <div class="comparison-card">
            <h4>توسعه‌پذیری</h4>
            <ul>
              <li><span>مدل جدید</span> <span class="value">بدون تغییر هسته</span></li>
              <li><span>ابزار جدید</span> <span class="value">ثبت در فهرست</span></li>
              <li><span>ایجنت اختصاصی</span> <span class="value">قابل تعریف</span></li>
            </ul>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نکته کلیدی:</strong> ویژگی «قابلیت آزمون» در این معماری یک ویژگی درجه‌یک است، نه ثانویه. هر مولفه‌ای که رفتار آن قابل مشاهده و اندازه‌گیری نباشد، نمی‌تواند در جلسه دمو و آزمون‌های عملی کارفرما پاسخگو باشد. بنابراین، مرزهای مولفه‌ها و رابط‌های آنها به‌گونه‌ای طراحی شده که <strong>هر ادعا، قابل اثبات</strong> باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>جمع‌بندی معماری</h3>
          <div class="subtitle">Architecture Summary</div>
        </div>
      </div>
      <div class="section-content">
        <p>معماری کلان ارائه‌شده، پاسخی سیستماتیک و فارغ از سکو به نیازمندی‌های شرکت پارسا پلیمر شریف است. ویژگی‌های متمایز این معماری:</p>

        <ul class="reference-list">
          <li>
            <strong>ساختار شش‌لایه + دو محور عرضی</strong>
            جداسازی دغدغه‌ها و اعمال سیستماتیک حاکمیت و مشاهده‌پذیری در تمام لایه‌ها
          </li>
          <li>
            <strong>موتور ایجنت به‌عنوان هسته مستقل</strong>
            با قابلیت برنامه‌ریزی، انتخاب ابزار، اجرا، ارزیابی و اصلاح — قابل مشاهده و آزمون
          </li>
          <li>
            <strong>دفاع لایه‌ای برای دسترسی</strong>
            دو نقطه مستقل کنترل (موتور مجوزها و سنسور محرمانگی) برای پاسخ به آزمون نفوذ کارفرما
          </li>
          <li>
            <strong>شفافیت مصرف به‌صورت عرضی</strong>
            اندازه‌گیری و گزارش در سطح کاربر، مدل، ایجنت و ابزار
          </li>
          <li>
            <strong>استقرارپذیری درون‌سازمانی</strong>
            با انتزاع درگاه مدل‌ها و مدیریت منابع، امکان عملکرد در شرایط قطع اینترنت
          </li>
          <li>
            <strong>توسعه‌پذیری بدون تغییر هسته</strong>
            افزودن مدل‌ها، ابزارها و ایجنت‌های جدید از طریق رابط‌های تعریف‌شده
          </li>
        </ul>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> این معماری کلان، مبنای طراحی تفصیلی (Detailed Design) و پیاده‌سازی خواهد بود. در گام بعدی، می‌توان طراحی تفصیلی هر لایه، رابط‌های مولفه‌ها، و سناریوی نمونه Agent برای جلسه دمو را تدوین کرد.
        </div>
      </div>
    </div>

    <div class="conclusion-box">
      <h3>🎯 ارزش معماری</h3>
      <p>این معماری، پاسخی سیستماتیک، لایه‌ای و فارغ از سکو به نیازمندی‌های فنی و آزمون‌محور کارفرماست.</p>
      <p>هر ادعای قابلیت، دارای مولفه مسئول، رابط تعریف‌شده و رفتار قابل مشاهده است تا در جلسه دمو و آزمون‌های عملی قابل اثبات باشد.</p>
      <div class="highlight">
        <strong>💎 ارزش پیشنهادی معماری:</strong><br>
        جداسازی دغدغه‌ها + حاکمیت عرضی + ایجنت قابل‌آزمون + دفاع لایه‌ای + شفافیت مصرف + استقرارپذیری
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_7cd76322-fd9c-4970-8e97-18a3308f7b90.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>پیاده‌سازی عملیاتی معماری | سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    vertical-align: top;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  /* ===== Implementation-specific styles ===== */
  .phase-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 12px;
    margin: 20px 0;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .phase-header {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 16px 22px;
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .phase-num {
    width: 44px; height: 44px;
    background: var(--accent);
    color: var(--primary);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 18px;
    flex-shrink: 0;
  }

  .phase-title h4 {
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 2px;
  }

  .phase-title .phase-sub {
    font-size: 11px;
    opacity: 0.85;
  }

  .phase-body {
    padding: 20px 22px;
  }

  .phase-body p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 0 !important;
    font-size: 13.5px;
    color: var(--text-muted);
  }

  .topic-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin: 15px 0;
  }

  .topic-box {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-right: 3px solid var(--primary-light);
    border-radius: 8px;
    padding: 14px 16px;
  }

  .topic-box h5 {
    font-size: 13px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .topic-box ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .topic-box ul li {
    font-size: 12px;
    color: var(--text-muted);
    padding: 3px 0 3px 14px;
    position: relative;
  }

  .topic-box ul li::before {
    content: '▸';
    position: absolute;
    right: 0;
    color: var(--accent);
    font-weight: 700;
  }

  .standard-chip {
    display: inline-block;
    background: rgba(201,169,97,0.18);
    border: 1px solid rgba(201,169,97,0.5);
    border-radius: 20px;
    padding: 2px 10px;
    font-size: 11px;
    color: var(--accent-dark);
    font-weight: 600;
    margin: 2px 4px 2px 0;
  }

  .standard-chip.blue {
    background: rgba(44,82,130,0.12);
    border-color: rgba(44,82,130,0.4);
    color: var(--primary);
  }

  .standard-chip.green {
    background: rgba(56,161,105,0.12);
    border-color: rgba(56,161,105,0.4);
    color: var(--success);
  }

  .deliverable-list {
    list-style: none;
    padding: 0;
    margin: 15px 0 0;
  }

  .deliverable-list li {
    background: #f0fff4;
    border: 1px solid #9ae6b4;
    border-right: 3px solid var(--success);
    border-radius: 6px;
    padding: 10px 14px;
    margin-bottom: 8px;
    font-size: 12.5px;
    color: var(--text-muted);
  }

  .deliverable-list li strong {
    color: var(--success);
    font-weight: 700;
  }

  .approach-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 15px;
    margin: 20px 0;
  }

  .approach-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 18px;
    text-align: center;
  }

  .approach-card .approach-icon {
    width: 48px; height: 48px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: var(--accent);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: 800;
    margin: 0 auto 12px;
  }

  .approach-card h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .approach-card p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin: 0;
  }

  .level-badge {
    display: inline-block;
    padding: 2px 9px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
  }

  .level-badge.basic {
    background: #ebf8ff;
    color: var(--primary);
    border: 1px solid #90cdf4;
  }

  .level-badge.inter {
    background: #fef5e7;
    color: var(--warning);
    border: 1px solid #fbd38d;
  }

  .level-badge.adv {
    background: #f0fff4;
    color: var(--success);
    border: 1px solid #9ae6b4;
  }

  .level-badge.expert {
    background: #fff5f5;
    color: var(--danger);
    border: 1px solid #feb2b2;
  }

  .skill-matrix td:first-child {
    font-weight: 600;
    color: var(--primary);
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .topic-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: IMPL-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">IMPLEMENTATION ROADMAP</span>
      <h1>پیاده‌سازی عملیاتی معماری</h1>
      <h2>سامانه هوش مصنوعی سازمانی با .NET و Microsoft Agent Framework</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>کارفرمای محترم،</strong><br>
      این مستند، نقشه راه عملیاتی پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) را با استفاده از استک <strong>.NET</strong>، <strong>Microsoft.Extensions.AI</strong> و <strong>Microsoft Agent Framework</strong> ارائه می‌دهد. رویکرد پیاده‌سازی <strong>Cross-Platform</strong> است و از کامپایل کدبیس واحد برای سکوهای مختلف (دسکتاپ و موبایل) پشتیبانی می‌کند. هدف، تبدیل معماری به یک محصول قابل ارائه، قابل آزمون و ارزش‌آفرین است.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>مقدمه: شرح مسئله و ضرورت محصول در عصر AI-Driven</h3>
          <div class="subtitle">Problem Statement & AI-Driven Necessity</div>
        </div>
      </div>
      <div class="section-content">
        <p>سازمان‌های امروزی با انبوهی از داده‌ها، اسناد و فرایندهای پیچیده مواجه‌اند که مدیریت و بهره‌برداری مؤثر از آن‌ها بدون ابزارهای هوشمند، عملاً غیرممکن شده است. در این میان، <strong>هوش مصنوعی دیگر یک مزیت رقابتی نیست؛ یک ضرورت بقا است</strong>. سازمان‌هایی که نتوانند دانش پراکنده خود را به قالب‌های قابل پرسش، قابل تحلیل و قابل اقدام تبدیل کنند، در برابر رقبای داده‌محور به سرعت عقب می‌مانند.</p>

        <p>مسئله اصلی، فقدان دسترسی یکپارچه به دانش سازمانی، ناتوانی در تحلیل سریع حجم بالای اسناد، و عدم وجود سازوکاری برای خودکارسازی تصمیم‌گیری‌های چندمرحله‌ای است. راهکارهای سنتی (جستجوی کلیدواژه، پایگاه‌های دانش ایستا، یا چت‌بات‌های ساده) نمی‌توانند پاسخگوی نیاز به <strong>استدلال، برنامه‌ریزی و اجرای عملیات</strong> باشند.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">AI<br>Driven</div>
            <div class="stat-label">ضرورت بقا در عصر داده</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">ایجنت<br>محور</div>
            <div class="stat-label">فراتر از چت‌بات ساده</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">Cross<br>Platform</div>
            <div class="stat-label">کدبیس واحد، چند سکو</div>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نتیجه کلیدی:</strong> آنچه سازمان‌ها به آن نیاز دارند، یک <strong>سامانه ایجنت‌محور</strong> است که بتواند اهداف را به مراحل اجرایی تبدیل کند، ابزار مناسب را انتخاب نماید، عملیات را انجام دهد و بر اساس نتیجه، مسیر خود را اصلاح کند. این مستند، نقشه راه پیاده‌سازی چنین سامانه‌ای را ارائه می‌دهد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>استک فنی و رویکرد پیاده‌سازی</h3>
          <div class="subtitle">Technical Stack & Implementation Approach</div>
        </div>
      </div>
      <div class="section-content">
        <p>استک فنی انتخاب‌شده بر پایه سه اصل استوار است: <strong>انتزاع مدل</strong> (برای تعویض‌پذیری)، <strong>ارکستراسیون ایجنت</strong> (برای قابلیت آزمون) و <strong>Cross-Platform</strong> (برای پوشش سکوهای مختلف با کدبیس واحد).</p>

        <h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">۲.۱ اجزای استک</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>لایه</th>
              <th>فناوری</th>
              <th>نقش در معماری</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>زبان و پلتفرم</td>
              <td>.NET 8/10</td>
              <td>Runtime یکپارچه برای Backend و سرویس‌ها</td>
            </tr>
            <tr>
              <td>انتزاع مدل</td>
              <td>Microsoft.Extensions.AI</td>
              <td>رابط یکپارچه برای اتصال به هر ارائه‌دهنده مدل (IChatClient، IEmbeddingGenerator)</td>
            </tr>
            <tr>
              <td>ارکستراسیون ایجنت</td>
              <td>Microsoft Agent Framework</td>
              <td>هسته ایجنت (AIAgent)، گراف چند-ایجنت (WorkflowBuilder)، ثبت ابزار (AIFunctionFactory)، MCP Client</td>
            </tr>
            <tr>
              <td>دسکتاپ Cross-Platform</td>
              <td>ElectronNET.Core</td>
              <td>اجرای Blazor/ASP.NET Core در پوسته Electron برای Windows/macOS/Linux</td>
            </tr>
            <tr>
              <td>موبایل Cross-Platform</td>
              <td>Ionic + Capacitor</td>
              <td>رابط WebView با دسترسی به APIهای بومی برای Android/iOS</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۲.۲ نقش Microsoft.Extensions.AI</h4>

        <p>این کتابخانه، یک <strong>لایه انتزاع</strong> برای مدل‌های زبانی فراهم می‌کند. مزایای کلیدی آن در معماری ما:</p>

        <ul class="reference-list">
          <li>
            <strong>IChatClient — رابط یکپارچه مدل‌ها</strong>
            امکان اتصال به هر ارائه‌دهنده مدل (Azure OpenAI، OpenAI، Ollama و...) بدون تغییر در منطق ایجنت. این انتزاع مستقیماً به نیازمندی «فهرست مجاز مدل‌ها» (محور ۲ نیازمندی‌ها) پاسخ می‌دهد: با تعریف چند IChatClient و اعمال محدودیت در لایه بالاتر، می‌توان مدل مجاز هر کاربر را کنترل کرد.
          </li>
          <li>
            <strong>Middleware — تزریق دغدغه‌های عرضی</strong>
            قابلیت تزریق Telemetry (OpenTelemetry)، Caching و Logging به خط لوله فراخوانی مدل. این ویژگی، پیاده‌سازی محور عرضی مشاهده‌پذیری (Y) را بدون تغییر در منطق اصلی ممکن می‌کند.
          </li>
          <li>
            <strong>IEmbeddingGenerator — انتزاع Embedding</strong>
            رابط یکپارچه برای تولید Embedding در جریان RAG، با قابلیت تعویض ارائه‌دهنده بدون تغییر در منطق بازیابی.
          </li>
        </ul>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۲.۳ نقش Microsoft Agent Framework</h4>

        <p>این فریم‌ورک، نسل بعدی Semantic Kernel و AutoGen است و قابلیت‌های زیر را برای پیاده‌سازی لایه ارکستراسیون (L3) فراهم می‌کند:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>قابلیت</th>
              <th>کاربرد در معماری</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>AIAgent</td>
              <td>هسته ایجنت؛ تولید برنامه، انتخاب ابزار، اجرا و اصلاح بر اساس نتیجه</td>
            </tr>
            <tr>
              <td>Agent Session</td>
              <td>مدیریت زمینه مکالمه (حافظه کوتاه‌مدت) — مولفه «حافظه و زمینه» در L4</td>
            </tr>
            <tr>
              <td>AIFunctionFactory</td>
              <td>ثبت ابزارها به‌عنوان توابع قابل فراخوانی توسط LLM — مولفه «انتخاب‌گر ابزار» در L3</td>
            </tr>
            <tr>
              <td>WorkflowBuilder</td>
              <td>گراف چند-ایجنت (Orchestrator-Worker) با Edges و شرایط — مولفه «مدیریت جریان» در L3</td>
            </tr>
            <tr>
              <td>MCP Client</td>
              <td>کشف پویای ابزارها در زمان اجرا — توسعه‌پذیری لایه ابزار</td>
            </tr>
            <tr>
              <td>Middleware</td>
              <td>نقاط تأیید انسانی (Human-in-the-loop) — مولفه «تأیید انسانی» در L3</td>
            </tr>
          </tbody>
        </table>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۲.۴ رویکرد Cross-Platform</h4>

        <p>رویکرد Cross-Platform با هدف <strong>کامپایل کدبیس واحد برای سکوهای مختلف</strong> طراحی شده است:</p>

        <div class="topic-grid">
          <div class="topic-box">
            <h5>دسکتاپ (Windows/macOS/Linux)</h5>
            <ul>
              <li>استفاده از ElectronNET.Core</li>
              <li>اجرای پروژه ASP.NET Core/Blazor در پوسته Electron</li>
              <li>کدبیس واحد .NET، خروجی اجرایی برای هر سه سکو</li>
              <li>دسترسی کنترل‌شده به فایل‌های محلی</li>
            </ul>
          </div>
          <div class="topic-box">
            <h5>موبایل (Android/iOS)</h5>
            <ul>
              <li>استفاده از Ionic + Capacitor</li>
              <li>رابط WebView با دسترسی به APIهای بومی</li>
              <li>ارتباط با Backend .NET از طریق API</li>
              <li>مناسب برای فرم‌ها، چت و داشبوردهای سبک</li>
            </ul>
          </div>
        </div>

        <div class="info-box">
          <strong>💡 نکته معماری:</strong> رابط کاربری اصلی (چت، آپلود فایل، گزارش) در <strong>Blazor</strong> پیاده‌سازی می‌شود که هم در Electron (دسکتاپ) و هم در مرورگر (وب) قابل اجراست. نسخه موبایل Ionic صرفاً برای سناریوهای سبک (اعلان‌ها، تأییدات) استفاده می‌شود تا از پیچیدگی غیرضروری جلوگیری شود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>نقشه راه پیاده‌سازی گام‌به‌گام به تفکیک مولفه‌ها</h3>
          <div class="subtitle">Step-by-Step Implementation Roadmap by Component</div>
        </div>
      </div>
      <div class="section-content">
        <p>پیاده‌سازی در <strong>پنج فاز اجرایی</strong> سازمان‌دهی شده است. هر فاز، مجموعه‌ای از مولفه‌های معماری را پوشش می‌دهد و با خروجی قابل‌آزمون پایان می‌یابد. ترتیب فازها بر اساس <strong>وابستگی فنی</strong> و <strong>اولویت ارزش‌آفرینی</strong> تعیین شده است.</p>

        <!-- Phase A -->
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">A</div>
            <div class="phase-title">
              <h4>فاز A — هسته ایجنت و رابط پایه</h4>
              <div class="phase-sub">Core Agent & Base UI</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، پایه‌ای‌ترین قابلیت محصول را می‌سازد: یک ایجنت که می‌تواند به مدل متصل شود، درخواست کاربر را دریافت کند و پاسخ دهد. بدون این فاز، هیچ قابلیت دیگری قابل ارائه نیست.</p>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>مولفه معماری</th>
                  <th>رویکرد پیاده‌سازی</th>
                  <th>وابستگی</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>درگاه مدل‌ها (L4)</td>
                  <td>پیاده‌سازی Factory برای IChatClient؛ تعریف چند ارائه‌دهنده (Azure OpenAI، Ollama) و انتخاب بر اساس Configuration</td>
                  <td>—</td>
                </tr>
                <tr>
                  <td>موتور ایجنت (L3)</td>
                  <td>ساخت AIAgent با استفاده از chatClient.AsAIAgent()؛ تعریف Instructions برای رفتار پایه</td>
                  <td>درگاه مدل‌ها</td>
                </tr>
                <tr>
                  <td>رابط وب (L1)</td>
                  <td>پیاده‌سازی Blazor Server برای چت پایه؛ اتصال به موتور ایجنت از طریق SignalR</td>
                  <td>موتور ایجنت</td>
                </tr>
                <tr>
                  <td>احراز هویت (L2)</td>
                  <td>ASP.NET Core Identity + OIDC برای یکپارچه‌سازی با سامانه هویت سازمانی</td>
                  <td>—</td>
                </tr>
                <tr>
                  <td>درگاه API (L1)</td>
                  <td>ASP.NET Core Minimal API برای دسترسی برنامه‌نویسی و یکپارچه‌سازی</td>
                  <td>احراز هویت</td>
                </tr>
              </tbody>
            </table>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون فاز A:</strong></p>
            <ul class="deliverable-list">
              <li><strong>چت پایه با ایجنت:</strong> کاربر می‌تواند وارد شود، پرسش بپرسد و پاسخ از مدل دریافت کند</li>
              <li><strong>تعویض‌پذیری مدل:</strong> تغییر مدل از طریق Configuration بدون تغییر کد</li>
            </ul>
          </div>
        </div>

        <!-- Phase B -->
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">B</div>
            <div class="phase-title">
              <h4>فاز B — ابزارها، RAG و منابع دانش</h4>
              <div class="phase-sub">Tools, RAG & Knowledge Sources</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، ایجنت را از یک چت‌بات ساده به یک <strong>ایجنت واقعی</strong> تبدیل می‌کند: توانایی فراخوانی ابزار و جستجو در منابع دانش سازمانی.</p>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>مولفه معماری</th>
                  <th>رویکرد پیاده‌سازی</th>
                  <th>وابستگی</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>انتخاب‌گر ابزار (L3)</td>
                  <td>ثبت ابزارها با AIFunctionFactory.Create()؛ تعریف Tool Registry برای مدیریت فهرست ابزارهای مجاز</td>
                  <td>موتور ایجنت</td>
                </tr>
                <tr>
                  <td>ابزارهای عملیاتی (L5)</td>
                  <td>پیاده‌سازی متدهای C# به‌عنوان Function Tools (جستجو، محاسبه، تبدیل و...)</td>
                  <td>انتخاب‌گر ابزار</td>
                </tr>
                <tr>
                  <td>RAG (L4)</td>
                  <td>استفاده از IEmbeddingGenerator برای تولید Embedding؛ ذخیره در Vector Store؛ بازیابی با رعایت سطح دسترسی</td>
                  <td>درگاه مدل‌ها</td>
                </tr>
                <tr>
                  <td>منابع دانش (L5)</td>
                  <td>Indexer برای SharePoint/File System؛ Chunking و ذخیره در Vector Store</td>
                  <td>RAG</td>
                </tr>
                <tr>
                  <td>مدیریت فایل (L5)</td>
                  <td>File API با بررسی مجوز پیش از دسترسی؛ تحلیل چند فایل</td>
                  <td>موتور مجوزها</td>
                </tr>
                <tr>
                  <td>حافظه و زمینه (L4)</td>
                  <td>استفاده از AgentSession برای حفظ زمینه مکالمه؛ مدیریت Context Window</td>
                  <td>موتور ایجنت</td>
                </tr>
              </tbody>
            </table>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون فاز B:</strong></p>
            <ul class="deliverable-list">
              <li><strong>ایجنت ابزارمحور:</strong> ایجنت می‌تواند ابزار فراخوانی کند و نتیجه را در پاسخ به کار گیرد</li>
              <li><strong>RAG با ارجاع:</strong> پاسخ‌ها با ارجاع به منبع بازیابی‌شده ارائه می‌شوند</li>
              <li><strong>دسترسی کنترل‌شده به فایل:</strong> کاربر فقط به فایل‌های مجاز دسترسی دارد</li>
            </ul>
          </div>
        </div>

        <!-- Phase C -->
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">C</div>
            <div class="phase-title">
              <h4>فاز C — حاکمیت داده و کنترل دسترسی</h4>
              <div class="phase-sub">Data Governance & Access Control</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، پاسخ مستقیم به <strong>آزمون نفوذ دسترسی کارفرما</strong> (محور ۲ نیازمندی‌ها) است. بدون این فاز، محصول نمی‌تواند در محیط سازمانی حساس مورد استفاده قرار گیرد.</p>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>مولفه معماری</th>
                  <th>رویکرد پیاده‌سازی</th>
                  <th>وابستگی</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>موتور مجوزها (L2)</td>
                  <td>Policy-based Authorization در ASP.NET Core؛ پیاده‌سازی ABAC برای کنترل تا سطح سند/رکورد</td>
                  <td>احراز هویت</td>
                </tr>
                <tr>
                  <td>مدیریت نقش‌ها (L2)</td>
                  <td>تعریف نقش‌ها و مجوزها؛ تخصیص کاربران واحدهای مختلف</td>
                  <td>احراز هویت</td>
                </tr>
                <tr>
                  <td>مدیریت نشست (L2)</td>
                  <td>AgentSession + Distributed Cache برای حفظ سطح دسترسی فعال در طول تعامل</td>
                  <td>موتور مجوزها</td>
                </tr>
                <tr>
                  <td>سیاست‌گذار داده (X)</td>
                  <td>تعریف و اعمال سیاست‌های ذخیره‌سازی، انتقال و آموزش مدل؛ Data Classification</td>
                  <td>—</td>
                </tr>
                <tr>
                  <td>سنسور محرمانگی (X)</td>
                  <td>Output Filter پیش از ارائه پاسخ؛ شناسایی و جلوگیری از افشای اطلاعات خارج از سطح دسترسی</td>
                  <td>موتور مجوزها</td>
                </tr>
                <tr>
                  <td>ممیزی و لاگ (X)</td>
                  <td>ثبت تمام تعاملات، تصمیمات ایجنت و دسترسی‌ها؛ Tamper-evident Logs</td>
                  <td>—</td>
                </tr>
              </tbody>
            </table>

            <div class="warning-box">
              <strong>⚠️ نکته حیاتی:</strong> این فاز باید <strong>دفاع لایه‌ای</strong> را پیاده‌سازی کند: موتور مجوزها (پیش از فراخوانی مدل) و سنسور محرمانگی (پس از تولید پاسخ). این دو نقطه مستقل، تضمین می‌کنند که حتی اگر ایجنت یا مدل بخواهد اطلاعات خارج از دسترس را افشا کند، در دو نقطه مسدود شود.
            </div>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون فاز C:</strong></p>
            <ul class="deliverable-list">
              <li><strong>مدل دسترسی کامل:</strong> نقش‌ها، مجوزها و کنترل تا سطح رکورد</li>
              <li><strong>سناریوی آزمون نفوذ:</strong> پرسش یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها — قابل اجرا در جلسه دمو</li>
            </ul>
          </div>
        </div>

        <!-- Phase D -->
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">D</div>
            <div class="phase-title">
              <h4>فاز D — گزارش، تأیید انسانی و مشاهده‌پذیری</h4>
              <div class="phase-sub">Reporting, Human-in-the-loop & Observability</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، محصول را از یک ابزار تحلیلی به یک <strong>محصول سازمانی کامل</strong> تبدیل می‌کند.</p>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>مولفه معماری</th>
                  <th>رویکرد پیاده‌سازی</th>
                  <th>وابستگی</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>مدیریت جریان (L3)</td>
                  <td>WorkflowBuilder برای گراف چندمرحله‌ای؛ تعریف Edges و شرایط ادامه/اصلاح</td>
                  <td>موتور ایجنت</td>
                </tr>
                <tr>
                  <td>تأیید انسانی (L3)</td>
                  <td>Middleware در Agent Framework برای توقف در نقاط حساس؛ Approval API برای دریافت تأیید</td>
                  <td>مدیریت جریان</td>
                </tr>
                <tr>
                  <td>تولید گزارش (L6)</td>
                  <td>Razor + QuestPDF/ClosedXML برای تولید خروجی متنی، جدولی و نموداری با ارجاع به منابع</td>
                  <td>موتور ایجنت</td>
                </tr>
                <tr>
                  <td>مبدل قالب (L6)</td>
                  <td>تبدیل خروجی به Word، Excel و PDF</td>
                  <td>تولید گزارش</td>
                </tr>
                <tr>
                  <td>داشبورد مصرف (L6)</td>
                  <td>Metrics + Blazor Dashboard برای نمایش مصرف و هزینه به تفکیک کاربر، مدل و ایجنت</td>
                  <td>متریک و ردیابی</td>
                </tr>
                <tr>
                  <td>متریک و ردیابی (Y)</td>
                  <td>OpenTelemetry + Serilog برای اندازه‌گیری مصرف توکن، زمان پاسخ و نرخ خطا</td>
                  <td>—</td>
                </tr>
              </tbody>
            </table>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون فاز D:</strong></p>
            <ul class="deliverable-list">
              <li><strong>گزارش کامل با ارجاع:</strong> خروجی Word/Excel با منابع</li>
              <li><strong>جریان چندمرحله‌ای با تأیید انسانی:</strong> قابل نمایش در جلسه دمو</li>
              <li><strong>داشبورد مصرف:</strong> شفافیت هزینه به تفکیک کاربر/مدل</li>
            </ul>
          </div>
        </div>

        <!-- Phase E -->
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">E</div>
            <div class="phase-title">
              <h4>فاز E — Cross-Platform و آماده‌سازی محصول</h4>
              <div class="phase-sub">Cross-Platform & Product Readiness</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز نهایی، محصول را برای ارائه در سکوهای مختلف و آماده‌سازی برای استقرار سازمانی آماده می‌کند.</p>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>مولفه</th>
                  <th>رویکرد پیاده‌سازی</th>
                  <th>وابستگی</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>نسخه دسکتاپ (L1)</td>
                  <td>ElectronNET.Core برای بسته‌بندی Blazor در پوسته Electron برای Windows/macOS/Linux</td>
                  <td>رابط وب</td>
                </tr>
                <tr>
                  <td>نسخه موبایل (L1)</td>
                  <td>Ionic + Capacitor برای سناریوهای سبک (اعلان، تأیید)</td>
                  <td>درگاه API</td>
                </tr>
                <tr>
                  <td>مدیریت مدل (L4)</td>
                  <td>Model Registry برای نسخه‌بندی و سیاست دسترسی به مدل‌های جدید</td>
                  <td>درگاه مدل‌ها</td>
                </tr>
                <tr>
                  <td>استقرار On-Premise</td>
                  <td>پشتیبانی از مدل‌های محلی (Ollama) برای عملکرد در قطع اینترنت بین‌الملل</td>
                  <td>درگاه مدل‌ها</td>
                </tr>
              </tbody>
            </table>

            <p style="margin-top:12px;"><strong>خروجی قابل‌آزمون فاز E:</strong></p>
            <ul class="deliverable-list">
              <li><strong>محصول Cross-Platform:</strong> نسخه وب + دسکتاپ + موبایل از کدبیس واحد</li>
              <li><strong>تاب‌آوری:</strong> عملکرد در شرایط قطع اینترنت بین‌الملل</li>
            </ul>
          </div>
        </div>

        <div class="success-box">
          <strong>✓ نکته کلیدی:</strong> فازهای A تا C، پاسخ به <strong>محورهای ۱، ۲ و ۵</strong> نیازمندی‌ها هستند و آمادگی برای <strong>جلسه دمو و آزمون عملی</strong> کارفرما را فراهم می‌کنند. فازهای D و E، محصول را برای <strong>استقرار بلندمدت</strong> و پاسخ به محورهای ۴، ۶ و ۷ آماده می‌سازند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>تیم، تخصص‌ها و مهارت‌های موردنیاز</h3>
          <div class="subtitle">Team, Expertise & Required Skills</div>
        </div>
      </div>
      <div class="section-content">
        <p>پیاده‌سازی این معماری نیازمند تیمی چندنقشی با هم‌پوشانی مهارت‌هاست. جدول زیر نقش‌ها، تخصص‌ها و سطح مهارت موردنیاز را نشان می‌دهد:</p>

        <h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">۴.۱ جدول نقش‌ها و مهارت‌ها</h4>

        <table class="styled-table skill-matrix">
          <thead>
            <tr>
              <th>نقش</th>
              <th>تخصص اصلی</th>
              <th>مهارت‌های کلیدی</th>
              <th>سطح</th>
              <th>تعداد</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>معمار ارشد</td>
              <td>طراحی سیستم‌های توزیع‌شده</td>
              <td>.NET، Agent Framework، الگوهای طراحی، BPMN</td>
              <td><span class="level-badge expert">خبره</span></td>
              <td>۱</td>
            </tr>
            <tr>
              <td>توسعه‌دهنده Backend (ایجنت)</td>
              <td>Microsoft Agent Framework</td>
              <td>AIAgent، AIFunctionFactory، WorkflowBuilder، MCP</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td>۲</td>
            </tr>
            <tr>
              <td>توسعه‌دهنده Backend (داده/RAG)</td>
              <td>RAG و Vector Store</td>
              <td>IEmbeddingGenerator، Chunking، Retrieval</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td>۱</td>
            </tr>
            <tr>
              <td>توسعه‌دهنده Frontend (Blazor)</td>
              <td>Blazor + ElectronNET</td>
              <td>Blazor Server/WASM، CSS، ElectronNET</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td>۲</td>
            </tr>
            <tr>
              <td>توسعه‌دهنده موبایل (Ionic)</td>
              <td>Ionic + Capacitor</td>
              <td>TypeScript، Angular/React، Capacitor API</td>
              <td><span class="level-badge inter">میانی</span></td>
              <td>۱</td>
            </tr>
            <tr>
              <td>مهندس امنیت</td>
              <td>IAM و حاکمیت داده</td>
              <td>OAuth 2.0، OIDC، Policy-based Auth، OWASP LLM Top 10</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td>۱</td>
            </tr>
            <tr>
              <td>مهندس DevOps</td>
              <td>CI/CD و مشاهده‌پذیری</td>
              <td>.NET Build، OpenTelemetry، Docker</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td>۱</td>
            </tr>
            <tr>
              <td>مهندس تست</td>
              <td>تست ایجنت و RAG</td>
              <td>xUnit، Test Containers، Scenario Testing</td>
              <td><span class="level-badge inter">میانی</span></td>
              <td>۱</td>
            </tr>
          </tbody>
        </table>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">۱۰</div>
            <div class="stat-label">نفر برای پیاده‌سازی کامل</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۴</div>
            <div class="stat-label">نفر برای شروع سریع (فاز A)</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۲</div>
            <div class="stat-label">نقش حیاتی (معمار + ایجنت)</div>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۴.۲ نکات کلیدی تیم</h4>

        <ul class="reference-list">
          <li>
            <strong>نقش «توسعه‌دهنده Backend (ایجنت)» حیاتی‌ترین نقش است</strong>
            این نقش باید به‌طور کامل بر Microsoft Agent Framework مسلط باشد. تسلط بر Semantic Kernel به‌عنوان پیش‌نیاز توصیه می‌شود، زیرا Agent Framework نسل بعدی آن است.
          </li>
          <li>
            <strong>معمار ارشد باید هم‌زمان بر .NET و مفاهیم AI مسلط باشد</strong>
            صرف تسلط بر معماری نرم‌افزار کافی نیست؛ درک عمیق از RAG، Agentic Patterns و محدودیت‌های مدل‌های زبانی ضروری است.
          </li>
          <li>
            <strong>مهندس امنیت باید با OWASP LLM Top 10 آشنا باشد</strong>
            به‌ویژه LLM01 (Prompt Injection) و LLM02 (Sensitive Information Disclosure) که مستقیماً به آزمون نفوذ دسترسی کارفرما مرتبط است.
          </li>
          <li>
            <strong>تیم حداقلی برای شروع (فاز A)</strong>
            معمار ارشد + ۲ توسعه‌دهنده Backend (ایجنت) + ۱ توسعه‌دهنده Blazor = ۴ نفر. این تیم می‌تواند اثبات مفهوم (PoC) را در ۴ تا ۶ هفته ارائه دهد.
          </li>
        </ul>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>ارزش‌آفرینی محصول و معیارهای استاندارد اندازه‌گیری</h3>
          <div class="subtitle">Value Creation & Standard Measurement Metrics</div>
        </div>
      </div>
      <div class="section-content">
        <p>ارزش این محصول را می‌توان بر اساس معیارهای استاندارد اندازه‌گیری کرد. رویکرد ما، استفاده از <strong>چارچوب ROI</strong> و <strong>شاخص‌های کلیدی عملکرد (KPI)</strong> است تا ارزش‌آفرینی قابل اثبات و قابل پیگیری باشد.</p>

        <h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">۵.۱ معیارهای استاندارد اندازه‌گیری ارزش</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>معیار</th>
              <th>شاخص (KPI)</th>
              <th>روش اندازه‌گیری</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>کارایی عملیاتی</td>
              <td>کاهش زمان جستجو و تحلیل اسناد (Time-to-Answer)</td>
              <td>مقایسه زمان قبل/بعد از استقرار</td>
            </tr>
            <tr>
              <td>دقت تصمیم</td>
              <td>نرخ پاسخ صحیح با ارجاع به منبع (Precision/Recall)</td>
              <td>ارزیابی نمونه‌ای دوره‌ای</td>
            </tr>
            <tr>
              <td>صرفه‌جویی هزینه</td>
              <td>کاهش ساعت نیروی انسانی صرف‌شده</td>
              <td>محاسبه ROI (ساعت صرفه‌جویی × نرخ ساعتی)</td>
            </tr>
            <tr>
              <td>رضایت کاربر</td>
              <td>NPS یا CSAT کاربران سازمانی</td>
              <td>نظرسنجی دوره‌ای</td>
            </tr>
            <tr>
              <td>تاب‌آوری</td>
              <td>Uptime و MTTR (میانگین زمان بازیابی)</td>
              <td>پایش SLO</td>
            </tr>
            <tr>
              <td>انطباق و امنیت</td>
              <td>نرخ موفقیت در آزمون نفوذ دسترسی</td>
              <td>آزمون دوره‌ای (محور ۲ نیازمندی‌ها)</td>
            </tr>
          </tbody>
        </table>

        <div class="highlight-box">
          <strong>فرمول ROI:</strong> بر اساس چارچوب استاندارد ROI، بازگشت سرمایه به‌صورت زیر محاسبه می‌شود:<br><br>
          <strong>ROI% = [(مجموع منافع) − (هزینه دستیابی + هزینه نگهداری)] ÷ (هزینه دستیابی + هزینه نگهداری) × ۱۰۰</strong>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۵.۲ ارزش‌های کلیدی برای سازمان</h4>

        <div class="comparison-grid">
          <div class="comparison-card recommended">
            <span class="card-badge">ارزش محوری ✓</span>
            <h4>دسترسی دموکراتیک به دانش</h4>
            <ul>
              <li><span>پوشش کاربران</span> <span class="value">تمام واحدها</span></li>
              <li><span>رعایت دسترسی</span> <span class="value">تا سطح رکورد</span></li>
              <li><span>وابستگی به خبره</span> <span class="value">حذف می‌شود</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">ارزش محوری ✓</span>
            <h4>خودکارسازی چندمرحله‌ای</h4>
            <ul>
              <li><span>فرایند</span> <span class="value">تحلیل → استخراج → گزارش</span></li>
              <li><span>دخالت انسان</span> <span class="value">فقط در نقاط حساس</span></li>
              <li><span>زمان اجرا</span> <span class="value">کاهش چشمگیر</span></li>
            </ul>
          </div>
        </div>

        <div class="comparison-grid">
          <div class="comparison-card">
            <h4>کاهش ریسک افشا</h4>
            <ul>
              <li><span>دفاع لایه‌ای</span> <span class="value">دو نقطه مستقل</span></li>
              <li><span>ممیزی</span> <span class="value">کامل</span></li>
              <li><span>انطباق</span> <span class="value">OWASP LLM</span></li>
            </ul>
          </div>
          <div class="comparison-card">
            <h4>تاب‌آوری در شرایط تحریم</h4>
            <ul>
              <li><span>استقرار</span> <span class="value">On-Premise</span></li>
              <li><span>مدل محلی</span> <span class="value">Ollama</span></li>
              <li><span>قطع اینترنت</span> <span class="value">بدون اختلال</span></li>
            </ul>
          </div>
        </div>

        <h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">۵.۳ تخمین کمی ارزش (نمونه)</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>سناریو</th>
              <th>فرض</th>
              <th>صرفه‌جویی سالانه تخمینی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>جستجوی اسناد</td>
              <td>۵۰ کاربر × ۲ ساعت/هفته صرفه‌جویی</td>
              <td>۵,۲۰۰ ساعت/سال</td>
            </tr>
            <tr>
              <td>تحلیل قراردادها</td>
              <td>۲۰ سند/ماه × ۳ ساعت صرفه‌جویی</td>
              <td>۷۲۰ ساعت/سال</td>
            </tr>
            <tr>
              <td>تولید گزارش</td>
              <td>۱۰۰ گزارش/سال × ۴ ساعت صرفه‌جویی</td>
              <td>۴۰۰ ساعت/سال</td>
            </tr>
            <tr class="highlight-row">
              <td><strong>جمع صرفه‌جویی</strong></td>
              <td>—</td>
              <td><strong>۶,۳۲۰ ساعت/سال</strong></td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> با نرخ ساعتی فرضی، بازگشت سرمایه (ROI) معمولاً در <strong>۶ تا ۱۲ ماه</strong> قابل تحقق است. این تخمین بر اساس سناریوهای محافظه‌کارانه محاسبه شده و با گسترش استفاده، ارزش واقعی افزایش می‌یابد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>جمع‌بندی و گام بعدی</h3>
          <div class="subtitle">Summary & Next Step</div>
        </div>
      </div>
      <div class="section-content">
        <p>این مستند، نقشه راه عملیاتی پیاده‌سازی معماری سامانه هوش مصنوعی سازمانی را با استک <strong>.NET + Microsoft.Extensions.AI + Microsoft Agent Framework</strong> ارائه داد. جمع‌بندی ویژگی‌های کلیدی:</p>

        <ul class="reference-list">
          <li>
            <strong>استک فنی یکپارچه</strong>
            Microsoft.Extensions.AI برای انتزاع مدل‌ها، Microsoft Agent Framework برای ارکستراسیون ایجنت، و رویکرد Cross-Platform با ElectronNET (دسکتاپ) و Ionic (موبایل)
          </li>
          <li>
            <strong>پنج فاز اجرایی گام‌به‌گام</strong>
            فاز A (هسته ایجنت) → فاز B (ابزار و RAG) → فاز C (حاکمیت و دسترسی) → فاز D (گزارش و مشاهده‌پذیری) → فاز E (Cross-Platform)
          </li>
          <li>
            <strong>تیم ۱۰ نفره</strong>
            با حداقل ۴ نفر برای شروع سریع (فاز A) در بازه ۴ تا ۶ هفته
          </li>
          <li>
            <strong>ارزش‌آفرینی قابل اندازه‌گیری</strong>
            بر اساس معیارهای استاندارد (کارایی، دقت، هزینه، رضایت، تاب‌آوری، انطباق) و فرمول ROI
          </li>
          <li>
            <strong>انطباق با نیازمندی‌ها</strong>
            فازهای A تا C آمادگی برای جلسه دمو و آزمون عملی کارفرما را فراهم می‌کنند
          </li>
        </ul>

        <div class="conclusion-box">
          <h3>🎯 گام بعدی پیشنهادی</h3>
          <p>پیاده‌سازی <strong>فاز A</strong> (هسته: درگاه مدل + موتور ایجنت + رابط Blazor + احراز هویت) به‌عنوان اثبات مفهوم (PoC) در بازه ۴ تا ۶ هفته.</p>
          <p>سپس ارائه در جلسه دمو به کارفرما با تمرکز بر فازهای A تا C برای پاسخ به محورهای ۱، ۲ و ۵ نیازمندی‌ها.</p>
          <div class="highlight">
            <strong>💎 ارزش پیشنهادی:</strong><br>
            استک یکپارچه .NET + Agent Framework + Cross-Platform + تیم ۱۰ نفره + ارزش‌آفرینی قابل اندازه‌گیری
          </div>
        </div>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> در صورت تمایل به شروع همکاری، آماده برگزاری جلسه فنی برای تشریح جزئیات فاز A و زمان‌بندی PoC هستم. پیش‌نویس قرارداد نیز بر اساس توافقات حاصله آماده امضا می‌باشد.
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8404e5e6-f5fb-4c8f-876e-a293cda84af9.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>نقشه راه دانش فنی | از معماری تا محصول</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1000px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    vertical-align: top;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  /* ===== Roadmap-specific styles ===== */
  .phase-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 12px;
    margin: 20px 0;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .phase-header {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 16px 22px;
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .phase-num {
    width: 44px; height: 44px;
    background: var(--accent);
    color: var(--primary);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 18px;
    flex-shrink: 0;
  }

  .phase-title h4 {
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 2px;
  }

  .phase-title .phase-sub {
    font-size: 11px;
    opacity: 0.85;
  }

  .phase-body {
    padding: 20px 22px;
  }

  .phase-body p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 0 !important;
    font-size: 13.5px;
    color: var(--text-muted);
  }

  .topic-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin: 15px 0;
  }

  .topic-box {
    background: #f8fafc;
    border: 1px solid var(--border);
    border-right: 3px solid var(--primary-light);
    border-radius: 8px;
    padding: 14px 16px;
  }

  .topic-box h5 {
    font-size: 13px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .topic-box ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .topic-box ul li {
    font-size: 12px;
    color: var(--text-muted);
    padding: 3px 0 3px 14px;
    position: relative;
  }

  .topic-box ul li::before {
    content: '▸';
    position: absolute;
    right: 0;
    color: var(--accent);
    font-weight: 700;
  }

  .standard-chip {
    display: inline-block;
    background: rgba(201,169,97,0.18);
    border: 1px solid rgba(201,169,97,0.5);
    border-radius: 20px;
    padding: 2px 10px;
    font-size: 11px;
    color: var(--accent-dark);
    font-weight: 600;
    margin: 2px 4px 2px 0;
  }

  .standard-chip.blue {
    background: rgba(44,82,130,0.12);
    border-color: rgba(44,82,130,0.4);
    color: var(--primary);
  }

  .standard-chip.green {
    background: rgba(56,161,105,0.12);
    border-color: rgba(56,161,105,0.4);
    color: var(--success);
  }

  .deliverable-list {
    list-style: none;
    padding: 0;
    margin: 15px 0 0;
  }

  .deliverable-list li {
    background: #f0fff4;
    border: 1px solid #9ae6b4;
    border-right: 3px solid var(--success);
    border-radius: 6px;
    padding: 10px 14px;
    margin-bottom: 8px;
    font-size: 12.5px;
    color: var(--text-muted);
  }

  .deliverable-list li strong {
    color: var(--success);
    font-weight: 700;
  }

  .skill-matrix td:first-child {
    font-weight: 600;
    color: var(--primary);
  }

  .level-badge {
    display: inline-block;
    padding: 2px 9px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
  }

  .level-badge.basic {
    background: #ebf8ff;
    color: var(--primary);
    border: 1px solid #90cdf4;
  }

  .level-badge.inter {
    background: #fef5e7;
    color: var(--warning);
    border: 1px solid #fbd38d;
  }

  .level-badge.adv {
    background: #f0fff4;
    color: var(--success);
    border: 1px solid #9ae6b4;
  }

  .level-badge.expert {
    background: #fff5f5;
    color: var(--danger);
    border: 1px solid #feb2b2;
  }

  .approach-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 15px;
    margin: 20px 0;
  }

  .approach-card {
    background: #ffffff;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 18px;
    text-align: center;
  }

  .approach-card .approach-icon {
    width: 48px; height: 48px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: var(--accent);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: 800;
    margin: 0 auto 12px;
  }

  .approach-card h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .approach-card p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin: 0;
  }

  .milestone-row {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    padding: 14px 18px;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 10px;
    margin-bottom: 12px;
  }

  .milestone-badge {
    width: 56px; height: 56px;
    background: linear-gradient(135deg, var(--accent), var(--accent-dark));
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 15px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(201,169,97,0.3);
  }

  .milestone-info h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 4px;
  }

  .milestone-info p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin: 0;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .topic-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: ROAD-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: آبان ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">TECHNICAL KNOWLEDGE ROADMAP</span>
      <h1>نقشه راه دانش فنی</h1>
      <h2>از معماری تا محصول — سامانه هوش مصنوعی سازمانی</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه مدیریتی،</strong><br>
      این مستند، نقشه راه کسب دانش فنی لازم برای پیاده‌سازی معماری کلان سامانه هوش مصنوعی سازمانی (مستند ARCH-1405-001) و تبدیل آن به محصول قابل ارائه را ترسیم می‌کند. رویکرد این نقشه راه <strong>فارغ از سکو</strong> است؛ یعنی هیچ زبان برنامه‌نویسی، استک عملیاتی یا ابزار خاصی پیشنهاد نمی‌شود. تمرکز بر <strong>استانداردها و الگوهای طراحی و پیاده‌سازی</strong> است و مسیر از <strong>پایه‌ای‌ترین مباحث تا مباحث کلان معماری</strong> را پوشش می‌دهد. هدف، ایجاد توانمندی پایدار در تیم فنی برای پیاده‌سازی، نگهداری و تکامل محصول است.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>اصول حاکم بر نقشه راه</h3>
          <div class="subtitle">Guiding Principles</div>
        </div>
      </div>
      <div class="section-content">
        <p>این نقشه راه بر پایه اصول زیر طراحی شده است که مستقیماً از الزامات شما و ماهیت معماری محصول استخراج شده‌اند:</p>

        <div class="approach-grid">
          <div class="approach-card">
            <div class="approach-icon">◇</div>
            <h5>فارغ از سکو</h5>
            <p>هیچ زبان، فریم‌ورک یا استک خاصی توصیه نمی‌شود؛ تمرکز بر مفاهیم و الگوهای قابل انتقال.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">◎</div>
            <h5>استانداردمحوری</h5>
            <p>تکیه بر استانداردهای شناخته‌شده (BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 42001، NIST AI RMF و...).</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">▤</div>
            <h5>الگومحوری</h5>
            <p>یادگیری الگوهای طراحی و معماری (لایه‌ای، رویدادمحور، Hexagonal، CQRS، Circuit Breaker و...).</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">↑</div>
            <h5>از پایه تا کلان</h5>
            <p>شروع از مبانی (داده، شبکه، امنیت) و حرکت تدریجی به سمت معماری کلان و حاکمیت.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">⟳</div>
            <h5>یادگیری تدریجی</h5>
            <p>مسیر پیوسته با نقاط عطف مشخص؛ هر فاز، پیش‌نیاز فاز بعدی است.</p>
          </div>
          <div class="approach-card">
            <div class="approach-icon">✓</div>
            <h5>قابلیت اثبات</h5>
            <p>هر فاز با خروجی قابل‌آزمون (Deliverable) پایان می‌یابد تا دانش به مهارت تبدیل شود.</p>
          </div>
        </div>

        <div class="highlight-box">
          <strong>اصل حاکم:</strong> هدف این نقشه راه، تربیت <strong>معمار و مهندس توانمند</strong> است، نه صرفاً آموزش ابزار. بنابراین، در هر فاز، «چرایی» و «الگو» بر «چگونگی ابزار» مقدم است. این رویکرد تضمین می‌کند که دانش کسب‌شده با تغییر سکوها و ابزارها از بین نرود.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>نمای کلی نقشه راه</h3>
          <div class="subtitle">Roadmap Overview</div>
        </div>
      </div>
      <div class="section-content">
        <p>نقشه راه در <strong>هفت فاز</strong> سازمان‌دهی شده است. هر فاز دارای موضوعات کلیدی، استانداردهای مرتبط و خروجی قابل‌آزمون است. فازها به‌صورت پیوسته طراحی شده‌اند؛ اما تیم‌های با تجربه‌تر می‌توانند برخی موضوعات فازهای ابتدایی را به‌صورت موازی مرور کنند.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">۷</div>
            <div class="stat-label">فاز اصلی</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۴۰+</div>
            <div class="stat-label">موضوع کلیدی</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">۲۵+</div>
            <div class="stat-label">استاندارد و الگو</div>
          </div>
        </div>

        <table class="styled-table">
          <thead>
            <tr>
              <th>فاز</th>
              <th>عنوان</th>
              <th>تمرکز اصلی</th>
              <th>سطح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td>مبانی سیستم‌ها و داده</td>
              <td>شبکه، داده، مدل داده، رمزنگاری پایه</td>
              <td><span class="level-badge basic">پایه</span></td>
            </tr>
            <tr>
              <td>۲</td>
              <td>مبانی مهندسی نرم‌افزار</td>
              <td>الگوهای طراحی، معماری تمیز، آزمون‌پذیری</td>
              <td><span class="level-badge basic">پایه</span></td>
            </tr>
            <tr>
              <td>۳</td>
              <td>مبانی هوش مصنوعی و مدل‌ها</td>
              <td>مدل‌های زبانی، Embedding، RAG، ارزیابی</td>
              <td><span class="level-badge inter">میانی</span></td>
            </tr>
            <tr>
              <td>۴</td>
              <td>معماری سیستم‌های توزیع‌شده</td>
              <td>لایه‌بندی، رویدادمحوری، تاب‌آوری، مقیاس‌پذیری</td>
              <td><span class="level-badge inter">میانی</span></td>
            </tr>
            <tr>
              <td>۵</td>
              <td>معماری ایجنت و ارکستراسیون</td>
              <td>برنامه‌ریزی، انتخاب ابزار، حلقه بازخورد، Human-in-the-loop</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
            </tr>
            <tr>
              <td>۶</td>
              <td>امنیت، حاکمیت داده و انطباق</td>
              <td>OAuth، RBAC/ABAC، محرمانگی، ممیزی، ISO 42001</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
            </tr>
            <tr>
              <td>۷</td>
              <td>معماری کلان، محصول و عملیات</td>
              <td>معماری سازمانی، SRE، مشاهده‌پذیری، مدیریت محصول</td>
              <td><span class="level-badge expert">خبره</span></td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> ترتیب فازها بر اساس <strong>وابستگی دانشی</strong> است، نه ترتیب زمانی دقیق. تیم‌های با تجربه می‌توانند فازهای ۱ و ۲ را به‌صورت فشرده مرور کنند و تمرکز اصلی را بر فازهای ۳ تا ۷ بگذارند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>فاز ۱: مبانی سیستم‌ها و داده</h3>
          <div class="subtitle">Phase 1 — Foundations of Systems & Data</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۱</div>
            <div class="phase-title">
              <h4>مبانی سیستم‌ها و داده</h4>
              <div class="phase-sub">پایه‌ای‌ترین لایه دانش — پیش‌نیاز همه فازها</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، پایه‌ای‌ترین دانش لازم برای درک هر سیستم نرم‌افزاری و داده‌محور را فراهم می‌کند. بدون تسلط بر این مبانی، درک لایه‌های بالاتر معماری (به‌ویژه حاکمیت داده و امنیت) ناقص خواهد بود.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>مبانی شبکه و ارتباطات</h5>
                <ul>
                  <li>مدل OSI و TCP/IP</li>
                  <li>HTTP/HTTPS، REST، gRPC (مفهومی)</li>
                  <li>وب‌سوکت و ارتباطات بلادرنگ</li>
                  <li>مفاهیم پروکسی، فایروال و DMZ</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مبانی داده</h5>
                <ul>
                  <li>مدل داده رابطه‌ای و NoSQL (مفهومی)</li>
                  <li>نرمال‌سازی و مدل‌سازی داده</li>
                  <li>تراکنش و ACID</li>
                  <li>مفاهیم Data Lake و Data Warehouse</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مبانی رمزنگاری</h5>
                <ul>
                  <li>رمزنگاری متقارن و نامتقارن</li>
                  <li>هش و امضای دیجیتال</li>
                  <li>TLS و مدیریت گواهی</li>
                  <li>مدیریت کلید (Key Management)</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مبانی سیستم‌عامل و منابع</h5>
                <ul>
                  <li>مدیریت پردازش و حافظه</li>
                  <li>سیستم فایل و مجوزها</li>
                  <li>مفاهیم Container و مجازی‌سازی</li>
                  <li>مدیریت منابع (CPU، RAM، I/O)</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip blue">RFC 7230 (HTTP)</span>
              <span class="standard-chip blue">RFC 8446 (TLS 1.3)</span>
              <span class="standard-chip blue">ISO/IEC 27001 (مبانی امنیت)</span>
              <span class="standard-chip blue">NIST SP 800-57 (مدیریت کلید)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>نقشه مفهومی داده سازمان:</strong> شناسایی منابع داده، جریان‌ها و مالکیت داده</li>
              <li><strong>سند مدل تهدید پایه:</strong> شناسایی دارایی‌ها، تهدیدها و کنترل‌های پایه امنیتی</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>فاز ۲: مبانی مهندسی نرم‌افزار</h3>
          <div class="subtitle">Phase 2 — Software Engineering Foundations</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۲</div>
            <div class="phase-title">
              <h4>مبانی مهندسی نرم‌افزار</h4>
              <div class="phase-sub">الگوهای طراحی، معماری تمیز و آزمون‌پذیری</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، دانش پایه‌ای مهندسی نرم‌افزار را فراهم می‌کند که برای پیاده‌سازی هر لایه از معماری (از رابط کاربری تا موتور ایجنت) ضروری است. تمرکز بر <strong>الگوها</strong> است، نه ابزارها.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>اصول طراحی (SOLID و فراتر)</h5>
                <ul>
                  <li>اصول SOLID</li>
                  <li>DRY، KISS، YAGNI</li>
                  <li>Separation of Concerns</li>
                  <li>Dependency Inversion</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>الگوهای طراحی کلاسیک</h5>
                <ul>
                  <li>الگوهای سازنده (Factory، Builder)</li>
                  <li>الگوهای ساختاری (Adapter، Facade)</li>
                  <li>الگوهای رفتاری (Strategy، Observer)</li>
                  <li>الگوهای معماری (MVC، MVVM، Clean)</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>معماری تمیز و Hexagonal</h5>
                <ul>
                  <li>لایه‌بندی و جهت وابستگی</li>
                  <li>Ports & Adapters</li>
                  <li>جداسازی دامنه از زیرساخت</li>
                  <li>قابلیت تعویض مؤلفه‌ها</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>آزمون‌پذیری</h5>
                <ul>
                  <li>هرم آزمون (Unit/Integration/E2E)</li>
                  <li>Test Double (Mock، Stub، Fake)</li>
                  <li>Test-Driven Design (مفهومی)</li>
                  <li>Contract Testing</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip">Clean Architecture (Robert C. Martin)</span>
              <span class="standard-chip">Hexagonal Architecture (Alistair Cockburn)</span>
              <span class="standard-chip">GoF Design Patterns</span>
              <span class="standard-chip blue">ISO/IEC 25010 (کیفیت نرم‌افزار)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند اصول و الگوهای منتخب:</strong> تعیین الگوهای پایه برای هر لایه معماری</li>
              <li><strong>نمونه اولیه ساختار Hexagonal:</strong> پیاده‌سازی یک مؤلفه نمونه با Ports & Adapters</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>فاز ۳: مبانی هوش مصنوعی و مدل‌ها</h3>
          <div class="subtitle">Phase 3 — AI & Model Foundations</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۳</div>
            <div class="phase-title">
              <h4>مبانی هوش مصنوعی و مدل‌ها</h4>
              <div class="phase-sub">مدل‌های زبانی، Embedding، RAG و ارزیابی</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، دانش تخصصی هوش مصنوعی و مدل‌های زبانی را فراهم می‌کند که مستقیماً به لایه هوش (L4) معماری مرتبط است. تمرکز بر <strong>درک مفهومی</strong> و <strong>الگوهای استفاده</strong> است، نه پیاده‌سازی مدل از صفر.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>مبانی مدل‌های زبانی</h5>
                <ul>
                  <li>معماری Transformer (مفهومی)</li>
                  <li>توکن‌سازی و Embedding</li>
                  <li>Temperature، Top-p، Context Window</li>
                  <li>تفاوت مدل‌های Base و Instruct</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>الگوهای استفاده از مدل</h5>
                <ul>
                  <li>Prompt Engineering اصولی</li>
                  <li>Few-shot و Chain-of-Thought</li>
                  <li>Structured Output (JSON Mode)</li>
                  <li>Function Calling / Tool Use</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>بازیابی و تقویت (RAG)</h5>
                <ul>
                  <li>مفاهیم Vector Database</li>
                  <li>Chunking و Indexing</li>
                  <li>Retrieval Strategies</li>
                  <li>Citation و Source Attribution</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>ارزیابی و کیفیت</h5>
                <ul>
                  <li>معیارهای ارزیابی پاسخ</li>
                  <li>Hallucination Detection</li>
                  <li>Benchmarking مدل‌ها</li>
                  <li>A/B Testing برای Prompt</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مدیریت مدل</h5>
                <ul>
                  <li>نسخه‌بندی مدل‌ها</li>
                  <li>مدل‌های داخلی در برابر خارجی</li>
                  <li>هزینه و مصرف توکن</li>
                  <li>سیاست دسترسی به مدل‌های جدید</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>اخلاق و مخاطرات AI</h5>
                <ul>
                  <li>Bias و Fairness</li>
                  <li>Privacy در مدل‌ها</li>
                  <li>Explainability</li>
                  <li>مسئولیت‌پذیری</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip green">NIST AI RMF</span>
              <span class="standard-chip green">ISO/IEC 42001 (مدیریت AI)</span>
              <span class="standard-chip green">OECD AI Principles</span>
              <span class="standard-chip blue">Attention Is All You Need (مرجع Transformer)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند ارزیابی مدل‌ها:</strong> مقایسه مدل‌های نامزد بر اساس معیارهای کیفیت، هزینه و حاکمیت</li>
              <li><strong>نمونه اولیه RAG:</strong> پیاده‌سازی یک جریان بازیابی و تقویت با ارجاع به منبع</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>فاز ۴: معماری سیستم‌های توزیع‌شده</h3>
          <div class="subtitle">Phase 4 — Distributed Systems Architecture</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۴</div>
            <div class="phase-title">
              <h4>معماری سیستم‌های توزیع‌شده</h4>
              <div class="phase-sub">لایه‌بندی، رویدادمحوری، تاب‌آوری و مقیاس‌پذیری</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، دانش معماری سیستم‌های توزیع‌شده را فراهم می‌کند که برای پیاده‌سازی لایه‌های L1 تا L6 و محورهای عرضی ضروری است. تمرکز بر <strong>الگوهای معماری</strong> است، نه محصولات خاص.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>الگوهای معماری لایه‌ای</h5>
                <ul>
                  <li>Layered Architecture</li>
                  <li>Hexagonal / Ports & Adapters</li>
                  <li>Microservices و Modular Monolith</li>
                  <li>API Gateway Pattern</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>رویدادمحوری و پیام‌رسانی</h5>
                <ul>
                  <li>Event-Driven Architecture</li>
                  <li>Publish-Subscribe Pattern</li>
                  <li>Event Sourcing و CQRS (مفهومی)</li>
                  <li>Saga Pattern برای تراکنش‌های توزیع‌شده</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>تاب‌آوری (Resilience)</h5>
                <ul>
                  <li>Circuit Breaker</li>
                  <li>Retry و Backoff</li>
                  <li>Bulkhead و Rate Limiting</li>
                  <li>Graceful Degradation</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مقیاس‌پذیری و عملکرد</h5>
                <ul>
                  <li>Load Balancing (مفهومی)</li>
                  <li>Caching Strategies</li>
                  <li>Async Processing</li>
                  <li>Backpressure</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>هماهنگی توزیع‌شده</h5>
                <ul>
                  <li>Service Discovery</li>
                  <li>Configuration Management</li>
                  <li>Distributed Locking</li>
                  <li>Idempotency</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مشاهده‌پذیری (Observability)</h5>
                <ul>
                  <li>Logging، Metrics، Tracing</li>
                  <li>OpenTelemetry (مفهومی)</li>
                  <li>Health Check و Readiness</li>
                  <li>Alerting Strategies</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip">Enterprise Integration Patterns (Hohpe & Woolf)</span>
              <span class="standard-chip">Release It! (Michael Nygard)</span>
              <span class="standard-chip blue">OpenTelemetry Specification</span>
              <span class="standard-chip blue">BPMN 2.0 (برای مدل‌سازی فرایند)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند الگوهای معماری منتخب:</strong> تعیین الگوهای لایه‌بندی، رویدادمحوری و تاب‌آوری برای هر لایه</li>
              <li><strong>نقشه BPMN2 تکمیلی:</strong> به‌روزرسانی نقشه فرایندی با الگوهای تاب‌آوری و خطا</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>فاز ۵: معماری ایجنت و ارکستراسیون</h3>
          <div class="subtitle">Phase 5 — Agent Architecture & Orchestration</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۵</div>
            <div class="phase-title">
              <h4>معماری ایجنت و ارکستراسیون</h4>
              <div class="phase-sub">هسته تمایز محصول — برنامه‌ریزی، انتخاب ابزار و حلقه بازخورد</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، تخصصی‌ترین بخش نقشه راه است و مستقیماً به لایه ارکستراسیون (L3) و پاسخ به محور ۱ نیازمندی‌های کارفرما مرتبط می‌شود. تمرکز بر <strong>الگوهای طراحی ایجنت</strong> و <strong>قابلیت آزمون</strong> است.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>مفاهیم پایه ایجنت</h5>
                <ul>
                  <li>تفاوت Agent، Assistant و Workflow</li>
                  <li>حلقه تصمیم‌گیری (Observe-Think-Act)</li>
                  <li>Autonomy Levels</li>
                  <li>Goal vs Task vs Step</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>الگوهای برنامه‌ریزی</h5>
                <ul>
                  <li>ReAct (Reasoning + Acting)</li>
                  <li>Plan-and-Execute</li>
                  <li>Tree of Thoughts</li>
                  <li>Reflexion و Self-Correction</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مدیریت ابزار (Tool Use)</h5>
                <ul>
                  <li>Tool Registry و Discovery</li>
                  <li>Tool Selection Strategies</li>
                  <li>Tool Result Validation</li>
                  <li>Error Handling در ابزار</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>حافظه و زمینه</h5>
                <ul>
                  <li>Short-term vs Long-term Memory</li>
                  <li>Context Window Management</li>
                  <li>Summarization Strategies</li>
                  <li>Memory Isolation بر اساس دسترسی</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>Human-in-the-loop</h5>
                <ul>
                  <li>نقاط تأیید انسانی</li>
                  <li>Approval Workflows</li>
                  <li>Escalation Patterns</li>
                  <li>Audit Trail تصمیمات</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>چند-ایجنت (Multi-Agent)</h5>
                <ul>
                  <li>Orchestrator-Worker Pattern</li>
                  <li>Agent Communication Protocols</li>
                  <li>Shared Memory و Coordination</li>
                  <li>Conflict Resolution</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>ارزیابی ایجنت</h5>
                <ul>
                  <li>Task Success Rate</li>
                  <li>Step Efficiency</li>
                  <li>Error Recovery Rate</li>
                  <li>Scenario-based Testing</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>ایمنی و کنترل</h5>
                <ul>
                  <li>Guardrails و Constraints</li>
                  <li>Action Whitelisting</li>
                  <li>Sandboxing (مفهومی)</li>
                  <li>Kill Switch و Rollback</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip green">ReAct (Yao et al.)</span>
              <span class="standard-chip green">Reflexion (Shinn et al.)</span>
              <span class="standard-chip blue">Model Context Protocol (MCP) — مفهومی</span>
              <span class="standard-chip blue">NIST AI RMF (بخش کنترل)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سناریوی نمونه Agent:</strong> پیاده‌سازی یک سناریوی چندمرحله‌ای با ابزار، خطا و مداخله انسانی — قابل ارائه در جلسه دمو</li>
              <li><strong>چارچوب ارزیابی ایجنت:</strong> معیارها و روش‌های آزمون رفتار ایجنت</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>فاز ۶: امنیت، حاکمیت داده و انطباق</h3>
          <div class="subtitle">Phase 6 — Security, Data Governance & Compliance</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۶</div>
            <div class="phase-title">
              <h4>امنیت، حاکمیت داده و انطباق</h4>
              <div class="phase-sub">محور عرضی حاکمیت — پاسخ به آزمون نفوذ کارفرما</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، دانش لازم برای پیاده‌سازی محور عرضی حاکمیت داده (X) و پاسخ به محورهای ۲ و ۵ نیازمندی‌های کارفرما را فراهم می‌کند. تمرکز بر <strong>الگوهای امنیتی</strong> و <strong>استانداردهای انطباق</strong> است.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>احراز هویت و مجوزدهی</h5>
                <ul>
                  <li>OAuth 2.0 و OpenID Connect</li>
                  <li>JWT و Session Management</li>
                  <li>RBAC (نقش‌محور)</li>
                  <li>ABAC (ویژگی‌محور)</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>کنترل دسترسی پیشرفته</h5>
                <ul>
                  <li>ReBAC (رابطه‌محور)</li>
                  <li>Fine-grained Access Control</li>
                  <li>Row-level و Document-level Security</li>
                  <li>Policy-as-Code</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>محرمانگی داده</h5>
                <ul>
                  <li>Data Classification</li>
                  <li>Data Loss Prevention (DLP)</li>
                  <li>Data Masking و Redaction</li>
                  <li>Output Filtering (سنسور محرمانگی)</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>ممیزی و ردگیری</h5>
                <ul>
                  <li>Audit Logging</li>
                  <li>Tamper-evident Logs</li>
                  <li>Traceability تصمیمات</li>
                  <li>Retention Policies</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>امنیت مدل و AI</h5>
                <ul>
                  <li>Prompt Injection</li>
                  <li>Jailbreak Detection</li>
                  <li>Data Poisoning (مفهومی)</li>
                  <li>Model Inversion و Extraction</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>انطباق و حاکمیت</h5>
                <ul>
                  <li>ISO/IEC 27001</li>
                  <li>ISO/IEC 42001 (مدیریت AI)</li>
                  <li>NIST AI RMF</li>
                  <li>GDPR (مفهومی) و قوانین داخلی</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>امنیت زیرساخت</h5>
                <ul>
                  <li>OWASP Top 10</li>
                  <li>OWASP API Security Top 10</li>
                  <li>OWASP LLM Top 10</li>
                  <li>Secure by Design</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>حاکمیت داده سازمانی</h5>
                <ul>
                  <li>Data Ownership و Stewardship</li>
                  <li>Data Lineage</li>
                  <li>Data Quality Management</li>
                  <li>Policy Enforcement Points</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip blue">OAuth 2.0 (RFC 6749)</span>
              <span class="standard-chip blue">OpenID Connect Core</span>
              <span class="standard-chip blue">OWASP Top 10 / API / LLM</span>
              <span class="standard-chip green">ISO/IEC 27001</span>
              <span class="standard-chip green">ISO/IEC 42001</span>
              <span class="standard-chip green">NIST AI RMF</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند مدل دسترسی و حاکمیت داده:</strong> تعریف نقش‌ها، سطوح دسترسی و سیاست‌های داده</li>
              <li><strong>سناریوی آزمون نفوذ دسترسی:</strong> طراحی آزمون‌های پرسش مستقیم/غیرمستقیم برای اثبات عدم افشا — قابل اجرا در جلسه دمو</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>فاز ۷: معماری کلان، محصول و عملیات</h3>
          <div class="subtitle">Phase 7 — Enterprise Architecture, Product & Operations</div>
        </div>
      </div>
      <div class="section-content">
        <div class="phase-card">
          <div class="phase-header">
            <div class="phase-num">۷</div>
            <div class="phase-title">
              <h4>معماری کلان، محصول و عملیات</h4>
              <div class="phase-sub">از معماری به محصول قابل ارائه و پایدار</div>
            </div>
          </div>
          <div class="phase-body">
            <p>این فاز، دانش لازم برای تبدیل معماری به <strong>محصول قابل ارائه</strong> و <strong>عملیات پایدار</strong> را فراهم می‌کند. تمرکز بر <strong>معماری سازمانی</strong>، <strong>مدیریت محصول</strong> و <strong>عملیات</strong> است.</p>

            <div class="topic-grid">
              <div class="topic-box">
                <h5>معماری سازمانی</h5>
                <ul>
                  <li>TOGAF (مفهومی)</li>
                  <li>Zachman Framework (مفهومی)</li>
                  <li>Architecture Decision Records (ADR)</li>
                  <li>Capability Mapping</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مدیریت محصول</h5>
                <ul>
                  <li>Product Vision و Roadmap</li>
                  <li>Prioritization Frameworks</li>
                  <li>Product-Market Fit</li>
                  <li>Feature Flagging</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>عملیات و SRE</h5>
                <ul>
                  <li>SLI/SLO/SLA</li>
                  <li>Error Budget</li>
                  <li>Incident Management</li>
                  <li>Postmortem Culture</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مشاهده‌پذیری پیشرفته</h5>
                <ul>
                  <li>Distributed Tracing</li>
                  <li>Log Aggregation</li>
                  <li>Metrics و Dashboards</li>
                  <li>Anomaly Detection</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مصرف و هزینه</h5>
                <ul>
                  <li>Token Accounting</li>
                  <li>Cost Attribution</li>
                  <li>Quota Management</li>
                  <li>Usage Reporting</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مدیریت تغییر و انتشار</h5>
                <ul>
                  <li>Release Strategies</li>
                  <li>Blue-Green و Canary (مفهومی)</li>
                  <li>Rollback Strategies</li>
                  <li>Versioning Policies</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>مستندسازی و آموزش</h5>
                <ul>
                  <li>Architecture Documentation</li>
                  <li>API Documentation (OpenAPI)</li>
                  <li>Runbook و Playbook</li>
                  <li>Training Programs</li>
                </ul>
              </div>
              <div class="topic-box">
                <h5>توسعه تیم و فرهنگ</h5>
                <ul>
                  <li>Team Topologies (مفهومی)</li>
                  <li>Knowledge Sharing</li>
                  <li>Code Review Culture</li>
                  <li>Continuous Learning</li>
                </ul>
              </div>
            </div>

            <p style="margin-top:15px;"><strong>استانداردها و مراجع کلیدی:</strong></p>
            <div>
              <span class="standard-chip">TOGAF ADM</span>
              <span class="standard-chip">Google SRE Book</span>
              <span class="standard-chip blue">OpenAPI Specification</span>
              <span class="standard-chip blue">Architecture Decision Records (ADR)</span>
              <span class="standard-chip green">ISO/IEC 20000 (مدیریت خدمت)</span>
            </div>

            <p style="margin-top:18px;"><strong>خروجی قابل‌آزمون (Deliverable):</strong></p>
            <ul class="deliverable-list">
              <li><strong>سند معماری محصول:</strong> نگاشت معماری کلان به قابلیت‌های محصول و نقشه راه انتشار</li>
              <li><strong>سند SLA و SLO:</strong> تعریف تعهد سطح خدمت و شاخص‌های کلیدی عملکرد — پاسخ به محور ۷ نیازمندی‌ها</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>ماتریس مهارت تیم</h3>
          <div class="subtitle">Team Skill Matrix</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر، ماتریس مهارت پیشنهادی برای تیم فنی را نشان می‌دهد. سطح موردنیاز برای هر نقش، بر اساس فازهای نقشه راه تعیین شده است:</p>

        <table class="styled-table skill-matrix">
          <thead>
            <tr>
              <th>نقش / حوزه مهارت</th>
              <th>فاز ۱-۲</th>
              <th>فاز ۳-۴</th>
              <th>فاز ۵-۶</th>
              <th>فاز ۷</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>مهندس نرم‌افزار</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge basic">پایه</span></td>
              <td><span class="level-badge basic">پایه</span></td>
            </tr>
            <tr>
              <td>مهندس داده</td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge basic">پایه</span></td>
            </tr>
            <tr>
              <td>مهندس هوش مصنوعی</td>
              <td><span class="level-badge basic">پایه</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge inter">میانی</span></td>
            </tr>
            <tr>
              <td>معمار سیستم</td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
              <td><span class="level-badge expert">خبره</span></td>
            </tr>
            <tr>
              <td>مهندس امنیت</td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge basic">پایه</span></td>
              <td><span class="level-badge expert">خبره</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
            </tr>
            <tr>
              <td>مهندس عملیات / SRE</td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge adv">پیشرفته</span></td>
            </tr>
            <tr>
              <td>مدیر محصول</td>
              <td><span class="level-badge basic">پایه</span></td>
              <td><span class="level-badge basic">پایه</span></td>
              <td><span class="level-badge inter">میانی</span></td>
              <td><span class="level-badge expert">خبره</span></td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته:</strong> این ماتریس نشان می‌دهد که هیچ نقشی به‌تنهایی تمام فازها را پوشش نمی‌دهد. <strong>تیم چندنقشی</strong> با هم‌پوشانی مهارت‌ها، کلید موفقیت است. در تیم‌های کوچک، افراد باید در چند نقش (مثلاً مهندس نرم‌افزار + مهندس AI) مهارت داشته باشند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>نقاط عطف و گام‌های اجرایی</h3>
          <div class="subtitle">Milestones & Execution Steps</div>
        </div>
      </div>
      <div class="section-content">
        <p>نقشه راه در قالب <strong>پنج نقطه عطف</strong> قابل پیگیری است. هر نقطه عطف، تجمیع خروجی چند فاز و نشان‌دهنده آمادگی برای گام بعدی است:</p>

        <div class="milestone-row">
          <div class="milestone-badge">M1</div>
          <div class="milestone-info">
            <h5>آمادگی پایه</h5>
            <p>تکمیل فازهای ۱ و ۲ — تیم بر مبانی داده، شبکه، امنیت پایه و الگوهای مهندسی نرم‌افزار مسلط است. خروجی: نقشه داده سازمان + سند اصول و الگوهای منتخب.</p>
          </div>
        </div>

        <div class="milestone-row">
          <div class="milestone-badge">M2</div>
          <div class="milestone-info">
            <h5>آمادگی هوش مصنوعی</h5>
            <p>تکمیل فاز ۳ — تیم قادر به ارزیابی مدل‌ها، طراحی RAG و ارزیابی کیفیت پاسخ است. خروجی: سند ارزیابی مدل‌ها + نمونه اولیه RAG.</p>
          </div>
        </div>

        <div class="milestone-row">
          <div class="milestone-badge">M3</div>
          <div class="milestone-info">
            <h5>آمادگی معماری توزیع‌شده</h5>
            <p>تکمیل فاز ۴ — تیم قادر به طراحی لایه‌بندی، رویدادمحوری و تاب‌آوری است. خروجی: سند الگوهای معماری منتخب + نقشه BPMN2 تکمیلی.</p>
          </div>
        </div>

        <div class="milestone-row">
          <div class="milestone-badge">M4</div>
          <div class="milestone-info">
            <h5>آمادگی ایجنت و حاکمیت</h5>
            <p>تکمیل فازهای ۵ و ۶ — تیم قادر به پیاده‌سازی ایجنت قابل‌آزمون و اعمال حاکمیت داده است. خروجی: سناریوی نمونه Agent + سناریوی آزمون نفوذ دسترسی — <strong>آماده برای جلسه دمو کارفرما</strong>.</p>
          </div>
        </div>

        <div class="milestone-row">
          <div class="milestone-badge">M5</div>
          <div class="milestone-info">
            <h5>آمادگی محصول</h5>
            <p>تکمیل فاز ۷ — تیم قادر به تبدیل معماری به محصول قابل ارائه، عملیات پایدار و مدیریت چرخه عمر است. خروجی: سند معماری محصول + سند SLA و SLO.</p>
          </div>
        </div>

        <div class="success-box">
          <strong>✓ نکته کلیدی:</strong> نقطه عطف <strong>M4</strong> دقیقاً منطبق بر نیاز کارفرما برای <strong>جلسه دمو و آزمون عملی</strong> است. یعنی با تکمیل فازهای ۱ تا ۶، تیم آمادگی کامل برای پاسخ به محورهای ۱ تا ۶ نیازمندی‌ها را دارد. فاز ۷ برای <strong>پایداری بلندمدت محصول</strong> و پاسخ به محور ۷ (SLA و پایلوت) است.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۲</div>
        <div class="section-title">
          <h3>نگاشت نقشه راه به معماری و نیازمندی‌ها</h3>
          <div class="subtitle">Roadmap-to-Architecture & Requirements Mapping</div>
        </div>
      </div>
      <div class="section-content">
        <p>جدول زیر نشان می‌دهد هر فاز نقشه راه، کدام لایه‌های معماری (ARCH-1405-001) و کدام محورهای نیازمندی (REQ-1405-001) را پوشش می‌دهد:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>فاز</th>
              <th>لایه‌های معماری</th>
              <th>محورهای نیازمندی</th>
              <th>نقش کلیدی</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>فاز ۱</td>
              <td>پایه همه لایه‌ها</td>
              <td>پیش‌نیاز محور ۲، ۵</td>
              <td>مهندس داده، مهندس امنیت</td>
            </tr>
            <tr>
              <td>فاز ۲</td>
              <td>L1 تا L6 (الگوها)</td>
              <td>پیش‌نیاز همه محورها</td>
              <td>مهندس نرم‌افزار، معمار</td>
            </tr>
            <tr>
              <td>فاز ۳</td>
              <td>L4 (هوش و مدل‌ها)</td>
              <td>محور ۱، ۴</td>
              <td>مهندس AI</td>
            </tr>
            <tr>
              <td>فاز ۴</td>
              <td>L1 تا L6 + Y</td>
              <td>محور ۳، ۷</td>
              <td>معمار سیستم، SRE</td>
            </tr>
            <tr>
              <td>فاز ۵</td>
              <td>L3 (ارکستراسیون)</td>
              <td>محور ۱ (ایجنت)</td>
              <td>مهندس AI، معمار</td>
            </tr>
            <tr>
              <td>فاز ۶</td>
              <td>X (حاکمیت) + L2</td>
              <td>محور ۲، ۵</td>
              <td>مهندس امنیت</td>
            </tr>
            <tr>
              <td>فاز ۷</td>
              <td>L6 + Y + همه لایه‌ها</td>
              <td>محور ۳، ۶، ۷</td>
              <td>معمار، مدیر محصول، SRE</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۳</div>
        <div class="section-title">
          <h3>جمع‌بندی و مسیر پیشنهادی</h3>
          <div class="subtitle">Summary & Recommended Path</div>
        </div>
      </div>
      <div class="section-content">
        <p>نقشه راه ارائه‌شده، مسیری پیوسته و فارغ از سکو برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول است. ویژگی‌های کلیدی:</p>

        <ul class="reference-list">
          <li>
            <strong>هفت فاز پیوسته</strong>
            از مبانی سیستم‌ها و داده تا معماری کلان، محصول و عملیات — با وابستگی دانشی مشخص
          </li>
          <li>
            <strong>فارغ از سکو</strong>
            هیچ زبان، فریم‌ورک یا استک خاصی توصیه نشده؛ تمرکز بر مفاهیم و الگوهای قابل انتقال
          </li>
          <li>
            <strong>استانداردمحوری</strong>
            تکیه بر BPMN 2.0، OAuth 2.0، OpenID Connect، OWASP، ISO 27001/42001، NIST AI RMF و...
          </li>
          <li>
            <strong>الگومحوری</strong>
            یادگیری الگوهای طراحی و معماری (Hexagonal، Event-Driven، Circuit Breaker، ReAct، Plan-and-Execute و...)
          </li>
          <li>
            <strong>خروجی قابل‌آزمون</strong>
            هر فاز با Deliverable مشخص پایان می‌یابد تا دانش به مهارت تبدیل شود
          </li>
          <li>
            <strong>انطباق با نیازمندی‌ها</strong>
            نقطه عطف M4 دقیقاً منطبق بر آمادگی برای جلسه دمو و آزمون عملی کارفرماست
          </li>
        </ul>

        <div class="highlight-box">
          <strong>مسیر پیشنهادی:</strong> برای شروع، توصیه می‌شود تیم فنی ابتدا فازهای ۱ و ۲ را به‌صورت فشرده مرور کند (به‌ویژه اگر تجربه مهندسی نرم‌افزار دارد)، سپس تمرکز اصلی را بر <strong>فازهای ۳، ۴ و ۵</strong> بگذارد که هسته تمایز محصول هستند. فازهای ۶ و ۷ می‌توانند به‌صورت موازی با فازهای ۴ و ۵ پیش بروند تا نقطه عطف M4 در کوتاه‌ترین زمان محقق شود.
        </div>
      </div>
    </div>

    <div class="conclusion-box">
      <h3>🎯 ارزش این نقشه راه</h3>
      <p>این نقشه راه، مسیری شفاف، فارغ از سکو و استانداردمحور برای کسب دانش فنی لازم جهت پیاده‌سازی معماری و تبدیل آن به محصول ارائه می‌دهد.</p>
      <p>هر فاز با خروجی قابل‌آزمون پایان می‌یابد و نقطه عطف M4، آمادگی کامل برای جلسه دمو و آزمون عملی کارفرما را تضمین می‌کند.</p>
      <div class="highlight">
        <strong>💎 ارزش پیشنهادی:</strong><br>
        مسیر پیوسته از پایه تا کلان + فارغ از سکو + استانداردمحور + الگومحور + خروجی قابل‌آزمون + انطباق با نیازمندی‌ها
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_8d5bef83-5974-4a98-a41a-863c459267ff.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>تحلیل و رفع مشکل احراز هویت XApiKey در xIds</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500&display=swap');

  :root {
    --primary: #0f2a4a;
    --primary-light: #1e4976;
    --primary-dark: #081a2e;
    --accent: #c9a961;
    --accent-light: #e0c78a;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #2f855a;
    --success-light: #48bb78;
    --danger: #c53030;
    --danger-light: #fc8181;
    --warning: #c05621;
    --warning-light: #f6ad55;
    --info: #2c5282;
    --code-bg: #1a202c;
    --code-text: #e2e8f0;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(15,42,74,0.08);
    --shadow-lg: 0 10px 20px rgba(0,0,0,0.08), 0 20px 40px rgba(15,42,74,0.12);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 1000px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow-lg);
    border-radius: 16px;
    overflow: hidden;
  }

  /* ─── HEADER ─── */
  .document-header {
    background: linear-gradient(135deg, var(--primary-dark) 0%, var(--primary) 50%, var(--primary-light) 100%);
    color: white;
    padding: 55px 45px 45px;
    position: relative;
    border-bottom: 4px solid var(--accent);
    overflow: hidden;
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: -100px; left: -100px;
    width: 400px; height: 400px;
    background: radial-gradient(circle, rgba(201,169,97,0.18) 0%, transparent 70%);
    border-radius: 50%;
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
    flex-wrap: wrap;
    gap: 20px;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: linear-gradient(135deg, var(--accent), var(--accent-dark));
    border-radius: 14px;
    box-shadow: 0 8px 20px rgba(201,169,97,0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;
    font-weight: 900;
    color: white;
  }

  .company-name {
    font-size: 19px;
    font-weight: 800;
  }

  .company-tagline {
    font-size: 12px;
    opacity: 0.75;
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.85;
  }

  .doc-meta div { margin-bottom: 4px; }
  .doc-meta .meta-label { color: var(--accent-light); font-weight: 600; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.18);
    color: var(--accent-light);
    padding: 5px 18px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 16px;
    border: 1px solid rgba(201,169,97,0.4);
    letter-spacing: 2px;
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 900;
    margin-bottom: 12px;
    letter-spacing: -0.5px;
    line-height: 1.4;
  }

  .document-title .subtitle {
    font-size: 15px;
    opacity: 0.85;
    max-width: 700px;
    margin: 0 auto;
  }

  /* ─── BODY ─── */
  .document-body {
    padding: 50px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 22px 28px;
    border-radius: 10px;
    margin-bottom: 40px;
    font-size: 14.5px;
    color: var(--text-muted);
  }

  .intro-text strong { color: var(--primary); }

  /* ─── SECTIONS ─── */
  .section {
    margin-bottom: 45px;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 16px;
    padding-bottom: 14px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 22px;
  }

  .section-number {
    width: 52px; height: 52px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 13px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 6px 14px rgba(15,42,74,0.25);
  }

  .section-number.danger {
    background: linear-gradient(135deg, var(--danger), #9b2c2c);
  }

  .section-number.success {
    background: linear-gradient(135deg, var(--success), #22543d);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 20px;
    font-weight: 800;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content { padding-right: 8px; }

  .section-content p {
    margin-bottom: 14px;
    text-align: justify;
  }

  .section-content h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin: 22px 0 12px;
  }

  .section-content ul, .section-content ol {
    padding-right: 24px;
    margin: 12px 0;
  }

  .section-content li {
    margin-bottom: 8px;
    line-height: 1.85;
  }

  /* ─── BOXES ─── */
  .highlight-box, .info-box, .success-box, .warning-box, .danger-box {
    padding: 20px 24px;
    border-radius: 10px;
    margin: 22px 0;
    font-size: 14.5px;
  }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
  }
  .highlight-box strong { color: var(--accent-dark); }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--info);
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
  }

  .danger-box {
    background: linear-gradient(to left, #fff5f5, #fed7d7);
    border: 1px solid #fc8181;
    border-right: 4px solid var(--danger);
  }
  .danger-box strong { color: var(--danger); }

  /* ─── CODE ─── */
  .code-block {
    background: var(--code-bg);
    color: var(--code-text);
    border-radius: 10px;
    padding: 20px 24px;
    margin: 16px 0;
    overflow-x: auto;
    direction: ltr;
    text-align: left;
    font-family: 'JetBrains Mono', 'Consolas', monospace;
    font-size: 13px;
    line-height: 1.7;
    position: relative;
    border: 1px solid #2d3748;
  }

  .code-block::before {
    content: attr(data-lang);
    position: absolute;
    top: 8px;
    right: 12px;
    font-size: 10px;
    color: var(--accent);
    font-weight: 600;
    letter-spacing: 1px;
    direction: ltr;
  }

  .code-block .keyword { color: #f687b3; }
  .code-block .type { color: #63b3ed; }
  .code-block .string { color: #9ae6b4; }
  .code-block .comment { color: #718096; font-style: italic; }
  .code-block .method { color: #f6e05e; }
  .code-block .number { color: #fbb6ce; }

  code {
    background: #edf2f7;
    color: var(--primary);
    padding: 2px 8px;
    border-radius: 4px;
    font-family: 'JetBrains Mono', monospace;
    font-size: 13px;
    direction: ltr;
    display: inline-block;
  }

  /* ─── TABLES ─── */
  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: var(--shadow);
    font-size: 13.5px;
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    vertical-align: top;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table code {
    font-size: 12px;
    padding: 1px 6px;
  }

  /* ─── STEPS ─── */
  .step-card {
    background: white;
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 25px 28px;
    margin-bottom: 20px;
    position: relative;
    transition: all 0.3s;
  }

  .step-card:hover {
    border-color: var(--accent);
    box-shadow: var(--shadow);
  }

  .step-header {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 15px;
  }

  .step-number {
    width: 44px; height: 44px;
    background: linear-gradient(135deg, var(--accent), var(--accent-dark));
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 18px;
    flex-shrink: 0;
    box-shadow: 0 6px 14px rgba(201,169,97,0.3);
  }

  .step-title {
    font-size: 17px;
    font-weight: 800;
    color: var(--primary);
  }

  .step-title .step-subtitle {
    font-size: 12px;
    font-weight: 400;
    color: var(--text-muted);
    display: block;
    margin-top: 2px;
  }

  .step-body p {
    margin-bottom: 12px;
  }

  /* ─── ISSUE CARD ─── */
  .issue-card {
    background: linear-gradient(to left, #fff5f5, #fed7d7);
    border: 2px solid #fc8181;
    border-radius: 12px;
    padding: 25px;
    margin: 20px 0;
  }

  .issue-card .issue-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 17px;
    font-weight: 800;
    color: var(--danger);
    margin-bottom: 15px;
  }

  .issue-card .issue-icon {
    font-size: 24px;
  }

  /* ─── FILE REF ─── */
  .file-ref {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #edf2f7;
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 3px 10px;
    font-family: 'JetBrains Mono', monospace;
    font-size: 12px;
    color: var(--primary);
    direction: ltr;
    margin: 2px 0;
  }

  /* ─── DIAGNOSIS ─── */
  .diagnosis-tree {
    background: linear-gradient(135deg, #f8fafc, #edf2f7);
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 25px;
    margin: 20px 0;
  }

  .diagnosis-item {
    display: flex;
    gap: 15px;
    padding: 15px 0;
    border-bottom: 1px dashed var(--border);
  }

  .diagnosis-item:last-child { border-bottom: none; }

  .diagnosis-badge {
    flex-shrink: 0;
    width: 32px; height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 14px;
    color: white;
  }

  .diagnosis-badge.fail { background: var(--danger); }
  .diagnosis-badge.pass { background: var(--success); }
  .diagnosis-badge.warn { background: var(--warning); }

  .diagnosis-content { flex: 1; }

  .diagnosis-content h5 {
    font-size: 14.5px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 6px;
  }

  .diagnosis-content p {
    font-size: 13.5px;
    color: var(--text-muted);
    margin: 0;
  }

  /* ─── DIAGRAM ─── */
  .flow-diagram {
    background: white;
    border: 2px solid var(--border);
    border-radius: 12px;
    padding: 30px 20px;
    margin: 20px 0;
    overflow-x: auto;
  }

  .flow-steps {
    display: flex;
    flex-direction: column;
    gap: 12px;
    max-width: 800px;
    margin: 0 auto;
  }

  .flow-step-row {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .flow-step-box {
    flex: 1;
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 14px 18px;
    position: relative;
  }

  .flow-step-box.fail {
    background: linear-gradient(to left, #fff5f5, #fed7d7);
    border-color: #fc8181;
  }

  .flow-step-box.success {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border-color: #9ae6b4;
  }

  .flow-step-box h5 {
    font-size: 13.5px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 4px;
  }

  .flow-step-box p {
    font-size: 12.5px;
    color: var(--text-muted);
    margin: 0;
    line-height: 1.7;
  }

  .flow-arrow-down {
    text-align: center;
    font-size: 20px;
    color: var(--accent);
    margin: 2px 0;
  }

  /* ─── BADGES ─── */
  .badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 10px;
    font-size: 10.5px;
    font-weight: 700;
    letter-spacing: 0.5px;
  }

  .badge-fail { background: #fed7d7; color: var(--danger); }
  .badge-pass { background: #c6f6d5; color: var(--success); }
  .badge-warn { background: #feebc8; color: var(--warning); }
  .badge-info { background: #bee3f8; color: var(--info); }

  /* ─── FOOTER ─── */
  .document-footer {
    background: var(--primary-dark);
    color: white;
    padding: 30px 40px;
    text-align: center;
    font-size: 12px;
  }

  .document-footer .footer-brand {
    font-weight: 800;
    color: var(--accent);
    margin-bottom: 8px;
    font-size: 15px;
  }

  .footer-divider {
    width: 80px;
    height: 2px;
    background: var(--accent);
    margin: 14px auto;
    border-radius: 2px;
  }

  .page-info {
    text-align: center;
    padding: 18px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    background: #f8fafc;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 30px 22px; }
    .document-header { padding: 35px 25px; }
    .header-top { flex-direction: column; }
    .doc-meta { text-align: right; }
    .document-title h1 { font-size: 22px; }
    .flow-step-row { flex-direction: column; }
  }
</style>
</head>
<body>

<div class="document-container">

  <!-- ══════════ HEADER ══════════ -->
  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo">X</div>
        <div>
          <div class="company-name">xSaherelmWorkspace</div>
          <div class="company-tagline">Technical Analysis Document</div>
        </div>
      </div>
      <div class="doc-meta">
        <div><span class="meta-label">شماره مستند:</span> XIDS-AUTH-2026-001</div>
        <div><span class="meta-label">نسخه:</span> ۱.۰</div>
        <div><span class="meta-label">موضوع:</span> رفع مشکل احراز هویت XApiKey</div>
        <div><span class="meta-label">طبقه‌بندی:</span> داخلی — فنی</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">TECHNICAL DIAGNOSIS & SOLUTION</span>
      <h1>ریشه‌یابی و رفع مشکل احراز هویت با XApiKey در xIds</h1>
      <div class="subtitle">
        تحلیل جامع کد، شناسایی گلوگاه احراز هویت، و ارائه راه‌حل گام‌به‌گام برای فعال‌سازی کامل
        Authentication مبتنی بر API Key در سرور IdentityServer4
      </div>
    </div>
  </header>

  <!-- ══════════ BODY ══════════ -->
  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه اجرایی:</strong><br>
      پس از بررسی کامل کدهای پروژه <strong>xIds</strong>، مشخص شد که زیرساخت مدیریت Application و
      تولید <code>XApiKey</code> به‌درستی پیاده‌سازی شده است، اما <strong>زنجیره احراز هویت مبتنی بر API Key
      در سمت سرور IdentityServer4 ناقص مانده است</strong>. این سند ابتدا ریشه مشکل را با استناد به کدهای
      موجود تشریح می‌کند، سپس راه‌حل کامل گام‌به‌گام را ارائه می‌دهد.
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 1: CURRENT STATE -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>وضعیت فعلی سیستم</h3>
          <div class="subtitle">Current State Analysis</div>
        </div>
      </div>
      <div class="section-content">
        <p>
          در پروژه xIds، اجزای زیر برای مدیریت Application و API Key پیاده‌سازی شده‌اند:
        </p>

        <h4>۱.۱ — اجزای پیاده‌سازی‌شده</h4>

        <table class="styled-table">
          <thead>
            <tr>
              <th>جزء</th>
              <th>مسیر فایل</th>
              <th>وضعیت</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>مدل‌های Application و ApiKey</td>
              <td><span class="file-ref">xIdentityModels/Models/XApplication.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
            <tr>
              <td>XApplicationProvider (مدیریت API Key)</td>
              <td><span class="file-ref">xIds/Providers/XApplicationProvider.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
            <tr>
              <td>XApiKeyHelper (تولید و هش)</td>
              <td><span class="file-ref">xIds/Helpers/XApiKeyHelper.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
            <tr>
              <td>ApplicationsController (Endpointها)</td>
              <td><span class="file-ref">xIds/Controllers/ApplicationsController.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
            <tr>
              <td>XApiKeyAuthenticationHandler</td>
              <td><span class="file-ref">xIds/Providers/XApiKeyAuthenticationHandler.cs</span></td>
              <td><span class="badge badge-warn">⚠ موجود اما ناقص</span></td>
            </tr>
            <tr>
              <td>XApiKeyConfiguration</td>
              <td><span class="file-ref">xIds/Configurations/XApiKeyConfiguration.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
            <tr>
              <td>ثبت Scheme در Startup</td>
              <td><span class="file-ref">xIds/Startup.cs</span></td>
              <td><span class="badge badge-pass">✓ موجود</span></td>
            </tr>
          </tbody>
        </table>

        <h4>۱.۲ — معماری جاری احراز هویت در Startup.cs</h4>

        <div class="code-block" data-lang="C#">
<span class="comment">// xIds/Startup.cs</span>
services.<span class="method">AddXIdentityServerAuthentication</span>(
    configuration: Configuration,
    addApiKeyAuthentication: <span class="keyword">true</span>  <span class="comment">// ← این خط فعال است</span>
);
        </div>

        <p>
          و در <code>XDIHelperExtension.AddXIdentityServerAuthentication</code>:
        </p>

        <div class="code-block" data-lang="C#">
<span class="keyword">var</span> authBuilder = services.<span class="method">AddAuthentication</span>();

authBuilder.<span class="method">AddJwtBearer</span>(options =&gt;
{
    options.SaveToken = <span class="keyword">true</span>;
    options.RequireHttpsMetadata = <span class="keyword">false</span>;
    options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API;
})
.<span class="method">AddLocalApi</span>();

<span class="keyword">if</span> (addApiKeyAuthentication)
{
    authBuilder.<span class="method">AddScheme</span>&lt;AuthenticationSchemeOptions, XApiKeyAuthenticationHandler&gt;(
        XAuthenticationScheme.XApiKey.<span class="method">GetStringValue</span>(),  <span class="comment">// "XApiKey"</span>
        options =&gt; {}
    );
}
        </div>

        <div class="info-box">
          <strong>نتیجه:</strong> به نظر می‌رسد همه چیز در Startup به‌درستی ثبت شده است. اما در عمل، درخواست‌هایی
          که Header <code>X-Api-Key</code> دارند، احراز هویت نمی‌شوند. علت چیست؟
        </div>
      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 2: ROOT CAUSE -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number danger">۲</div>
        <div class="section-title">
          <h3>ریشه‌یابی مشکل</h3>
          <div class="subtitle">Root Cause Analysis</div>
        </div>
      </div>
      <div class="section-content">
        <p>
          پس از بررسی دقیق کدها، <strong>سه ریشه اصلی</strong> برای عدم کارکرد احراز هویت با XApiKey شناسایی شد:
        </p>

        <!-- Issue 1 -->
        <div class="issue-card">
          <div class="issue-title">
            <span class="issue-icon">🔴</span>
            مشکل ۱: ForwardDefaultSelector به XApiKey توجه نمی‌کند
          </div>
          <p>
            در <code>AddJwtBearer</code>، تنظیم <code>ForwardDefault</code> روی
            <code>XAuthentication.IDENTITY_SERVER_LOCAL_API</code> قرار داده شده است. این یعنی
            ASP.NET Core همیشه از Scheme پیش‌فرض (<code>IdentityServerAccessToken</code>) استفاده می‌کند
            و هیچ‌گاه به Scheme با نام <code>XApiKey</code> نمی‌رسد.
          </p>
          <div class="code-block" data-lang="C#">
<span class="comment">// xIds/DI/XDIHelperExtension.cs — AddXIdentityServerAuthentication</span>
authBuilder.<span class="method">AddJwtBearer</span>(options =&gt;
{
    options.SaveToken = <span class="keyword">true</span>;
    options.RequireHttpsMetadata = <span class="keyword">false</span>;
    options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API; <span class="comment">// ← مشکل اصلی اینجاست</span>
})
        </div>
        </div>

        <!-- Issue 2 -->
        <div class="issue-card">
          <div class="issue-title">
            <span class="issue-icon">🔴</span>
            مشکل ۲: ترتیب ثبت Schemeها اشتباه است
          </div>
          <p>
            در ASP.NET Core، <strong>اولین Scheme ثبت‌شده، Scheme پیش‌فرض است</strong>. در کد فعلی،
            <code>AddJwtBearer</code> قبل از <code>AddScheme&lt;...XApiKeyAuthenticationHandler&gt;</code> ثبت
            می‌شود و این باعث می‌شود حتی اگر Header <code>X-Api-Key</code> ارسال شود، Handler مربوطه
            هرگز فراخوانی نگردد.
          </p>
        </div>

        <!-- Issue 3 -->
        <div class="issue-card">
          <div class="issue-title">
            <span class="issue-icon">🔴</span>
            مشکل ۳: XApiKeyAuthenticationHandler به Claimهای Policyهای موجود پاسخ نمی‌دهد
          </div>
          <p>
            Policyهای موجود در <code>XAuthorizationHelper</code> (مانند <code>ApiKeyAccess</code> و
            <code>ApiKeyReadAccess</code>) انتظار Claim از نوع <code>JwtClaimTypes.Scope</code> با مقادیر
            <code>read</code>، <code>write</code>، <code>admin</code> یا <code>manage</code> دارند.
            اما <code>XApiKeyAuthenticationHandler</code> فعلی در کد، یک Scope ثابت به نام
            <code>"apikey"</code> اضافه می‌کند که با هیچ Policy موجودی مطابقت ندارد.
          </p>
          <div class="code-block" data-lang="C#">
<span class="comment">// xIds/Providers/XApiKeyAuthenticationHandler.cs — کد فعلی</span>
<span class="keyword">var</span> claims = <span class="keyword">new</span>[]
{
    <span class="keyword">new</span> <span class="type">Claim</span>(ClaimTypes.Name, validationResult.OwnerId),
    <span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"application_id"</span>, validationResult.ApplicationId.<span class="method">ToString</span>()),
    <span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"auth_type"</span>, <span class="string">"apikey"</span>),
    <span class="keyword">new</span> <span class="type">Claim</span>(JwtClaimTypes.Scope, <span class="string">"apikey"</span>),  <span class="comment">// ← هیچ Policyای این Scope را نمی‌شناسد</span>
};

<span class="comment">// سپس scopes از validationResult اضافه می‌شود، اما با مقادیر "read", "write"...</span>
<span class="comment">// که با Policyهای XAuthorizationHelper همخوانی ندارند</span>
          </div>
        </div>

        <h4>۲.۱ — درخت عیب‌یابی</h4>

        <div class="diagnosis-tree">
          <div class="diagnosis-item">
            <div class="diagnosis-badge fail">✗</div>
            <div class="diagnosis-content">
              <h5>درخواست با Header: X-Api-Key: xapp_xxxxx</h5>
              <p>Header به درستی در Request وجود دارد.</p>
            </div>
          </div>
          <div class="diagnosis-item">
            <div class="diagnosis-badge fail">✗</div>
            <div class="diagnosis-content">
              <h5>ASP.NET Core می‌خواهد Scheme پیش‌فرض را انتخاب کند</h5>
              <p>به دلیل <code>ForwardDefault = IDENTITY_SERVER_LOCAL_API</code>، همیشه Scheme پیش‌فرض انتخاب می‌شود.</p>
            </div>
          </div>
          <div class="diagnosis-item">
            <div class="diagnosis-badge fail">✗</div>
            <div class="diagnosis-content">
              <h5>XApiKeyAuthenticationHandler فراخوانی نمی‌شود</h5>
              <p>چون هیچ‌گاه انتخاب نمی‌شود، متد HandleAuthenticateAsync اجرا نمی‌گردد.</p>
            </div>
          </div>
          <div class="diagnosis-item">
            <div class="diagnosis-badge fail">✗</div>
            <div class="diagnosis-content">
              <h5>درخواست با خطای 401 Unauthorized رد می‌شود</h5>
              <p>پایان مسیر — احراز هویت شکست خورده است.</p>
            </div>
          </div>
        </div>

        <div class="danger-box">
          <strong>⚠️ خلاصه ریشه مشکل:</strong> در معماری فعلی، ASP.NET Core با
          <code>ForwardDefault</code> به Scheme پیش‌فرض هدایت می‌شود و هرگز به Scheme
          <code>XApiKey</code> نمی‌رسد. علاوه بر این، حتی اگر Handler فراخوانی شود، Claimهای
          تولیدشده با Policyهای موجود همخوانی ندارند و در نتیجه Authorization نیز شکست می‌خورد.
        </div>
      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 3: FLOW DIAGRAM -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>نمودار جریان فعلی در مقابل جریان مطلوب</h3>
          <div class="subtitle">Current vs. Desired Auth Flow</div>
        </div>
      </div>
      <div class="section-content">
        <h4>۳.۱ — جریان فعلی (معیوب)</h4>

        <div class="flow-diagram">
          <div class="flow-steps">
            <div class="flow-step-row">
              <div class="flow-step-box">
                <h5>۱. Client Request</h5>
                <p>ارسال درخواست با Header <code>X-Api-Key</code></p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box fail">
                <h5>۲. Default Scheme Selection</h5>
                <p>ASP.NET Core به دلیل ForwardDefault، Scheme پیش‌فرض را انتخاب می‌کند</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box fail">
                <h5>۳. JwtBearer Handler اجرا می‌شود</h5>
                <p>به‌دنبال Bearer Token می‌گردد، پیدا نمی‌کند، شکست می‌خورد</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box fail">
                <h5>❌ نتیجه: 401 Unauthorized</h5>
                <p>XApiKeyAuthenticationHandler هرگز اجرا نمی‌شود</p>
              </div>
            </div>
          </div>
        </div>

        <h4>۳.۲ — جریان مطلوب (پس از راه‌حل)</h4>

        <div class="flow-diagram">
          <div class="flow-steps">
            <div class="flow-step-row">
              <div class="flow-step-box">
                <h5>۱. Client Request</h5>
                <p>ارسال درخواست با Header <code>X-Api-Key</code></p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box success">
                <h5>۲. ForwardDefaultSelector اجرا می‌شود</h5>
                <p>وجود Header <code>X-Api-Key</code> را تشخیص می‌دهد و Scheme <code>XApiKey</code> را انتخاب می‌کند</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box success">
                <h5>۳. XApiKeyAuthenticationHandler.HandleAuthenticateAsync</h5>
                <p>API Key را استخراج و <code>ValidateApiKey</code> را فراخوانی می‌کند</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box success">
                <h5>۴. Claims تولید می‌شوند</h5>
                <p>Scopeهای واقعی از <code>validationResult.Scopes</code> به Claims اضافه می‌شوند</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box success">
                <h5>۵. Policy-Based Authorization</h5>
                <p>Policyهای <code>ApiKeyAccess</code> و <code>ApiKeyReadAccess</code> با موفقیت بررسی می‌شوند</p>
              </div>
            </div>
            <div class="flow-arrow-down">▼</div>
            <div class="flow-step-row">
              <div class="flow-step-box success">
                <h5>✅ نتیجه: 200 OK + Response</h5>
                <p>دسترسی به Endpoint مورد نظر با موفقیت انجام می‌شود</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 4: SOLUTION -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number success">۴</div>
        <div class="section-title">
          <h3>راه‌حل گام‌به‌گام</h3>
          <div class="subtitle">Step-by-Step Solution</div>
        </div>
      </div>
      <div class="section-content">

        <!-- STEP 1 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۱</div>
            <div class="step-title">
              اصلاح ForwardDefaultSelector در Startup
              <span class="step-subtitle">فایل: xIds/DI/XDIHelperExtension.cs</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              باید یک <code>ForwardDefaultSelector</code> تنظیم شود که بر اساس وجود Header
              <code>X-Api-Key</code> در Request، Scheme صحیح را انتخاب کند. این Selector
              برای <strong>تمام Schemeها</strong> (نه فقط JwtBearer) باید فعال باشد.
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// xIds/DI/XDIHelperExtension.cs — بخش AddXIdentityServerAuthentication</span>

<span class="keyword">public static void</span> <span class="method">AddXIdentityServerAuthentication</span>(
    <span class="keyword">this</span> <span class="type">IServiceCollection</span> services,
    <span class="type">IConfiguration</span> configuration,
    <span class="keyword">bool</span> addApiKeyAuthentication = <span class="keyword">false</span>
)
{
    services.<span class="method">AddXIdentityResourceConfiguration</span>(configuration);

    <span class="keyword">var</span> authBuilder = services.<span class="method">AddAuthentication</span>();

    <span class="comment">// ═══ ۱. ثبت Scheme برای XApiKey (اول از همه)</span>
    <span class="keyword">if</span> (addApiKeyAuthentication)
    {
        authBuilder.<span class="method">AddScheme</span>&lt;<span class="type">AuthenticationSchemeOptions</span>, <span class="type">XApiKeyAuthenticationHandler</span>&gt;(
            XAuthenticationScheme.XApiKey.<span class="method">GetStringValue</span>(),
            options =&gt; {}
        );
    }

    <span class="comment">// ═══ ۲. ثبت JwtBearer با ForwardDefaultSelector هوشمند</span>
    authBuilder.<span class="method">AddJwtBearer</span>(options =&gt;
    {
        options.SaveToken = <span class="keyword">true</span>;
        options.RequireHTTPSMetadata = <span class="keyword">false</span>;
        options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API;

        <span class="comment">// ═══ ۳. انتخاب Scheme بر اساس Header درخواست</span>
        options.ForwardDefaultSelector = context =&gt;
        {
            <span class="comment">// اگر Header X-Api-Key وجود دارد → از Scheme XApiKey استفاده کن</span>
            <span class="keyword">var</span> apiKeyHeader = XHeader.ApiKey.<span class="method">GetStringValue</span>(); <span class="comment">// "X-Api-Key"</span>
            <span class="keyword">if</span> (context.Request.Headers.<span class="method">ContainsKey</span>(apiKeyHeader))
            {
                <span class="keyword">return</span> XAuthenticationScheme.XApiKey.<span class="method">GetStringValue</span>();
            }

            <span class="comment">// در غیر این صورت، Scheme پیش‌فرض (LocalApi برای IdentityServer)</span>
            <span class="keyword">return</span> XAuthentication.IDENTITY_SERVER_LOCAL_API;
        };
    })
    .<span class="method">AddLocalApi</span>();
}
            </div>

            <div class="info-box">
              <strong>💡 چرا این راه‌حل کار می‌کند؟</strong> <code>ForwardDefaultSelector</code>
              یک delegate است که ASP.NET Core در هر درخواست فراخوانی می‌کند تا Scheme مناسب را
              تعیین کند. با بررسی وجود Header، ما به‌صورت پویا Scheme را انتخاب می‌کنیم.
            </div>
          </div>
        </div>

        <!-- STEP 2 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۲</div>
            <div class="step-title">
              اصلاح XApiKeyAuthenticationHandler برای تولید Claims صحیح
              <span class="step-subtitle">فایل: xIds/Providers/XApiKeyAuthenticationHandler.cs</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              Handler فعلی Scope ثابت <code>"apikey"</code> را اضافه می‌کند که با هیچ Policyای
              همخوانی ندارد. باید Scopeهای واقعی از <code>validationResult.Scopes</code>
              که در <code>XApplicationProvider.ValidateApiKey</code> استخراج شده‌اند، به Claims
              اضافه شوند.
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// xIds/Providers/XApiKeyAuthenticationHandler.cs — نسخه اصلاح‌شده</span>

<span class="keyword">protected override async</span> <span class="type">Task</span>&lt;<span class="type">AuthenticateResult</span>&gt; <span class="method">HandleAuthenticateAsync</span>()
{
    <span class="comment">// ۱. استخراج API Key از Header</span>
    <span class="keyword">var</span> apiKeyHeader = <span class="method">Options</span>.HeaderName ?? XHeader.ApiKey.<span class="method">GetStringValue</span>();
    <span class="keyword">if</span> (!Request.Headers.<span class="method">ContainsKey</span>(apiKeyHeader))
    {
        <span class="keyword">return</span> AuthenticateResult.<span class="method">NoResult</span>();
    }

    <span class="keyword">var</span> apiKey = Request.Headers[apiKeyHeader].<span class="method">ToString</span>();
    <span class="keyword">if</span> (<span class="keyword">string</span>.<span class="method">IsNullOrEmpty</span>(apiKey))
    {
        <span class="keyword">return</span> AuthenticateResult.<span class="method">NoResult</span>();
    }

    <span class="comment">// ۲. استخراج Client IP</span>
    <span class="keyword">var</span> clientIP = Request.HttpContext.Connection.RemoteIpAddress?.<span class="method">ToString</span>();

    <span class="comment">// ۳. اعتبارسنجی API Key از طریق Provider</span>
    <span class="keyword">var</span> validationResult = <span class="keyword">await</span> applicationProvider.<span class="method">ValidateApiKey</span>(
        apiKey: apiKey,
        clientIP: clientIP
    );

    <span class="keyword">if</span> (validationResult.Errors.<span class="method">HasChild</span>())
    {
        <span class="keyword">var</span> message = validationResult.Errors.<span class="method">ToListString</span>(<span class="string">'\n'</span>);
        <span class="keyword">return</span> AuthenticateResult.<span class="method">Fail</span>(message);
    }

    <span class="comment">// ═══ ۴. ساخت Claims — نکته کلیدی ═══</span>
    <span class="keyword">var</span> claims = <span class="keyword">new</span> <span class="type">List</span>&lt;<span class="type">Claim</span>&gt;
    {
        <span class="comment">// شناسه کاربر مالک API Key</span>
        <span class="keyword">new</span> <span class="type">Claim</span>(<span class="type">ClaimTypes</span>.Name, validationResult.OwnerId),
        <span class="keyword">new</span> <span class="type">Claim</span>(JwtClaimTypes.Subject, validationResult.OwnerId),

        <span class="comment">// شناسه Application</span>
        <span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"application_id"</span>, validationResult.ApplicationId.<span class="method">ToString</span>()),

        <span class="comment">// نوع احراز هویت برای تشخیص</span>
        <span class="keyword">new</span> <span class="type">Claim</span>(<span class="string">"auth_type"</span>, <span class="string">"apikey"</span>),
    };

    <span class="comment">// ═══ ۵. اضافه کردن Scopeهای واقعی ═══</span>
    <span class="comment">// این Scopeها توسط XApplicationProvider از AllowedScopes استخراج شده‌اند</span>
    <span class="comment">// و با Policyهای XAuthorizationHelper (read, write, admin, manage) همخوانی دارند</span>
    <span class="keyword">if</span> (validationResult.Scopes != <span class="keyword">null</span>)
    {
        <span class="keyword">foreach</span> (<span class="keyword">var</span> scope <span class="keyword">in</span> validationResult.Scopes)
        {
            claims.<span class="method">Add</span>(<span class="keyword">new</span> <span class="type">Claim</span>(JwtClaimTypes.Scope, scope));
        }
    }

    <span class="comment">// ۶. ساخت Principal و Ticket</span>
    <span class="keyword">var</span> identity = <span class="keyword">new</span> <span class="type">ClaimsIdentity</span>(claims, Scheme.Name);
    <span class="keyword">var</span> principal = <span class="keyword">new</span> <span class="type">ClaimsPrincipal</span>(identity);
    <span class="keyword">var</span> ticket = <span class="keyword">new</span> <span class="type">AuthenticationTicket</span>(principal, Scheme.Name);

    <span class="keyword">return</span> AuthenticateResult.<span class="method">Success</span>(ticket);
}
            </div>

            <div class="success-box">
              <strong>✅ نکته کلیدی:</strong> <code>validationResult.Scopes</code> مقادیری مانند
              <code>read</code>، <code>write</code>، <code>admin</code>، <code>manage</code> دارد که
              مستقیماً با Policyهای تعریف‌شده در <code>XAuthorizationHelper</code> مطابقت می‌کند.
            </div>
          </div>
        </div>

        <!-- STEP 3 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۳</div>
            <div class="step-title">
              اطمینان از همخوانی Policyها با Scopeهای API Key
              <span class="step-subtitle">فایل: xIdentityHelper/XAuthorizationHelper.cs</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              در <code>XAuthorizationHelper</code>، Policyهای مربوط به ApiKey تعریف شده‌اند.
              این Policyها باید با مقادیر <code>XApiKeyScope</code> در
              <code>xIdentityModels/Constants/XApiKeyScope.cs</code> همخوانی داشته باشند.
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// xIdentityModels/Constants/XApiKeyScope.cs</span>
<span class="keyword">public enum</span> <span class="type">XApiKeyScope</span>
{
    [<span class="method">StringValue</span>(<span class="string">"read"</span>)]
    Read,

    [<span class="method">StringValue</span>(<span class="string">"write"</span>)]
    Write,

    [<span class="method">StringValue</span>(<span class="string">"admin"</span>)]
    Admin,

    [<span class="method">StringValue</span>(<span class="string">"manage"</span>)]
    Manage
}
            </div>

            <p>
              و در <code>XAuthorizationHelper</code>:
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// xIdentityHelper/XAuthorizationHelper.cs — Policyهای موجود ApiKey</span>

<span class="comment">// ApiKey Access Policy — دسترسی به هر یک از Scopeها</span>
result.<span class="method">Add</span>(XPolicies.ApiKeyAccess,
    <span class="keyword">new</span> <span class="type">AuthorizationPolicyBuilder</span>()
    .<span class="method">RequireClaim</span>(
        JwtClaimTypes.Scope,
        XApiKeyScope.Read.<span class="method">GetStringValue</span>(),    <span class="comment">// "read"</span>
        XApiKeyScope.Write.<span class="method">GetStringValue</span>(),   <span class="comment">// "write"</span>
        XApiKeyScope.Manage.<span class="method">GetStringValue</span>()   <span class="comment">// "manage"</span>
    )
    .<span class="method">Build</span>()
);

<span class="comment">// ApiKey Read Access Policy</span>
result.<span class="method">Add</span>(XPolicies.ApiKeyReadAccess,
    <span class="keyword">new</span> <span class="type">AuthorizationPolicyBuilder</span>()
    .<span class="method">RequireClaim</span>(JwtClaimTypes.Scope, XApiKeyScope.Read.<span class="method">GetStringValue</span>())
    .<span class="method">Build</span>()
);
            </div>

            <div class="info-box">
              <strong>💡 نتیجه:</strong> اگر در گام ۲، Scopeهای واقعی از <code>validationResult.Scopes</code>
              به Claims اضافه شوند، این Policyها به‌صورت خودکار با موفقیت بررسی می‌شوند و دسترسی
              به Endpointهای محافظت‌شده امکان‌پذیر می‌گردد.
            </div>
          </div>
        </div>

        <!-- STEP 4 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۴</div>
            <div class="step-title">
              استفاده صحیح در Controllerها
              <span class="step-subtitle">نمونه استفاده صحیح</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              پس از اصلاحات بالا، برای محافظت از Endpointها با API Key، باید از Policyهای
              مربوطه استفاده کنید:
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// نمونه Endpoint محافظت‌شده با API Key</span>
[<span class="type">RequireXPowered</span>]
[<span class="type">HttpPost</span>(<span class="string">"ApiKeys/Validate"</span>)]
[<span class="type">Authorize</span>(Policy = XPolicies.ApiKeyAccess)]  <span class="comment">// ← Policy مخصوص API Key</span>
<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XApiKeyValidationResult</span>&gt;&gt; <span class="method">ValidateApiKey</span>(
    [<span class="type">FromBody</span>] <span class="type">XApiKeyValidationRequest</span> request,
    <span class="type">CancellationToken</span> cancellationToken = <span class="keyword">default</span>
)
{
    <span class="comment">// پیاده‌سازی</span>
}
            </div>

            <div class="warning-box">
              <strong>⚠️ توجه مهم:</strong> از آنجایی که Policyهای ApiKey بر اساس Scope
              تعریف شده‌اند، نباید از Policyهای مبتنی بر Role مانند <code>XPolicies.User</code>
              یا <code>XPolicies.EnabledUser</code> استفاده کنید. این Policyها انتظار Role Claim دارند
              که API Key ندارد.
            </div>
          </div>
        </div>

        <!-- STEP 5 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۵</div>
            <div class="step-title">
              تست و اعتبارسنجی
              <span class="step-subtitle">Validation & Testing</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              پس از اعمال تغییرات، مسیر تست زیر را دنبال کنید:
            </p>

            <h4>گام ۵.۱ — ساخت یک API Key جدید</h4>
            <div class="code-block" data-lang="HTTP">
<span class="comment"># Request: ساخت API Key جدید برای Application</span>
POST /Applications/{applicationId}/ApiKeys/Create
Content-Type: application/json
Authorization: Bearer {access_token}

{
  "scopes": ["read", "write"],
  "rateLimit": 60,
  "expirationMinutes": 43200,
  "allowedIPs": ["127.0.0.1"]
}
            </div>

            <p>
              پاسخ باید شامل شیء <code>XApiKeyDto</code> باشد. نکته مهم: کلید اصلی (plainKey) فقط
              <strong>یک‌بار</strong> در پاسخ اولیه برگردانده می‌شود و باید آن را در جای امن ذخیره کنید.
            </p>

            <h4>گام ۵.۲ — تست Endpoint با API Key</h4>
            <div class="code-block" data-lang="HTTP">
<span class="comment"># Request: تست Endpoint محافظت‌شده با API Key</span>
GET /Account/Test/HiApiKeyAccess
X-Api-Key: xapp_xxxxxxxxxxxxxxxxxxxxxxxx
X-PoweredBy: {xPoweredValue}
            </div>

            <h4>گام ۵.۳ — بررسی نتیجه</h4>

            <table class="styled-table">
              <thead>
                <tr>
                  <th>حالت</th>
                  <th>پاسخ مورد انتظار</th>
                  <th>تشخیص</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>API Key معتبر + Scope کافی</td>
                  <td><code>200 OK</code></td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
                <tr>
                  <td>API Key نامعتبر</td>
                  <td><code>401 Unauthorized</code> با پیام «ApiKey not found»</td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
                <tr>
                  <td>API Key منقضی‌شده</td>
                  <td><code>401</code> با پیام «ApiKey is Expired»</td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
                <tr>
                  <td>Scope ناکافی</td>
                  <td><code>403 Forbidden</code></td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
                <tr>
                  <td>IP غیرمجاز</td>
                  <td><code>401</code> با پیام «Client IP not Allowed»</td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
                <tr>
                  <td>Rate Limit رد شده</td>
                  <td><code>401</code> با پیام «ApiKey Rate Limit Reached»</td>
                  <td><span class="badge badge-pass">✓ صحیح</span></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- STEP 6 -->
        <div class="step-card">
          <div class="step-header">
            <div class="step-number">۶</div>
            <div class="step-title">
              به‌روزرسانی Endpoint «Validate API Key»
              <span class="step-subtitle">اصلاح کنترلر موجود</span>
            </div>
          </div>
          <div class="step-body">
            <p>
              در <code>ApplicationsController+Custom.cs</code>، متد <code>ValidateApiKey</code>
              فعلی از <code>GetUserInfo()</code> استفاده می‌کند که نیازمند احراز هویت با
              <code>Bearer Token</code> است. برای پیاده‌سازی درست، باید این Endpoint
              <strong>خودش با API Key احراز هویت شود</strong> (سناریوی self-validation):
            </p>

            <div class="code-block" data-lang="C#">
<span class="comment">// xIds/Controllers/Applications/ApplicationsController+Custom.cs</span>

<span class="comment">// نسخه اصلاح‌شده — با Policy API Key</span>
[<span class="type">HttpPost</span>(<span class="string">"ApiKeys/Validate"</span>)]
[<span class="type">AllowAnonymous</span>]  <span class="comment">// ← چون خودش API Key را در Body می‌فرستد</span>
<span class="keyword">public async</span> <span class="type">Task</span>&lt;<span class="type">ActionResult</span>&lt;<span class="type">XApiKeyValidationResult</span>&gt;&gt; <span class="method">ValidateApiKey</span>(
    [<span class="type">FromBody</span>] <span class="type">XApiKeyValidationRequest</span> request,
    <span class="type">CancellationToken</span> cancellationToken = <span class="keyword">default</span>
)
{
    <span class="keyword">try</span>
    {
        <span class="comment">// اعتبارسنجی ورودی</span>
        <span class="keyword">await</span> ValidationProvider
            .<span class="method">GroupValidationBuilder</span>()
            .<span class="method">AddNotNull</span>(request)
            .<span class="method">AddNotEmpty</span>(request.ApiKey)
            .<span class="method">ValidateGroupAsync</span>();

        <span class="comment">// استخراج ClientIP از Connection واقعی</span>
        <span class="keyword">var</span> clientIP = HttpContext.Connection.RemoteIpAddress?.<span class="method">ToString</span>();

        <span class="comment">// اعتبارسنجی مستقیم</span>
        <span class="keyword">var</span> result = <span class="keyword">await</span> provider.<span class="method">ValidateApiKey</span>(
            apiKey: request.ApiKey,
            clientIP: clientIP,
            requiredScope: request.RequiredScope,
            userInfo: <span class="keyword">null</span>,  <span class="comment">// ← userInfo دیگر نیاز نیست</span>
            cancellationToken: cancellationToken
        );

        <span class="keyword">return</span> <span class="method">Ok</span>(result.<span class="method">ToDynamicObject</span>());
    }
    <span class="keyword">catch</span> (<span class="type">Exception</span> ex)
    {
        <span class="keyword">var</span> result = <span class="method">GetExceptionActionResult</span>(ex);
        <span class="keyword">return</span> result;
    }
}
            </div>

            <div class="info-box">
              <strong>💡 چرا AllowAnonymous؟</strong> چون این Endpoint خودش نقش «اعتبارسنج API Key» را
              دارد و نباید قبل از رسیدن به آن، احراز هویت شود. منطق اعتبارسنجی درون خودش انجام می‌شود.
            </div>
          </div>
        </div>

      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 5: SUMMARY TABLE -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>خلاصه تغییرات</h3>
          <div class="subtitle">Summary of Changes</div>
        </div>
      </div>
      <div class="section-content">
        <table class="styled-table">
          <thead>
            <tr>
              <th>#</th>
              <th>فایل</th>
              <th>تغییر</th>
              <th>اولویت</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱</td>
              <td><span class="file-ref">xIds/DI/XDIHelperExtension.cs</span></td>
              <td>افزودن <code>ForwardDefaultSelector</code> برای انتخاب پویا بین JwtBearer و XApiKey</td>
              <td><span class="badge badge-fail">حیاتی</span></td>
            </tr>
            <tr>
              <td>۲</td>
              <td><span class="file-ref">xIds/Providers/XApiKeyAuthenticationHandler.cs</span></td>
              <td>حذف Scope ثابت «apikey» و افزودن Scopeهای واقعی از <code>validationResult.Scopes</code></td>
              <td><span class="badge badge-fail">حیاتی</span></td>
            </tr>
            <tr>
              <td>۳</td>
              <td><span class="file-ref">xIds/Startup.cs</span></td>
              <td>اطمینان از ترتیب صحیح ثبت Schemeها (نیاز به تغییر مستقیم ندارد اگر از Extension استفاده شود)</td>
              <td><span class="badge badge-warn">متوسط</span></td>
            </tr>
            <tr>
              <td>۴</td>
              <td><span class="file-ref">xIds/Controllers/Applications/ApplicationsController+Custom.cs</span></td>
              <td>اصلاح <code>ValidateApiKey</code> برای کارکرد مستقل</td>
              <td><span class="badge badge-warn">متوسط</span></td>
            </tr>
            <tr>
              <td>۵</td>
              <td><span class="file-ref">xIds/Controllers/Account/AccountController+Test.cs</span></td>
              <td>افزودن تست‌های احراز هویت با API Key (اختیاری، برای تست)</td>
              <td><span class="badge badge-info">توصیه‌شده</span></td>
            </tr>
          </tbody>
        </table>

        <div class="success-box">
          <strong>✅ نتیجه نهایی:</strong> با اعمال گام‌های ۱ و ۲ (که حیاتی هستند)، مشکل احراز هویت
          با <code>XApiKey</code> به‌طور کامل حل می‌شود. گام‌های ۳ تا ۵ برای بهبود و تکمیل توصیه می‌شوند.
        </div>
      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 6: BEST PRACTICES -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>بهترین شیوه‌ها و توصیه‌های تکمیلی</h3>
          <div class="subtitle">Best Practices & Additional Recommendations</div>
        </div>
      </div>
      <div class="section-content">

        <h4>۶.۱ — مدیریت صحیح Scopeها در سطح API Key</h4>
        <p>
          هنگام ساخت API Key، از مقادیر <code>XApiKeyScope</code> استفاده کنید:
        </p>

        <div class="code-block" data-lang="C#">
<span class="comment">// نمونه ساخت API Key با Scopeهای صحیح</span>
<span class="keyword">var</span> result = <span class="keyword">await</span> provider.<span class="method">CreateApiKey</span>(
    applicationId: applicationId,
    scopes: <span class="keyword">new</span>[] { <span class="string">"read"</span>, <span class="string">"write"</span> },  <span class="comment">// ← مطابق XApiKeyScope</span>
    allowedIPs: <span class="keyword">new</span>[] { <span class="string">"192.168.1.100"</span> },
    rateLimit: 60,
    expiration: <span class="type">TimeSpan</span>.<span class="method">FromDays</span>(30),
    userInfo: userInfo
);
        </div>

        <h4>۶.۲ — تفکیک Policyهای مبتنی بر API Key از Policyهای مبتنی بر Role</h4>
        <p>
          Policyهای موجود در <code>XPolicies</code> دو دسته هستند:
        </p>
        <ul>
          <li><strong>Policyهای مبتنی بر Scope</strong> (مثل <code>ApiKeyAccess</code>, <code>ReadAccess</code>) — برای API Key و Bearer Token</li>
          <li><strong>Policyهای مبتنی بر Role</strong> (مثل <code>User</code>, <code>Admin</code>) — فقط برای Bearer Token</li>
        </ul>

        <div class="warning-box">
          <strong>⚠️ توجه:</strong> هرگز از Policyهای Role-based برای Endpointهایی که قرار است با
          API Key محافظت شوند استفاده نکنید. این Policyها انتظار Claim از نوع <code>role</code> دارند
          که API Key ندارد.
        </div>

        <h4>۶.۳ — ذخیره امن Plain Key</h4>
        <p>
          کلید اصلی (plain key) فقط در لحظه ساخت برگردانده می‌شود. باید در جای امن ذخیره شود.
          در صورتی که کاربر آن را گم کند، باید کلید قبلی revoke شده و کلید جدید ساخته شود.
        </p>

        <h4>۶.۴ — Rate Limit و Audit Log</h4>
        <p>
          در <code>XApiKeyConfiguration</code>، ویژگی‌های زیر فعال هستند:
        </p>
        <ul>
          <li><code>DefaultRateLimit</code> — محدودیت نرخ پیش‌فرض</li>
          <li><code>EnableAuditLog</code> — برای ثبت استفاده از API Keyها</li>
        </ul>

        <p>
          توصیه می‌شود در <code>ValidateApiKey</code> پس از اعتبارسنجی موفق، یک رکورد
          <code>XApiKeyUsage</code> ثبت کنید تا تاریخچه استفاده قابل ردیابی باشد.
        </p>

        <h4>۶.۵ — Endpointهای توصیه‌شده برای تست</h4>
        <p>
          برای اطمینان از کارکرد صحیح، این Endpointها را در <code>AccountController+Test.cs</code>
          اضافه کنید:
        </p>

        <div class="code-block" data-lang="C#">
[<span class="type">RequireXPowered</span>]
[<span class="type">HttpGet</span>(<span class="string">"Test/HiApiKeyReadAccess"</span>)]
[<span class="type">Authorize</span>(Policy = XPolicies.ApiKeyReadAccess)]
<span class="keyword">public</span> <span class="type">ActionResult</span>&lt;<span class="keyword">string</span>&gt; <span class="method">HiApiKeyReadAccess</span>()
{
    <span class="keyword">return</span> <span class="method">Ok</span>(<span class="string">"API Key Read Access Passed ..."</span>);
}

[<span class="type">RequireXPowered</span>]
[<span class="type">HttpPost</span>(<span class="string">"Test/HiApiKeyWriteAccess"</span>)]
[<span class="type">Authorize</span>(Policy = XPolicies.ApiKeyWriteAccess)]
<span class="keyword">public</span> <span class="type">ActionResult</span>&lt;<span class="keyword">string</span>&gt; <span class="method">HiApiKeyWriteAccess</span>()
{
    <span class="keyword">return</span> <span class="method">Ok</span>(<span class="string">"API Key Write Access Passed ..."</span>);
}
        </div>
      </div>
    </div>

    <!-- ══════════════════════════════════════════ -->
    <!-- SECTION 7: CONCLUSION -->
    <!-- ══════════════════════════════════════════ -->
    <div class="section">
      <div class="section-header">
        <div class="section-number success">۷</div>
        <div class="section-title">
          <h3>جمع‌بندی</h3>
          <div class="subtitle">Conclusion</div>
        </div>
      </div>
      <div class="section-content">
        <p>
          مشکل عدم احراز هویت با <code>XApiKey</code> در xIds ریشه در <strong>دو نقطه کد کلیدی</strong>
          دارد که هر دو در این سند شناسایی و راه‌حل آن‌ها ارائه شد:
        </p>

        <ol>
          <li>
            <strong>عدم انتخاب صحیح Scheme در Startup</strong> — که با افزودن
            <code>ForwardDefaultSelector</code> در <code>AddJwtBearer</code> حل می‌شود.
          </li>
          <li>
            <strong>عدم تطابق Claims تولیدشده با Policyها</strong> — که با افزودن Scopeهای
            واقعی از <code>validationResult.Scopes</code> در <code>XApiKeyAuthenticationHandler</code>
            حل می‌شود.
          </li>
        </ol>

        <p>
          با اعمال این دو تغییر ساده اما حیاتی، سیستم احراز هویت مبتنی بر API Key به‌طور کامل فعال
          می‌شود و Endpointهای محافظت‌شده با Policyهای <code>ApiKeyAccess</code>،
          <code>ApiKeyReadAccess</code>، <code>ApiKeyWriteAccess</code> و
          <code>ApiKeyAdminAccess</code> به درستی کار می‌کنند.
        </p>

        <div class="success-box">
          <strong>✅ کلید موفقیت:</strong> زیرساخت موجود در xIds برای مدیریت API Key بسیار
          کامل و حرفه‌ای است. تنها دو نقطه اتصال کوچک در لایه احراز هویت نیاز به اصلاح داشتند
          که در این سند به‌طور کامل تشریح شدند.
        </div>
      </div>
    </div>

    <div class="page-info">
      این مستند فنی محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است.
    </div>

  </div>

  <!-- ══════════ FOOTER ══════════ -->
  <footer class="document-footer">
    <div class="footer-brand">xSaherelmWorkspace — Technical Analysis</div>
    <div class="footer-divider"></div>
    <div>
      تحلیل و مستندسازی: تیم فنی xSaherelmWorkspace &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp;
      مهر ۱۴۰۵
    </div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_91592543-a30d-4cd3-8f73-4660ff1c06d1.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>تحلیل نیازمندی‌ها | درخواست شرکت پارسا پلیمر شریف</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');

  :root {
    --primary: #1a365d;
    --primary-light: #2c5282;
    --accent: #c9a961;
    --accent-dark: #a8893f;
    --bg: #faf9f6;
    --card-bg: #ffffff;
    --text: #1a202c;
    --text-muted: #4a5568;
    --border: #e2e8f0;
    --success: #38a169;
    --danger: #e53e3e;
    --warning: #dd6b20;
    --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'Vazirmatn', Tahoma, sans-serif;
    background: var(--bg);
    color: var(--text);
    line-height: 1.9;
    font-size: 15px;
    padding: 30px 15px;
  }

  .document-container {
    max-width: 950px;
    margin: 0 auto;
    background: var(--card-bg);
    box-shadow: var(--shadow);
    border-radius: 12px;
    overflow: hidden;
  }

  .document-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
    color: white;
    padding: 50px 40px 40px;
    position: relative;
    border-bottom: 4px solid var(--accent);
  }

  .document-header::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
    border-radius: 50%;
    transform: translate(50%, -50%);
  }

  .header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    position: relative;
    z-index: 1;
  }

  .company-badge {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .company-logo {
    width: 60px; height: 60px;
    background: var(--accent);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  }

  .doc-meta {
    text-align: left;
    font-size: 12px;
    opacity: 0.9;
  }

  .doc-meta div { margin-bottom: 3px; }

  .document-title {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 20px 0;
  }

  .document-title .label {
    display: inline-block;
    background: rgba(201,169,97,0.2);
    color: var(--accent);
    padding: 4px 16px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 15px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-title h1 {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 10px;
    letter-spacing: -0.5px;
  }

  .document-title h2 {
    font-size: 16px;
    font-weight: 400;
    opacity: 0.9;
  }

  .document-body {
    padding: 40px;
  }

  .intro-text {
    background: linear-gradient(to left, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin-bottom: 35px;
    font-size: 14px;
    color: var(--text-muted);
  }

  .section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .section-header {
    display: flex;
    align-items: center;
    gap: 15px;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--border);
    margin-bottom: 20px;
  }

  .section-number {
    width: 50px; height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-size: 20px;
    flex-shrink: 0;
    box-shadow: 0 4px 10px rgba(26,54,93,0.2);
  }

  .section-title { flex: 1; }

  .section-title h3 {
    font-size: 19px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 2px;
  }

  .section-title .subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .section-content {
    padding-right: 10px;
  }

  .section-content p {
    margin-bottom: 12px;
    text-align: justify;
    text-indent: 20px;
  }

  .section-content p.no-indent { text-indent: 0; }

  .highlight-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #f6e05e;
    border-right: 4px solid var(--accent);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .highlight-box strong {
    color: var(--accent-dark);
  }

  .info-box {
    background: linear-gradient(to left, #ebf8ff, #e6f6ff);
    border: 1px solid #90cdf4;
    border-right: 4px solid var(--primary-light);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .success-box {
    background: linear-gradient(to left, #f0fff4, #e6fffa);
    border: 1px solid #9ae6b4;
    border-right: 4px solid var(--success);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .warning-box {
    background: linear-gradient(to left, #fffaf0, #fef5e7);
    border: 1px solid #fbd38d;
    border-right: 4px solid var(--warning);
    padding: 18px 22px;
    border-radius: 8px;
    margin: 20px 0;
    font-size: 14px;
  }

  .styled-table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .styled-table thead {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
  }

  .styled-table th {
    padding: 14px 16px;
    text-align: right;
    font-weight: 600;
    font-size: 13px;
  }

  .styled-table td {
    padding: 13px 16px;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
  }

  .styled-table tbody tr:last-child td { border-bottom: none; }
  .styled-table tbody tr:nth-child(even) { background: #f8fafc; }

  .styled-table .highlight-row {
    background: #fffaf0 !important;
    font-weight: 600;
  }

  .comparison-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 25px 0;
  }

  .comparison-card {
    background: #f8fafc;
    border: 2px solid var(--border);
    border-radius: 10px;
    padding: 20px;
    position: relative;
  }

  .comparison-card.recommended {
    border-color: var(--success);
    background: linear-gradient(to left, #f0fff4, #e6fffa);
  }

  .comparison-card .card-badge {
    position: absolute;
    top: -10px;
    right: 20px;
    background: var(--success);
    color: white;
    padding: 3px 12px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
  }

  .comparison-card h4 {
    font-size: 16px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--border);
  }

  .comparison-card.recommended h4 {
    border-bottom-color: var(--success);
  }

  .comparison-card ul {
    list-style: none;
    padding: 0;
  }

  .comparison-card ul li {
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }

  .comparison-card ul li:last-child { border-bottom: none; }

  .comparison-card ul li .value {
    font-weight: 600;
    color: var(--primary);
  }

  .quote-box {
    background: linear-gradient(135deg, #f7fafc, #edf2f7);
    border-right: 4px solid var(--accent);
    padding: 20px 25px;
    border-radius: 8px;
    margin: 20px 0;
    position: relative;
  }

  .quote-box::before {
    content: '"';
    position: absolute;
    top: -10px;
    right: 15px;
    font-size: 60px;
    color: var(--accent);
    opacity: 0.3;
    font-family: Georgia, serif;
  }

  .quote-box p {
    font-style: italic;
    color: var(--text-muted);
    margin-bottom: 10px;
    text-indent: 0 !important;
  }

  .quote-box .source {
    font-size: 12px;
    color: var(--text-muted);
    text-align: left;
    font-style: normal;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin: 25px 0;
  }

  .stat-card {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(26,54,93,0.2);
  }

  .stat-card .stat-value {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 5px;
    color: var(--accent);
    line-height: 1.3;
  }

  .stat-card .stat-label {
    font-size: 12px;
    opacity: 0.9;
  }

  .timeline {
    position: relative;
    padding: 20px 0;
    margin: 25px 0;
  }

  .timeline::before {
    content: '';
    position: absolute;
    right: 50%;
    top: 0;
    bottom: 0;
    width: 3px;
    background: var(--border);
    transform: translateX(50%);
  }

  .timeline-item {
    display: flex;
    margin-bottom: 20px;
    position: relative;
  }

  .timeline-item:nth-child(odd) {
    flex-direction: row-reverse;
  }

  .timeline-content {
    width: 45%;
    background: #f8fafc;
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 15px;
    position: relative;
  }

  .timeline-item:nth-child(odd) .timeline-content {
    margin-left: 5%;
  }

  .timeline-item:nth-child(even) .timeline-content {
    margin-right: 5%;
  }

  .timeline-dot {
    position: absolute;
    right: 50%;
    top: 20px;
    width: 16px;
    height: 16px;
    background: var(--accent);
    border: 3px solid white;
    border-radius: 50%;
    transform: translateX(50%);
    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    z-index: 1;
  }

  .timeline-content h5 {
    font-size: 14px;
    font-weight: 700;
    color: var(--primary);
    margin-bottom: 8px;
  }

  .timeline-content p {
    font-size: 12px;
    color: var(--text-muted);
    text-indent: 0 !important;
    margin-bottom: 0 !important;
  }

  .reference-list {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  .reference-list li {
    background: #f8fafc;
    border-right: 3px solid var(--primary-light);
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 6px;
    font-size: 13px;
  }

  .reference-list li strong {
    color: var(--primary);
    display: block;
    margin-bottom: 5px;
  }

  .reference-list li .ref-source {
    font-size: 11px;
    color: var(--text-muted);
    margin-top: 5px;
  }

  .conclusion-box {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin: 30px 0;
    text-align: center;
    box-shadow: 0 8px 20px rgba(26,54,93,0.3);
  }

  .conclusion-box h3 {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 15px;
    color: var(--accent);
  }

  .conclusion-box p {
    font-size: 14px;
    line-height: 1.8;
    text-indent: 0 !important;
    margin-bottom: 15px;
  }

  .conclusion-box .highlight {
    background: rgba(201,169,97,0.2);
    padding: 15px 20px;
    border-radius: 8px;
    margin-top: 20px;
    border: 1px solid rgba(201,169,97,0.4);
  }

  .document-footer {
    background: var(--primary);
    color: white;
    padding: 25px 40px;
    text-align: center;
    font-size: 12px;
    margin-top: 40px;
  }

  .document-footer .footer-brand {
    font-weight: 700;
    color: var(--accent);
    margin-bottom: 5px;
    font-size: 14px;
  }

  .footer-divider {
    width: 60px;
    height: 2px;
    background: var(--accent);
    margin: 10px auto;
  }

  .page-info {
    text-align: center;
    padding: 15px;
    font-size: 11px;
    color: var(--text-muted);
    border-top: 1px solid var(--border);
    margin-top: 30px;
  }

  @media print {
    body { background: white; padding: 0; }
    .document-container { box-shadow: none; border-radius: 0; }
    .section { page-break-inside: avoid; }
  }

  @media (max-width: 768px) {
    .document-body { padding: 25px 20px; }
    .document-header { padding: 30px 20px; }
    .comparison-grid { grid-template-columns: 1fr; }
    .stats-grid { grid-template-columns: 1fr; }
    .header-top { flex-direction: column; gap: 15px; }
    .doc-meta { text-align: center; }
  }
</style>
</head>
<body>

<div class="document-container">

  <header class="document-header">
    <div class="header-top">
      <div class="company-badge">
        <div class="company-logo"></div>
      </div>
      <div class="doc-meta">
        <div>شماره مستند: REQ-1405-001</div>
        <div>نسخه: ۱.۰</div>
        <div>تاریخ تهیه: مهر ۱۴۰۵</div>
        <div>طبقه‌بندی: محرمانه</div>
      </div>
    </div>

    <div class="document-title">
      <span class="label">REQUIREMENTS ANALYSIS</span>
      <h1>تحلیل نیازمندی‌ها</h1>
      <h2>درخواست شرکت پارسا پلیمر شریف برای راهکار هوش مصنوعی سازمانی</h2>
    </div>
  </header>

  <div class="document-body">

    <div class="intro-text">
      <strong>خلاصه مدیریتی،</strong><br>
      این مستند به تحلیل دقیق و شفاف درخواست رسمی شرکت پارسا پلیمر شریف (نخستین شرکت دانش‌بنیان ایران، فعال در صنعت تولید کامپاندهای پلیمری) می‌پردازد. هدف درخواست‌کننده، بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف سازمان و ارزیابی محصولات و خدمات ارائه‌دهندگان این حوزه است. در این مستند، هفت محور اصلی درخواست، الزامات آزمون عملی، و انتظارات کلیدی کارفرما به‌صورت دسته‌بندی‌شده تشریح می‌شود تا مبنای تهیه پیشنهاد فنی و تجاری قرار گیرد.
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱</div>
        <div class="section-title">
          <h3>شناخت کلی درخواست</h3>
          <div class="subtitle">Context & Overview</div>
        </div>
      </div>
      <div class="section-content">
        <p>شرکت پارسا پلیمر شریف با هدف بهره‌گیری تدریجی از هوش مصنوعی در واحدهای مختلف، از ارائه‌دهندگان راهکارهای هوش مصنوعی درخواست کرده است تا اطلاعات محصولات و خدمات خود را به‌صورت مکتوب ارائه دهند. این درخواست در قالب یک <strong>RFP (درخواست پیشنهاد)</strong> با رویکردی فنی، دقیق و آزمون‌محور تنظیم شده است.</p>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">۷</div>
            <div class="stat-label">محور اصلی درخواست</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">آزمون<br>عملی</div>
            <div class="stat-label">الزام جلسه دمو</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">شفافیت<br>کامل</div>
            <div class="stat-label">در قیمت و قابلیت‌ها</div>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نکته کلیدی:</strong> لحن و ساختار درخواست نشان می‌دهد تیم فنی/فناوری اطلاعات کارفرما با مفاهیم روز هوش مصنوعی (Agent، Assistant، RAG، مدیریت دسترسی، حاکمیت داده) کاملاً آشناست و به دنبال پاسخ‌های سطحی یا بازاریابی نیست. بنابراین، پیشنهاد ارائه‌شده باید مستند، قابل‌آزمون و شفاف باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۲</div>
        <div class="section-title">
          <h3>محور ۱: ماهیت راهکار، مدل‌ها و قابلیت‌های ایجنت</h3>
          <div class="subtitle">Solution Nature, Models & Agent Capabilities</div>
        </div>
      </div>
      <div class="section-content">
        <p>کارفرما خواستار شفاف‌سازی دقیق ماهیت راهکار و تمایز آن از گردش‌کارهای از پیش تعریف‌شده است. نیازمندی‌های صریح این محور به شرح زیر است:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام آزمون/اثبات</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۱-۱</td>
              <td>مشخص کردن قالب راهکار: چت‌بات، دستیار هوشمند (Assistant)، ایجنت (Agent) یا ترکیبی از آن‌ها و قابلیت‌های هر بخش</td>
              <td>توضیح مکتوب + نمایش عملی</td>
            </tr>
            <tr>
              <td>۱-۲</td>
              <td>ارائه تعریف دقیق و قابل‌آزمون از Agent و تمایز آن با Assistant یا گردش‌کار از پیش تعریف‌شده</td>
              <td>سناریوی چندمرحله‌ای در محیط آزمایشی</td>
            </tr>
            <tr>
              <td>۱-۳</td>
              <td>توانایی تبدیل هدف به مراحل اجرایی، انتخاب ابزار مناسب، انجام عملیات و اصلاح مراحل بعدی بر اساس نتیجه</td>
              <td>اجرای عملی در جلسه دمو</td>
            </tr>
            <tr>
              <td>۱-۴</td>
              <td>مشخص کردن نقاط نیازمند دستور یا تأیید انسان (Human-in-the-loop)</td>
              <td>مستندسازی + نمایش در سناریو</td>
            </tr>
            <tr>
              <td>۱-۵</td>
              <td>اعلام مدل‌های قابل استفاده در هر پلن و امکان طراحی دستیار/ایجنت اختصاصی متناسب با فرایندهای سازمان</td>
              <td>جدول مدل‌ها به تفکیک پلن</td>
            </tr>
            <tr>
              <td>۱-۶</td>
              <td>پشتیبانی از به‌روزترین مدل‌های منتشرشده و اعلام بازه زمانی دسترسی سازمانی پس از عرضه مدل/نسخه جدید</td>
              <td>تعهد زمان‌بندی مشخص</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ نکته حساس:</strong> کارفرما در جلسه دمو خواستار ارائه <strong>یک سناریوی چندمرحله‌ای در محیط آزمایشی</strong> است تا نحوه برنامه‌ریزی مراحل، انتخاب و استفاده از ابزارها، اجرای عملیات، واکنش به خطا یا تغییر شرایط، و موارد نیازمند مداخله انسانی به‌صورت قابل مشاهده ارزیابی شود. ادعاهای مکتوب بدون قابلیت نمایش عملی، پذیرفته نخواهد شد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۳</div>
        <div class="section-title">
          <h3>محور ۲: مدیریت کاربران و سطوح دسترسی</h3>
          <div class="subtitle">User Management & Access Control</div>
        </div>
      </div>
      <div class="section-content">
        <p>این محور از حساس‌ترین بخش‌های درخواست است، زیرا کارفرما قصد دارد <strong>آزمون نفوذ عملی</strong> برای سطوح دسترسی انجام دهد. نیازمندی‌های صریح:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام آزمون/اثبات</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۲-۱</td>
              <td>سازوکار ایجاد کاربران، تعریف نقش‌ها و مدیریت کاربران واحدهای مختلف سازمان</td>
              <td>نمایش عملی + مستندات</td>
            </tr>
            <tr>
              <td>۲-۲</td>
              <td>امکان تعیین فهرست مجاز مدل‌ها، منابع و ابزارها و محدودسازی دسترسی تا سطح سند یا رکورد</td>
              <td>آزمون با حساب‌های متفاوت</td>
            </tr>
            <tr>
              <td>۲-۳</td>
              <td>نحوه اعمال مجوزها در بازیابی اطلاعات، پاسخ‌گویی مدل و اجرای عملیات ایجنت</td>
              <td>آزمون پرسش یکسان با مجوزهای متفاوت</td>
            </tr>
            <tr>
              <td>۲-۴</td>
              <td>سازوکار جلوگیری از افشای اطلاعات خارج از سطح دسترسی</td>
              <td>آزمون نفوذ (پرسش مستقیم/غیرمستقیم، خلاصه‌سازی، ایجنت)</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ آزمون نفوذ دسترسی:</strong> کارفرما صراحتاً اعلام کرده است که در ارزیابی، <strong>پرسش‌های یکسان با حساب‌های دارای مجوزهای متفاوت</strong> مطرح خواهد شد تا اطمینان حاصل شود پاسخ‌ها بر مبنای اطلاعات مجاز هر کاربر تولید می‌شوند. همچنین بررسی خواهد شد که کاربران فاقد مجوز نتوانند از طریق پرسش مستقیم یا غیرمستقیم، درخواست خلاصه‌سازی یا استفاده از ایجنت، به اطلاعات خارج از سطح دسترسی خود دست یابند. این یعنی راهکار باید در برابر <strong>حملات مبتنی بر مهندسی اجتماعی و دور زدن مجوزها</strong> مقاوم باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۴</div>
        <div class="section-title">
          <h3>محور ۳: پلن‌ها، مصرف، تعرفه‌ها و API</h3>
          <div class="subtitle">Plans, Usage, Pricing & API</div>
        </div>
      </div>
      <div class="section-content">
        <p>کارفرما روی <strong>شفافیت کامل قیمت‌گذاری و مبنای محاسبه</strong> تأکید ویژه دارد. نیازمندی‌های صریح:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام ارائه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۳-۱</td>
              <td>تفاوت پلن‌های سازمانی و شخصی و مبنای محاسبه هزینه (اشتراک هر کاربر یا اعتبار مصرفی)</td>
              <td>جدول مقایسه‌ای شفاف</td>
            </tr>
            <tr>
              <td>۳-۲</td>
              <td>نحوه تعیین سهمیه درخواست‌ها، سقف مصرف و مدیریت اتمام سهمیه</td>
              <td>مستندات + مثال عددی</td>
            </tr>
            <tr>
              <td>۳-۳</td>
              <td>هزینه یک درخواست معمول با مدل GPT5.6 Sol و مبنای محاسبه آن</td>
              <td>عدد دقیق + فرمول محاسبه</td>
            </tr>
            <tr>
              <td>۳-۴</td>
              <td>گزارش مصرف و هزینه به تفکیک کاربر، مدل و ایجنت و قابلیت‌های بهینه‌سازی مصرف</td>
              <td>نمایش نمونه گزارش</td>
            </tr>
            <tr>
              <td>۳-۵</td>
              <td>با فرض استفاده انحصاری از GPT5.6 Sol، تعداد توکن ماهانه تخصیصی به کل شرکت در هر پلن</td>
              <td>عدد دقیق به تفکیک پلن</td>
            </tr>
            <tr>
              <td>۳-۶</td>
              <td>در صورت اعتباری‌بودن پلن، ظرفیت معادل مصرف ماهانه با این مدل همراه با فرض و مبنای محاسبه</td>
              <td>سناریوی محاسبه شفاف</td>
            </tr>
            <tr>
              <td>۳-۷</td>
              <td>امکان تهیه API و استفاده از حساب/اعتبار اختصاصی سازمان و اینکه تعرفه آن با اشتراک کاربران مشترک است یا مستقل</td>
              <td>توضیح مکتوب + شرایط</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته کلیدی:</strong> اشاره صریح کارفرما به مدل «GPT5.6 Sol» نشان می‌دهد که انتظار دارند ارائه‌دهنده از جدیدترین مدل‌ها پشتیبانی کند و پاسخ <strong>دقیق و عددی</strong> (نه کلی) بدهد. پاسخ‌های مبهم یا بدون مبنای محاسبه، در ارزیابی رد خواهند شد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۵</div>
        <div class="section-title">
          <h3>محور ۴: رابط کاربری، فایل‌ها و گزارش‌ها</h3>
          <div class="subtitle">UI, Files & Reports</div>
        </div>
      </div>
      <div class="section-content">
        <p>نیازمندی‌های صریح این محور:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام ارائه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۴-۱</td>
              <td>ارائه رابط کاربری اختصاصی سازمان و نسخه دسکتاپ و امکانات هرکدام</td>
              <td>نمایش عملی + مستندات</td>
            </tr>
            <tr>
              <td>۴-۲</td>
              <td>دسترسی مستقیم و کنترل‌شده به فایل‌ها و پوشه‌های محلی یا شبکه سازمان</td>
              <td>آزمون عملی دسترسی</td>
            </tr>
            <tr>
              <td>۴-۳</td>
              <td>تحلیل ارتباط میان چند فایل</td>
              <td>سناریوی عملی</td>
            </tr>
            <tr>
              <td>۴-۴</td>
              <td>خروجی‌های متنی، جدولی و نموداری</td>
              <td>نمونه خروجی</td>
            </tr>
            <tr>
              <td>۴-۵</td>
              <td>قابلیت ویرایش گزارش‌ها، ارجاع به منابع و دریافت در قالب‌های Word و Excel</td>
              <td>نمایش عملی + فایل نمونه</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۶</div>
        <div class="section-title">
          <h3>محور ۵: حاکمیت داده، محرمانگی و معماری استقرار</h3>
          <div class="subtitle">Data Governance, Confidentiality & Deployment Architecture</div>
        </div>
      </div>
      <div class="section-content">
        <p>این محور برای یک شرکت دانش‌بنیان تولیدی (با اطلاعات حساس فرمولاسیون، مشتریان و فرایندها) <strong>بسیار حیاتی</strong> است. نیازمندی‌های صریح:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام ارائه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۵-۱</td>
              <td>محل ذخیره و پردازش اطلاعات سازمان و اینکه چه محتوایی به سرویس‌های ثالث منتقل می‌شود</td>
              <td>مستندات معماری + دیاگرام</td>
            </tr>
            <tr>
              <td>۵-۲</td>
              <td>سیاست استفاده از داده‌ها و مکالمات برای آموزش یا بهبود مدل‌ها</td>
              <td>سیاست مکتوب و شفاف</td>
            </tr>
            <tr>
              <td>۵-۳</td>
              <td>امکان نگهداری داده‌ها و رابط کاربری در زیرساخت شرکت (On-Premise) و استفاده از مدل‌ها/ایجنت‌های خارجی از طریق API</td>
              <td>توضیح معماری + شرایط</td>
            </tr>
            <tr>
              <td>۵-۴</td>
              <td>در این ساختار، مالکیت، مجوزهای دسترسی و مسئولیت هر بخش چگونه تعیین می‌شود</td>
              <td>مستند حقوقی/فنی</td>
            </tr>
          </tbody>
        </table>

        <div class="warning-box">
          <strong>⚠️ حساسیت بالا:</strong> انتظار <strong>استقرار درون‌سازمانی (On-Premise)</strong> و کنترل کامل داده وجود دارد. ارائه‌دهندگانی که فقط راهکار ابری ارائه می‌دهند، باید بتوانند سیاست‌های حاکمیت داده و عدم استفاده از داده برای آموزش مدل را به‌صورت مکتوب و قابل استناد تضمین کنند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۷</div>
        <div class="section-title">
          <h3>محور ۶: پیاده‌سازی، اختصاصی‌سازی، آموزش و پشتیبانی</h3>
          <div class="subtitle">Implementation, Customization, Training & Support</div>
        </div>
      </div>
      <div class="section-content">
        <p>نیازمندی‌های صریح این محور:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام ارائه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۶-۱</td>
              <td>حدود سفارشی‌سازی و امکان توسعه توسط تیم داخلی سازمان</td>
              <td>مستندات + مثال</td>
            </tr>
            <tr>
              <td>۶-۲</td>
              <td>هزینه و زمان تهیه سامانه، استقرار و توسعه اختصاصی و نحوه محاسبه آن</td>
              <td>جدول زمان‌بندی و هزینه</td>
            </tr>
            <tr>
              <td>۶-۳</td>
              <td>برنامه آموزش کاربران و مدیران، مستندات تحویلی و شرایط و هزینه پشتیبانی</td>
              <td>برنامه مدون</td>
            </tr>
            <tr>
              <td>۶-۴</td>
              <td>اینکه تیم سازمان پس از آموزش چه فعالیت‌هایی را می‌تواند مستقل انجام دهد</td>
              <td>فهرست شفاف</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۸</div>
        <div class="section-title">
          <h3>محور ۷: عملکرد، پایداری و ارزیابی عملی</h3>
          <div class="subtitle">Performance, Reliability & Practical Evaluation</div>
        </div>
      </div>
      <div class="section-content">
        <p>نیازمندی‌های صریح این محور:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>ردیف</th>
              <th>نیازمندی</th>
              <th>الزام ارائه</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>۷-۱</td>
              <td>زمان پاسخ‌گویی برای درخواست معمول، تحلیل فایل و اجرای ایجنت</td>
              <td>اعداد دقیق + شرایط اندازه‌گیری</td>
            </tr>
            <tr>
              <td>۷-۲</td>
              <td>تعهد سطح خدمت (SLA)</td>
              <td>سند SLA</td>
            </tr>
            <tr>
              <td>۷-۳</td>
              <td>وضعیت قابلیت‌های سامانه هنگام قطع اینترنت بین‌الملل</td>
              <td>سناریوی تاب‌آوری</td>
            </tr>
            <tr>
              <td>۷-۴</td>
              <td>شرایط ارائه دمو و اجرای پایلوت محدود (زمان، هزینه، پیش‌نیازها)</td>
              <td>پیشنهاد مدون پایلوت</td>
            </tr>
          </tbody>
        </table>

        <div class="info-box">
          <strong>💡 نکته کلیدی:</strong> پرسش صریح درباره <strong>عملکرد هنگام قطع اینترنت بین‌الملل</strong> نشان‌دهنده نیاز به راهکار پایدار داخلی است. ارائه‌دهندگانی که راهکارشان کاملاً وابسته به سرویس‌های ابری خارجی است، باید محدودیت‌ها را شفاف اعلام کنند.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۹</div>
        <div class="section-title">
          <h3>الزامات فرایندی و قالب ارائه</h3>
          <div class="subtitle">Process Requirements & Submission Format</div>
        </div>
      </div>
      <div class="section-content">
        <p>علاوه بر محتوای فنی، کارفرما الزامات فرایندی زیر را نیز مشخص کرده است:</p>

        <table class="styled-table">
          <thead>
            <tr>
              <th>الزام</th>
              <th>توضیح</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>قالب ارائه</td>
              <td>توضیحات مکتوب، پیشنهاد فنی و تجاری، کاتالوگ یا مستندات موجود</td>
            </tr>
            <tr>
              <td>تفکیک قابلیت‌ها</td>
              <td>قابلیت‌های موجود / نیازمند سفارشی‌سازی / در برنامه توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها</td>
            </tr>
            <tr>
              <td>جلسه دمو</td>
              <td>بررسی موردبه‌مورد تمام محورها همراه با توضیحات و مستندات</td>
            </tr>
            <tr>
              <td>آزمون عملی</td>
              <td>امکان اجرای آزمون‌های عملی برای قابلیت‌های اجرایی</td>
            </tr>
            <tr>
              <td>سناریوی Agent</td>
              <td>ارائه یک سناریوی چندمرحله‌ای در محیط آزمایشی</td>
            </tr>
            <tr>
              <td>آزمون دسترسی</td>
              <td>پرسش‌های یکسان با حساب‌های متفاوت + تلاش برای دور زدن مجوزها</td>
            </tr>
            <tr>
              <td>زمان‌بندی</td>
              <td>اعلام زمان پیشنهادی برای جلسه معرفی و دمو</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۰</div>
        <div class="section-title">
          <h3>جمع‌بندی و ویژگی‌های متمایز درخواست</h3>
          <div class="subtitle">Summary & Distinctive Characteristics</div>
        </div>
      </div>
      <div class="section-content">
        <p>این درخواست یک <strong>RFP بالغ، فنی و آزمون‌محور</strong> است که چند ویژگی متمایز دارد:</p>

        <div class="comparison-grid">
          <div class="comparison-card">
            <h4>ویژگی ۱: اثبات عملی، نه ادعا</h4>
            <ul>
              <li><span>رویکرد</span> <span class="value">سناریوی قابل‌آزمون</span></li>
              <li><span>دمو</span> <span class="value">عملی و تعاملی</span></li>
              <li><span>دسترسی</span> <span class="value">آزمون نفوذ</span></li>
            </ul>
          </div>
          <div class="comparison-card">
            <h4>ویژگی ۲: حساسیت به حاکمیت داده</h4>
            <ul>
              <li><span>استقرار</span> <span class="value">درون‌سازمانی</span></li>
              <li><span>داده</span> <span class="value">کنترل کامل</span></li>
              <li><span>آموزش مدل</span> <span class="value">شفافیت سیاست</span></li>
            </ul>
          </div>
        </div>

        <div class="comparison-grid">
          <div class="comparison-card">
            <h4>ویژگی ۳: شفافیت مالی</h4>
            <ul>
              <li><span>قیمت</span> <span class="value">اعداد دقیق</span></li>
              <li><span>مبنا</span> <span class="value">فرمول محاسبه</span></li>
              <li><span>گزارش</span> <span class="value">تفکیک مصرف</span></li>
            </ul>
          </div>
          <div class="comparison-card recommended">
            <span class="card-badge">فرصت ✓</span>
            <h4>ویژگی ۴: رویکرد تدریجی و پایلوت</h4>
            <ul>
              <li><span>شروع</span> <span class="value">کم‌ریسک</span></li>
              <li><span>پایلوت</span> <span class="value">محدود و قابل ارزیابی</span></li>
              <li><span>توسعه</span> <span class="value">تدریجی</span></li>
            </ul>
          </div>
        </div>

        <div class="highlight-box">
          <strong>نتیجه کلیدی:</strong> تیم ارزیابی کارفرما از اصطلاحات دقیق (Agent در برابر Assistant، Human-in-the-loop، سطح دسترسی تا رکورد، فهرست مجاز مدل‌ها) استفاده می‌کند که نشان‌دهنده وجود تیم فنی قوی و آگاه در سمت کارفرماست. بنابراین، پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد.
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <div class="section-number">۱۱</div>
        <div class="section-title">
          <h3>گام‌های بعدی پیشنهادی</h3>
          <div class="subtitle">Recommended Next Steps</div>
        </div>
      </div>
      <div class="section-content">
        <p>با توجه به تحلیل فوق، تهیه پیشنهاد فنی و تجاری نیازمند موارد زیر است:</p>

        <ul class="reference-list">
          <li>
            <strong>پاسخ موردبه‌مورد، مستند و قابل‌آزمون به هر ۷ محور</strong>
            همراه با شواهد و مستندات پشتیبان
          </li>
          <li>
            <strong>جدول تفکیک قابلیت‌ها</strong>
            موجود / سفارشی‌سازی / در توسعه / غیرقابل ارائه — همراه با محدودیت‌ها و هزینه‌ها
          </li>
          <li>
            <strong>سناریوی نمونه Agent</strong>
            برای ارائه و اجرا در جلسه دمو (چندمرحله‌ای، با ابزارها، خطا و مداخله انسانی)
          </li>
          <li>
            <strong>شفافیت کامل قیمت‌گذاری</strong>
            با مبنای محاسبه، اعداد دقیق توکن و هزینه هر درخواست
          </li>
          <li>
            <strong>برنامه پایلوت محدود</strong>
            شامل زمان، هزینه، پیش‌نیازها و معیارهای ارزیابی موفقیت
          </li>
          <li>
            <strong>زمان‌بندی جلسه معرفی و دمو</strong>
            همراه با آمادگی برای آزمون‌های عملی
          </li>
        </ul>

        <div class="info-box">
          <strong>📞 گام بعدی:</strong> پس از تأیید این تحلیل نیازمندی‌ها، مستند پیشنهاد فنی و تجاری (شامل پاسخ به هر ۷ محور، جدول قابلیت‌ها، سناریوی Agent، قیمت‌گذاری شفاف و برنامه پایلوت) تهیه و ارائه خواهد شد.
        </div>
      </div>
    </div>

    <div class="conclusion-box">
      <h3>🎯 جمع‌بندی نهایی</h3>
      <p>درخواست شرکت پارسا پلیمر شریف، یک RFP فنی، دقیق و آزمون‌محور است که بر شفافیت، اثبات عملی و حاکمیت داده تأکید دارد.</p>
      <p>پیشنهاد ارائه‌شده باید در سطحی حرفه‌ای، مستند و قابل دفاع در جلسه دمو باشد و بتواند در آزمون‌های عملی (سناریوی Agent، آزمون نفوذ دسترسی، عملکرد در قطع اینترنت) پاسخگو باشد.</p>
      <div class="highlight">
        <strong>💎 ارزش پیشنهادی مورد انتظار:</strong><br>
        شفافیت کامل + قابلیت اثبات عملی + حاکمیت داده + قیمت‌گذاری دقیق + آمادگی پایلوت
      </div>
    </div>

    <div class="page-info">
      این مستند محرمانه بوده و صرفاً جهت ارائه به کارفرمای محترم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
    </div>

  </div>

  <footer class="document-footer">
    <div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل</div>
    <div class="footer-divider"></div>
    <div>تاریخ تهیه: مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
  </footer>

</div>

</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_9e6b15de-b071-4dfe-bbc6-7ecb47d1dc50.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>بررسی فنی و راهنمای جامع ابزار AirLLM</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 950px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge {
display: flex;
align-items: center;
gap: 12px;
}
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 800;
font-size: 10px;
text-align: center;
line-height: 1.2;
}
.doc-meta {
text-align: left;
font-size: 12px;
opacity: 0.9;
}
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
font-weight: 400;
opacity: 0.9;
}
.document-body {
padding: 40px;
}
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 {
font-size: 19px;
font-weight: 700;
color: var(--primary);
margin-bottom: 2px;
}
.section-title .subtitle {
font-size: 12px;
color: var(--text-muted);
}
.section-content {
padding-right: 10px;
}
.section-content p {
margin-bottom: 12px;
text-align: justify;
text-indent: 20px;
}
.section-content p.no-indent { text-indent: 0; }
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box strong {
color: var(--accent-dark);
}
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--primary-light);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th {
padding: 14px 16px;
text-align: right;
font-weight: 600;
font-size: 13px;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
font-size: 13px;
}
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row {
background: #fffaf0 !important;
font-weight: 600;
}
pre {
background-color: #1a202c;
color: #e2e8f0;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
direction: ltr;
text-align: left;
margin: 15px 0;
font-family: 'Courier New', Courier, monospace;
font-size: 13px;
line-height: 1.6;
border-right: 4px solid var(--accent);
}
code {
font-family: 'Courier New', Courier, monospace;
background-color: #edf2f7;
color: var(--danger);
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
direction: ltr;
display: inline-block;
}
pre code {
background-color: transparent;
color: inherit;
padding: 0;
}
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 {
font-size: 22px;
font-weight: 800;
margin-bottom: 15px;
color: var(--accent);
}
.conclusion-box p {
font-size: 14px;
line-height: 1.8;
text-indent: 0 !important;
margin-bottom: 15px;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand {
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
font-size: 14px;
}
.footer-divider {
width: 60px;
height: 2px;
background: var(--accent);
margin: 10px auto;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
@media print {
body { background: white; padding: 0; }
.document-container { box-shadow: none; border-radius: 0; }
.section { page-break-inside: avoid; }
}
@media (max-width: 768px) {
.document-body { padding: 25px 20px; }
.document-header { padding: 30px 20px; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo">فن آوران<br>ساحر علم</div>
</div>
<div class="doc-meta">
<div>شماره مستند: TECH-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: ۲۸ مهر ۱۴۰۵</div>
<div>طبقه‌بندی: داخلی / فنی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL REVIEW & GUIDE</span>
<h1>بررسی فنی و راهنمای جامع ابزار AirLLM</h1>
<h2>تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود</h2>
</div>
</header>

<div class="document-body">
<div class="intro-text">
<strong>همکاران و ذینفعان محترم،</strong><br>
این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار <strong>AirLLM</strong> را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است.
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی</h3>
<div class="subtitle">Executive Summary</div>
</div>
</div>
<div class="section-content">
<p>ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.</p>
<div class="highlight-box">
<strong>نتیجه کلیدی:</strong> با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>معماری و مکانیزم عملکرد</h3>
<div class="subtitle">Architecture & Mechanism</div>
</div>
</div>
<div class="section-content">
<p>مکانیزم اصلی AirLLM بر پایه تکنیک <strong>«بارگذاری لایه‌ای» (Layer-wise Loading)</strong> استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:</p>
<div class="info-box">
<strong>گام ۱: تجزیه و ذخیره‌سازی اولیه</strong><br>
در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود.
<br><br>
<strong>گام ۲: بارگذاری پویا در GPU</strong><br>
در حین فرآیند استنتاج، تنها <strong>یک لایه</strong> از مدل در هر لحظه روی GPU بارگذاری می‌شود.
<br><br>
<strong>گام ۳: محاسبه و انتقال حالت (State)</strong><br>
پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود.
</div>
<div class="success-box">
<strong>💡 نتیجه معماری:</strong> این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>مدل‌های پشتیبانی‌شده و مصرف حافظه</h3>
<div class="subtitle">Supported Models & VRAM Consumption</div>
</div>
</div>
<div class="section-content">
<p>این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:</p>
<table class="styled-table">
<thead>
<tr>
<th>نام مدل</th>
<th>اندازه تقریبی</th>
<th>حداقل VRAM مورد نیاز</th>
</tr>
</thead>
<tbody>
<tr>
<td>Qwen3 / Mistral / Phi</td>
<td>≈8B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۲ گیگابایت</td>
</tr>
<tr>
<td>Qwen3-30B / Mixtral (MoE)</td>
<td>30–47B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-27B (dense VL)</td>
<td>27B</td>
<td style="color: var(--success); font-weight: 600;">~۳.۳۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-Flash-Next (MoE + PLE)</td>
<td>~180B</td>
<td style="color: var(--success); font-weight: 600;">~۵.۹۵ گیگابایت</td>
</tr>
<tr>
<td>Llama 3.x 70B (full precision)</td>
<td>70B</td>
<td style="color: var(--success); font-weight: 600;">~۴ گیگابایت</td>
</tr>
<tr class="highlight-row">
<td>DeepSeek-V3</td>
<td>671B</td>
<td style="color: var(--accent-dark); font-weight: 700;">~۱۲ گیگابایت</td>
</tr>
</tbody>
</table>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>راهنمای گام‌به‌گام پیاده‌سازی</h3>
<div class="subtitle">Step-by-Step Implementation Guide</div>
</div>
</div>
<div class="section-content">
<p>برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:</p>
<div class="warning-box">
<strong>پیش‌نیاز حیاتی:</strong> اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا.
</div>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۱: نصب کتابخانه</h4>
<pre><code>pip install airllm</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۲: مقداردهی اولیه مدل</h4>
<pre><code>from airllm import AutoModel

# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
model = AutoModel.from_pretrained("Qwen/Qwen3-32B")

# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
# model = AutoModel.from_pretrained("model-name", compression='4bit')
</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۳: آماده‌سازی ورودی و اجرای استنتاج</h4>
<pre><code>MAX_LENGTH = 128
input_text = ['What is the capital of United States?']

input_tokens = model.tokenizer(
    input_text,
    return_tensors="pt",
    return_attention_mask=False,
    truncation=True,
    max_length=MAX_LENGTH,
    padding=False
)

generation_output = model.generate(
    input_tokens['input_ids'].cuda(),
    max_new_tokens=20,
    use_cache=True,
    return_dict_in_generate=True
)

output = model.tokenizer.decode(generation_output.sequences[0])
print(output)
</code></pre>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>جمع‌بندی و توصیه‌های فنی</h3>
<div class="subtitle">Conclusion & Technical Recommendations</div>
</div>
</div>
<div class="section-content">
<p>با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:</p>
<table class="styled-table">
<thead>
<tr>
<th>مزیت</th>
<th>روش سنتی (بارگذاری کامل)</th>
<th>روش AirLLM (لایه‌ای)</th>
</tr>
</thead>
<tbody>
<tr>
<td>مصرف VRAM</td>
<td style="color: var(--danger); font-weight: 600;">بسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)</td>
<td style="color: var(--success); font-weight: 600;">بهینه و متناسب با اندازه لایه</td>
</tr>
<tr>
<td>نیاز به کوانتیزاسیون</td>
<td>الزامی برای کاهش مصرف</td>
<td style="color: var(--success); font-weight: 600;">غیرالزامی (حفظ دقت کامل)</td>
</tr>
<tr>
<td>سرعت استنتاج (با فشرده‌سازی)</td>
<td>پایه</td>
<td style="color: var(--success); font-weight: 600;">تا ۳ برابر سریع‌تر (با 4bit/8bit)</td>
</tr>
<tr class="highlight-row">
<td><strong>ارزش خالص فنی</strong></td>
<td>—</td>
<td style="color: var(--success); font-weight: 700; font-size: 15px;">بسیار بالاتر</td>
</tr>
</tbody>
</table>

<div class="conclusion-box">
<h3>🎯 توصیه نهایی معماری</h3>
<p>با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.</p>
<p>این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face
</div>
</div>
</div>
</div>

<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>

<footer class="document-footer">
<div class="footer-brand">طراحی و تدوین: هادی خزاعی اصل | معمار ارشد و توسعه‌دهنده سامانه‌های نرم‌افزاری</div>
<div class="footer-divider"></div>
<div>شرکت: فن آوران ساحر علم &nbsp;|&nbsp; تاریخ تهیه: ۲۸ مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: داخلی / فنی</div>
</footer>
</div>
</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_b85c4c9b-e4d4-48df-97ff-eb50ee55f39b.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مستندات فنی پیاده‌سازی احراز هویت XApiKey در xIds</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
        :root {
            --primary: #1a365d;
            --primary-light: #2c5282;
            --accent: #c9a961;
            --accent-dark: #a8893f;
            --bg: #faf9f6;
            --card-bg: #ffffff;
            --text: #1a202c;
            --text-muted: #4a5568;
            --border: #e2e8f0;
            --success: #38a169;
            --danger: #e53e3e;
            --warning: #dd6b20;
            --shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
            --code-bg: #f7fafc;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Vazirmatn', Tahoma, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.8;
            font-size: 15px;
            padding: 30px 15px;
        }
        .document-container {
            max-width: 1000px;
            margin: 0 auto;
            background: var(--card-bg);
            box-shadow: var(--shadow);
            border-radius: 12px;
            overflow: hidden;
        }
        .document-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
            color: white;
            padding: 40px;
            position: relative;
            border-bottom: 4px solid var(--accent);
        }
        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .doc-meta {
            text-align: left;
            font-size: 13px;
            opacity: 0.9;
        }
        .doc-meta div { margin-bottom: 4px; }
        .document-title h1 {
            font-size: 26px;
            font-weight: 800;
            margin-bottom: 8px;
        }
        .document-title h2 {
            font-size: 16px;
            font-weight: 400;
            opacity: 0.9;
        }
        .document-body {
            padding: 40px;
        }
        .section {
            margin-bottom: 40px;
            page-break-inside: avoid;
        }
        .section-header {
            display: flex;
            align-items: center;
            gap: 15px;
            padding-bottom: 12px;
            border-bottom: 2px solid var(--border);
            margin-bottom: 20px;
        }
        .section-number {
            width: 40px; height: 40px;
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 800;
            font-size: 18px;
            flex-shrink: 0;
        }
        .section-title h3 {
            font-size: 18px;
            font-weight: 700;
            color: var(--primary);
        }
        .section-content p {
            margin-bottom: 15px;
            text-align: justify;
        }
        .code-block {
            background: var(--code-bg);
            border: 1px solid var(--border);
            border-right: 4px solid var(--accent);
            border-radius: 6px;
            padding: 15px;
            margin: 15px 0;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            overflow-x: auto;
            direction: ltr;
            text-align: left;
        }
        .highlight-box {
            background: #fffaf0;
            border: 1px solid #f6e05e;
            border-right: 4px solid var(--accent);
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
        }
        .success-box {
            background: #f0fff4;
            border: 1px solid #9ae6b4;
            border-right: 4px solid var(--success);
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
        }
        .warning-box {
            background: #fff5f5;
            border: 1px solid #feb2b2;
            border-right: 4px solid var(--danger);
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            padding: 12px;
            border: 1px solid var(--border);
            text-align: right;
        }
        th {
            background: var(--primary);
            color: white;
        }
        tr:nth-child(even) { background: #f8fafc; }
        .document-footer {
            background: var(--primary);
            color: white;
            padding: 20px;
            text-align: center;
            font-size: 12px;
        }
        .footer-brand {
            font-weight: 700;
            color: var(--accent);
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="document-container">
        <header class="document-header">
            <div class="header-top">
                <div class="doc-meta">
                    <div>شماره مستند: TECH-XIDS-APIKEY-001</div>
                    <div>نسخه: ۱.۰</div>
                    <div>تاریخ تهیه: ۲۰ مهر ۱۴۰۵</div>
                    <div>طبقه‌بندی: داخلی - فنی</div>
                </div>
            </div>
            <div class="document-title">
                <h1>راهنمای جامع پیاده‌سازی و عیب‌یابی احراز هویت XApiKey</h1>
                <h2>پروژه xIds (Identity Server) | ماژول مدیریت Application و API Key</h2>
            </div>
        </header>

        <div class="document-body">
            
            <div class="section">
                <div class="section-header">
                    <div class="section-number">۱</div>
                    <div class="section-title">
                        <h3>مقدمه و بررسی وضعیت فعلی</h3>
                    </div>
                </div>
                <div class="section-content">
                    <p>
                        در پروژه <strong>xIds</strong>، زیرساخت کاملی برای مدیریت <code>XApplication</code> و <code>XApiKey</code> پیاده‌سازی شده است. 
                        کلاس‌های <code>XApplicationProvider</code> و <code>XApiKeyHelper</code> وظیفه تولید، هش کردن و اعتبارسنجی کلیدها را بر عهده دارند.
                        با این حال، چالش اصلی در لایه <strong>Authentication Middleware</strong> و نحوه اتصال آن به Policyهای موجود بود.
                    </p>
                    <div class="highlight-box">
                        <strong>مشکل شناسایی شده:</strong> درخواست‌های ارسالی با هدر <code>X-Api-Key</code> توسط ASP.NET Core نادیده گرفته می‌شدند، زیرا Scheme پیش‌فرض روی JWT Bearer تنظیم شده بود و Handler مخصوص ApiKey فراخوانی نمی‌شد.
                    </div>
                </div>
            </div>

            <div class="section">
                <div class="section-header">
                    <div class="section-number">۲</div>
                    <div class="section-title">
                        <h3>راه‌حل فنی: اصلاح زنجیره احراز هویت</h3>
                    </div>
                </div>
                <div class="section-content">
                    <p>برای رفع مشکل، دو تغییر اساسی در فایل <code>xIds/DI/XDIHelperExtension.cs</code> اعمال شد:</p>
                    
                    <h4>الف) ثبت Scheme اختصاصی برای XApiKey</h4>
                    <p>قبل از ثبت JwtBearer، Scheme مربوط به ApiKey ثبت می‌شود تا در لیست Authentication Schemes وجود داشته باشد.</p>
                    
                    <h4>ب) استفاده از ForwardDefaultSelector هوشمند</h4>
                    <p>به جای استفاده ثابت از <code>ForwardDefault</code>، از یک Delegate استفاده می‌کنیم که Header درخواست را بررسی می‌کند.</p>

                    <div class="code-block">
// xIds/DI/XDIHelperExtension.cs

public static void AddXIdentityServerAuthentication(
    this IServiceCollection services,
    IConfiguration configuration,
    bool addApiKeyAuthentication = false)
{
    services.AddXIdentityResourceConfiguration(configuration);
    var authBuilder = services.AddAuthentication();

    // 1. ثبت Scheme برای XApiKey (اولویت اول)
    if (addApiKeyAuthentication)
    {
        authBuilder.AddScheme&lt;AuthenticationSchemeOptions, XApiKeyAuthenticationHandler&gt;(
            XAuthenticationScheme.XApiKey.GetStringValue(), // "XApiKey"
            options => { });
    }

    // 2. ثبت JwtBearer با Selector هوشمند
    authBuilder.AddJwtBearer(options =>
    {
        options.SaveToken = true;
        options.RequireHttpsMetadata = false;
        
        // انتخاب دینامیک Scheme بر اساس هدر درخواست
        options.ForwardDefaultSelector = context =>
        {
            var apiKeyHeader = XHeader.ApiKey.GetStringValue(); // "X-Api-Key"
            if (context.Request.Headers.ContainsKey(apiKeyHeader))
            {
                return XAuthenticationScheme.XApiKey.GetStringValue();
            }
            // در غیر این صورت، از احراز هویت استاندارد IdentityServer استفاده کن
            return XAuthentication.IDENTITY_SERVER_LOCAL_API;
        };
    })
    .AddLocalApi();
}
                    </div>
                </div>
            </div>

            <div class="section">
                <div class="section-header">
                    <div class="section-number">۳</div>
                    <div class="section-title">
                        <h3>اصلاح Claims تولید شده در Handler</h3>
                    </div>
                </div>
                <div class="section-content">
                    <p>
                        در فایل <code>xIds/Providers/XApiKeyAuthenticationHandler.cs</code>، متد <code>HandleAuthenticateAsync</code> باید Claimهای صحیح را تولید کند تا با Policyهای تعریف شده در <code>XAuthorizationHelper</code> همخوانی داشته باشد.
                    </p>
                    <div class="warning-box">
                        <strong>نکته مهم:</strong> Policyهای ApiKey بر اساس Scope (مانند read, write, admin) کار می‌کنند، نه Role. بنابراین Claim از نوع <code>JwtClaimTypes.Scope</code> ضروری است.
                    </div>
                    <div class="code-block">
protected override async Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
{
    // ... استخراج و اعتبارسنجی ApiKey ...
    
    var validationResult = await applicationProvider.ValidateApiKey(apiKey, clientIP);
    
    if (validationResult.Errors.HasChild())
        return AuthenticateResult.Fail(string.Join(", ", validationResult.Errors));

    var claims = new List&lt;Claim&gt;
    {
        new Claim(ClaimTypes.Name, validationResult.OwnerId),
        new Claim(JwtClaimTypes.Subject, validationResult.OwnerId),
        new Claim("application_id", validationResult.ApplicationId.ToString()),
        new Claim("auth_type", "apikey"),
    };

    // افزودن Scopeهای مجاز به Claims
    if (validationResult.Scopes != null)
    {
        foreach (var scope in validationResult.Scopes)
        {
            claims.Add(new Claim(JwtClaimTypes.Scope, scope));
        }
    }

    var identity = new ClaimsIdentity(claims, Scheme.Name);
    var principal = new ClaimsPrincipal(identity);
    var ticket = new AuthenticationTicket(principal, Scheme.Name);

    return AuthenticateResult.Success(ticket);
}
                    </div>
                </div>
            </div>

            <div class="section">
                <div class="section-header">
                    <div class="section-number">۴</div>
                    <div class="section-title">
                        <h3>نحوه استفاده در Controllerها</h3>
                    </div>
                </div>
                <div class="section-content">
                    <p>برای محافظت از Endpointها با ApiKey، از Attributeهای زیر استفاده کنید:</p>
                    <div class="code-block">
[RequireXPowered]
[Authorize(Policy = XPolicies.ApiKeyAccess)] // دسترسی کلی
public async Task&lt;ActionResult&gt; MySecureAction() { ... }

[Authorize(Policy = XPolicies.ApiKeyReadAccess)] // فقط خواندن
public async Task&lt;ActionResult&gt; GetItems() { ... }
                    </div>
                    <div class="success-box">
                        <strong>تست موفقیت‌آمیز:</strong> اکنون با ارسال هدر <code>X-Api-Key: xapp_...</code> به Endpointهای فوق، احراز هویت انجام شده و دسترسی اعطا می‌شود.
                    </div>
                </div>
            </div>

            <div class="section">
                <div class="section-header">
                    <div class="section-number">۵</div>
                    <div class="section-title">
                        <h3>چک‌لیست نهایی استقرار</h3>
                    </div>
                </div>
                <div class="section-content">
                    <table>
                        <thead>
                            <tr>
                                <th>ردیف</th>
                                <th>اقدام</th>
                                <th>وضعیت</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>۱</td>
                                <td>بررسی ثبت <code>AddXIdentityServerAuthentication</code> در Startup با پارامتر <code>true</code></td>
                                <td>✅ انجام شد</td>
                            </tr>
                            <tr>
                                <td>۲</td>
                                <td>اطمینان از وجود Policyهای <code>ApiKeyAccess</code> در <code>XAuthorizationHelper</code></td>
                                <td>✅ موجود است</td>
                            </tr>
                            <tr>
                                <td>۳</td>
                                <td>تست ایجاد ApiKey جدید از طریق <code>/Applications/{id}/ApiKeys/Create</code></td>
                                <td>✅ تست شد</td>
                            </tr>
                            <tr>
                                <td>۴</td>
                                <td>تست دسترسی به <code>/Account/Test/HiApiKeyAccess</code> با کلید معتبر</td>
                                <td>✅ پاس شد</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>

        <footer class="document-footer">
            <div class="footer-brand">تهیه شده توسط: هادی خزاعی اصل | شرکت فن آوران ساحر علم</div>
            <div>تاریخ انتشار: ۲۰ مهر ۱۴۰۵</div>
        </footer>
    </div>
</body>
</html>

### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\wwwroot\Storage\Uploads\Document\xSaherElm_de98d2ce-3d9d-4990-a129-ea2bdd3b5216.html

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>بررسی فنی و راهنمای جامع ابزار AirLLM</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 950px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge {
display: flex;
align-items: center;
gap: 12px;
}
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 800;
font-size: 10px;
text-align: center;
line-height: 1.2;
}
.doc-meta {
text-align: left;
font-size: 12px;
opacity: 0.9;
}
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
font-weight: 400;
opacity: 0.9;
}
.document-body {
padding: 40px;
}
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 {
font-size: 19px;
font-weight: 700;
color: var(--primary);
margin-bottom: 2px;
}
.section-title .subtitle {
font-size: 12px;
color: var(--text-muted);
}
.section-content {
padding-right: 10px;
}
.section-content p {
margin-bottom: 12px;
text-align: justify;
text-indent: 20px;
}
.section-content p.no-indent { text-indent: 0; }
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box strong {
color: var(--accent-dark);
}
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--primary-light);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th {
padding: 14px 16px;
text-align: right;
font-weight: 600;
font-size: 13px;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
font-size: 13px;
}
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row {
background: #fffaf0 !important;
font-weight: 600;
}
pre {
background-color: #1a202c;
color: #e2e8f0;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
direction: ltr;
text-align: left;
margin: 15px 0;
font-family: 'Courier New', Courier, monospace;
font-size: 13px;
line-height: 1.6;
border-right: 4px solid var(--accent);
}
code {
font-family: 'Courier New', Courier, monospace;
background-color: #edf2f7;
color: var(--danger);
padding: 2px 6px;
border-radius: 4px;
font-size: 13px;
direction: ltr;
display: inline-block;
}
pre code {
background-color: transparent;
color: inherit;
padding: 0;
}
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 {
font-size: 22px;
font-weight: 800;
margin-bottom: 15px;
color: var(--accent);
}
.conclusion-box p {
font-size: 14px;
line-height: 1.8;
text-indent: 0 !important;
margin-bottom: 15px;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand {
font-weight: 700;
color: var(--accent);
margin-bottom: 5px;
font-size: 14px;
}
.footer-divider {
width: 60px;
height: 2px;
background: var(--accent);
margin: 10px auto;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
@media print {
body { background: white; padding: 0; }
.document-container { box-shadow: none; border-radius: 0; }
.section { page-break-inside: avoid; }
}
@media (max-width: 768px) {
.document-body { padding: 25px 20px; }
.document-header { padding: 30px 20px; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
}
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge">
<div class="company-logo">فن آوران<br>ساحر علم</div>
</div>
<div class="doc-meta">
<div>شماره مستند: TECH-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: ۲۸ مهر ۱۴۰۵</div>
<div>طبقه‌بندی: داخلی / فنی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL REVIEW & GUIDE</span>
<h1>بررسی فنی و راهنمای جامع ابزار AirLLM</h1>
<h2>تحلیل معماری، قابلیت‌ها و راهنمای پیاده‌سازی مدل‌های زبانی بزرگ روی سخت‌افزار محدود</h2>
</div>
</header>

<div class="document-body">
<div class="intro-text">
<strong>همکاران و ذینفعان محترم،</strong><br>
این مستند به‌عنوان تحلیلی جامع و مبتنی بر بررسی‌های فنی عمیق، ابزار <strong>AirLLM</strong> را از منظر معماری، کارایی و نحوه پیاده‌سازی مورد ارزیابی قرار می‌دهد. هدف از تهیه این سند، ارائه شفافیت کامل فنی و تسهیل تصمیم‌گیری برای به‌کارگیری این راهکار در زیرساخت‌های هوش مصنوعی با منابع محدود است.
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی</h3>
<div class="subtitle">Executive Summary</div>
</div>
</div>
<div class="section-content">
<p>ابزار AirLLM یک کتابخانه پیشرفته در حوزه هوش مصنوعی است که با هدف کاهش چشمگیر مصرف حافظه گرافیکی (VRAM) در هنگام استنتاج (Inference) و آموزش (Training) مدل‌های زبانی بزرگ (LLM) طراحی شده است. این ابزار امکان اجرای مدل‌های عظیم (مانند مدل‌های ۷۰ میلیارد پارامتری و بالاتر) را روی کارت‌های گرافیک با ظرفیت حداقل ۴ گیگابایت فراهم می‌کند، بدون آنکه نیاز به کوانتیزاسیون (Quantization)، تقطیر (Distillation) یا هرس کردن (Pruning) مدل باشد.</p>
<div class="highlight-box">
<strong>نتیجه کلیدی:</strong> با به‌کارگیری AirLLM، محدودیت‌های سخت‌افزاری به حداقل رسیده و امکان استقرار مدل‌های پیشرفته (حتی مدل‌های ۶۷۱ میلیارد پارامتری مانند DeepSeek-V3) روی سخت‌افزارهای سطح متوسط با مصرف حدود ۱۲ گیگابایت VRAM میسر می‌گردد.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>معماری و مکانیزم عملکرد</h3>
<div class="subtitle">Architecture & Mechanism</div>
</div>
</div>
<div class="section-content">
<p>مکانیزم اصلی AirLLM بر پایه تکنیک <strong>«بارگذاری لایه‌ای» (Layer-wise Loading)</strong> استوار است. به جای بارگذاری کل مدل در حافظه گرافیکی، این ابزار فرآیند را به گام‌های زیر تقسیم می‌کند:</p>
<div class="info-box">
<strong>گام ۱: تجزیه و ذخیره‌سازی اولیه</strong><br>
در اولین اجرا، مدل اصلی از مخزن Hugging Face دریافت شده و به صورت لایه‌به‌لایه در حافظه دیسک (Storage) ذخیره می‌شود.
<br><br>
<strong>گام ۲: بارگذاری پویا در GPU</strong><br>
در حین فرآیند استنتاج، تنها <strong>یک لایه</strong> از مدل در هر لحظه روی GPU بارگذاری می‌شود.
<br><br>
<strong>گام ۳: محاسبه و انتقال حالت (State)</strong><br>
پس از انجام محاسبات روی لایه فعلی، نتایج میانی (Activations) به لایه بعدی منتقل شده و لایه قبلی بلافاصله از VRAM تخلیه می‌شود.
</div>
<div class="success-box">
<strong>💡 نتیجه معماری:</strong> این رویکرد باعث می‌شود حافظه VRAM مورد نیاز، به جای وابستگی به اندازه کل مدل، تنها به اندازه بزرگ‌ترین لایه مدل وابسته باشد که انقلابی در مدیریت منابع محسوب می‌شود.
</div>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>مدل‌های پشتیبانی‌شده و مصرف حافظه</h3>
<div class="subtitle">Supported Models & VRAM Consumption</div>
</div>
</div>
<div class="section-content">
<p>این کتابخانه با تقریباً تمام خانواده‌های مدل‌های متن‌باز محبوب سازگاری کامل دارد. جدول زیر نمایی از توانایی AirLLM در مدیریت منابع برای مدل‌های مختلف را نشان می‌دهد:</p>
<table class="styled-table">
<thead>
<tr>
<th>نام مدل</th>
<th>اندازه تقریبی</th>
<th>حداقل VRAM مورد نیاز</th>
</tr>
</thead>
<tbody>
<tr>
<td>Qwen3 / Mistral / Phi</td>
<td>≈8B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۲ گیگابایت</td>
</tr>
<tr>
<td>Qwen3-30B / Mixtral (MoE)</td>
<td>30–47B</td>
<td style="color: var(--success); font-weight: 600;">~۱ تا ۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-27B (dense VL)</td>
<td>27B</td>
<td style="color: var(--success); font-weight: 600;">~۳.۳۳ گیگابایت</td>
</tr>
<tr>
<td>Qwen3.8-Flash-Next (MoE + PLE)</td>
<td>~180B</td>
<td style="color: var(--success); font-weight: 600;">~۵.۹۵ گیگابایت</td>
</tr>
<tr>
<td>Llama 3.x 70B (full precision)</td>
<td>70B</td>
<td style="color: var(--success); font-weight: 600;">~۴ گیگابایت</td>
</tr>
<tr class="highlight-row">
<td>DeepSeek-V3</td>
<td>671B</td>
<td style="color: var(--accent-dark); font-weight: 700;">~۱۲ گیگابایت</td>
</tr>
</tbody>
</table>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>راهنمای گام‌به‌گام پیاده‌سازی</h3>
<div class="subtitle">Step-by-Step Implementation Guide</div>
</div>
</div>
<div class="section-content">
<p>برای استقرار و اجرای این ابزار، مراحل زیر به دقت طراحی و پیاده‌سازی شده‌اند:</p>
<div class="warning-box">
<strong>پیش‌نیاز حیاتی:</strong> اطمینان از وجود فضای دیسک کافی در پوشه کش Hugging Face برای ذخیره‌سازی لایه‌های تجزیه‌شده مدل در اولین اجرا.
</div>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۱: نصب کتابخانه</h4>
<pre><code>pip install airllm</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۲: مقداردهی اولیه مدل</h4>
<pre><code>from airllm import AutoModel

# شناسه مخزن Hugging Face مدل مورد نظر را وارد کنید
model = AutoModel.from_pretrained("Qwen/Qwen3-32B")

# نکته: برای فعال‌سازی فشرده‌سازی و افزایش سرعت تا ۳ برابر (اختیاری):
# model = AutoModel.from_pretrained("model-name", compression='4bit')
</code></pre>

<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۳: آماده‌سازی ورودی و اجرای استنتاج</h4>
<pre><code>MAX_LENGTH = 128
input_text = ['What is the capital of United States?']

input_tokens = model.tokenizer(
    input_text,
    return_tensors="pt",
    return_attention_mask=False,
    truncation=True,
    max_length=MAX_LENGTH,
    padding=False
)

generation_output = model.generate(
    input_tokens['input_ids'].cuda(),
    max_new_tokens=20,
    use_cache=True,
    return_dict_in_generate=True
)

output = model.tokenizer.decode(generation_output.sequences[0])
print(output)
</code></pre>
</div>
</div>

<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>جمع‌بندی و توصیه‌های فنی</h3>
<div class="subtitle">Conclusion & Technical Recommendations</div>
</div>
</div>
<div class="section-content">
<p>با توجه به تحلیل‌های انجام‌شده، به‌کارگیری AirLLM مزایای بی‌نظیری را برای پروژه‌هایی با محدودیت سخت‌افزاری فراهم می‌آورد:</p>
<table class="styled-table">
<thead>
<tr>
<th>مزیت</th>
<th>روش سنتی (بارگذاری کامل)</th>
<th>روش AirLLM (لایه‌ای)</th>
</tr>
</thead>
<tbody>
<tr>
<td>مصرف VRAM</td>
<td style="color: var(--danger); font-weight: 600;">بسیار بالا (غیرقابل اجرا روی GPUهای ضعیف)</td>
<td style="color: var(--success); font-weight: 600;">بهینه و متناسب با اندازه لایه</td>
</tr>
<tr>
<td>نیاز به کوانتیزاسیون</td>
<td>الزامی برای کاهش مصرف</td>
<td style="color: var(--success); font-weight: 600;">غیرالزامی (حفظ دقت کامل)</td>
</tr>
<tr>
<td>سرعت استنتاج (با فشرده‌سازی)</td>
<td>پایه</td>
<td style="color: var(--success); font-weight: 600;">تا ۳ برابر سریع‌تر (با 4bit/8bit)</td>
</tr>
<tr class="highlight-row">
<td><strong>ارزش خالص فنی</strong></td>
<td>—</td>
<td style="color: var(--success); font-weight: 700; font-size: 15px;">بسیار بالاتر</td>
</tr>
</tbody>
</table>

<div class="conclusion-box">
<h3>🎯 توصیه نهایی معماری</h3>
<p>با توجه به بررسی‌های جامع فنی، استفاده از AirLLM بهترین انتخاب برای استقرار مدل‌های زبانی بزرگ در محیط‌هایی با محدودیت VRAM است.</p>
<p>این راهکار نه تنها هزینه‌های زیرساختی را به شکل قابل‌توجهی کاهش می‌دهد، بلکه بدون قربانی کردن دقت مدل (در حالت بدون فشرده‌سازی)، عملکردی پایدار و قابل اتکا ارائه می‌کند.</p>
<div class="highlight">
<strong>💎 ارزش پیشنهادی:</strong><br>
حذف محدودیت سخت‌افزاری + حفظ دقت مدل + امکان فشرده‌سازی اختیاری برای افزایش سرعت + سازگاری گسترده با اکوسیستم Hugging Face
</div>
</div>
</div>
</div>

<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>

<footer class="document-footer">
<div class="footer-brand">طراحی و تدوین: هادی خزاعی اصل | معمار ارشد و توسعه‌دهنده سامانه‌های نرم‌افزاری</div>
<div class="footer-divider"></div>
<div>شرکت: فن آوران ساحر علم &nbsp;|&nbsp; تاریخ تهیه: ۲۸ مهر ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: داخلی / فنی</div>
</footer>
</div>
</body>
</html>
