Fix typevar variance for agent deps #3319
                
     Merged
            
            
          
      
        
          +110
        
        
          −11
        
        
          
        
      
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Right now, the variance of
RunContextis the reverse of what it should be, because we are reusing a typevar rather than creating a type-specific one. Because of this, you can't define reusable tools that use deps but aren't exact matches on the agent deps type. This change fixes the typing (it is actually incorrect, this is a typing bugfix not just a change), and in particular makes it work to define tools as accepting supertypes of the agent's actual deps class, as you can see in the newtyped_deps.pyfile I added as a typing test.(I recall pointing out the potential for reusing typevars to cause issues when we first did it; it won't surprise me if it remains an issue. In general I would strongly prefer to use
infer_varianceif it wasn't for the fact that it makes it impossible to have dataclasses in 3.13 that are covariant due to the__replace__method.)This addresses the issue described in this thread: https://pydanticlogfire.slack.com/archives/C083V7PMHHA/p1762185662720909