diff --git a/TelegramSearchBot.LLM.Test/Service/AI/LLM/OpencodeSessionHeadersTests.cs b/TelegramSearchBot.LLM.Test/Service/AI/LLM/OpencodeSessionHeadersTests.cs new file mode 100644 index 00000000..25d7b6a8 --- /dev/null +++ b/TelegramSearchBot.LLM.Test/Service/AI/LLM/OpencodeSessionHeadersTests.cs @@ -0,0 +1,46 @@ +using System; +using System.Net.Http; +using TelegramSearchBot.Service.AI.LLM; +using Xunit; + +namespace TelegramSearchBot.LLM.Test.Service.AI.LLM { + public class OpencodeSessionHeadersTests { + private static HttpClient Client() => new HttpClient(); + + [Theory] + [InlineData("https://opencode.ai/zen/v1")] + [InlineData("https://opencode.ai/zen/v1/")] + [InlineData("https://www.opencode.ai/zen/v1")] + public void Apply_Opengateways_AddsSessionAndUserAgent(string gateway) { + using var client = Client(); + + OpencodeSessionHeaders.Apply(client, gateway, "tsb-123"); + + Assert.Equal("tsb-123", string.Join(",", client.DefaultRequestHeaders.GetValues("x-opencode-session"))); + Assert.Equal("TelegramSearchBot/1.0", string.Join(",", client.DefaultRequestHeaders.GetValues("User-Agent"))); + } + + [Theory] + [InlineData("https://api.openai.com/v1")] + [InlineData("https://api.minimaxi.com/v1")] + [InlineData(null)] + [InlineData("")] + public void Apply_NonOpencodeGateways_AddsNothing(string gateway) { + using var client = Client(); + + OpencodeSessionHeaders.Apply(client, gateway, "tsb-123"); + + Assert.False(client.DefaultRequestHeaders.Contains("x-opencode-session")); + } + + [Fact] + public void Apply_Twice_DoesNotDuplicateSessionHeader() { + using var client = Client(); + + OpencodeSessionHeaders.Apply(client, "https://opencode.ai/zen/v1", "tsb-1"); + OpencodeSessionHeaders.Apply(client, "https://opencode.ai/zen/v1", "tsb-1"); + + Assert.Single(client.DefaultRequestHeaders.GetValues("x-opencode-session")); + } + } +} diff --git a/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIResponsesService.cs b/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIResponsesService.cs index e603ff6c..e36110f8 100644 --- a/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIResponsesService.cs +++ b/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIResponsesService.cs @@ -266,6 +266,7 @@ private async IAsyncEnumerable ExecWithResponsesApiAsync( // --- Create Responses client --- using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel, binding, $"tsb-{ChatId}"); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)), Transport = new HttpClientPipelineTransport(httpClient), @@ -543,6 +544,7 @@ public async IAsyncEnumerable ResumeFromSnapshotAsync( } using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel, binding, $"tsb-{snapshot.ChatId}"); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)), Transport = new HttpClientPipelineTransport(httpClient), @@ -761,6 +763,7 @@ public async Task GenerateEmbeddingsAsync(string text, string modelName } using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, endpoint); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(endpoint), Transport = new HttpClientPipelineTransport(httpClient), @@ -835,6 +838,7 @@ public async Task> GetAllModels(LLMChannel channel) { UseProxy = true }; using var httpClient = new HttpClient(handler); + OpencodeSessionHeaders.Apply(httpClient, channel.Gateway); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(channel.Gateway), @@ -865,6 +869,7 @@ public async Task> GetAllModels(LLMChannel channel, LLMApiBi UseProxy = true }; using var httpClient = new HttpClient(handler); + OpencodeSessionHeaders.Apply(httpClient, channel, binding); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)), @@ -888,6 +893,7 @@ public async Task IsHealthyAsync(LLMChannel channel, LLMApiBinding binding public async Task> GetAllModelsWithCapabilities(LLMChannel channel) { using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel.Gateway); try { var internalApiUrl = channel.Gateway.TrimEnd('/') + "/dashboard/onboarding/models"; @@ -939,6 +945,7 @@ public async Task AnalyzeImageAsync(string photoPath, string modelName, } using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel, binding); // For image analysis, use Chat Completions API (vision support is more mature) var clientOptions = new OpenAIClientOptions { diff --git a/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIService.cs b/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIService.cs index 129c0f53..2c7efabd 100644 --- a/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIService.cs +++ b/TelegramSearchBot.LLM/Service/AI/LLM/OpenAIService.cs @@ -280,6 +280,7 @@ public virtual async Task> GetAllModels(LLMChannel channel) }; using var httpClient = new HttpClient(handler); + OpencodeSessionHeaders.Apply(httpClient, channel.Gateway); // --- Client Setup --- var clientOptions = new OpenAIClientOptions { @@ -352,6 +353,7 @@ private async Task> GetGenericOpenAICompatibleModels(LLMChan if (!string.IsNullOrEmpty(apiKey)) { httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); } + OpencodeSessionHeaders.Apply(httpClient, channel, binding); // 构建模型列表 URL,确保路径正确 var gatewayBase = NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding)).TrimEnd('/'); @@ -483,6 +485,7 @@ public virtual async Task> GetAllModelsWithCa // 尝试使用OpenAI内部API获取模型能力信息 var internalApiUrl = channel.Gateway.TrimEnd('/') + "/dashboard/onboarding/models"; httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {channel.ApiKey}"); + OpencodeSessionHeaders.Apply(httpClient, channel.Gateway); var response = await httpClient.GetAsync(internalApiUrl); if (response.IsSuccessStatusCode) { @@ -1221,6 +1224,7 @@ private async IAsyncEnumerable ExecWithNativeToolCallingAsync( excludeDynamicTail: true); using var client = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{ChatId}"); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))), Transport = new HttpClientPipelineTransport(client), @@ -1516,6 +1520,7 @@ private async IAsyncEnumerable ExecWithXmlToolCallingAsync( excludeDynamicTail: true); using var client = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{ChatId}"); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))), Transport = new HttpClientPipelineTransport(client), @@ -1696,6 +1701,7 @@ public async IAsyncEnumerable ResumeFromSnapshotAsync(LlmContinuationSna excludeDynamicTail: false); using var client = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{snapshot.ChatId}"); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))), Transport = new HttpClientPipelineTransport(client), @@ -2005,6 +2011,7 @@ public async Task GenerateEmbeddingsAsync(string text, string modelName } using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel, binding); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, endpoint)), @@ -2118,6 +2125,7 @@ public async Task AnalyzeImageAsync(string photoPath, string modelName, } using var httpClient = _httpClientFactory.CreateClient(); + OpencodeSessionHeaders.Apply(httpClient, channel, binding); var clientOptions = new OpenAIClientOptions { Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))), diff --git a/TelegramSearchBot.LLM/Service/AI/LLM/OpencodeSessionHeaders.cs b/TelegramSearchBot.LLM/Service/AI/LLM/OpencodeSessionHeaders.cs new file mode 100644 index 00000000..fbb2ff26 --- /dev/null +++ b/TelegramSearchBot.LLM/Service/AI/LLM/OpencodeSessionHeaders.cs @@ -0,0 +1,32 @@ +using System; +using System.Net.Http; +using TelegramSearchBot.Model.AI; +using TelegramSearchBot.Model.Data; + +namespace TelegramSearchBot.Service.AI.LLM { + /// + /// OpenCode Go requires a stable `x-opencode-session` per conversation for every request. + /// https://opencode.ai/docs/go/#where-can-i-use-it + /// + internal static class OpencodeSessionHeaders { + internal const string GlobalSessionId = "tsb-global"; + + // ponytail: session id is derived from ChatId (stable per conversation); switch to real + // session keys only if opencode ever requires stricter per-thread routing. + internal static void Apply(HttpClient httpClient, string gateway, string sessionId = GlobalSessionId) { + if (httpClient == null || + string.IsNullOrWhiteSpace(gateway) || + !gateway.Contains("opencode", StringComparison.OrdinalIgnoreCase)) { + return; + } + + httpClient.DefaultRequestHeaders.Remove("x-opencode-session"); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("x-opencode-session", sessionId); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "TelegramSearchBot/1.0"); + } + + // 检测用实际请求 endpoint(binding 优先,回退 channel.Gateway)。 + internal static void Apply(HttpClient httpClient, LLMChannel channel, LLMApiBinding binding, string sessionId = GlobalSessionId) + => Apply(httpClient, LlmBindingSupport.ResolveEndpoint(channel, binding), sessionId); + } +}