diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index a1cde1eec2ec..1643778207a7 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -212,3 +212,9 @@ backend/internal/handler/gateway_gemini_envelope_test.go backend/internal/service/model_plaza_currency_test.go backend/internal/service/model_plaza_currency_update_test.go backend/internal/handler/model_plaza_currency_test.go + +# Anthropic media fixtures share compatEffortPolicyUpstream, absent in historical RED. +# Current candidate/GREEN retains both files and the complete media assertions. +# Frozen candidate blobs: eb860ff6bb7a0900ed1243d29d58c7ae4ae0eb83 / a69b0b585c25073321953af8630d64c743db2893. +backend/internal/handler/gateway_anthropic_media_test.go +backend/internal/handler/gateway_anthropic_tool_media_test.go diff --git a/backend/internal/handler/gateway_anthropic_media_test.go b/backend/internal/handler/gateway_anthropic_media_test.go new file mode 100644 index 000000000000..eb860ff6bb7a --- /dev/null +++ b/backend/internal/handler/gateway_anthropic_media_test.go @@ -0,0 +1,133 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Use the real handlers, scheduler and converters, capturing only the HTTP boundary. +func TestGatewayAnthropicMediaHandlers(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, stream := range []bool{false, true} { + for _, field := range []string{"image", "file"} { + for _, tc := range []struct { + name string + uri string + blockType string + sourceType string + }{ + {"png", "data:image/png;base64,c3ludGhldGlj", "image", "base64"}, + {"jpeg", "data:image/jpeg;base64,c3ludGhldGlj", "image", "base64"}, + {"gif", "data:image/gif;base64,c3ludGhldGlj", "image", "base64"}, + {"webp", "data:image/webp;base64,c3ludGhldGlj", "image", "base64"}, + {"pdf", "data:application/pdf;base64,c3ludGhldGlj", "document", "base64"}, + {"plain", "data:text/plain;base64,c3ludGhldGlj", "document", "text"}, + {"url", "https://example.invalid/private.png", "", ""}, + {"video", "data:video/mp4;base64,cHJpdmF0ZQ==", "reject", ""}, + {"audio", "data:audio/mpeg;base64,cHJpdmF0ZQ==", "reject", ""}, + {"unknown", "data:application/octet-stream;base64,cHJpdmF0ZQ==", "reject", ""}, + {"malformed", "data:image/png,private-payload", "reject", ""}, + {"bad_base64", "data:image/png;base64,private-payload!", "reject", ""}, + {"empty", "data:image/png;base64,", "reject", ""}, + } { + t.Run(fmt.Sprintf("%s/stream=%t/%s/%s", endpoint, stream, field, tc.name), func(t *testing.T) { + cfg := &config.Config{} + groupID := int64(9810) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9811, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9811, GroupID: groupID}}, + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + upstream := &compatEffortPolicyUpstream{} + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billing := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + gateway := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usage, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{gatewayService: gateway, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0)} + part := map[string]any{"type": "input_image", "image_url": tc.uri} + text := map[string]any{"type": "input_text", "text": "synthetic prompt"} + if field == "file" { + part = map[string]any{"type": "input_file", "file_data": tc.uri} + } + request := map[string]any{"model": "claude-sonnet-4-5", "stream": stream} + if endpoint == "chat/completions" { + text["type"] = "text" + part = map[string]any{"type": "image_url", "image_url": map[string]string{"url": tc.uri}} + if field == "file" { + part = map[string]any{"type": "file", "file": map[string]string{"file_data": tc.uri}} + } + request["messages"] = []any{map[string]any{"role": "user", "content": []any{text, part}}} + } else { + request["input"] = []any{map[string]any{"role": "user", "content": []any{text, part}}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + // Use the new-key default; restricted keys reject opaque media + // during final context admission before this conversion oracle. + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 9812, UserID: 9813, GroupID: &groupID, Group: group, AllowLongContext: true, User: &service.User{ID: 9813, Balance: 100}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9813}) + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + if tc.blockType == "reject" { + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), "invalid_request_error") + require.NotEmpty(t, gjson.Get(recorder.Body.String(), "error.message").String()) + require.NotContains(t, recorder.Body.String(), "private") + require.NotContains(t, recorder.Body.String(), "cHJpdmF0ZQ") + require.Empty(t, upstream.bodies) + require.Empty(t, usage.created) + require.Empty(t, billingRepo.commands) + return + } + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.bodies, 1) + blocks := gjson.GetBytes(upstream.bodies[0], "messages.0.content").Array() + if tc.blockType == "" { + require.Len(t, blocks, 1) // preserve the legacy URL omission + } else { + require.Len(t, blocks, 2) + require.Equal(t, tc.blockType, blocks[1].Get("type").String()) + require.Equal(t, tc.sourceType, blocks[1].Get("source.type").String()) + if tc.sourceType == "text" { + require.Equal(t, "synthetic", blocks[1].Get("source.data").String()) + } + } + }) + } + } + } + } +} diff --git a/backend/internal/handler/gateway_anthropic_tool_media_test.go b/backend/internal/handler/gateway_anthropic_tool_media_test.go new file mode 100644 index 000000000000..bb8fe94b03ed --- /dev/null +++ b/backend/internal/handler/gateway_anthropic_tool_media_test.go @@ -0,0 +1,157 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type anthropicToolMediaUpstream struct{ compatEffortPolicyUpstream } + +func (u *anthropicToolMediaUpstream) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) { + return u.DoWithTLS(req, proxy, id, concurrency, nil) +} + +func TestGatewayAnthropicChatToolMediaRejectsBeforeFlattening(t *testing.T) { + testAnthropicChatToolMedia(t, false) +} + +func TestNativeAnthropicChatToolMediaRejectsBeforeFlattening(t *testing.T) { + testAnthropicChatToolMedia(t, true) +} + +func testAnthropicChatToolMedia(t *testing.T, native bool) { + t.Helper() + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + for _, role := range []string{"tool", "function"} { + for _, field := range []string{"image", "file"} { + for _, tc := range []struct { + name string + uri string + want string + }{ + {"video", "data:video/mp4;base64,cHJpdmF0ZQ==", "reject"}, + {"audio", "data:audio/mpeg;base64,cHJpdmF0ZQ==", "reject"}, + {"unknown", "data:application/octet-stream;base64,cHJpdmF0ZQ==", "reject"}, + {"malformed_header", "data:image/png,private-payload", "reject"}, + {"malformed_base64", "data:image/png;base64,private-payload!", "reject"}, + {"empty", "data:image/png;base64,", "reject"}, + {"png", "data:image/png;base64,c3ludGhldGlj", "image"}, + {"jpeg", "data:image/jpeg;base64,c3ludGhldGlj", "image"}, + {"gif", "data:image/gif;base64,c3ludGhldGlj", "image"}, + {"webp", "data:image/webp;base64,c3ludGhldGlj", "image"}, + {"pdf", "data:application/pdf;base64,c3ludGhldGlj", "document"}, + {"plain", "data:text/plain;base64,c3ludGhldGlj", "document"}, + {"string_control", "literal data:video/mp4;base64,cHJpdmF0ZQ==", "string"}, + } { + t.Run(fmt.Sprintf("stream=%t/%s/%s/%s", stream, role, field, tc.name), func(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + platform, model := service.PlatformAnthropic, "claude-sonnet-4-5" + if native { + platform, model = service.PlatformKimi, "k3" + } + groupID := int64(3131) + group := &service.Group{ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9811, Platform: platform, Type: service.AccountTypeAPIKey, Status: service.StatusActive, + Schedulable: true, Concurrency: 1, GroupIDs: []int64{groupID}, + Credentials: map[string]any{"api_key": "test-key", "api_protocol": service.APIProtocolAnthropic, "base_url": "https://anthropic.example"}, + AccountGroups: []service.AccountGroup{{AccountID: 9811, GroupID: groupID}}, + } + upstream := &anthropicToolMediaUpstream{} + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billing := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + media := map[string]any{"type": "image_url", "image_url": map[string]string{"url": tc.uri}} + if field == "file" { + media = map[string]any{"type": "file", "file": map[string]string{"file_data": tc.uri}} + } + var content any = []any{map[string]string{"type": "text", "text": "tool text"}, media} + if tc.want == "string" { + content = tc.uri + } + assistant := map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"id": "call_1", "type": "function", "function": map[string]string{"name": "read", "arguments": "{}"}}}} + result := map[string]any{"role": role, "tool_call_id": "call_1", "content": content} + if role == "function" { + assistant = map[string]any{"role": "assistant", "function_call": map[string]string{"name": "read", "arguments": "{}"}} + result = map[string]any{"role": role, "name": "read", "content": content} + } + body, err := json.Marshal(map[string]any{"model": model, "stream": stream, "messages": []any{map[string]string{"role": "user", "content": "read"}, assistant, result}}) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + // Match the new-key default so context admission does not + // reject opaque media before the MIME/preservation assertions. + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 99, UserID: 100, GroupID: &groupID, Group: group, AllowLongContext: true, User: &service.User{ID: 100, Balance: 100}}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 100}) + if native { + gateway := service.NewOpenAIGatewayService( + &openAIWSUsageHandlerAccountRepoStub{account: *account}, nil, usage, billingRepo, nil, nil, nil, nil, cfg, + nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{}, + nil, nil, nil, nil, nil, nil, nil, + ) + t.Cleanup(gateway.CloseOpenAIWSPool) + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg) + h.ChatCompletions(c) + } else { + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + gateway := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usage, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{gatewayService: gateway, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0)} + h.ChatCompletions(c) + } + if tc.want == "reject" { + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), "invalid_request_error") + require.NotContains(t, recorder.Body.String(), "private") + require.NotContains(t, recorder.Body.String(), "cHJpdmF0ZQ") + require.Empty(t, upstream.bodies) + require.Empty(t, usage.created) + require.Empty(t, billingRepo.commands) + return + } + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.bodies, 1) + toolContent := gjson.GetBytes(upstream.bodies[0], "messages.2.content.0.content") + if tc.want == "string" { + require.Equal(t, tc.uri, toolContent.String()) + return + } + require.Equal(t, "tool text", toolContent.Get("0.text").String()) + require.Equal(t, tc.want, toolContent.Get("1.type").String()) + wantSource, wantData := "base64", "c3ludGhldGlj" + if tc.name == "plain" { + wantSource, wantData = "text", "synthetic" + } + require.Equal(t, wantSource, toolContent.Get("1.source.type").String()) + require.Equal(t, wantData, toolContent.Get("1.source.data").String()) + require.Equal(t, gjson.GetBytes(upstream.bodies[0], "messages.1.content.0.id").String(), gjson.GetBytes(upstream.bodies[0], "messages.2.content.0.tool_use_id").String()) + }) + } + } + } + } +} diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index e6174e5271e6..bd0766aad0ab 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -535,6 +535,10 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu parts = append(parts, part) case "image", "document": + if block.Type == "document" && block.Source != nil && block.Source.Type == "text" && block.Source.MediaType == "text/plain" { + parts = append(parts, GeminiPart{Text: block.Source.Data}) + continue + } if block.Source != nil && block.Source.Type == "base64" && strings.TrimSpace(block.Source.Data) != "" { parts = append(parts, GeminiPart{ InlineData: &GeminiInlineData{ @@ -633,6 +637,13 @@ func parseToolResultContent(content json.RawMessage, isError bool) string { if text, ok := item["text"].(string); ok { texts = append(texts, text) } + if item["type"] == "document" { + if source, ok := item["source"].(map[string]any); ok && source["type"] == "text" && source["media_type"] == "text/plain" { + if text, ok := source["data"].(string); ok { + texts = append(texts, text) + } + } + } } result := strings.Join(texts, "\n") if strings.TrimSpace(result) == "" { diff --git a/backend/internal/pkg/antigravity/tool_result_images_test.go b/backend/internal/pkg/antigravity/tool_result_images_test.go index 6f68f788864d..d34dfe0434e0 100644 --- a/backend/internal/pkg/antigravity/tool_result_images_test.go +++ b/backend/internal/pkg/antigravity/tool_result_images_test.go @@ -9,6 +9,23 @@ import ( "github.com/tidwall/gjson" ) +func TestResponsesPlainDocumentSurvivesAnthropicBridge(t *testing.T) { + var req apicompat.ResponsesRequest + require.NoError(t, json.Unmarshal([]byte(`{"input":[{"role":"user","content":[{"type":"input_file","file_data":"data:text/plain;base64,c3ludGhldGlj"}]}]}`), &req)) + anthropic, err := apicompat.ResponsesToAnthropicRequest(&req) + require.NoError(t, err) + body, err := json.Marshal(anthropic) + require.NoError(t, err) + var claude ClaudeRequest + require.NoError(t, json.Unmarshal(body, &claude)) + wire, err := TransformClaudeToGeminiWithOptions(&claude, "test-project", "gemini-2.5-flash", TransformOptions{}) + require.NoError(t, err) + require.Equal(t, "synthetic", gjson.GetBytes(wire, "request.contents.0.parts.0.text").String()) + content := json.RawMessage(`[{"type":"document","source":{"type":"text","media_type":"text/plain","data":"synthetic"}}]`) + require.Equal(t, "synthetic", parseToolResultContent(content, false)) + require.Empty(t, extractToolResultInlineParts(content), "plain text must stay in the function response text") +} + func TestResponsesToolResultImagesStayWithTheirCalls(t *testing.T) { for _, model := range []string{"gemini-3.8-flash", "gemini-4-argon"} { t.Run(model, func(t *testing.T) { diff --git a/backend/internal/pkg/apicompat/anthropic_media.go b/backend/internal/pkg/apicompat/anthropic_media.go new file mode 100644 index 000000000000..101d96a779fb --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_media.go @@ -0,0 +1,182 @@ +package apicompat + +import ( + "encoding/base64" + "encoding/json" + "io" + "strings" + "unicode/utf8" +) + +// AnthropicMediaError identifies a client media validation failure. Its message +// contains only fixed text, never a client URI, MIME header or embedded payload. +type AnthropicMediaError struct { + reason string +} + +func (e *AnthropicMediaError) Error() string { return e.reason } + +// ValidateChatCompletionsAnthropicMedia validates existing media carriers before +// the generic Chat→Responses bridge can flatten tool/function content arrays. +// Strings are never interpreted as media. Non-data URLs keep their legacy policy. +func ValidateChatCompletionsAnthropicMedia(req *ChatCompletionsRequest) error { + for _, message := range req.Messages { + var parts []ChatContentPart + if json.Unmarshal(message.Content, &parts) != nil { + continue + } + for _, part := range parts { + uri := "" + switch { + case part.Type == "image_url" && part.ImageURL != nil: + uri = part.ImageURL.URL + case part.Type == "file" && part.File != nil: + uri = part.File.FileData + } + if _, err := dataURIToAnthropicMediaBlock(uri); err != nil { + return err + } + } + } + return nil +} + +// PreserveChatCompletionsAnthropicToolMedia restores structured tool output +// after generic conversion. Item order and generated legacy function call IDs +// are unchanged. Only actual content arrays with convertible data URI media are +// replaced; string tool output and the generic bridge remain untouched. +func PreserveChatCompletionsAnthropicToolMedia(chat *ChatCompletionsRequest, responses *ResponsesRequest) error { + var items []json.RawMessage + if err := json.Unmarshal(responses.Input, &items); err != nil { + return err + } + next := 0 + changed := false + for _, message := range chat.Messages { + if message.Role != "tool" && message.Role != "function" { + continue + } + var wire map[string]json.RawMessage + for next < len(items) { + if err := json.Unmarshal(items[next], &wire); err != nil { + return err + } + var itemType string + if err := json.Unmarshal(wire["type"], &itemType); err != nil { + return err + } + if itemType == "function_call_output" { + break + } + wire = nil + next++ + } + if next == len(items) { + break + } + next++ + var parts []ChatContentPart + if json.Unmarshal(message.Content, &parts) != nil { + continue + } + converted := convertChatContentPartsToResponses(parts) + hasMedia := false + for _, part := range converted { + if part.Type == "input_image" || part.Type == "input_file" { + block, err := responsesMediaPartToAnthropicBlock(part, ResponsesToAnthropicOptions{StrictMedia: true}) + if err != nil { + return err + } + hasMedia = hasMedia || block != nil + } + } + if hasMedia { + content, err := json.Marshal(converted) + if err != nil { + return err + } + // Keep an actual output array on the wire; a JSON-encoded string + // would be ordinary tool text on the next conversion. + wire["output"] = content + items[next-1], err = json.Marshal(wire) + if err != nil { + return err + } + changed = true + } + } + if changed { + input, err := json.Marshal(items) + if err != nil { + return err + } + responses.Input = input + } + return nil +} + +func responsesMediaPartToAnthropicBlock(part ResponsesContentPart, opts ResponsesToAnthropicOptions) (*AnthropicContentBlock, error) { + uri := part.ImageURL + blockType := "image" + if part.Type == "input_file" { + uri, blockType = part.FileData, "document" + } + if opts.StrictMedia { + return dataURIToAnthropicMediaBlock(uri) + } + // Preserve the pre-strict intermediary policy for Gemini/Antigravity: + // carry the declared MIME and base64 bytes without applying Anthropic's + // allowlist or validating another target protocol's media constraints. + if !strings.HasPrefix(uri, "data:") { + return nil, nil + } + mediaType, rest, ok := strings.Cut(strings.TrimPrefix(uri, "data:"), ";") + if !ok || !strings.HasPrefix(rest, "base64,") { + return nil, nil + } + source := &AnthropicImageSource{Type: "base64", MediaType: mediaType, Data: strings.TrimPrefix(rest, "base64,")} + // Retain the valid plain-text source introduced with the MIME fix. If it + // cannot be decoded, preserve the legacy carrier for the final target. + if mediaType == "text/plain" { + if data, err := base64.StdEncoding.DecodeString(source.Data); err == nil && utf8.Valid(data) { + blockType, source.Type, source.Data = "document", "text", string(data) + } + } + return &AnthropicContentBlock{Type: blockType, Source: source}, nil +} + +// dataURIToAnthropicMediaBlock chooses the block by MIME rather than by the +// OpenAI field name. Only the existing data:;base64, policy is +// supported; non-data URLs and file IDs remain unconverted, without fetching. +func dataURIToAnthropicMediaBlock(uri string) (*AnthropicContentBlock, error) { + if !strings.HasPrefix(uri, "data:") { + return nil, nil + } + header, data, ok := strings.Cut(strings.TrimPrefix(uri, "data:"), ";base64,") + if !ok || header == "" || strings.ContainsAny(header, ";, \t\r\n") || strings.TrimSpace(data) == "" { + return nil, &AnthropicMediaError{reason: "invalid media data URI for Anthropic conversion; expected data:;base64,"} + } + blockType := "image" + switch header { + case "image/png", "image/jpeg", "image/gif", "image/webp": + case "application/pdf", "text/plain": + blockType = "document" + default: + return nil, &AnthropicMediaError{reason: "unsupported media type for Anthropic conversion; supported types are image/png, image/jpeg, image/gif, image/webp, application/pdf and text/plain"} + } + source := &AnthropicImageSource{Type: "base64", MediaType: header, Data: data} + if header == "text/plain" { + decoded, err := base64.StdEncoding.DecodeString(data) + if err != nil || !utf8.Valid(decoded) { + return nil, &AnthropicMediaError{reason: "invalid base64 UTF-8 text document for Anthropic conversion"} + } + // Anthropic PlainTextSource takes decoded text, not base64 bytes. + source.Type, source.Data = "text", string(decoded) + } else { + // Validate encoding without allocating another copy of binary media. + if _, err := io.Copy(io.Discard, base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))); err != nil { + return nil, &AnthropicMediaError{reason: "invalid base64 media data for Anthropic conversion"} + } + } + return &AnthropicContentBlock{Type: blockType, Source: source}, nil +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_media_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_media_test.go new file mode 100644 index 000000000000..e73424a41c7d --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_media_test.go @@ -0,0 +1,154 @@ +package apicompat + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestResponsesToAnthropicMediaMIMEBlocks(t *testing.T) { + for _, field := range []string{"input_image", "input_file"} { + for _, mime := range []string{"image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf", "text/plain"} { + t.Run(field+"/"+mime, func(t *testing.T) { + data := base64.StdEncoding.EncodeToString([]byte("synthetic media")) + part := ResponsesContentPart{Type: field} + uri := "data:" + mime + ";base64," + data + if field == "input_image" { + part.ImageURL = uri + } else { + part.FileData = uri + } + content, err := json.Marshal([]ResponsesContentPart{part}) + require.NoError(t, err) + input, err := json.Marshal([]ResponsesInputItem{{Role: "user", Content: content}}) + require.NoError(t, err) + out, err := ResponsesToAnthropicRequestWithOptions(&ResponsesRequest{Model: "claude-sonnet-4-5", Input: input}, ResponsesToAnthropicOptions{StrictMedia: true}) + require.NoError(t, err) + require.Len(t, out.Messages, 1) + blocks := parseContentBlocks(out.Messages[0].Content) + require.Len(t, blocks, 1) + wantType, sourceType := "image", "base64" + if mime == "application/pdf" || mime == "text/plain" { + wantType = "document" + } + if mime == "text/plain" { + sourceType, data = "text", "synthetic media" + } + require.Equal(t, wantType, blocks[0].Type) + require.Equal(t, &AnthropicImageSource{Type: sourceType, MediaType: mime, Data: data}, blocks[0].Source) + }) + } + } +} + +func TestResponsesToAnthropicMediaRejectsSafely(t *testing.T) { + for _, field := range []string{"input_image", "input_file"} { + for index, uri := range []string{ + "data:video/mp4;base64,cHJpdmF0ZQ==", "data:audio/mpeg;base64,cHJpdmF0ZQ==", + "data:application/octet-stream;base64,cHJpdmF0ZQ==", "data:image/svg+xml;base64,cHJpdmF0ZQ==", + "data:private-header;base64,cHJpdmF0ZQ==", "data:;base64,cHJpdmF0ZQ==", + "data:image/png,cHJpdmF0ZQ==", "data:image/png;base64,", "data:image/png;base64,private-invalid!", + "data:image/png;charset=utf-8;base64,cHJpdmF0ZQ==", "data:text/plain;base64,/w==", + } { + t.Run(fmt.Sprintf("%s/case_%02d", field, index), func(t *testing.T) { + key := "image_url" + if field == "input_file" { + key = "file_data" + } + content, err := json.Marshal([]map[string]string{{"type": field, key: uri}, {"type": "input_text", "text": "private-text"}}) + require.NoError(t, err) + input, err := json.Marshal([]ResponsesInputItem{{Role: "user", Content: content}}) + require.NoError(t, err) + out, err := ResponsesToAnthropicRequestWithOptions(&ResponsesRequest{Model: "claude-sonnet-4-5", Input: input}, ResponsesToAnthropicOptions{StrictMedia: true}) + require.Nil(t, out) + require.Error(t, err) + require.NotContains(t, err.Error(), "private") + require.NotContains(t, err.Error(), "cHJpdmF0ZQ") + require.NotContains(t, err.Error(), uri) + }) + } + } +} + +func TestResponsesToAnthropicMediaURLPolicy(t *testing.T) { + out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Input: json.RawMessage(`[{"role":"user","content":[{"type":"input_text","text":"keep"},{"type":"input_image","image_url":"https://example.invalid/private.png"},{"type":"input_file","file_data":"https://example.invalid/private.pdf"},{"type":"input_file","file_id":"file_1"}]}]`)}) + require.NoError(t, err) + require.Len(t, out.Messages, 1) + require.JSONEq(t, `[{"type":"text","text":"keep"}]`, string(out.Messages[0].Content)) +} + +func TestResponsesToAnthropicToolMediaRejectsSafely(t *testing.T) { + out, err := ResponsesToAnthropicRequestWithOptions(&ResponsesRequest{Input: json.RawMessage(`[{"type":"function_call","name":"read","call_id":"call_1","arguments":"{}"},{"type":"function_call_output","call_id":"call_1","output":[{"type":"input_image","image_url":"data:video/mp4;base64,cHJpdmF0ZQ=="}]}]`)}, ResponsesToAnthropicOptions{StrictMedia: true}) + require.Nil(t, out) + require.Error(t, err) + require.NotContains(t, err.Error(), "cHJpdmF0ZQ") +} + +func TestResponsesToAnthropicMediaLeavesTextUntouched(t *testing.T) { + // Media-like text is ordinary customer text, including in tool output. + const text = "literal data:video/mp4;base64,cHJpdmF0ZQ==" + input, err := json.Marshal([]map[string]any{ + {"role": "user", "content": text}, + {"type": "function_call", "name": "read", "call_id": "call_1", "arguments": "{}"}, + {"type": "function_call_output", "call_id": "call_1", "output": text}, + }) + require.NoError(t, err) + out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Input: input}) + require.NoError(t, err) + require.Len(t, out.Messages, 3) + require.Equal(t, text, parseContentBlocks(out.Messages[0].Content)[0].Text) + tool := parseContentBlocks(out.Messages[2].Content)[0] + require.Equal(t, "tool_result", tool.Type) + var output string + require.NoError(t, json.Unmarshal(tool.Content, &output)) + require.Equal(t, text, output) +} + +func TestResponsesToAnthropicMediaPolicyDefaultsRemainCompatible(t *testing.T) { + for _, mime := range []string{"video/mp4", "audio/mpeg", "application/octet-stream"} { + t.Run(mime, func(t *testing.T) { + input := json.RawMessage(`[{"role":"user","content":[{"type":"input_image","image_url":"data:` + mime + `;base64,c3ludGhldGlj"}]}]`) + request := &ResponsesRequest{Input: input} + out, err := ResponsesToAnthropicRequest(request) + require.NoError(t, err) + block := parseContentBlocks(out.Messages[0].Content)[0] + require.Equal(t, "image", block.Type) + require.Equal(t, mime, block.Source.MediaType) + require.Equal(t, "c3ludGhldGlj", block.Source.Data) + _, err = ResponsesToAnthropicRequestWithOptions(request, ResponsesToAnthropicOptions{StrictMedia: true}) + var mediaErr *AnthropicMediaError + require.ErrorAs(t, err, &mediaErr) + }) + } +} + +func TestChatAnthropicToolMediaPreservesParallelAndStringOutputs(t *testing.T) { + var chat ChatCompletionsRequest + require.NoError(t, json.Unmarshal([]byte(`{"messages":[ + {"role":"user","content":"read"}, + {"role":"assistant","tool_calls":[{"id":"call_A","type":"function","function":{"name":"read","arguments":"{}"}},{"id":"call_B","type":"function","function":{"name":"read","arguments":"{}"}},{"id":"call_C","type":"function","function":{"name":"read","arguments":"{}"}}]}, + {"role":"tool","tool_call_id":"call_A","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,c3ludGhldGlj"}}]}, + {"role":"tool","tool_call_id":"call_B","content":"literal data:video/mp4;base64,c3ludGhldGlj"}, + {"role":"tool","tool_call_id":"call_C","content":[{"type":"file","file":{"file_data":"data:text/plain;base64,c3ludGhldGlj"}}]} + ]}`), &chat)) + require.NoError(t, ValidateChatCompletionsAnthropicMedia(&chat)) + responses, err := ChatCompletionsToResponses(&chat) + require.NoError(t, err) + require.NoError(t, PreserveChatCompletionsAnthropicToolMedia(&chat, responses)) + out, err := ResponsesToAnthropicRequestWithOptions(responses, ResponsesToAnthropicOptions{StrictMedia: true}) + require.NoError(t, err) + require.Len(t, out.Messages, 3) + blocks := parseContentBlocks(out.Messages[2].Content) + require.Len(t, blocks, 3) + require.Equal(t, "call_A", blocks[0].ToolUseID) + require.Equal(t, "image", parseContentBlocks(blocks[0].Content)[0].Type) + require.Equal(t, "call_B", blocks[1].ToolUseID) + var text string + require.NoError(t, json.Unmarshal(blocks[1].Content, &text)) + require.Equal(t, "literal data:video/mp4;base64,c3ludGhldGlj", text) + require.Equal(t, "call_C", blocks[2].ToolUseID) + require.Equal(t, "synthetic", parseContentBlocks(blocks[2].Content)[0].Source.Data) +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go index 5f8c5664fc78..2c0d8c299e0c 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go @@ -9,17 +9,30 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/claude" ) -// ResponsesToAnthropicRequest converts a Responses API request into an -// Anthropic Messages request. This is the reverse of AnthropicToResponses and -// enables Anthropic platform groups to accept OpenAI Responses API requests -// by converting them to the native /v1/messages format before forwarding upstream. +// ResponsesToAnthropicOptions separates actual Anthropic targets from callers +// that use Anthropic blocks only as an intermediate representation. +type ResponsesToAnthropicOptions struct { + // StrictMedia validates MIME and encoding for an actual Anthropic target. + // Leave false when these blocks are only an intermediate representation. + StrictMedia bool +} + +// ResponsesToAnthropicRequest retains the permissive media carrier policy for +// existing intermediate-protocol callers. Anthropic targets must opt into strict +// media validation with ResponsesToAnthropicRequestWithOptions. func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, error) { + return ResponsesToAnthropicRequestWithOptions(req, ResponsesToAnthropicOptions{}) +} + +// ResponsesToAnthropicRequestWithOptions converts a request with an explicit +// target media policy; all other request conversion semantics are shared. +func ResponsesToAnthropicRequestWithOptions(req *ResponsesRequest, opts ResponsesToAnthropicOptions) (*AnthropicRequest, error) { isOpus55 := claude.IsOpus55(req.Model) isSonnet55 := claude.IsSonnet55(req.Model) isHaiku55 := claude.IsHaiku55(req.Model) isFableOrMythos52 := claude.IsFable52(req.Model) || claude.IsMythos52(req.Model) isAdaptiveModel := isOpus55 || isSonnet55 || isHaiku55 || isFableOrMythos52 - system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isAdaptiveModel) + system, messages, err := convertResponsesInputToAnthropicWithOptions(req.Instructions, req.Input, isAdaptiveModel, opts) if err != nil { return nil, err } @@ -185,6 +198,10 @@ func mapResponsesEffortToAnthropic(effort string) string { // a Responses API instructions + input array. Returns the system as raw JSON // (for Anthropic's polymorphic system field) and a list of Anthropic messages. func convertResponsesInputToAnthropic(instructions string, inputRaw json.RawMessage, preserveThinking bool) (json.RawMessage, []AnthropicMessage, error) { + return convertResponsesInputToAnthropicWithOptions(instructions, inputRaw, preserveThinking, ResponsesToAnthropicOptions{}) +} + +func convertResponsesInputToAnthropicWithOptions(instructions string, inputRaw json.RawMessage, preserveThinking bool, opts ResponsesToAnthropicOptions) (json.RawMessage, []AnthropicMessage, error) { var systemParts []string if strings.TrimSpace(instructions) != "" { systemParts = append(systemParts, strings.TrimSpace(instructions)) @@ -236,7 +253,10 @@ func convertResponsesInputToAnthropic(instructions string, inputRaw json.RawMess case item.Type == "function_call_output": // function_call_output → user message with tool_result block - contentJSON := responsesFunctionOutputToAnthropicContent(item) + contentJSON, err := responsesFunctionOutputToAnthropicContent(item, opts) + if err != nil { + return nil, nil, err + } block := AnthropicContentBlock{ Type: "tool_result", ToolUseID: fromResponsesCallIDToAnthropic(item.CallID), @@ -271,7 +291,7 @@ func convertResponsesInputToAnthropic(instructions string, inputRaw json.RawMess } case item.Role == "user": - content, err := convertResponsesUserToAnthropicContent(item.Content) + content, err := convertResponsesUserToAnthropicContent(item.Content, opts) if err != nil { return nil, nil, err } @@ -309,7 +329,7 @@ func convertResponsesInputToAnthropic(instructions string, inputRaw json.RawMess if item.Content == nil { continue } - content, err := convertResponsesUserToAnthropicContent(item.Content) + content, err := convertResponsesUserToAnthropicContent(item.Content, opts) if err != nil { return nil, nil, err } @@ -340,14 +360,14 @@ func convertResponsesInputToAnthropic(instructions string, inputRaw json.RawMess return system, messages, nil } -func responsesFunctionOutputToAnthropicContent(item ResponsesInputItem) json.RawMessage { +func responsesFunctionOutputToAnthropicContent(item ResponsesInputItem, opts ResponsesToAnthropicOptions) (json.RawMessage, error) { if len(item.outputRaw) == 0 { output := item.Output if output == "" { output = "(empty)" } content, _ := json.Marshal(output) - return content + return content, nil } var parts []ResponsesContentPart @@ -359,24 +379,32 @@ func responsesFunctionOutputToAnthropicContent(item ResponsesInputItem) json.Raw if part.Text != "" { blocks = append(blocks, AnthropicContentBlock{Type: "text", Text: part.Text}) } - case "input_image": - if source := dataURIToAnthropicImageSource(part.ImageURL); source != nil { - blocks = append(blocks, AnthropicContentBlock{Type: "image", Source: source}) + case "input_image", "input_file": + if part.Type == "input_file" && !opts.StrictMedia { + // Legacy intermediate tool outputs recognized images only. + continue + } + block, err := responsesMediaPartToAnthropicBlock(part, opts) + if err != nil { + return nil, err + } + if block != nil { + blocks = append(blocks, *block) } } } if len(blocks) > 0 { content, _ := json.Marshal(blocks) - return content + return content, nil } if len(parts) == 0 { content, _ := json.Marshal("(empty)") - return content + return content, nil } } content, _ := json.Marshal(item.Output) - return content + return content, nil } // normalizeAnthropicToolPairing rebuilds the message sequence so it satisfies @@ -547,7 +575,7 @@ func anthropicContentIsOnlyBlankText(content json.RawMessage) bool { return true } -func convertResponsesUserToAnthropicContent(raw json.RawMessage) (json.RawMessage, error) { +func convertResponsesUserToAnthropicContent(raw json.RawMessage, opts ResponsesToAnthropicOptions) (json.RawMessage, error) { if len(raw) == 0 { return json.Marshal("") // empty string content } @@ -575,21 +603,13 @@ func convertResponsesUserToAnthropicContent(raw json.RawMessage) (json.RawMessag Text: p.Text, }) } - case "input_image": - src := dataURIToAnthropicImageSource(p.ImageURL) - if src != nil { - blocks = append(blocks, AnthropicContentBlock{ - Type: "image", - Source: src, - }) + case "input_image", "input_file": + block, err := responsesMediaPartToAnthropicBlock(p, opts) + if err != nil { + return nil, err } - case "input_file": - src := dataURIToAnthropicFileSource(p.FileData) - if src != nil { - blocks = append(blocks, AnthropicContentBlock{ - Type: "document", - Source: src, - }) + if block != nil { + blocks = append(blocks, *block) } } } @@ -654,36 +674,6 @@ func fromResponsesCallIDToAnthropic(id string) string { return id } -// dataURIToAnthropicImageSource parses a data URI into an AnthropicImageSource. -func dataURIToAnthropicImageSource(dataURI string) *AnthropicImageSource { - if !strings.HasPrefix(dataURI, "data:") { - return nil - } - // Format: data:;base64, - rest := strings.TrimPrefix(dataURI, "data:") - semicolonIdx := strings.Index(rest, ";") - if semicolonIdx < 0 { - return nil - } - mediaType := rest[:semicolonIdx] - rest = rest[semicolonIdx+1:] - if !strings.HasPrefix(rest, "base64,") { - return nil - } - data := strings.TrimPrefix(rest, "base64,") - return &AnthropicImageSource{ - Type: "base64", - MediaType: mediaType, - Data: data, - } -} - -// dataURIToAnthropicFileSource parses a data URI into a document source. -// file_id-only parts are not convertible here and stay dropped. -func dataURIToAnthropicFileSource(fileData string) *AnthropicImageSource { - return dataURIToAnthropicImageSource(fileData) -} - // mergeConsecutiveMessages merges consecutive messages with the same role // because Anthropic requires alternating user/assistant turns. func mergeConsecutiveMessages(messages []AnthropicMessage) []AnthropicMessage { diff --git a/backend/internal/service/gateway_anthropic_media_test.go b/backend/internal/service/gateway_anthropic_media_test.go new file mode 100644 index 000000000000..2bf74cde6c38 --- /dev/null +++ b/backend/internal/service/gateway_anthropic_media_test.go @@ -0,0 +1,221 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestGeminiCompatibilityMediaPolicyIsTargetScoped(t *testing.T) { + testCompatibilityMediaPolicy(t, false) +} + +func TestAntigravityCompatibilityMediaPolicyIsTargetScoped(t *testing.T) { + testCompatibilityMediaPolicy(t, true) +} + +// Exercise both production service entry points and capture their actual +// outbound request. A synthetic success proves conversion only, not media +// understanding by any provider. +func testCompatibilityMediaPolicy(t *testing.T, antigravity bool) { + t.Helper() + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, stream := range []bool{false, true} { + for _, field := range []string{"image", "file"} { + for _, mime := range []string{"video/mp4", "audio/mpeg", "application/octet-stream", "image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf", "text/plain"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s/%s", endpoint, stream, field, mime), func(t *testing.T) { + uri := "data:" + mime + ";base64,c3ludGhldGlj" + part := map[string]any{"type": "input_image", "image_url": uri} + if field == "file" { + part = map[string]any{"type": "input_file", "file_data": uri} + } + request := map[string]any{"model": "gemini-2.5-flash", "stream": stream} + if antigravity { + request["model"] = "gemini-3.1-pro-high" + } + if endpoint == "chat/completions" { + part = map[string]any{"type": "image_url", "image_url": map[string]string{"url": uri}} + if field == "file" { + part = map[string]any{"type": "file", "file": map[string]string{"file_data": uri}} + } + request["messages"] = []any{map[string]any{"role": "user", "content": []any{part}}} + } else { + request["input"] = []any{map[string]any{"role": "user", "content": []any{part}}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{compatibilityMediaSuccessResponse(stream, antigravity)}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + if antigravity { + require.Equal(t, "Bearer fresh-oauth-token", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("x-goog-api-key")) + require.Equal(t, "/v1internal:streamGenerateContent", req.URL.Path) + } else { + require.Equal(t, "synthetic-api-key", req.Header.Get("x-goog-api-key")) + require.Empty(t, req.Header.Get("Authorization")) + action := ":generateContent" + if stream { + action = ":streamGenerateContent" + } + require.True(t, strings.HasSuffix(req.URL.Path, action)) + } + }, + } + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/"+endpoint, body) + var result *ForwardResult + if antigravity { + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + if endpoint == "chat/completions" { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + } else { + result, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + } + } else { + svc := &GeminiMessagesCompatService{tokenProvider: &GeminiTokenProvider{}, httpUpstream: upstream, cfg: &config.Config{}} + account := &Account{ID: 9812, Platform: PlatformGemini, Type: AccountTypeAPIKey, Concurrency: 1, + Credentials: map[string]any{"api_key": "synthetic-api-key"}} + if endpoint == "chat/completions" { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body) + } else { + result, err = svc.ForwardAsResponses(context.Background(), c, account, body) + } + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, 1, upstream.callCount) + require.Len(t, upstream.requestBodies, 1) + require.Contains(t, recorder.Body.String(), "ok") + root := "contents" + if antigravity { + root = "request.contents" + require.False(t, gjson.GetBytes(upstream.requestBodies[0], "contents").Exists()) + } else { + require.False(t, gjson.GetBytes(upstream.requestBodies[0], "request").Exists()) + } + wire := gjson.GetBytes(upstream.requestBodies[0], root+".0.parts.0") + if mime == "text/plain" { + require.Equal(t, "synthetic", wire.Get("text").String()) + } else if field == "file" && mime != "application/pdf" { + // Both fixtures target Gemini models, so Antigravity also + // uses the shared converter's legacy document-as-text carrier. + // Only PDF/plain document handling is upgraded. + legacy := gjson.Parse(wire.Get("text").String()) + require.Equal(t, "document", legacy.Get("type").String()) + require.Equal(t, mime, legacy.Get("source.media_type").String()) + require.Equal(t, "c3ludGhldGlj", legacy.Get("source.data").String()) + } else { + require.Equal(t, mime, wire.Get("inlineData.mimeType").String()) + require.Equal(t, "c3ludGhldGlj", wire.Get("inlineData.data").String()) + } + }) + } + } + } + } +} + +// Code Assist and Antigravity wrap Gemini results and always stream upstream; +// AI Studio API-key routes use plain JSON or plain SSE to match clientStream. +func compatibilityMediaSuccessResponse(clientStream, codeAssist bool) *http.Response { + body := `{"responseId":"synthetic-media","candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":8,"candidatesTokenCount":3}}` + if codeAssist { + body = `{"response":` + body + `}` + } + contentType := "application/json" + if clientStream || codeAssist { + contentType = "text/event-stream" + body = "data: " + body + "\n\n" + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(body))} +} + +func TestGeminiCompatibilityMediaPolicyOAuthControls(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, endpoint := range []string{"chat/completions", "responses"} { + t.Run(fmt.Sprintf("%s/stream=%t", endpoint, stream), func(t *testing.T) { + request := map[string]any{"model": "gemini-2.5-flash", "stream": stream} + const uri = "data:video/mp4;base64,c3ludGhldGlj" + if endpoint == "chat/completions" { + request["messages"] = []any{map[string]any{"role": "user", "content": []any{map[string]any{"type": "image_url", "image_url": map[string]string{"url": uri}}}}} + } else { + request["input"] = []any{map[string]any{"role": "user", "content": []any{map[string]string{"type": "input_image", "image_url": uri}}}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{compatibilityMediaSuccessResponse(stream, true)}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + require.Equal(t, "Bearer synthetic-token", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("x-goog-api-key")) + require.Equal(t, "/v1internal:streamGenerateContent", req.URL.Path) + }, + } + svc := &GeminiMessagesCompatService{tokenProvider: &GeminiTokenProvider{}, httpUpstream: upstream, cfg: &config.Config{}} + account := &Account{ID: 9813, Platform: PlatformGemini, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "synthetic-token", "project_id": "synthetic-project"}} + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/"+endpoint, body) + if endpoint == "responses" { + result, err := svc.ForwardAsResponses(context.Background(), c, account, body) + require.Error(t, err) + require.Nil(t, result) + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), "Gemini OAuth accounts do not support Responses compatibility") + require.Zero(t, upstream.callCount) + require.Empty(t, upstream.requestBodies) + return + } + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, recorder.Code) + require.Contains(t, recorder.Body.String(), "ok") + require.Equal(t, 1, upstream.callCount) + require.Len(t, upstream.requestBodies, 1) + wire := gjson.GetBytes(upstream.requestBodies[0], "request.contents.0.parts.0.inlineData") + require.Equal(t, "video/mp4", wire.Get("mimeType").String()) + require.Equal(t, "c3ludGhldGlj", wire.Get("data").String()) + }) + } + } +} + +func TestGeminiDocumentsSurviveAnthropicMIMEBridge(t *testing.T) { + for _, tc := range []struct { + mime string + path string + want string + }{ + {"text/plain", "contents.0.parts.0.text", "synthetic"}, + {"application/pdf", "contents.0.parts.0.inlineData.data", "c3ludGhldGlj"}, + } { + t.Run(tc.mime, func(t *testing.T) { + var req apicompat.ResponsesRequest + input := `{"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:` + tc.mime + `;base64,c3ludGhldGlj"}]}]}` + require.NoError(t, json.Unmarshal([]byte(input), &req)) + anthropic, err := apicompat.ResponsesToAnthropicRequest(&req) + require.NoError(t, err) + body, err := json.Marshal(anthropic) + require.NoError(t, err) + wire, err := convertClaudeMessagesToGeminiGenerateContent(body, "gemini-2.5-flash") + require.NoError(t, err) + require.Equal(t, tc.want, gjson.GetBytes(wire, tc.path).String()) + }) + } + textSource := map[string]any{"type": "document", "source": map[string]any{"type": "text", "media_type": "text/plain", "data": "synthetic"}} + require.Equal(t, "synthetic", extractClaudeContentText([]any{textSource})) + require.Empty(t, extractClaudeToolResultImageParts([]any{textSource})) +} diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index d77d9c9eaa8e..69b899a9dcd6 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -46,12 +46,20 @@ func (s *GatewayService) ForwardAsChatCompletions( } originalModel := ccReq.Model clientStream := ccReq.Stream + if err := apicompat.ValidateChatCompletionsAnthropicMedia(&ccReq); err != nil { + writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } // 2. Convert CC → Responses → Anthropic (chained conversion) responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq) if err != nil { return nil, fmt.Errorf("convert chat completions to responses: %w", err) } + if err := apicompat.PreserveChatCompletionsAnthropicToolMedia(&ccReq, responsesReq); err != nil { + writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to convert tool media") + return nil, err + } // Resolve the final upstream model before model-specific conversion. mappedModel := originalModel @@ -74,9 +82,10 @@ func (s *GatewayService) ForwardAsChatCompletions( return nil, err } responsesReq.Model = mappedModel - anthropicReq, err := apicompat.ResponsesToAnthropicRequest(responsesReq) + anthropicReq, err := apicompat.ResponsesToAnthropicRequestWithOptions(responsesReq, apicompat.ResponsesToAnthropicOptions{StrictMedia: true}) if err != nil { - if isClaude55SignedThinkingModel(mappedModel) { + var mediaErr *apicompat.AnthropicMediaError + if errors.As(err, &mediaErr) || isClaude55SignedThinkingModel(mappedModel) { writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } return nil, fmt.Errorf("convert responses to anthropic: %w", err) diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 41244b8496de..d25fe543699a 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -85,9 +85,10 @@ func (s *GatewayService) ForwardAsResponses( return nil, err } responsesReq.Model = mappedModel - anthropicReq, err := apicompat.ResponsesToAnthropicRequest(&responsesReq) + anthropicReq, err := apicompat.ResponsesToAnthropicRequestWithOptions(&responsesReq, apicompat.ResponsesToAnthropicOptions{StrictMedia: true}) if err != nil { - if isClaude55SignedThinkingModel(mappedModel) { + var mediaErr *apicompat.AnthropicMediaError + if errors.As(err, &mediaErr) || isClaude55SignedThinkingModel(mappedModel) { writeResponsesError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } return nil, fmt.Errorf("convert responses to anthropic: %w", err) diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 1071ec6bc178..bdf5b346dc95 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -3702,8 +3702,22 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str toolImageParts = append(toolImageParts, images...) } parts = append(parts, map[string]any{"functionResponse": response}) - case "image": + case "image", "document": if src, ok := bm["source"].(map[string]any); ok { + if bm["type"] == "document" && src["media_type"] != "application/pdf" && src["media_type"] != "text/plain" { + // Keep legacy file carriers for non-Anthropic targets. + // Their MIME is not an Anthropic rejection policy here. + if b, err := json.Marshal(bm); err == nil { + parts = append(parts, map[string]any{"text": string(b)}) + } + continue + } + if src["type"] == "text" && src["media_type"] == "text/plain" { + if data, ok := src["data"].(string); ok { + parts = append(parts, map[string]any{"text": data}) + } + continue + } if srcType, _ := src["type"].(string); srcType == "base64" { mediaType, _ := src["media_type"].(string) data, _ := src["data"].(string) @@ -3785,6 +3799,13 @@ func extractClaudeContentText(v any) string { _, _ = sb.WriteString(text) } } + if pm["type"] == "document" { + if source, ok := pm["source"].(map[string]any); ok && source["type"] == "text" && source["media_type"] == "text/plain" { + if text, ok := source["data"].(string); ok { + _, _ = sb.WriteString(text) + } + } + } } return sb.String() default: @@ -3802,7 +3823,7 @@ func extractClaudeToolResultImageParts(v any) []any { parts := make([]any, 0) for _, part := range arr { pm, ok := part.(map[string]any) - if !ok || pm["type"] != "image" { + if !ok || (pm["type"] != "image" && pm["type"] != "document") { continue } source, ok := pm["source"].(map[string]any) diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index e284960db8e0..3e21d408bdc6 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -56,6 +56,10 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( return nil, fmt.Errorf("missing model in request") } clientStream := ccReq.Stream + if err := apicompat.ValidateChatCompletionsAnthropicMedia(&ccReq); err != nil { + writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return nil, err + } // 2. Convert CC → Responses → Anthropic (chained conversion) responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq) @@ -63,6 +67,10 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to convert request") return nil, fmt.Errorf("convert chat completions to responses: %w", err) } + if err := apicompat.PreserveChatCompletionsAnthropicToolMedia(&ccReq, responsesReq); err != nil { + writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to convert tool media") + return nil, err + } // Resolve the mapped model before choosing its thinking/tool protocol. billingModel := resolveOpenAIForwardModel(account, originalModel, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) @@ -71,7 +79,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( return nil, err } responsesReq.Model = upstreamModel - anthropicReq, err := apicompat.ResponsesToAnthropicRequest(responsesReq) + anthropicReq, err := apicompat.ResponsesToAnthropicRequestWithOptions(responsesReq, apicompat.ResponsesToAnthropicOptions{StrictMedia: true}) if err != nil { writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, fmt.Errorf("convert responses to anthropic: %w", err) diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index ca5606ede7c7..3104eb4114ad 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -73,7 +73,7 @@ func (s *OpenAIGatewayService) forwardResponsesViaNativeAnthropic( return nil, err } responsesReq.Model = upstreamModel - anthropicReq, err := apicompat.ResponsesToAnthropicRequest(&responsesReq) + anthropicReq, err := apicompat.ResponsesToAnthropicRequestWithOptions(&responsesReq, apicompat.ResponsesToAnthropicOptions{StrictMedia: true}) if err != nil { writeResponsesError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, fmt.Errorf("convert responses to anthropic: %w", err)