client

package
v0.260604.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 4, 2026 License: MPL-2.0 Imports: 38 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultMaxIdleConns        = 100
	DefaultMaxIdleConnsPerHost = 2
)

Go defaults for reference (not used directly, only for documentation)

View Source
const (
	DefaultTransportTTL             = 15 * time.Minute // Default time-to-live for cached transports (reduced from 120min for better session lifecycle management)
	DefaultTransportCleanupInterval = 5 * time.Minute  // Default interval for cleanup task
)

Constants for transport TTL and cleanup interval

View Source
const ClaudeCodeSystemBody = "" /* 150-byte string literal not displayed */
View Source
const ClaudeCodeSystemHeader = "You are Claude Code, Anthropic's official CLI for Claude."

ClaudeCodeSystemHeader is a special system message for Claude Code OAuth subscriptions

View Source
const (
	ProxyURLNone = "none" // Special value to force direct connection (disable proxy)
)

Constants for proxy URL values

View Source
const ScenarioContextKey contextKey = "scenario"

Variables

ProviderTransportPolicy defines transport reuse behavior per provider type OAuth providers generally require per-session transports for proper isolation

Functions

func CreateHTTPClientWithProxy

func CreateHTTPClientWithProxy(proxyURL string) *http.Client

CreateHTTPClientWithProxy creates an HTTP client with proxy support. Supports http(s) and socks5 proxy URLs; falls back to http.DefaultClient for any parse/scheme failure (logged).

func GetProbeToolChoiceAutoAnthropic added in v0.260514.1

func GetProbeToolChoiceAutoAnthropic() anthropic.ToolChoiceUnionParam

GetProbeToolChoiceAutoAnthropic returns auto tool choice for testing

func GetProbeToolsAnthropic added in v0.260514.1

func GetProbeToolsAnthropic() []anthropic.ToolUnionParam

GetProbeToolsAnthropic returns predefined tools in Anthropic format for probe testing Uses bash tool to execute simple file system operations

func GetProbeToolsOpenAI added in v0.260514.1

func GetProbeToolsOpenAI() []openai.ChatCompletionToolUnionParam

GetProbeToolsOpenAI returns predefined tools in OpenAI format for probe testing Uses bash tool to execute simple file system operations

func GetProbeToolsResponses added in v0.260514.1

func GetProbeToolsResponses() []responses.ToolUnionParam

GetProbeToolsResponses returns predefined tools in Responses API format for probe testing Uses bash tool to execute simple file system operations

func IsClaudeOAuthToken

func IsClaudeOAuthToken(apiKey string) bool

IsClaudeOAuthToken checks if the given API key is a Claude OAuth token by checking for the "sk-ant-oat" prefix.

func IsModelsEndpointNotSupported

func IsModelsEndpointNotSupported(err error) bool

IsModelsEndpointNotSupported checks if an error is ErrModelsEndpointNotSupported

func NewTransportKey added in v0.260414.2000

func NewTransportKey(providerUUID string, proxyURL string, issuer ai.Issuer, session typ.SessionID) typ.TransportKey

NewTransportKey creates a TransportKey with optional session scoping. sessionID is only included in the key when:

  • issuer requires per-session transports (TransportPerSession)
  • session is not empty
  • session is not an IP-fallback (which would create one transport per IP)

Note: ProxyURL is NOT part of the key. Proxy is a provider configuration that affects how the transport is created, but doesn't create a separate pool.

func SetTransportConfig

func SetTransportConfig(config *TransportConfig)

SetTransportConfig updates the transport pool configuration Pass nil to reset to Go defaults (backward compatible) When RespectEnvProxy changes, cached transports are cleared immediately so that the new proxy policy takes effect on the next request.

Types

type AnthropicClient

type AnthropicClient struct {
	// contains filtered or unexported fields
}

AnthropicClient wraps the Anthropic SDK client

func NewAnthropicClient

func NewAnthropicClient(provider *typ.Provider, model string, sessionID typ.SessionID, extraOptions ...anthropicOption.RequestOption) (*AnthropicClient, error)

NewAnthropicClient creates a new Anthropic client wrapper

func (*AnthropicClient) APIStyle

func (c *AnthropicClient) APIStyle() protocol.APIStyle

ProviderType returns the provider type

func (*AnthropicClient) BetaMessagesNew

BetaMessagesNew creates a new beta message request

func (*AnthropicClient) BetaMessagesNewStreaming

BetaMessagesNewStreaming creates a new beta streaming message request

func (*AnthropicClient) Client

func (c *AnthropicClient) Client() *anthropic.Client

Client returns the underlying Anthropic SDK client

func (*AnthropicClient) Close

func (c *AnthropicClient) Close() error

Close closes any resources held by the client

func (*AnthropicClient) GetProvider

func (c *AnthropicClient) GetProvider() *typ.Provider

GetProvider returns the provider for this client

func (*AnthropicClient) HttpClient

func (c *AnthropicClient) HttpClient() *http.Client

HttpClient returns the underlying HTTP client for passthrough/proxy operations

func (*AnthropicClient) ListModels

func (c *AnthropicClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models from the Anthropic API

func (*AnthropicClient) MessagesCountTokens

MessagesCountTokens counts tokens for a message request

func (*AnthropicClient) MessagesNew

MessagesNew creates a new message request

func (*AnthropicClient) MessagesNewStreaming

MessagesNewStreaming creates a new streaming message request

func (*AnthropicClient) Probe added in v0.260514.1

func (c *AnthropicClient) Probe(ctx context.Context, model string) ProbeResult

ProbeChatEndpoint tests the messages endpoint with a minimal request

func (*AnthropicClient) ProbeModelsEndpoint

func (c *AnthropicClient) ProbeModelsEndpoint(ctx context.Context) ProbeResult

ProbeModelsEndpoint tests the models list endpoint

func (*AnthropicClient) ProbeOptionsEndpoint

func (c *AnthropicClient) ProbeOptionsEndpoint(ctx context.Context) ProbeResult

ProbeOptionsEndpoint tests basic connectivity with an OPTIONS request

func (*AnthropicClient) ProbeStream added in v0.260514.1

func (c *AnthropicClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with configurable test mode (public interface)

func (*AnthropicClient) SetRecordSink

func (c *AnthropicClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client

type AnthropicClientInterface added in v0.260514.1

type AnthropicClientInterface interface {
	// Core API methods
	MessagesNew(ctx context.Context, req *anthropic.MessageNewParams) (*anthropic.Message, error)
	MessagesNewStreaming(ctx context.Context, req *anthropic.MessageNewParams) *anthropicstream.Stream[anthropic.MessageStreamEventUnion]
	BetaMessagesNew(ctx context.Context, req *anthropic.BetaMessageNewParams) (*anthropic.BetaMessage, error)
	BetaMessagesNewStreaming(ctx context.Context, req *anthropic.BetaMessageNewParams) *anthropicstream.Stream[anthropic.BetaRawMessageStreamEventUnion]
	MessagesCountTokens(ctx context.Context, req *anthropic.MessageCountTokensParams) (*anthropic.MessageTokensCount, error)
	BetaMessagesCountTokens(ctx context.Context, req *anthropic.BetaMessageCountTokensParams) (*anthropic.BetaMessageTokensCount, error)

	// Utility methods
	ListModels(ctx context.Context) ([]string, error)
	Close() error
	GetProvider() *typ.Provider
	APIStyle() protocol.APIStyle
	SetRecordSink(sink *obs.Sink)
	Client() *anthropic.Client

	// Prober interface methods
	Probe(ctx context.Context, model string) ProbeResult
	ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)
}

AnthropicClientInterface defines the contract for Anthropic-compatible clients. Both AnthropicClient and ClaudeClient (for Claude Code OAuth) implement this interface.

type AntigravityClient added in v0.260531.1

type AntigravityClient struct {
	*GoogleClient
}

AntigravityClient wraps GoogleClient with Antigravity OAuth-specific behaviors. Antigravity also speaks the Google Code Assist envelope (same host as Gemini CLI) but with its own User-Agent, requestType, and the "request"/"requestId" shape from the desktop Antigravity client.

func NewAntigravityClient added in v0.260531.1

func NewAntigravityClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*AntigravityClient, error)

NewAntigravityClient builds an AntigravityClient. The project_id must already be present in OAuth metadata (populated by AntigravityHook.AfterToken via loadCodeAssist).

type ClaudeClient added in v0.260514.1

type ClaudeClient struct {
	*AnthropicClient
}

ClaudeClient wraps AnthropicClient with Claude Code OAuth-specific behaviors. It creates an Anthropic SDK client directly with Claude Code headers and middleware, then embeds it for delegation.

Claude Code (Claude Code OAuth) limitations: - Does NOT support /models endpoint (returns 404) - Requires special headers (applied via SDK options) - Requires tool prefix stripping (applied via middleware)

func NewClaudeClient added in v0.260514.1

func NewClaudeClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*ClaudeClient, error)

NewClaudeClient creates a new Claude client wrapper. It builds an Anthropic SDK client with Claude Code specific headers and middleware, then wraps it in an AnthropicClient for delegation.

func (*ClaudeClient) APIStyle added in v0.260514.1

func (c *ClaudeClient) APIStyle() protocol.APIStyle

APIStyle returns the API style.

func (*ClaudeClient) BetaMessagesCountTokens added in v0.260514.1

BetaMessagesCountTokens counts tokens for a beta message request.

func (*ClaudeClient) BetaMessagesNew added in v0.260514.1

BetaMessagesNew creates a new beta message request.

func (*ClaudeClient) BetaMessagesNewStreaming added in v0.260514.1

BetaMessagesNewStreaming creates a new beta streaming message request.

func (*ClaudeClient) Client added in v0.260514.1

func (c *ClaudeClient) Client() *anthropic.Client

Client returns the underlying Anthropic SDK client.

func (*ClaudeClient) Close added in v0.260514.1

func (c *ClaudeClient) Close() error

Close closes any resources held by the client.

func (*ClaudeClient) GetProvider added in v0.260514.1

func (c *ClaudeClient) GetProvider() *typ.Provider

GetProvider returns the provider for this client.

func (*ClaudeClient) Guard added in v0.260514.1

func (*ClaudeClient) GuardBeta added in v0.260514.1

func (*ClaudeClient) ListModels added in v0.260514.1

func (c *ClaudeClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models. For Claude Code OAuth, this returns an error as the token cannot access /models endpoint.

func (*ClaudeClient) MessagesCountTokens added in v0.260514.1

MessagesCountTokens counts tokens for a message request.

func (*ClaudeClient) MessagesNew added in v0.260514.1

MessagesNew creates a new message request.

func (*ClaudeClient) MessagesNewStreaming added in v0.260514.1

MessagesNewStreaming creates a new streaming message request.

func (*ClaudeClient) Probe added in v0.260514.1

func (c *ClaudeClient) Probe(ctx context.Context, model string) ProbeResult

ProbeChatEndpoint tests the messages endpoint.

func (*ClaudeClient) ProbeModelsEndpoint added in v0.260531.1

func (c *ClaudeClient) ProbeModelsEndpoint(ctx context.Context) ProbeResult

ProbeModelsEndpoint reports the /models endpoint as unavailable without issuing a request. Claude Code OAuth tokens cannot access /models, so probing would always fail and may spam upstream with rejected calls.

func (*ClaudeClient) ProbeStream added in v0.260514.1

func (c *ClaudeClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with configurable test mode for Claude Code OAuth. This uses the ClaudeClient's own MessagesNewStreaming method which properly applies: - Beta headers (only for probe operations) - Thinking field disabling - Session ID injection via Guard pattern

Note: Beta headers are ONLY applied during probe, not during normal message passing.

func (*ClaudeClient) SetRecordSink added in v0.260514.1

func (c *ClaudeClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client.

type ClientPool

type ClientPool struct {
	// contains filtered or unexported fields
}

ClientPool manages client instances for different providers. With SessionBoundTransport, connection pooling is handled at the Transport layer, so ClientPool simply creates new client instances as needed.

Transports are automatically shared via TransportPool based on:

providerUUID + sessionID (for OAuth providers)

ProxyURL is used to configure the transport but is NOT part of the key.

Clients are automatically cleaned up via finalizers when garbage collected.

func NewClientPool

func NewClientPool() *ClientPool

NewClientPool creates a new ClientPool with default settings.

func (*ClientPool) GetAnthropicClient

func (p *ClientPool) GetAnthropicClient(ctx context.Context, provider *typ.Provider, model string) AnthropicClientInterface

GetAnthropicClient returns an Anthropic client wrapper for the specified provider. For Claude Code OAuth providers, returns a ClaudeClient with special handling. sessionID is resolved from ctx via typ.GetSessionID; pass context.Background() when no session is available.

func (*ClientPool) GetGoogleClient

func (p *ClientPool) GetGoogleClient(ctx context.Context, provider *typ.Provider, model string) *GoogleClient

GetGoogleClient returns a Google client wrapper for the specified provider. For Gemini CLI / Antigravity OAuth providers it dispatches to the dedicated xxx_client constructors, which layer the Code Assist envelope transport. sessionID is resolved from ctx via typ.GetSessionID; pass context.Background() when no session is available.

func (*ClientPool) GetOpenAIClient

func (p *ClientPool) GetOpenAIClient(ctx context.Context, provider *typ.Provider, model string) OpenAIClientInterface

GetOpenAIClient returns an OpenAI client wrapper for the specified provider. For Codex OAuth providers, returns a CodexClient with special handling. For Kimi Code OAuth providers, returns a KimiClient with special handling. sessionID is resolved from ctx via typ.GetSessionID; pass context.Background() when no session is available.

func (*ClientPool) GetRecordSink

func (p *ClientPool) GetRecordSink() *obs.Sink

GetRecordSink returns the record sink.

func (*ClientPool) InvalidateProvider

func (p *ClientPool) InvalidateProvider(providerUUID string)

InvalidateProvider invalidates all transports for a specific provider UUID. This should be called when provider credentials are updated (e.g., OAuth token refresh).

Note: Since ClientPool no longer caches clients, this only invalidates the TransportPool entries. Client instances will be garbage collected naturally.

func (*ClientPool) InvalidateSession added in v0.260409.1540

func (p *ClientPool) InvalidateSession(providerUUID, sessionID string)

InvalidateSession invalidates transports for a specific session. This is useful when a session ends or its OAuth token is revoked.

Note: Since ClientPool no longer caches clients, this only invalidates the TransportPool entries. Client instances will be garbage collected naturally.

func (*ClientPool) SetRecordSink

func (p *ClientPool) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client pool. Note: This only affects newly created clients, not existing ones.

func (*ClientPool) Stats

func (p *ClientPool) Stats() map[string]interface{}

Stats provides statistics about the client pool and transport pool.

type ClientPoolBuilder

type ClientPoolBuilder struct {
	// contains filtered or unexported fields
}

ClientPoolBuilder builds a ClientPool with specified configuration.

func NewClientPoolBuilder

func NewClientPoolBuilder() *ClientPoolBuilder

NewClientPoolBuilder creates a new builder with default settings.

func (*ClientPoolBuilder) Build

func (b *ClientPoolBuilder) Build() *ClientPool

Build creates the ClientPool with configured settings.

func (*ClientPoolBuilder) WithRecordSink

func (b *ClientPoolBuilder) WithRecordSink(sink *obs.Sink) *ClientPoolBuilder

WithRecordSink sets the record sink for all clients.

type CodexClient added in v0.260514.1

type CodexClient struct {
	*OpenAIClient
}

CodexClient wraps OpenAIClient with Codex-specific behaviors. It embeds OpenAIClient to inherit standard OpenAI API functionality, while overriding methods that require special handling for ChatGPT backend API.

Codex (ChatGPT OAuth) limitations: - Does NOT support standard Chat Completions API - Does NOT support /models endpoint - Does NOT support /images/generations endpoint - ONLY supports Responses API with special parameters

func NewCodexClient added in v0.260514.1

func NewCodexClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*CodexClient, error)

NewCodexClient creates a new Codex client wrapper. The base OpenAIClient is configured with codexRoundTripper for path/header transformation.

func (*CodexClient) ChatCompletionsNew added in v0.260514.1

ChatCompletionsNew creates a new chat completion request. For Codex, this returns an error as ChatGPT backend API does not support standard Chat Completions. Use Responses API instead.

func (*CodexClient) ChatCompletionsNewStreaming added in v0.260514.1

ChatCompletionsNewStreaming creates a new streaming chat completion request. For Codex, this returns nil as ChatGPT backend API does not support standard Chat Completions. Use Responses API instead.

func (*CodexClient) Client added in v0.260514.1

func (c *CodexClient) Client() *openai.Client

Client returns the underlying OpenAI SDK client. For CodexClient, we delegate to the embedded OpenAIClient.

func (*CodexClient) ImagesGenerate added in v0.260514.1

ImagesGenerate creates a new image generation request. For Codex, this transforms the request to use the Responses API with the image_generation tool, as ChatGPT backend API does not support the standard /images/generations endpoint. Persistence of generated images is handled by the server layer, not the client.

func (*CodexClient) ListModels added in v0.260514.1

func (c *CodexClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models. For Codex, this returns an error as ChatGPT OAuth tokens cannot access /models endpoint.

func (*CodexClient) Probe added in v0.260514.1

func (c *CodexClient) Probe(ctx context.Context, model string) ProbeResult

ProbeChatEndpoint tests the chat endpoint. For Codex, this delegates to the embedded OpenAIClient's probeResponsesEndpoint.

func (*CodexClient) ProbeResponsesStream added in v0.260514.1

func (c *CodexClient) ProbeResponsesStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

func (*CodexClient) ProbeStream added in v0.260514.1

func (c *CodexClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with configurable test mode (public interface) Codex uses the Responses API with proper beta headers

func (*CodexClient) ResponsesNew added in v0.260531.1

ResponsesNew creates a new Responses API request. For Codex, this internally uses streaming mode and assembles the result into a non-streaming Response, as required by the ChatGPT backend API.

func (*CodexClient) ResponsesNewStreaming added in v0.260514.1

ResponsesNewStreaming creates a new streaming Responses API request with Codex-specific defaults.

func (*CodexClient) SetRecordSink added in v0.260514.1

func (c *CodexClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client. For CodexClient, we delegate to the embedded OpenAIClient.

type ErrCodexNotSupported added in v0.260514.1

type ErrCodexNotSupported struct {
	Operation string
	Reason    string
}

ErrCodexNotSupported is returned when attempting to use an OpenAI API that is not supported by Codex

func (*ErrCodexNotSupported) Error added in v0.260514.1

func (e *ErrCodexNotSupported) Error() string

type ErrKimiNotSupported added in v0.260604.1

type ErrKimiNotSupported struct {
	Operation string
	Reason    string
}

ErrKimiNotSupported is returned when attempting to use an OpenAI API that is not supported by Kimi Code

func (*ErrKimiNotSupported) Error added in v0.260604.1

func (e *ErrKimiNotSupported) Error() string

type ErrModelsEndpointNotSupported

type ErrModelsEndpointNotSupported struct {
	Provider string
	Reason   string
}

ErrModelsEndpointNotSupported is returned when the provider does not support the models endpoint

func (*ErrModelsEndpointNotSupported) Error

type GeminiClient added in v0.260531.1

type GeminiClient struct {
	*GoogleClient
}

GeminiClient wraps GoogleClient with Gemini CLI OAuth-specific behaviors. It embeds *GoogleClient to inherit standard genai SDK functionality, while swapping in a transport that speaks the Google Code Assist envelope.

Gemini CLI (Google Code Assist OAuth) requirements:

  • Authorization: Bearer <token> (not X-Goog-Api-Key)
  • Rewrite /v1beta/models/<m>:<op> → /v1internal:<op>
  • Wrap body with {model, project, user_prompt_id, request}
  • Unwrap the "response" envelope on the way back

func NewGeminiClient added in v0.260531.1

func NewGeminiClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*GeminiClient, error)

NewGeminiClient builds a GeminiClient. The project_id stored on the OAuth detail by GeminiHook.AfterToken (loadCodeAssist/onboardUser) is required for every generateContent call — without it the Code Assist API rejects the request, so we still construct the client but log a warning.

type GoogleClient

type GoogleClient struct {
	// contains filtered or unexported fields
}

GoogleClient wraps the Google genai SDK client

func NewGoogleClient

func NewGoogleClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*GoogleClient, error)

NewGoogleClient creates a new Google client wrapper. sessionID is used for session-scoped transport creation for OAuth providers.

For provider-specific wire formats (Gemini CLI / Antigravity Code Assist envelope), prefer the dedicated *Client constructors (NewGeminiClient, NewAntigravityClient) — they layer the right round tripper on top of the session-bound transport. NewGoogleClient itself stays generic.

func (*GoogleClient) APIStyle

func (c *GoogleClient) APIStyle() protocol.APIStyle

ProviderType returns the provider type

func (*GoogleClient) Client

func (c *GoogleClient) Client() *genai.Client

Client returns the underlying Google genai SDK client

func (*GoogleClient) Close

func (c *GoogleClient) Close() error

Close closes any resources held by the client

func (*GoogleClient) GenerateContent

func (c *GoogleClient) GenerateContent(ctx context.Context, model string, contents []*genai.Content, config *genai.GenerateContentConfig) (*genai.GenerateContentResponse, error)

GenerateContent generates content using the Google API

func (*GoogleClient) GenerateContentStream

func (c *GoogleClient) GenerateContentStream(ctx context.Context, model string, contents []*genai.Content, config *genai.GenerateContentConfig) iter.Seq2[*genai.GenerateContentResponse, error]

GenerateContentStream generates content using streaming

func (*GoogleClient) GetProvider

func (c *GoogleClient) GetProvider() *typ.Provider

GetProvider returns the provider for this client

func (*GoogleClient) ListModels

func (c *GoogleClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models from the Google Gemini API Note: Google genai SDK doesn't have a direct ListModels method, so we return ErrModelsEndpointNotSupported to signal the caller to use template fallback.

func (*GoogleClient) Probe added in v0.260514.1

func (c *GoogleClient) Probe(ctx context.Context, model string) ProbeResult

ProbeChatEndpoint tests the chat endpoint with a minimal request

func (*GoogleClient) ProbeModelsEndpoint

func (c *GoogleClient) ProbeModelsEndpoint(ctx context.Context) ProbeResult

ProbeModelsEndpoint tests the models list endpoint

func (*GoogleClient) ProbeOptionsEndpoint

func (c *GoogleClient) ProbeOptionsEndpoint(ctx context.Context) ProbeResult

ProbeOptionsEndpoint tests basic connectivity with an OPTIONS request

func (*GoogleClient) ProbeStream added in v0.260514.1

func (c *GoogleClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with configurable test mode (public interface)

func (*GoogleClient) SetRecordSink

func (c *GoogleClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client

type KimiClient added in v0.260604.1

type KimiClient struct {
	*OpenAIClient
}

KimiClient wraps OpenAIClient with Kimi-specific behaviors. It embeds OpenAIClient to inherit standard OpenAI API functionality, while applying Kimi-specific normalization before requests.

Kimi Code OAuth requirements: - Requires Kimi-cli impersonation headers (X-Msh-*, User-Agent) - Requires model name normalization (strip "kimi-" prefix) - Requires tool message format normalization for API compatibility

func NewKimiClient added in v0.260604.1

func NewKimiClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*KimiClient, error)

NewKimiClient creates a new Kimi client wrapper. The base OpenAIClient is configured with kimiRoundTripper for Kimi-cli impersonation headers.

func (*KimiClient) APIStyle added in v0.260604.1

func (c *KimiClient) APIStyle() protocol.APIStyle

APIStyle returns the API style (OpenAI) for this client.

func (*KimiClient) ChatCompletionsNew added in v0.260604.1

func (c *KimiClient) ChatCompletionsNew(ctx context.Context, req openai.ChatCompletionNewParams) (*openai.ChatCompletion, error)

ChatCompletionsNew creates a new chat completion request with Kimi normalization.

func (*KimiClient) ChatCompletionsNewStreaming added in v0.260604.1

ChatCompletionsNewStreaming creates a new streaming chat completion request with Kimi normalization.

func (*KimiClient) Client added in v0.260604.1

func (c *KimiClient) Client() *openai.Client

Client returns the underlying OpenAI SDK client.

func (*KimiClient) Close added in v0.260604.1

func (c *KimiClient) Close() error

Close closes the client and releases resources.

func (*KimiClient) EmbeddingsNew added in v0.260604.1

EmbeddingsNew creates embeddings with Kimi model normalization.

func (*KimiClient) GetProvider added in v0.260604.1

func (c *KimiClient) GetProvider() *typ.Provider

GetProvider returns the provider configuration.

func (*KimiClient) ImagesGenerate added in v0.260604.1

ImagesGenerate is not supported by Kimi Code OAuth providers.

func (*KimiClient) ListModels added in v0.260604.1

func (c *KimiClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models.

func (*KimiClient) Probe added in v0.260604.1

func (c *KimiClient) Probe(ctx context.Context, model string) ProbeResult

Probe tests the chat endpoint for Kimi provider.

func (*KimiClient) ProbeChatEndpoint added in v0.260604.1

func (c *KimiClient) ProbeChatEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)

ProbeChatEndpoint tests the chat endpoint with Kimi model normalization.

func (*KimiClient) ProbeResponsesEndpoint added in v0.260604.1

func (c *KimiClient) ProbeResponsesEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)

ProbeResponsesEndpoint tests the Responses endpoint with Kimi model normalization.

func (*KimiClient) ProbeResponsesStream added in v0.260604.1

func (c *KimiClient) ProbeResponsesStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeResponsesStream performs a streaming Responses API probe with Kimi model normalization.

func (*KimiClient) ProbeStream added in v0.260604.1

func (c *KimiClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with Kimi model normalization.

func (*KimiClient) ResponsesNew added in v0.260604.1

ResponsesNew is not supported by Kimi Code OAuth providers.

func (*KimiClient) ResponsesNewStreaming added in v0.260604.1

ResponsesNewStreaming is not supported by Kimi Code OAuth providers.

func (*KimiClient) SetRecordSink added in v0.260604.1

func (c *KimiClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client. For KimiClient, we delegate to the embedded OpenAIClient.

type ModelLister

type ModelLister interface {
	// ListModels returns the list of available models from the provider API
	// Returns ErrModelsEndpointNotSupported if the provider does not support the models endpoint
	ListModels(ctx context.Context) ([]string, error)
}

ModelLister defines the interface for fetching model lists from provider APIs

type OpenAIClient

type OpenAIClient struct {
	HttpClient *http.Client
	// contains filtered or unexported fields
}

OpenAIClient wraps the OpenAI SDK client

func NewOpenAIClient

func NewOpenAIClient(provider *typ.Provider, model string, sessionID typ.SessionID, extraOptions ...option.RequestOption) (*OpenAIClient, error)

NewOpenAIClient creates a new OpenAI client wrapper

func (*OpenAIClient) APIStyle

func (c *OpenAIClient) APIStyle() protocol.APIStyle

ProviderType returns the provider type

func (*OpenAIClient) ChatCompletionsNew

ChatCompletionsNew creates a new chat completion request

func (*OpenAIClient) ChatCompletionsNewStreaming

ChatCompletionsNewStreaming creates a new streaming chat completion request

func (*OpenAIClient) Client

func (c *OpenAIClient) Client() *openai.Client

Client returns the underlying OpenAI SDK client

func (*OpenAIClient) Close

func (c *OpenAIClient) Close() error

Close closes any resources held by the client

func (*OpenAIClient) EmbeddingsNew added in v0.260507.1

EmbeddingsNew creates a new embeddings request

func (*OpenAIClient) GetProvider

func (c *OpenAIClient) GetProvider() *typ.Provider

GetProvider returns the provider for this client

func (*OpenAIClient) ImagesGenerate added in v0.260514.1

ImagesGenerate creates a new image generation request. Most providers speak the OpenAI /images/generations contract and are served directly by the SDK client. Vendors with a bespoke image API (DashScope async tasks, MiniMax's custom endpoint) are dispatched through the imagegen adapters, which translate to and from the OpenAI request/response shape so callers see one uniform surface regardless of the upstream.

func (*OpenAIClient) ListModels

func (c *OpenAIClient) ListModels(ctx context.Context) ([]string, error)

ListModels returns the list of available models from the OpenAI-compatible API

func (*OpenAIClient) Probe added in v0.260514.1

func (c *OpenAIClient) Probe(ctx context.Context, model string) ProbeResult

ProbeChatEndpoint tests the chat completions endpoint with a minimal request

func (*OpenAIClient) ProbeChatEndpoint

func (c *OpenAIClient) ProbeChatEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)

ProbeChatEndpoint explicitly probes the Chat Completions endpoint.

func (*OpenAIClient) ProbeModelsEndpoint

func (c *OpenAIClient) ProbeModelsEndpoint(ctx context.Context) ProbeResult

ProbeModelsEndpoint tests the models list endpoint

func (*OpenAIClient) ProbeOptionsEndpoint

func (c *OpenAIClient) ProbeOptionsEndpoint(ctx context.Context) ProbeResult

ProbeOptionsEndpoint tests basic connectivity with an OPTIONS request

func (*OpenAIClient) ProbeResponsesEndpoint added in v0.260531.1

func (c *OpenAIClient) ProbeResponsesEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)

ProbeResponsesEndpoint explicitly probes the Responses API endpoint.

func (*OpenAIClient) ProbeResponsesStream added in v0.260514.1

func (c *OpenAIClient) ProbeResponsesStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeResponsesStream performs a streaming probe using Responses API (for Codex)

func (*OpenAIClient) ProbeStream added in v0.260514.1

func (c *OpenAIClient) ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)

ProbeStream performs a streaming probe with configurable test mode (public interface)

func (*OpenAIClient) ResponsesNew

ResponsesNew creates a new Responses API request

func (*OpenAIClient) ResponsesNewStreaming

ResponsesNewStreaming creates a new streaming Responses API request

func (*OpenAIClient) SetRecordSink

func (c *OpenAIClient) SetRecordSink(sink *obs.Sink)

SetRecordSink sets the record sink for the client

type OpenAIClientInterface added in v0.260514.1

type OpenAIClientInterface interface {
	// Core API methods
	ChatCompletionsNew(ctx context.Context, req openai.ChatCompletionNewParams) (*openai.ChatCompletion, error)
	ChatCompletionsNewStreaming(ctx context.Context, req openai.ChatCompletionNewParams) *ssestream.Stream[openai.ChatCompletionChunk]
	ImagesGenerate(ctx context.Context, req openai.ImageGenerateParams) (*openai.ImagesResponse, error)
	ResponsesNew(ctx context.Context, req responses.ResponseNewParams) (*responses.Response, error)
	ResponsesNewStreaming(ctx context.Context, req responses.ResponseNewParams) *ssestream.Stream[responses.ResponseStreamEventUnion]
	EmbeddingsNew(ctx context.Context, req openai.EmbeddingNewParams) (*openai.CreateEmbeddingResponse, error)

	// Utility methods
	ListModels(ctx context.Context) ([]string, error)
	Close() error
	GetProvider() *typ.Provider
	APIStyle() protocol.APIStyle
	SetRecordSink(sink *obs.Sink)

	// Prober interface methods
	Probe(ctx context.Context, model string) ProbeResult
	ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)
	ProbeResponsesStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)
	ProbeChatEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)
	ProbeResponsesEndpoint(ctx context.Context, model string, opts ProbeEndpointOptions) (*ProbeResult, error)

	// Client returns the underlying OpenAI SDK client (for advanced usage)
	Client() *openai.Client
}

OpenAIClientInterface defines the contract for OpenAI-compatible clients. Both OpenAIClient and CodexClient implement this interface.

type ProbeEndpointOptions added in v0.260531.1

type ProbeEndpointOptions struct {
	Message string
	Stream  bool
	Mode    ProbeMode
}

ProbeEndpointOptions controls endpoint-explicit probing.

type ProbeEndpointType added in v0.260531.1

type ProbeEndpointType string

ProbeEndpointType identifies which OpenAI-compatible endpoint a probe must hit.

const (
	ProbeEndpointChat      ProbeEndpointType = "chat"
	ProbeEndpointResponses ProbeEndpointType = "responses"
)

type ProbeMode added in v0.260514.1

type ProbeMode string

ProbeMode defines the test mode for probeStream

const (
	ProbeModeSimple    ProbeMode = "simple"
	ProbeModeStreaming ProbeMode = "streaming"
	ProbeModeTool      ProbeMode = "tool"
)

type ProbeResult

type ProbeResult struct {
	// Basic fields
	Success      bool   `json:"success"`
	Message      string `json:"message,omitempty"`
	Content      string `json:"content,omitempty"`
	LatencyMs    int64  `json:"latency_ms"`
	ModelsCount  int    `json:"models_count,omitempty"`
	ErrorMessage string `json:"error_message,omitempty"`

	// Streaming mode indicator
	Stream bool `json:"stream,omitempty"`

	// Token usage
	PromptTokens     int `json:"prompt_tokens,omitempty"`
	CompletionTokens int `json:"completion_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens,omitempty"`

	// Tool calls (for tool mode)
	ToolCalls []ProbeToolCall `json:"tool_calls,omitempty"`

	// Request URL (for debugging)
	RequestURL string `json:"request_url,omitempty"`
}

ProbeResult represents the result of a probe operation (for both simple and streaming)

func ToProbeResult added in v0.260514.1

func ToProbeResult(content string, latencyMs int64, requestURL string, isStreaming bool) *ProbeResult

ToProbeResult creates a ProbeResult with basic fields

type ProbeToolCall added in v0.260514.1

type ProbeToolCall struct {
	ID    string                 `json:"id"`
	Name  string                 `json:"name"`
	Input map[string]interface{} `json:"input"`
}

ProbeToolCall represents a tool call in probe response

type ProbeUsage

type ProbeUsage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
}

ProbeUsage represents token usage from a probe operation

type Prober

type Prober interface {
	// Probe tests the chat/messages endpoint with a minimal request
	// Returns a ProbeResult with success status, latency, and any response content
	Probe(ctx context.Context, model string) ProbeResult

	// ProbeStream performs a streaming probe with configurable test mode.
	// Deprecated for endpoint capability routing: use endpoint-explicit probe methods
	// such as OpenAIClient.ProbeChatEndpoint and OpenAIClient.ProbeResponsesEndpoint.
	ProbeStream(ctx context.Context, model, message string, testMode ProbeMode) (*ProbeResult, error)
}

Prober defines the interface for client probe capabilities

type RecordRoundTripper

type RecordRoundTripper struct {
	// contains filtered or unexported fields
}

RecordRoundTripper is an http.RoundTripper that records requests and responses

func NewRecordRoundTripper

func NewRecordRoundTripper(transport http.RoundTripper, recordSink *obs.Sink, provider *typ.Provider) *RecordRoundTripper

NewRecordRoundTripper creates a new record round tripper

func (*RecordRoundTripper) RoundTrip

func (r *RecordRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes a single HTTP transaction and records request/response

type SessionBoundTransport added in v0.260414.2000

type SessionBoundTransport struct {
	// contains filtered or unexported fields
}

SessionBoundTransport is a RoundTripper that binds to a specific session. It stores the sessionID and routes all requests through that session's transport. This enables session-scoped transport isolation while keeping the http.Client as a lightweight, stateless shell.

func (*SessionBoundTransport) RoundTrip added in v0.260414.2000

func (t *SessionBoundTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper for SessionBoundTransport. It acquires the transport for the stored session (incrementing refCount), executes the request, and wraps the response body to auto-release on close.

type TestTransportPool added in v0.260414.2000

type TestTransportPool struct {
	// contains filtered or unexported fields
}

TestTransportPool is a test double for TransportPool that tracks which transport keys were requested.

func NewTestTransportPool added in v0.260414.2000

func NewTestTransportPool() *TestTransportPool

NewTestTransportPool creates a new test transport pool.

func (*TestTransportPool) AcquireTransport added in v0.260423.0

func (p *TestTransportPool) AcquireTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) (*http.Transport, func())

AcquireTransport returns a transport for the given configuration. The release function is a no-op for tests (no reference counting).

func (*TestTransportPool) Clear added in v0.260414.2000

func (p *TestTransportPool) Clear()

Clear clears all transports and keys.

func (*TestTransportPool) GetTransport added in v0.260414.2000

func (p *TestTransportPool) GetTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) *http.Transport

GetTransport returns or creates a transport for the given configuration. It tracks the key for test verification.

func (*TestTransportPool) InvalidateSession added in v0.260414.2000

func (p *TestTransportPool) InvalidateSession(providerUUID, sessionID string)

InvalidateSession is a no-op for tests (unless specifically needed).

func (*TestTransportPool) Keys added in v0.260414.2000

func (p *TestTransportPool) Keys() []string

Keys returns all transport keys that were requested.

func (*TestTransportPool) Stats added in v0.260414.2000

func (p *TestTransportPool) Stats() map[string]interface{}

Stats returns statistics about the transport pool.

type TransportConfig

type TransportConfig struct {
	MaxIdleConns        *int  // nil = use Go default (100)
	MaxIdleConnsPerHost *int  // nil = use Go default (2)
	MaxConnsPerHost     *int  // nil = use Go default (0, no limit)
	DisableKeepAlives   *bool // nil = use Go default (false)

	// RespectEnvProxy controls whether providers without explicit proxy configuration
	// should use environment/system proxy settings (HTTP_PROXY, HTTPS_PROXY, macOS system proxy, etc.)
	// Default (nil): false - providers without proxy_url connect directly
	// Set to true: providers without proxy_url will use system/environment proxy
	RespectEnvProxy *bool // nil = use default (false)

}

TransportConfig holds the configuration for HTTP transport connection pooling All fields are pointers so that zero-value (nil) means "use Go default"

type TransportPool

type TransportPool struct {
	// contains filtered or unexported fields
}

TransportPool manages shared HTTP transports for clients Transports are keyed by: providerUUID + sessionID (for OAuth providers) This allows multiple clients to share the same connection pool when they use the same provider+session combination. For OAuth providers, transports are session-scoped to prevent cross-session contamination.

Note: ProxyURL is NOT part of the transport key. It's used to configure how the transport is created, but doesn't create a separate pool.

func GetGlobalTransportPool

func GetGlobalTransportPool() *TransportPool

GetGlobalTransportPool returns the global transport pool singleton

func (*TransportPool) AcquireTransport added in v0.260423.0

func (tp *TransportPool) AcquireTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) (*http.Transport, func())

AcquireTransport returns a transport for the given configuration and increments its reference count. The caller MUST call the returned release function exactly once when the request is complete (typically by wrapping the response body). This prevents the cleanup task from evicting a transport that has active in-flight requests.

func (*TransportPool) Clear

func (tp *TransportPool) Clear()

Clear removes all transports from the pool and closes idle connections. Transports with active in-flight requests (refCount > 0) are marked for deferred removal (lastAccess set to epoch) and will be cleaned up on the next cycle after their requests complete.

func (*TransportPool) GetTransport

func (tp *TransportPool) GetTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) *http.Transport

GetTransport returns or creates a shared HTTP transport for the given configuration. The transport key is based on: providerUUID + sessionID (for OAuth providers). proxyURL is used to configure the transport but is NOT part of the key. sessionID is used to scope transports for OAuth providers that require per-session isolation.

Note: For in-flight request tracking (preventing cleanup of active transports), use AcquireTransport instead.

func (*TransportPool) InvalidateProvider added in v0.260414.2000

func (tp *TransportPool) InvalidateProvider(providerUUID string)

InvalidateProvider removes all transports associated with a specific provider UUID. This should be called when provider credentials are updated (e.g., OAuth token refresh). Transports with active requests are marked for deferred removal.

func (*TransportPool) InvalidateSession added in v0.260414.2000

func (tp *TransportPool) InvalidateSession(providerUUID, sessionID string)

InvalidateSession removes all transports associated with a specific session for a provider. This should be called when a session ends or its OAuth token is revoked. Transports with active requests are marked for deferred removal.

func (*TransportPool) StartCleanupTask

func (tp *TransportPool) StartCleanupTask(interval, ttl time.Duration)

StartCleanupTask starts a periodic cleanup task that removes expired transports

func (*TransportPool) Stats

func (tp *TransportPool) Stats() map[string]interface{}

Stats returns statistics about the transport pool

type TransportPoolInterface added in v0.260414.2000

type TransportPoolInterface interface {
	GetTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) *http.Transport
	AcquireTransport(providerUUID, model, proxyURL string, issuer ai.Issuer, sessionID typ.SessionID) (*http.Transport, func())
}

TransportPoolInterface defines the interface for transport pools. This allows both the real TransportPool and test doubles to be used.

type TransportReusePolicy added in v0.260414.2000

type TransportReusePolicy string

TransportReusePolicy defines whether transports can be shared across sessions

const (
	// TransportReusable - transport can be shared across sessions (API-key providers)
	TransportReusable TransportReusePolicy = "reusable"
	// TransportPerSession - each session needs its own transport (OAuth providers)
	TransportPerSession TransportReusePolicy = "per_session"
)

func GetTransportReusePolicy added in v0.260414.2000

func GetTransportReusePolicy(issuer ai.Issuer) TransportReusePolicy

GetTransportReusePolicy returns the transport reuse policy for a provider type Returns TransportPerSession for unknown provider types (safer default)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL