diff --git a/sdk/api/handlers/gemini/gemini_handlers.go b/sdk/api/handlers/gemini/gemini_handlers.go index 6af2431255..575da6bf5e 100644 --- a/sdk/api/handlers/gemini/gemini_handlers.go +++ b/sdk/api/handlers/gemini/gemini_handlers.go @@ -12,6 +12,8 @@ import ( "strings" "time" + "github.com/MoeForge/moego/json" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" . "github.com/router-for-me/CLIProxyAPI/v8/internal/constant" @@ -423,12 +425,131 @@ func (h *GeminiAPIHandler) forwardGeminiStream(c *gin.Context, flusher http.Flus if errMsg.Error != nil && errMsg.Error.Error() != "" { errText = errMsg.Error.Error() } - body := handlers.BuildErrorResponseBody(status, errText) + body := buildGeminiErrorResponseBody(status, errText) if alt == "" { - _, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", string(body)) + // Emit a raw Google APIError JSON frame without "event: error" or "data:" + // wrapping so google.golang.org/genai's iterateResponseStream decodes it + // as *genai.APIError in its default branch across all SDK versions. + _, _ = fmt.Fprintf(c.Writer, "%s\n\n", string(body)) } else { _, _ = c.Writer.Write(body) } }, }) } + +type geminiErrorResponse struct { + Error *geminiErrorDetail `json:"error"` +} + +type geminiErrorDetail struct { + Code int `json:"code"` + Message string `json:"message"` + Status string `json:"status"` + Details []map[string]any `json:"details,omitempty"` +} + +func geminiRPCStatusFromHTTPStatus(status int) string { + switch status { + case http.StatusBadRequest: + return "INVALID_ARGUMENT" + case http.StatusUnauthorized: + return "UNAUTHENTICATED" + case http.StatusForbidden: + return "PERMISSION_DENIED" + case http.StatusNotFound: + return "NOT_FOUND" + case http.StatusRequestTimeout, http.StatusGatewayTimeout: + return "DEADLINE_EXCEEDED" + case http.StatusConflict: + return "ABORTED" + case http.StatusTooManyRequests: + return "RESOURCE_EXHAUSTED" + case 499: + return "CANCELLED" + case http.StatusNotImplemented: + return "UNIMPLEMENTED" + case http.StatusBadGateway, http.StatusServiceUnavailable: + return "UNAVAILABLE" + default: + if status >= http.StatusInternalServerError { + return "INTERNAL" + } + if status >= http.StatusBadRequest { + return "INVALID_ARGUMENT" + } + return "UNKNOWN" + } +} + +func extractGeminiErrorMessage(raw, fallback string) string { + if !ojson.Valid(raw) { + return fallback + } + root := ojson.Parse(raw) + for _, path := range []string{"error.message", "0.error.message", "message"} { + res := root.Get(path) + if res.Type == ojson.String { + if msg := strings.TrimSpace(res.String()); msg != "" { + return msg + } + } + } + return fallback +} + +// buildGeminiErrorResponseBody builds a compact single-line Google RPC error +// JSON body compatible with google.golang.org/genai's APIError struct. +func buildGeminiErrorResponseBody(status int, errText string) []byte { + if status <= 0 { + status = http.StatusInternalServerError + } + trimmed := strings.TrimSpace(errText) + if trimmed == "" { + trimmed = http.StatusText(status) + } + + if trimmed != "" && ojson.Valid(trimmed) { + var existing geminiErrorResponse + if errUnmarshal := json.Unmarshal([]byte(trimmed), &existing); errUnmarshal == nil && existing.Error != nil && existing.Error.Code > 0 { + if strings.TrimSpace(existing.Error.Status) == "" { + existing.Error.Status = geminiRPCStatusFromHTTPStatus(existing.Error.Code) + } + if strings.TrimSpace(existing.Error.Message) == "" { + existing.Error.Message = http.StatusText(existing.Error.Code) + } + if payload, errMarshal := json.Marshal(existing); errMarshal == nil { + return payload + } + } + if strings.HasPrefix(trimmed, "[") { + var existingList []geminiErrorResponse + if errUnmarshal := json.Unmarshal([]byte(trimmed), &existingList); errUnmarshal == nil && len(existingList) > 0 && existingList[0].Error != nil && existingList[0].Error.Code > 0 { + entry := existingList[0] + if strings.TrimSpace(entry.Error.Status) == "" { + entry.Error.Status = geminiRPCStatusFromHTTPStatus(entry.Error.Code) + } + if strings.TrimSpace(entry.Error.Message) == "" { + entry.Error.Message = http.StatusText(entry.Error.Code) + } + if payload, errMarshal := json.Marshal(entry); errMarshal == nil { + return payload + } + } + } + } + + message := extractGeminiErrorMessage(trimmed, trimmed) + rpcStatus := geminiRPCStatusFromHTTPStatus(status) + payload, errMarshal := json.Marshal(geminiErrorResponse{ + Error: &geminiErrorDetail{ + Code: status, + Message: message, + Status: rpcStatus, + }, + }) + if errMarshal != nil { + return []byte(fmt.Sprintf(`{"error":{"code":%d,"message":%q,"status":%q}}`, status, message, rpcStatus)) + } + return payload +} diff --git a/sdk/api/handlers/gemini/gemini_handlers_stream_error_test.go b/sdk/api/handlers/gemini/gemini_handlers_stream_error_test.go index 500b82d73f..2216fbb7cd 100644 --- a/sdk/api/handlers/gemini/gemini_handlers_stream_error_test.go +++ b/sdk/api/handlers/gemini/gemini_handlers_stream_error_test.go @@ -1,9 +1,11 @@ package gemini import ( + "bytes" "context" "errors" "fmt" + "io" "net/http" "net/http/httptest" "strings" @@ -11,8 +13,11 @@ import ( "testing" "time" + "github.com/MoeForge/moego/json" "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -174,7 +179,259 @@ func TestGeminiStreamGenerateContentSendKeepAliveBeforeFTWritesSSEErrorOnFailure if !strings.HasPrefix(body, "\n\n") { t.Fatalf("missing empty SSE keep-alive frame: %q", body) } - if !strings.Contains(body, "event: error\ndata: ") || !strings.Contains(body, "gemini upstream failed after keepalive") { - t.Fatalf("missing Gemini SSE JSON error event after keepalive: %q", body) + if strings.Contains(body, "event: error") { + t.Fatalf("unexpected SSE event: error frame after keepalive: %q", body) + } + payloads, apiErrors := parseGoGenAIStream(t, recorder.Body.Bytes()) + if len(payloads) != 0 { + t.Fatalf("payload count = %d, want 0; body=%q", len(payloads), body) + } + if len(apiErrors) != 1 { + t.Fatalf("APIError count = %d, want 1; body=%q", len(apiErrors), body) + } + if apiErrors[0].Code != http.StatusInternalServerError || apiErrors[0].Status != "INTERNAL" || !strings.Contains(apiErrors[0].Message, "gemini upstream failed after keepalive") { + t.Fatalf("APIError = %+v, want 500 INTERNAL containing keepalive error", apiErrors[0]) + } +} + +type testStatusError struct { + code int + msg string +} + +func (e testStatusError) Error() string { return e.msg } +func (e testStatusError) StatusCode() int { return e.code } + +type goGenAIAPIError struct { + Code int `json:"code,omitempty"` + Message string `json:"message,omitempty"` + Status string `json:"status,omitempty"` + Details []map[string]any `json:"details,omitempty"` +} + +type goGenAIResponseWithError struct { + ErrorInfo *goGenAIAPIError `json:"error,omitempty"` +} + +// parseGoGenAIStream mirrors google.golang.org/genai's iterateResponseStream +// framing and default-branch APIError decoding so both pre- and post-2026-10 +// versions of the Go GenAI SDK accept the terminal error frame. +func parseGoGenAIStream(t *testing.T, body []byte) ([][]byte, []goGenAIAPIError) { + t.Helper() + var payloads [][]byte + var apiErrors []goGenAIAPIError + for _, frame := range bytes.Split(body, []byte("\n\n")) { + if len(frame) == 0 { + continue + } + prefix, data, _ := bytes.Cut(frame, []byte(":")) + switch string(prefix) { + case "data": + payloads = append(payloads, bytes.TrimSpace(data)) + default: + var respWithError goGenAIResponseWithError + if errUnmarshal := json.Unmarshal(frame, &respWithError); errUnmarshal != nil || respWithError.ErrorInfo == nil { + t.Fatalf("iterateResponseStream: invalid stream chunk: %s:%s (unmarshal err=%v)", string(prefix), string(data), errUnmarshal) + } + apiErrors = append(apiErrors, *respWithError.ErrorInfo) + } + } + return payloads, apiErrors +} + +func TestGeminiStreamGenerateContentPostCommitErrorEmitsGoGenAIAPIError(t *testing.T) { + gin.SetMode(gin.TestMode) + + thoughtChunk := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"reasoning"}]}}]}`) + + tests := []struct { + name string + query string + streamErr error + wantCode int + wantStatus string + wantMessage string + wantDetails int + }{ + { + name: "plain_text_502_after_thought_chunk", + query: "?alt=sse", + streamErr: testStatusError{code: http.StatusBadGateway, msg: "upstream returned zero output with finishReason MALFORMED_FUNCTION_CALL"}, + wantCode: http.StatusBadGateway, + wantStatus: "UNAVAILABLE", + wantMessage: "upstream returned zero output with finishReason MALFORMED_FUNCTION_CALL", + }, + { + name: "upstream_google_rpc_json_error_preserved", + query: "?alt=sse", + streamErr: testStatusError{ + code: http.StatusTooManyRequests, + msg: "{\n \"error\": {\n \"code\": 429,\n \"message\": \"Quota exceeded for model\",\n \"status\": \"RESOURCE_EXHAUSTED\",\n \"details\": [{\"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\", \"reason\": \"RATE_LIMIT_EXCEEDED\"}]\n }\n}", + }, + wantCode: http.StatusTooManyRequests, + wantStatus: "RESOURCE_EXHAUSTED", + wantMessage: "Quota exceeded for model", + wantDetails: 1, + }, + { + name: "openai_style_json_error_converted_to_google_rpc", + query: "?alt=sse", + streamErr: testStatusError{code: http.StatusBadGateway, msg: `{"error":{"message":"backend failure","type":"server_error","code":"internal_server_error"}}`}, + wantCode: http.StatusBadGateway, + wantStatus: "UNAVAILABLE", + wantMessage: "backend failure", + }, + { + name: "non_sse_alt_json_emits_google_rpc_error", + query: "?alt=json", + streamErr: testStatusError{code: http.StatusBadGateway, msg: "upstream returned zero output with finishReason MALFORMED_FUNCTION_CALL"}, + wantCode: http.StatusBadGateway, + wantStatus: "UNAVAILABLE", + wantMessage: "upstream returned zero output with finishReason MALFORMED_FUNCTION_CALL", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + chunks := make(chan coreexecutor.StreamChunk, 2) + chunks <- coreexecutor.StreamChunk{Payload: thoughtChunk} + chunks <- coreexecutor.StreamChunk{Err: tc.streamErr} + close(chunks) + + exec := &preFTKeepAliveGeminiExecutor{chunks: chunks} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(exec) + model := "post-commit-err-gemini-" + tc.name + auth := &coreauth.Auth{ID: "post-commit-err-auth-" + tc.name, Provider: exec.Identifier(), Status: coreauth.StatusActive} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewGeminiAPIHandler(base) + router := gin.New() + router.POST("/v1beta/models/*action", h.GeminiHandler) + + req := httptest.NewRequest( + http.MethodPost, + "/v1beta/models/"+model+":streamGenerateContent"+tc.query, + strings.NewReader(`{"contents":[{"parts":[{"text":"hi"}]}]}`), + ) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%q", rec.Code, rec.Body.String()) + } + body := rec.Body.Bytes() + if bytes.Contains(body, []byte("event: error")) { + t.Fatalf("unexpected SSE event: error frame in body: %q", string(body)) + } + + if tc.query == "?alt=json" { + if !bytes.HasPrefix(body, thoughtChunk) { + t.Fatalf("non-SSE body missing initial chunk prefix: %q", string(body)) + } + tail := bytes.TrimSpace(body[len(thoughtChunk):]) + var respWithError goGenAIResponseWithError + if errUnmarshal := json.Unmarshal(tail, &respWithError); errUnmarshal != nil || respWithError.ErrorInfo == nil { + t.Fatalf("non-SSE trailing error failed APIError unmarshal: err=%v tail=%q", errUnmarshal, string(tail)) + } + if respWithError.ErrorInfo.Code != tc.wantCode || respWithError.ErrorInfo.Status != tc.wantStatus || respWithError.ErrorInfo.Message != tc.wantMessage { + t.Fatalf("APIError = %+v, want code=%d status=%q message=%q", respWithError.ErrorInfo, tc.wantCode, tc.wantStatus, tc.wantMessage) + } + return + } + + payloads, apiErrors := parseGoGenAIStream(t, body) + if len(payloads) != 1 { + t.Fatalf("payload count = %d, want 1; body=%q", len(payloads), string(body)) + } + if len(apiErrors) != 1 { + t.Fatalf("APIError count = %d, want 1; body=%q", len(apiErrors), string(body)) + } + got := apiErrors[0] + if got.Code != tc.wantCode || got.Status != tc.wantStatus || got.Message != tc.wantMessage { + t.Fatalf("APIError = %+v, want code=%d status=%q message=%q", got, tc.wantCode, tc.wantStatus, tc.wantMessage) + } + if len(got.Details) != tc.wantDetails { + t.Fatalf("APIError details count = %d, want %d; got=%+v", len(got.Details), tc.wantDetails, got.Details) + } + }) + } +} + +func TestGeminiStreamGenerateContentPostThoughtMalformedFunctionCallThroughAntigravity(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"planning tool call..."}]}}],"modelVersion":"gemini-4-neon"}}`+"\n\n") + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig-only","text":""}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"thoughtsTokenCount":10,"totalTokenCount":60},"modelVersion":"gemini-4-neon"}}`+"\n\n") + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(executor.NewAntigravityExecutor(cfg)) + + model := "gemini-4-neon-issue8547" + auth := &coreauth.Auth{ + ID: "ag-issue8547", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-8547", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-8547", + }, + Attributes: map[string]string{"base_url": upstream.URL}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register error = %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewGeminiAPIHandler(base) + router := gin.New() + router.POST("/v1beta/models/*action", h.GeminiHandler) + + req := httptest.NewRequest( + http.MethodPost, + "/v1beta/models/"+model+":streamGenerateContent?alt=sse", + strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"run tool"}]}]}`), + ) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 after thought chunk commits stream; body=%q", rec.Code, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "event: error") { + t.Fatalf("unexpected SSE event: error frame: %q", rec.Body.String()) + } + + payloads, apiErrors := parseGoGenAIStream(t, rec.Body.Bytes()) + if len(payloads) != 1 { + t.Fatalf("payload count = %d, want 1 (thought chunk); body=%q", len(payloads), rec.Body.String()) + } + if len(apiErrors) != 1 { + t.Fatalf("APIError count = %d, want 1; body=%q", len(apiErrors), rec.Body.String()) + } + if apiErrors[0].Code != http.StatusBadGateway || apiErrors[0].Status != "UNAVAILABLE" || !strings.Contains(apiErrors[0].Message, "MALFORMED_FUNCTION_CALL") { + t.Fatalf("APIError = %+v, want 502 UNAVAILABLE containing MALFORMED_FUNCTION_CALL", apiErrors[0]) } }