基于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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.IO;
using Moli.Desktop.Diagnostics;
 
namespace Moli.Desktop.Llm;
 
public sealed class AiChatClient : IAiChatClient
{
    private readonly HttpClient _httpClient;
    private readonly IDiagnosticsService _diagnostics;
    private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
    private readonly ConcurrentDictionary<string, string> _sessionTokens = new(StringComparer.OrdinalIgnoreCase);
 
    public AiChatClient(HttpClient httpClient, IDiagnosticsService diagnostics)
    {
        _httpClient = httpClient;
        _diagnostics = diagnostics;
    }
 
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/chat/models", null, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data) ||
            !data.TryGetProperty("models", out var modelsElement) ||
            modelsElement.ValueKind != JsonValueKind.Array)
        {
            return [];
        }
 
        var defaultModel = data.TryGetProperty("defaultModel", out var defaultModelElement)
            ? defaultModelElement.GetString()
            : null;
 
        return modelsElement
            .EnumerateArray()
            .Where(item => item.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(item.GetString()))
            .Select(item =>
            {
                var id = item.GetString()!;
                return new LlmModelSummary
                {
                    Id = id,
                    Label = id == defaultModel ? $"{id} *" : id,
                    Provider = "aichat",
                    SupportsStreaming = true,
                    Enabled = true
                };
            })
            .ToList();
    }
 
    public async Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        try
        {
            using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/projects", null, cancellationToken).ConfigureAwait(false);
            if (!TryGetProjectsData(document.RootElement, out var data))
            {
                _diagnostics.Record(
                    DiagnosticSeverity.Warning,
                    LlmErrorCodes.AiChatProjectLoadFailed,
                    "AiChat project response did not contain a project array.",
                    new Dictionary<string, string> { ["baseUrl"] = runtimeConfig.AiChat.BaseUrl });
                return [];
            }
 
            return data.EnumerateArray()
                .Select(ParseProject)
                .Where(project => project is not null)
                .Select(project => project!)
                .ToList();
        }
        catch (AiChatClientException ex)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                ex.Code,
                "AiChat projects could not be loaded.",
                new Dictionary<string, string>
                {
                    ["baseUrl"] = runtimeConfig.AiChat.BaseUrl,
                    ["exception"] = ex.GetType().Name
                });
            throw;
        }
    }
 
    public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        LlmPluginRuntimeConfig runtimeConfig,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        JsonDocument? sendDocument = null;
        LlmErrorEvent? startError = null;
        try
        {
            var message = request.Messages.LastOrDefault(message => string.Equals(message.Role, "user", StringComparison.OrdinalIgnoreCase))?.Content
                ?? request.Messages.Last().Content;
            var payload = new
            {
                projectId = request.ProjectId,
                modelName = request.ModelId,
                message
            };
            sendDocument = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/chat/send", payload, cancellationToken).ConfigureAwait(false);
        }
        catch (AiChatClientException ex)
        {
            startError = new LlmErrorEvent { RequestId = request.RequestId, Code = ex.Code, Message = ex.Message };
        }
 
        if (startError is not null)
        {
            yield return startError;
            yield break;
        }
 
        var generationDocument = sendDocument;
        if (generationDocument is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.AiChatApiFailed,
                Message = "AiChat did not return a valid generation stream."
            };
            yield break;
        }
 
        using (generationDocument)
        {
            if (!TryGetData(generationDocument.RootElement, out var data) ||
                !data.TryGetProperty("generationId", out var generationIdElement) ||
                !data.TryGetProperty("streamToken", out var streamTokenElement) ||
                string.IsNullOrWhiteSpace(generationIdElement.GetString()) ||
                string.IsNullOrWhiteSpace(streamTokenElement.GetString()))
            {
                yield return new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.AiChatApiFailed,
                    Message = "AiChat did not return a valid generation stream."
                };
                yield break;
            }
 
            var path = $"/api/chat/generations/{Uri.EscapeDataString(generationIdElement.GetString()!)}/stream?token={Uri.EscapeDataString(streamTokenElement.GetString()!)}";
            await foreach (var streamEvent in StreamAiChatEventsAsync(runtimeConfig, request.RequestId, path, cancellationToken).ConfigureAwait(false))
            {
                yield return streamEvent;
            }
        }
    }
 
    public async Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/auth/me", null, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data))
        {
            return new AiChatMemoryCapabilities();
        }
 
        return new AiChatMemoryCapabilities
        {
            CanUseMemory = ReadBool(data, "canUseMemory"),
            CanViewMemory = ReadBool(data, "canViewMemory"),
            CanManageMemory = ReadBool(data, "canManageMemory")
        };
    }
 
    public async Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default)
    {
        var query = new List<string>();
        if (!string.IsNullOrWhiteSpace(request.Scope))
        {
            query.Add($"scope={Uri.EscapeDataString(request.Scope)}");
        }
 
        if (!string.IsNullOrWhiteSpace(request.ProjectId))
        {
            query.Add($"projectId={Uri.EscapeDataString(request.ProjectId)}");
        }
 
        var path = "/api/memories" + (query.Count > 0 ? "?" + string.Join("&", query) : "");
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
 
    public async Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories", request, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
 
    public async Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(memoryId))
        {
            throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "memoryId is required.");
        }
 
        using var _ = await SendJsonAsync(runtimeConfig, HttpMethod.Delete, $"/api/memories/{Uri.EscapeDataString(memoryId)}", null, cancellationToken).ConfigureAwait(false);
    }
 
    public async Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories/recall", request, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
 
    private async IAsyncEnumerable<LlmStreamEvent> StreamAiChatEventsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string requestId,
        string path,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        using var request = await CreateRequestAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        if (!response.IsSuccessStatusCode)
        {
            yield return new LlmErrorEvent
            {
                RequestId = requestId,
                Code = MapStatusCode(response.StatusCode),
                Message = $"AiChat stream returned {(int)response.StatusCode}."
            };
            yield break;
        }
 
        await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
        using var reader = new StreamReader(stream, Encoding.UTF8);
        var eventName = "message";
        var dataLines = new List<string>();
 
        while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (line.StartsWith(":", StringComparison.Ordinal))
            {
                continue;
            }
 
            if (line.Length == 0)
            {
                foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines)))
                {
                    yield return streamEvent;
                    if (streamEvent is LlmCompletedEvent or LlmErrorEvent)
                    {
                        yield break;
                    }
                }
 
                eventName = "message";
                dataLines.Clear();
                continue;
            }
 
            if (line.StartsWith("event:", StringComparison.OrdinalIgnoreCase))
            {
                eventName = line["event:".Length..].Trim();
                continue;
            }
 
            if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                dataLines.Add(line["data:".Length..].TrimStart());
            }
        }
 
        if (dataLines.Count > 0)
        {
            foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines)))
            {
                yield return streamEvent;
                if (streamEvent is LlmCompletedEvent or LlmErrorEvent)
                {
                    yield break;
                }
            }
        }
 
        yield return new LlmErrorEvent
        {
            RequestId = requestId,
            Code = LlmErrorCodes.AiChatSseInterrupted,
            Message = "AiChat stream ended before completion."
        };
    }
 
    private IEnumerable<LlmStreamEvent> ParseSseEvent(string requestId, string eventName, string data)
    {
        if (string.IsNullOrWhiteSpace(data))
        {
            yield break;
        }
 
        JsonDocument document;
        try
        {
            document = JsonDocument.Parse(data);
        }
        catch (JsonException ex)
        {
            throw new AiChatClientException(LlmErrorCodes.StreamParseFailed, "Failed to parse AiChat stream chunk.", ex);
        }
 
        using (document)
        {
            var root = document.RootElement;
            if (eventName.Equals("chunk", StringComparison.OrdinalIgnoreCase) &&
                root.TryGetProperty("delta", out var delta) &&
                delta.ValueKind == JsonValueKind.String)
            {
                yield return new LlmDeltaEvent { RequestId = requestId, Delta = delta.GetString() ?? "" };
                yield break;
            }
 
            if (eventName.Equals("snapshot", StringComparison.OrdinalIgnoreCase) &&
                root.TryGetProperty("content", out var content) &&
                content.ValueKind == JsonValueKind.String &&
                !string.IsNullOrEmpty(content.GetString()))
            {
                yield return new LlmDeltaEvent { RequestId = requestId, Delta = content.GetString() ?? "" };
                yield break;
            }
 
            if (eventName.Equals("done", StringComparison.OrdinalIgnoreCase))
            {
                yield return new LlmCompletedEvent { RequestId = requestId };
                yield break;
            }
 
            if (eventName.Equals("failed", StringComparison.OrdinalIgnoreCase) ||
                eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase))
            {
                var message = root.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String
                    ? error.GetString() ?? "AiChat request failed."
                    : eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase) ? "AiChat request was aborted." : "AiChat request failed.";
                yield return new LlmErrorEvent { RequestId = requestId, Code = LlmErrorCodes.AiChatApiFailed, Message = message };
            }
        }
    }
 
    private async Task<JsonDocument> SendJsonAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        HttpMethod method,
        string path,
        object? payload,
        CancellationToken cancellationToken)
    {
        using var request = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false);
        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            ClearSession(runtimeConfig);
            using var retry = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false);
            using var retryResponse = await _httpClient.SendAsync(retry, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
            return await ReadJsonResponseAsync(retryResponse, cancellationToken).ConfigureAwait(false);
        }
 
        return await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false);
    }
 
    private async Task<HttpRequestMessage> CreateRequestAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        HttpMethod method,
        string path,
        object? payload,
        CancellationToken cancellationToken)
    {
        var uri = BuildUri(runtimeConfig, path);
        var request = new HttpRequestMessage(method, uri);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
        if (!path.Equals("/api/auth/login", StringComparison.OrdinalIgnoreCase))
        {
            var sessionToken = await EnsureSessionAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
            request.Headers.Add("x-session-token", sessionToken);
        }
 
        if (payload is not null)
        {
            request.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json");
        }
 
        return request;
    }
 
    private async Task<string> EnsureSessionAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken)
    {
        var key = SessionKey(runtimeConfig);
        if (_sessionTokens.TryGetValue(key, out var existing) && !string.IsNullOrWhiteSpace(existing))
        {
            return existing;
        }
 
        var email = runtimeConfig.AiChat.Account.Email;
        var password = ResolvePassword(runtimeConfig);
        if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
        {
            throw new AiChatClientException(LlmErrorCodes.AiChatCredentialMissing, "AiChat account or password is missing.");
        }
 
        using var request = new HttpRequestMessage(HttpMethod.Post, BuildUri(runtimeConfig, "/api/auth/login"))
        {
            Content = new StringContent(
                JsonSerializer.Serialize(new { email, password }, _jsonOptions),
                Encoding.UTF8,
                "application/json")
        };
        using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
        using var document = await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data) ||
            !data.TryGetProperty("sessionToken", out var token) ||
            token.ValueKind != JsonValueKind.String ||
            string.IsNullOrWhiteSpace(token.GetString()))
        {
            throw new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "AiChat login did not return a session token.");
        }
 
        _sessionTokens[key] = token.GetString()!;
        return token.GetString()!;
    }
 
    private async Task<JsonDocument> ReadJsonResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken)
    {
        await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
        JsonDocument document;
        try
        {
            document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
        }
        catch (JsonException) when (response.Content.Headers.ContentLength == 0)
        {
            document = JsonDocument.Parse("""{"ok":true}""");
        }
 
        if (!response.IsSuccessStatusCode)
        {
            var (code, message) = ExtractError(document.RootElement, response.StatusCode);
            document.Dispose();
            throw new AiChatClientException(code, message);
        }
 
        if (document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind == JsonValueKind.False)
        {
            var (code, message) = ExtractError(document.RootElement, response.StatusCode);
            document.Dispose();
            throw new AiChatClientException(code, message);
        }
 
        return document;
    }
 
    private static AiChatProjectSummary? ParseProject(JsonElement item)
    {
        if (!item.TryGetProperty("id", out var id) || id.ValueKind != JsonValueKind.String)
        {
            return null;
        }
 
        return new AiChatProjectSummary
        {
            Id = id.GetString()!,
            Name = item.TryGetProperty("name", out var name) && name.ValueKind == JsonValueKind.String ? name.GetString() ?? id.GetString()! : id.GetString()!,
            ProjectType = item.TryGetProperty("projectType", out var projectType) && projectType.ValueKind == JsonValueKind.String ? projectType.GetString() ?? "CHAT" : "CHAT",
            MemoryMode = item.TryGetProperty("memoryMode", out var memoryMode) && memoryMode.ValueKind == JsonValueKind.String ? memoryMode.GetString() ?? "ISOLATED" : "ISOLATED"
        };
    }
 
    private static AiChatJsonResult CloneData(JsonDocument document)
    {
        if (!TryGetData(document.RootElement, out var data))
        {
            return new AiChatJsonResult();
        }
 
        return new AiChatJsonResult { Data = JsonSerializer.Deserialize<object>(data.GetRawText()) };
    }
 
    private static bool TryGetData(JsonElement root, out JsonElement data)
    {
        if (root.TryGetProperty("data", out data))
        {
            return true;
        }
 
        data = default;
        return false;
    }
 
    private static bool TryGetProjectsData(JsonElement root, out JsonElement projects)
    {
        if (TryGetData(root, out var data))
        {
            if (data.ValueKind == JsonValueKind.Array)
            {
                projects = data;
                return true;
            }
 
            if (data.ValueKind == JsonValueKind.Object &&
                data.TryGetProperty("projects", out var nestedProjects) &&
                nestedProjects.ValueKind == JsonValueKind.Array)
            {
                projects = nestedProjects;
                return true;
            }
        }
 
        projects = default;
        return false;
    }
 
    private static bool ReadBool(JsonElement root, string property)
        => root.TryGetProperty(property, out var value) &&
           (value.ValueKind == JsonValueKind.True || (value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed));
 
    private static (string Code, string Message) ExtractError(JsonElement root, HttpStatusCode statusCode)
    {
        var apiCode = root.TryGetProperty("code", out var codeElement) && codeElement.ValueKind == JsonValueKind.String
            ? codeElement.GetString()
            : null;
        var message = root.TryGetProperty("error", out var errorElement) && errorElement.ValueKind == JsonValueKind.String
            ? errorElement.GetString() ?? $"AiChat returned {(int)statusCode}."
            : $"AiChat returned {(int)statusCode}.";
 
        return (MapApiCode(apiCode, statusCode), message);
    }
 
    private static string MapApiCode(string? apiCode, HttpStatusCode statusCode)
    {
        if (string.Equals(apiCode, "TOKEN_TOTAL_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(apiCode, "TOKEN_PER_REQUEST_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase))
        {
            return LlmErrorCodes.AiChatQuotaExceeded;
        }
 
        if (string.Equals(apiCode, "PERMISSION_DENIED", StringComparison.OrdinalIgnoreCase))
        {
            return LlmErrorCodes.AiChatMemoryPermissionDenied;
        }
 
        if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
        {
            return LlmErrorCodes.AiChatLoginFailed;
        }
 
        return apiCode ?? LlmErrorCodes.AiChatApiFailed;
    }
 
    private static string MapStatusCode(HttpStatusCode statusCode)
        => statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden
            ? LlmErrorCodes.AiChatLoginFailed
            : LlmErrorCodes.AiChatApiFailed;
 
    private static Uri BuildUri(LlmPluginRuntimeConfig runtimeConfig, string path)
    {
        var baseUrl = string.IsNullOrWhiteSpace(runtimeConfig.AiChat.BaseUrl)
            ? "http://192.168.1.111:13000"
            : runtimeConfig.AiChat.BaseUrl;
        if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var baseUri) ||
            baseUri.Scheme is not ("http" or "https"))
        {
            throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "AiChat baseUrl must be an absolute HTTP or HTTPS URL.");
        }
 
        return new Uri(baseUri, path);
    }
 
    private static string? ResolvePassword(LlmPluginRuntimeConfig runtimeConfig)
    {
        var envName = runtimeConfig.AiChat.Account.PasswordEnv;
        if (!string.IsNullOrWhiteSpace(envName))
        {
            var envValue = Environment.GetEnvironmentVariable(envName)
                ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.User)
                ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.Machine);
            if (!string.IsNullOrWhiteSpace(envValue))
            {
                return envValue;
            }
        }
 
        return runtimeConfig.AiChat.Account.Password;
    }
 
    private void ClearSession(LlmPluginRuntimeConfig runtimeConfig)
    {
        _sessionTokens.TryRemove(SessionKey(runtimeConfig), out _);
    }
 
    private static string SessionKey(LlmPluginRuntimeConfig runtimeConfig)
        => $"{runtimeConfig.AiChat.BaseUrl}|{runtimeConfig.AiChat.Account.Email}";
}