基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-14 b84db8983d63a9a981083ebce1a139860c6bdf25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
using System.Collections.Concurrent;
using System.Net.Http;
using System.Runtime.CompilerServices;
using Moli.Desktop.Diagnostics;
 
namespace Moli.Desktop.Llm;
 
public sealed class LlmGatewayService : ILlmGatewayService
{
    private static readonly HashSet<string> AllowedRoles = new(StringComparer.OrdinalIgnoreCase)
    {
        "system",
        "user",
        "assistant"
    };
 
    private readonly ILlmModelRegistry _registry;
    private readonly ICredentialStore _credentialStore;
    private readonly ILlmProviderAdapterFactory _adapterFactory;
    private readonly IDiagnosticsService _diagnostics;
    private readonly IAiChatClient? _aiChatClient;
    private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase);
    private readonly ConcurrentDictionary<string, string> _requestPlugins = new(StringComparer.OrdinalIgnoreCase);
 
    public LlmGatewayService(
        ILlmModelRegistry registry,
        ICredentialStore credentialStore,
        ILlmProviderAdapterFactory adapterFactory,
        IDiagnosticsService diagnostics,
        IAiChatClient? aiChatClient = null)
    {
        _registry = registry;
        _credentialStore = credentialStore;
        _adapterFactory = adapterFactory;
        _diagnostics = diagnostics;
        _aiChatClient = aiChatClient;
    }
 
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
    {
        var document = await _registry.LoadAsync(cancellationToken).ConfigureAwait(false);
        return document.Models
            .Where(model => model.Enabled)
            .Select(model => new LlmModelSummary
            {
                Id = model.Id,
                Label = model.Label,
                Provider = model.Provider,
                SupportsStreaming = model.SupportsStreaming,
                Enabled = model.Enabled
            })
            .ToList();
    }
 
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        if (runtimeConfig.IsAiChatMode)
        {
            if (!runtimeConfig.HasAiChatAccount || _aiChatClient is null)
            {
                return [];
            }
 
            var aiChatModels = await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
            return aiChatModels
                .Select(model => model with { Label = FormatAiChatLabel(model) })
                .ToList();
        }
 
        var customModels = runtimeConfig.Models
            .Where(IsUsableRuntimeModel)
            .Select(model => ToCustomSummary(model, runtimeConfig.DefaultModel))
            .ToList();
        var providerModels = await GetProviderModelSummariesAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
        if (customModels.Count > 0 || providerModels.Count > 0)
        {
            return [.. customModels, .. providerModels];
        }
 
        return await GetModelsAsync(cancellationToken).ConfigureAwait(false);
    }
 
    public async Task<AiChatProjectsResult> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        if (!runtimeConfig.HasAiChatAccount)
        {
            return new AiChatProjectsResult
            {
                Status = AiChatProjectStatuses.NotConfigured,
                Projects = []
            };
        }
 
        if (_aiChatClient is null)
        {
            return new AiChatProjectsResult
            {
                Status = AiChatProjectStatuses.NotConnected,
                Message = "AiChat client is not available.",
                Projects = []
            };
        }
 
        try
        {
            var projects = await _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
            return new AiChatProjectsResult
            {
                Status = AiChatProjectStatuses.Ready,
                Projects = projects
            };
        }
        catch (Exception ex) when (ex is AiChatClientException or HttpRequestException)
        {
            return new AiChatProjectsResult
            {
                Status = AiChatProjectStatuses.NotConnected,
                Message = ex.Message,
                Projects = []
            };
        }
    }
 
    public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
        => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
            ? Task.FromResult(new AiChatMemoryCapabilities())
            : _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken);
 
    public Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default)
        => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken);
 
    public Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default)
        => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken);
 
    public Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default)
        => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
            ? Task.CompletedTask
            : _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken);
 
    public Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default)
        => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken);
 
    public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        if (!IsValidRequest(request, out var validationError))
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.RequestInvalid,
                Message = validationError
            };
            yield break;
        }
 
        if (string.Equals(request.Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase))
        {
            if (_aiChatClient is null)
            {
                yield return new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.AiChatApiFailed,
                    Message = "AiChat client is not available."
                };
                yield break;
            }
 
            await foreach (var streamEvent in _aiChatClient.StreamChatAsync(request, request.RuntimeConfig, cancellationToken).ConfigureAwait(false))
            {
                yield return streamEvent;
            }
 
            yield break;
        }
 
        var model = await ResolveDirectModelAsync(request, cancellationToken).ConfigureAwait(false);
        if (model is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.ModelNotFound,
                Message = "Selected LLM model is unavailable."
            };
            yield break;
        }
 
        var adapter = _adapterFactory.Get(model.Provider);
        if (adapter is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.ProviderUnsupported,
                Message = "Selected LLM provider is unsupported."
            };
            yield break;
        }
 
        var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        var timeoutMs = request.Options.TimeoutMs ?? model.RequestDefaults.TimeoutMs;
        linkedCts.CancelAfter(TimeSpan.FromMilliseconds(timeoutMs));
        _activeRequests[request.RequestId] = linkedCts;
        _requestPlugins[request.RequestId] = request.PluginId;
 
        var secret = await _credentialStore.ResolveSecretAsync(model.AuthRef, linkedCts.Token).ConfigureAwait(false);
        if (!string.IsNullOrWhiteSpace(model.AuthRef) && string.IsNullOrWhiteSpace(secret))
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.CredentialMissing,
                Message = "LLM credential is missing. Check the model authRef configuration."
            };
            yield break;
        }
 
        var providerRequest = new LlmProviderRequest
        {
            RequestId = request.RequestId,
            Model = model,
            Messages = request.Messages,
            Options = request.Options,
            ApiKey = secret
        };
 
        await using var enumerator = adapter.StreamAsync(providerRequest, linkedCts.Token).GetAsyncEnumerator(linkedCts.Token);
        while (true)
        {
            LlmStreamEvent? nextEvent = null;
            try
            {
                if (!await enumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    _requestPlugins.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                    yield break;
                }
 
                var chunk = enumerator.Current;
                if (!string.IsNullOrEmpty(chunk.Delta))
                {
                    nextEvent = new LlmDeltaEvent { RequestId = request.RequestId, Delta = chunk.Delta };
                }
                if (chunk.IsCompleted)
                {
                    nextEvent = new LlmCompletedEvent { RequestId = request.RequestId, Usage = chunk.Usage };
                }
            }
            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
            {
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.Timeout,
                    Message = "LLM request timed out."
                };
            }
            catch (HttpRequestException ex)
            {
                RecordFailure(request, model, LlmErrorCodes.EndpointUnavailable, ex.GetType().Name);
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.EndpointUnavailable,
                    Message = "LLM endpoint is unavailable."
                };
            }
            catch (LlmProviderException ex)
            {
                RecordFailure(request, model, ex.Code, ex.GetType().Name);
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = ex.Code,
                    Message = ex.Message
                };
            }
            finally
            {
                if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    _requestPlugins.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                }
            }
 
            if (nextEvent is null)
            {
                continue;
            }
 
            yield return nextEvent;
            if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
            {
                yield break;
            }
        }
    }
 
    public Task CancelAsync(string requestId, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        if (_activeRequests.TryRemove(requestId, out var cts))
        {
            _requestPlugins.TryRemove(requestId, out _);
            cts.Cancel();
            cts.Dispose();
        }
 
        return Task.CompletedTask;
    }
 
    public Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var matchingIds = _requestPlugins
            .Where(kvp => string.Equals(kvp.Value, pluginId, StringComparison.OrdinalIgnoreCase))
            .Select(kvp => kvp.Key)
            .ToList();
 
        foreach (var requestId in matchingIds)
        {
            if (_activeRequests.TryRemove(requestId, out var cts))
            {
                _requestPlugins.TryRemove(requestId, out _);
                cts.Cancel();
                cts.Dispose();
            }
        }
 
        return Task.CompletedTask;
    }
 
    private static bool IsValidRequest(LlmChatRequest request, out string error)
    {
        if (string.IsNullOrWhiteSpace(request.RequestId) ||
            string.IsNullOrWhiteSpace(request.PluginId) ||
            string.IsNullOrWhiteSpace(request.InstanceId) ||
            string.IsNullOrWhiteSpace(request.ModelId))
        {
            error = "requestId, pluginId, instanceId and modelId are required.";
            return false;
        }
 
        if (request.Messages.Count == 0 || request.Messages.Any(message =>
                string.IsNullOrWhiteSpace(message.Content) ||
                !AllowedRoles.Contains(message.Role)))
        {
            error = "At least one valid message is required.";
            return false;
        }
 
        error = "";
        return true;
    }
 
    private static bool IsUsableRuntimeModel(LlmModelConfig model)
        => model.Enabled &&
           !string.IsNullOrWhiteSpace(model.Id) &&
           !string.IsNullOrWhiteSpace(model.Label) &&
           !string.IsNullOrWhiteSpace(model.Provider) &&
           !string.IsNullOrWhiteSpace(model.ApiModel) &&
           LlmOpenAiUrls.IsAbsoluteHttpUrl(model.GetBaseUrl());
 
    private async Task<LlmModelConfig?> ResolveDirectModelAsync(LlmChatRequest request, CancellationToken cancellationToken)
    {
        var custom = request.RuntimeConfig.Models.FirstOrDefault(model =>
            IsUsableRuntimeModel(model) &&
            string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase));
        if (custom is not null)
        {
            return custom;
        }
 
        if (LlmProviderModelIds.TryParse(request.ModelId, out var providerId, out var apiModel))
        {
            var provider = request.RuntimeConfig.Providers.FirstOrDefault(item =>
                IsUsableProvider(item) &&
                string.Equals(item.Id, providerId, StringComparison.OrdinalIgnoreCase));
            if (provider is not null)
            {
                return CreateProviderModel(provider, apiModel);
            }
        }
 
        return await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false);
    }
 
    private async Task<IReadOnlyList<LlmModelSummary>> GetProviderModelSummariesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken)
    {
        var providers = runtimeConfig.Providers.Where(IsUsableProvider).ToList();
        if (providers.Count == 0)
        {
            return [];
        }
 
        var tasks = providers.Select(provider => LoadProviderModelsAsync(provider, runtimeConfig.DefaultModel, cancellationToken)).ToList();
        var batches = await Task.WhenAll(tasks).ConfigureAwait(false);
        return batches.SelectMany(item => item).ToList();
    }
 
    private async Task<IReadOnlyList<LlmModelSummary>> LoadProviderModelsAsync(
        LlmProviderConfig provider,
        string? defaultModel,
        CancellationToken cancellationToken)
    {
        try
        {
            var adapter = _adapterFactory.Get(ResolveProtocol(provider));
            if (adapter is null)
            {
                return [];
            }
 
            var apiKey = await _credentialStore.ResolveSecretAsync(provider.AuthRef, cancellationToken).ConfigureAwait(false);
            using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            timeout.CancelAfter(TimeSpan.FromSeconds(10));
            var ids = await adapter.ListModelIdsAsync(provider.BaseUrl, apiKey, timeout.Token).ConfigureAwait(false);
            return ids
                .Where(id => !string.IsNullOrWhiteSpace(id))
                .Select(apiModel => ToProviderSummary(provider, apiModel, defaultModel))
                .ToList();
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex)
        {
            RecordProviderCatalogFailure(provider, ex);
            return [];
        }
    }
 
    private static LlmModelSummary ToCustomSummary(LlmModelConfig model, string? defaultModel)
        => new()
        {
            Id = model.Id,
            Label = WithDefaultMark($"{model.Label}(Custom)", model.Id, defaultModel),
            Provider = model.Provider,
            SupportsStreaming = model.SupportsStreaming,
            Enabled = model.Enabled
        };
 
    private static LlmModelSummary ToProviderSummary(LlmProviderConfig provider, string apiModel, string? defaultModel)
    {
        var id = LlmProviderModelIds.Create(provider.Id, apiModel);
        return new LlmModelSummary
        {
            Id = id,
            Label = WithDefaultMark($"{apiModel}({provider.Label})", id, defaultModel),
            Provider = ResolveProtocol(provider),
            SupportsStreaming = true,
            Enabled = true
        };
    }
 
    private static string FormatAiChatLabel(LlmModelSummary model)
    {
        var isDefault = model.Label.EndsWith(" *", StringComparison.Ordinal);
        return isDefault ? $"{model.Id}(AiChat) *" : $"{model.Id}(AiChat)";
    }
 
    private static string WithDefaultMark(string label, string id, string? defaultModel)
        => string.Equals(id, defaultModel, StringComparison.OrdinalIgnoreCase)
            ? $"{label} *"
            : label;
 
    private static bool IsUsableProvider(LlmProviderConfig provider)
        => provider.Enabled &&
           !string.IsNullOrWhiteSpace(provider.Id) &&
           !string.IsNullOrWhiteSpace(provider.Label) &&
           LlmOpenAiUrls.IsAbsoluteHttpUrl(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null));
 
    private static string ResolveProtocol(LlmProviderConfig provider)
        => string.IsNullOrWhiteSpace(provider.Protocol) ? "openai-compatible" : provider.Protocol;
 
    private static LlmModelConfig CreateProviderModel(LlmProviderConfig provider, string apiModel)
        => new()
        {
            Id = LlmProviderModelIds.Create(provider.Id, apiModel),
            Label = $"{apiModel}({provider.Label})",
            Provider = ResolveProtocol(provider),
            BaseUrl = LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null),
            AuthRef = provider.AuthRef,
            ApiModel = apiModel,
            SupportsStreaming = true,
            Enabled = true
        };
 
    private void RecordFailure(LlmChatRequest request, LlmModelConfig model, string code, string exception)
    {
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            code,
            "LLM request failed.",
            new Dictionary<string, string>
            {
                ["requestId"] = request.RequestId,
                ["modelId"] = request.ModelId,
                ["provider"] = model.Provider,
                ["endpointHost"] = LlmOpenAiUrls.Host(model.GetBaseUrl()),
                ["exception"] = exception
            });
    }
 
    private void RecordProviderCatalogFailure(LlmProviderConfig provider, Exception exception)
    {
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            LlmErrorCodes.EndpointUnavailable,
            "LLM provider model catalog could not be loaded.",
            new Dictionary<string, string>
            {
                ["providerId"] = provider.Id,
                ["endpointHost"] = LlmOpenAiUrls.Host(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null)),
                ["exception"] = exception.GetType().Name
            });
    }
}