using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Moli.Desktop.Diagnostics; using Moli.Desktop.Host; namespace Moli.Desktop.Llm; public sealed class LlmModelRegistry : ILlmModelRegistry { public const string FileName = "llm-models.json"; private readonly DesktopPaths _paths; private readonly IDiagnosticsService _diagnostics; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, WriteIndented = true, Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; public LlmModelRegistry(DesktopPaths paths, IDiagnosticsService diagnostics) { _paths = paths; _diagnostics = diagnostics; } public async Task LoadAsync(CancellationToken cancellationToken = default) { Directory.CreateDirectory(_paths.ConfigDirectory); var path = Path.Combine(_paths.ConfigDirectory, FileName); if (!File.Exists(path)) { var created = CreateDefault(); await SaveAsync(created, cancellationToken).ConfigureAwait(false); return created; } try { await using var stream = File.OpenRead(path); var document = await JsonSerializer.DeserializeAsync(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (document is null || document.SchemaVersion <= 0) { throw new JsonException("LLM settings document is empty or missing schemaVersion."); } return Normalize(document); } catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) { BackupInvalidFile(path); var recovered = CreateDefault(); await SaveAsync(recovered, cancellationToken).ConfigureAwait(false); _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.ConfigurationRecovered, "Recovered llm-models.json from invalid configuration.", new Dictionary { ["exception"] = ex.GetType().Name }); return recovered; } } public async Task GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(modelId)) { return null; } var document = await LoadAsync(cancellationToken).ConfigureAwait(false); return document.Models.FirstOrDefault(model => model.Enabled && string.Equals(model.Id, modelId, StringComparison.OrdinalIgnoreCase)); } private async Task SaveAsync(LlmSettingsDocument document, CancellationToken cancellationToken) { Directory.CreateDirectory(_paths.ConfigDirectory); var path = Path.Combine(_paths.ConfigDirectory, FileName); var tempPath = path + ".tmp"; var backupPath = path + ".bak"; await using (var stream = File.Create(tempPath)) { await JsonSerializer.SerializeAsync(stream, document, _jsonOptions, cancellationToken).ConfigureAwait(false); } if (File.Exists(path)) { File.Copy(path, backupPath, overwrite: true); } File.Move(tempPath, path, overwrite: true); } private LlmSettingsDocument Normalize(LlmSettingsDocument document) { var seen = new HashSet(StringComparer.OrdinalIgnoreCase); var normalized = new List(); foreach (var model in document.Models) { if (!IsValidModel(model, seen)) { continue; } seen.Add(model.Id); normalized.Add(model); } var defaultModel = normalized.Any(model => model.Enabled && string.Equals(model.Id, document.DefaultModel, StringComparison.OrdinalIgnoreCase)) ? document.DefaultModel : normalized.FirstOrDefault(model => model.Enabled)?.Id; return document with { DefaultModel = defaultModel, Models = normalized }; } private bool IsValidModel(LlmModelConfig model, HashSet seen) { if (string.IsNullOrWhiteSpace(model.Id) || seen.Contains(model.Id)) { RecordInvalid(model.Id, "Model id is empty or duplicated."); return false; } if (string.IsNullOrWhiteSpace(model.Label) || model.Label.Length > 40) { RecordInvalid(model.Id, "Model label is empty or too long."); return false; } if (string.IsNullOrWhiteSpace(model.Provider)) { RecordInvalid(model.Id, "Model provider is required."); return false; } if (!Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")) { RecordInvalid(model.Id, "Model endpoint must be an absolute HTTP or HTTPS URL."); return false; } if (string.IsNullOrWhiteSpace(model.ApiModel)) { RecordInvalid(model.Id, "apiModel is required."); return false; } return true; } private void RecordInvalid(string? modelId, string message) { _diagnostics.Record( DiagnosticSeverity.Warning, "LlmModelInvalid", message, new Dictionary { ["modelId"] = modelId ?? "" }); } private static LlmSettingsDocument CreateDefault() => new() { DefaultModel = null, Models = [ new LlmModelConfig { Id = "local-openai-compatible", Label = "Local", Provider = "openai-compatible", Endpoint = "http://127.0.0.1:11434/v1/chat/completions", AuthRef = null, ApiModel = "qwen2.5:14b", SupportsStreaming = true, Enabled = false } ] }; private static void BackupInvalidFile(string path) { if (!File.Exists(path)) { return; } var timestamp = DateTimeOffset.Now.ToString("yyyyMMddHHmmss"); var invalidPath = Path.Combine( Path.GetDirectoryName(path)!, $"{Path.GetFileNameWithoutExtension(path)}.invalid.{timestamp}{Path.GetExtension(path)}"); File.Move(path, invalidPath, overwrite: true); } }