using System.Net; using System.Net.Http.Headers; using System.Text; using System.Text.Json.Nodes; namespace XFEWorkflow.Plugins.AgentBrowser; public static class AgentApiSettings { public const string PrivateCredential = "agent-browser.deepseek"; public static string NormalizeKey(string value) { var key = value.Trim(); if (key.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) key = key[7..].Trim(); if (key.Equals("Bearer", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("Bearer 后缺少实际的 API Key"); if (key.Length > 4096 || key.Any(c => c <= ' ' || c >= 127 || c is '"' or '\'')) throw new ArgumentException("API Key 只能填写密钥本身,不能包含空格、换行、引号或中文"); return key; } public static string ResolveReference(string enteredKey, string selectedReference, IReadOnlyCollection references) { if (NormalizeKey(enteredKey).Length > 0) return PrivateCredential; if (selectedReference.Length > 0 && !references.Contains(selectedReference)) throw new ArgumentException("所选 API Key 凭据不存在,请直接填写密钥后保存"); return selectedReference; } public static async Task> VerifyAsync(HttpClient http, AgentOptions options, string key, CancellationToken ct) { key = NormalizeKey(key); var completion = options.CompletionUri(); if (!completion.IsLoopback && key.Length == 0) throw new ArgumentException("请先填写 DeepSeek API Key"); var endpoint = new Uri(completion.AbsoluteUri[..^"chat/completions".Length] + "models"); using var request = new HttpRequestMessage(HttpMethod.Get, endpoint); if (key.Length > 0) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(20)); using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); if (!response.IsSuccessStatusCode) throw new HttpRequestException(response.StatusCode switch { HttpStatusCode.Unauthorized => "API Key 验证失败(401),请检查密钥和 API 地址", HttpStatusCode.PaymentRequired => "DeepSeek 余额不足(402),请检查账户余额", HttpStatusCode.Forbidden => "服务拒绝访问(403),请检查密钥权限", HttpStatusCode.NotFound => "模型列表接口不存在(404),请检查 API 地址", HttpStatusCode.TooManyRequests => "服务请求过于频繁(429),请稍后重试", _ => $"API 验证失败(HTTP {(int)response.StatusCode})" }, null, response.StatusCode); await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token); using var reader = new StreamReader(stream); var text = new StringBuilder(); var buffer = new char[4096]; int read; while ((read = await reader.ReadAsync(buffer.AsMemory(), timeout.Token)) > 0) { text.Append(buffer, 0, read); if (text.Length > 1024 * 1024) throw new IOException("模型列表超过 1 MiB"); } var json = JsonNode.Parse(text.ToString())?.AsObject(); if (json?["data"] is not JsonArray models) throw new IOException("服务未返回有效的模型列表"); return models.OfType().Select(x => x["id"]?.GetValue()).OfType().Where(x => x.Length > 0).Distinct().ToArray(); } }