client

package
v1.261203.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MPL-2.0 Imports: 74 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 AdvisorDepthHeader = "X-Tingly-Advisor-Depth"

AdvisorDepthHeader marks advisor loopback requests. When the advisor provider points back at tingly-box itself, the inbound side reads this header to mark the request as an advisor loopback and skip MCP tool injection, instead of recursively re-injecting the advisor tool (see protocolserver/protocol_transform.go and transform_mcp_tool_injection.go).

View Source
const (

	// AnthropicContext1m is the exported version for use in other packages
	AnthropicContext1m = anthropicContext1m
)
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 OpenCodeSessionHeader = "x-opencode-session"

OpenCodeSessionHeader is the conversation identifier OpenCode Zen requires on every request. Without it the upstream rejects the call with HTTP 400 `MissingSessionID` ("Request is missing x-opencode-session and cannot be routed efficiently"), so the gateway must supply one on the Tingly-Box → OpenCode hop; the client's own header never survives, because the SDK builds a fresh outbound request (#1713).

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

Constants for proxy URL values

View Source
const ScenarioContextKey contextKey = "scenario"

ScenarioContextKey carries the request's scenario name into the outbound request context (set by the protocol server's routing middleware). Consumed by servertool hooks today; the wire-level recorder planned in .design/recording.md §4 will read it too.

Variables

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

Functions

func ApplyHeaderOverrides added in v0.260924.1

func ApplyHeaderOverrides(h http.Header, overrides map[string]string)

ApplyHeaderOverrides sets each override on h in name order; an empty value removes the header instead.

func ApplyProbeHeaderOverridesToClient added in v0.260924.1

func ApplyProbeHeaderOverridesToClient(c interface{})

ApplyProbeHeaderOverridesToClient layers probeHeaderOverridesRoundTripper onto a probe client's transport. Call it before the other probe wrappers so it sits innermost. Probe clients only — never production instances.

func ApplyProbeHeadersToClient added in v0.260611.1

func ApplyProbeHeadersToClient(c interface{})

ApplyProbeHeadersToClient wraps the HTTP transport of a client so that probe headers from the context are forwarded on every outgoing request. Call this only on probe clients — not on production client instances.

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 GetProbeHeaderOverrides added in v0.260924.1

func GetProbeHeaderOverrides(ctx context.Context) (map[string]string, bool)

GetProbeHeaderOverrides returns the overrides stored by WithProbeHeaderOverrides, if any.

func GetProbeHeaders added in v0.260611.1

func GetProbeHeaders(ctx context.Context) (map[string]string, bool)

GetProbeHeaders returns probe headers stored in ctx by WithProbeHeaders. Returns nil, false when no headers are present.

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 IsOpenCodeZen added in v0.260910.1

func IsOpenCodeZen(apiBase string) bool

IsOpenCodeZen reports whether apiBase points at OpenCode Zen. Both products live on the same host and both route through the session header: "/zen/v1" (pay-as-you-go) and "/zen/go/v1" (the Go subscription), plus their Anthropic-style bases without the "/v1" suffix.

Matching goes through ops.SplitProviderHostPath for the same reason the request-side vendor transforms do: a relay whose URL merely mentions the host in its path is not OpenCode.

func IsWorkBuddyChannelRefusal added in v1.261029.0

func IsWorkBuddyChannelRefusal(err error) bool

IsWorkBuddyChannelRefusal identifies a non-retryable HTTP status that can use the existing provider fallback. Numeric codes alone are not enough.

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.

func SupportsAnthropicCountTokens added in v0.260806.1

func SupportsAnthropicCountTokens(provider *typ.Provider) bool

SupportsAnthropicCountTokens reports whether the provider's anthropic-style backend exposes /v1/messages/count_tokens. The bedrock adapter rewrites only /v1/complete and /v1/messages — count_tokens would be signed and sent verbatim to bedrock-runtime, which 404s — so Bedrock providers need a local estimate instead. Lives in the client package because it is SDK-adapter knowledge, not protocol-handler knowledge.

func WithAdvisorLoopback added in v0.260827.1

func WithAdvisorLoopback(ctx context.Context) context.Context

WithAdvisorLoopback marks ctx so advisorLoopbackTransport stamps AdvisorDepthHeader on outbound requests. The advisor tool calls this right before its SDK calls (mcp/runtime/advisor_call.go).

func WithProbeHeaderOverrides added in v0.260924.1

func WithProbeHeaderOverrides(ctx context.Context, overrides map[string]string) context.Context

WithProbeHeaderOverrides stores overrides in ctx so probeHeaderOverridesRoundTripper applies them to every SDK HTTP call carrying that context.

func WithProbeHeaders added in v0.260611.1

func WithProbeHeaders(ctx context.Context, headers map[string]string) context.Context

WithProbeHeaders stores headers in ctx so that clients using probeHeaderRoundTripper inject them into each SDK HTTP call.

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 over the standard transport chain for its auth type.

func NewBedrockClient added in v0.260806.1

func NewBedrockClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*AnthropicClient, error)

NewBedrockClient builds an Anthropic-compatible client that targets Amazon Bedrock. Bedrock speaks the Anthropic Messages API for Claude models but authenticates with AWS SigV4 (or a Bedrock bearer token) and lives at a region-specific host. All of the URL/body rewriting, request signing, and eventstream→SSE normalization is done by the anthropic-sdk-go/bedrock adapter; this constructor only translates the stored credential bundle into it and layers it on top of the generic Anthropic client (which still owns proxy, User-Agent, logging, and timeout behavior).

func NewKimiAnthropicClient added in v1.261026.0

func NewKimiAnthropicClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*AnthropicClient, error)

NewKimiAnthropicClient serves the Anthropic side of a dual Kimi Code provider: the generic Anthropic client with the same kimi-cli impersonation headers the OpenAI side sends, and the OAuth access token as a bearer.

func NewOpenCodeAnthropicClient added in v0.260910.1

func NewOpenCodeAnthropicClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*AnthropicClient, error)

NewOpenCodeAnthropicClient is the Anthropic-shape counterpart: OpenCode Zen publishes an Anthropic-style base too ("/zen/go" alongside "/zen/go/v1"), and the session header is required there just the same. No behavior of the generic Anthropic client changes, so this returns it directly rather than wrapping it in a vendor type.

func NewVModelAnthropicClient added in v0.260903.1

func NewVModelAnthropicClient(provider *typ.Provider, base http.RoundTripper) (*AnthropicClient, error)

NewVModelAnthropicClient is the Anthropic counterpart of NewVModelOpenAIClient.

func NewVertexAnthropicClient added in v0.260806.1

func NewVertexAnthropicClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*AnthropicClient, error)

NewVertexAnthropicClient builds an Anthropic client that targets Claude on GCP Vertex AI. The anthropic-sdk-go/vertex adapter loads a service-account OAuth2 token source and rewrites /v1/messages to the Vertex publisher endpoint; this constructor supplies the credentials from the stored bundle.

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) (*ModelListResult, 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

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) (*ModelListResult, error)
	Close() error
	GetProvider() *typ.Provider
	APIStyle() protocol.APIStyle
	Client() *anthropic.Client
}

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
	// contains filtered or unexported fields
}

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(ctx context.Context, 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.

ctx is the inbound request context: the pool constructs a client per request, so per-request flags resolved here (the claude_org_id rule flag via typ.GetRuleFlags) are correctly scoped to the request being served.

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) (*ModelListResult, error)

ListModels returns the list of available models.

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.

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) 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) SetVModelTransport added in v0.260903.1

func (p *ClientPool) SetVModelTransport(rt http.RoundTripper)

SetVModelTransport installs the transport virtual-model providers are dispatched over (vmodelclient.NewTransport over the server's listener).

func (*ClientPool) Stats

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

Stats provides statistics about the client pool and transport pool.

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 the public /images/generations or /images/edits contracts; generation rides the Responses API (image_generation tool) and editing uses the Codex-native JSON images endpoint (see codex_images.go)
  • Chat surfaces ONLY work through the 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) ImagesEdit added in v0.260827.1

ImagesEdit serves an OpenAI /images/edits request against the Codex-native images edit endpoint. The multipart-style file inputs are inlined as base64 data URLs per the Codex wire protocol.

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) (*ModelListResult, error)

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

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.

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) (*ModelListResult, 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.

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) ImagesEdit added in v0.260827.1

ImagesEdit is not supported by Kimi Code OAuth providers.

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) (*ModelListResult, error)

ListModels returns the list of available models.

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.

type ModelListResult added in v0.260813.1

type ModelListResult struct {
	Models []string
	Raw    any
}

ModelListResult carries parsed model IDs and the raw upstream payload.

type ModelLister

type ModelLister interface {
	// ListModels returns parsed model IDs and, when available, the raw upstream
	// payload. Unsupported providers return ErrModelsEndpointNotSupported.
	ListModels(ctx context.Context) (*ModelListResult, error)
	Close() error
}

ModelLister fetches 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 NewAzureClient added in v0.260806.1

func NewAzureClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*OpenAIClient, error)

NewAzureClient builds an OpenAI-compatible client that targets Azure OpenAI. Azure uses the same Chat/Responses contract as OpenAI but with a deployment- shaped URL, an api-version query parameter, and an api-key header instead of a bearer token. The openai-go/azure adapter handles that rewrite; this constructor supplies endpoint/version/key from the stored bundle and layers it on the generic OpenAI client (which keeps proxy, User-Agent, logging, timeout).

func NewOpenAIClient

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

NewOpenAIClient creates a new OpenAI client wrapper over the standard pooled transport chain (session-bound base, rule flags, advisor loopback, logging).

func NewVModelOpenAIClient added in v0.260903.1

func NewVModelOpenAIClient(provider *typ.Provider, base http.RoundTripper) (*OpenAIClient, error)

NewVModelOpenAIClient builds an OpenAI client for a virtual-model provider over base, the transport that dials this process's virtualserver (vmodelclient.NewTransport). It layers vmodel/client on the generic OpenAI client the way the Azure constructor layers the azure adapter: SDK, retries-off, request timeout and the rule-flag / advisor / logging chain are the generic ones; only the base URL (vmodel:// → http://vmodel.internal/...) and the base transport differ. No pooled network transport is created.

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) DecisionsNew added in v1.261006.2

func (c *OpenAIClient) DecisionsNew(ctx context.Context, body []byte) ([]byte, error)

DecisionsNew posts a decision request to {APIBase}/decisions and returns the raw JSON answer. The body travels opaquely; auth, proxy, and error handling come from the same SDK client as every other OpenAI endpoint. Upstream errors are returned as *openai.Error and keep their HTTP status.

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) ImagesEdit added in v0.260827.1

ImagesEdit forwards an OpenAI /images/edits request. OpenAI-compatible providers are served by the SDK's multipart upload. Vendors whose edit surface is shaped differently — xAI (JSON only), Qianfan (JSON, inverted mask), DashScope (Wanx image2image / qwen-image multimodal) — go through the imagegen edit adapters, which translate to and from the OpenAI shape. MiniMax has no edit surface and is rejected with a clear error instead of a confusing upstream 404.

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) (*ModelListResult, error)

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

func (*OpenAIClient) ResponsesNew

ResponsesNew creates a new Responses API request

func (*OpenAIClient) ResponsesNewStreaming

ResponsesNewStreaming creates a new streaming Responses API request

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)
	ImagesEdit(ctx context.Context, req openai.ImageEditParams) (*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)
	DecisionsNew(ctx context.Context, body []byte) ([]byte, error)

	// Utility methods
	ListModels(ctx context.Context) (*ModelListResult, error)
	Close() error
	GetProvider() *typ.Provider
	APIStyle() protocol.APIStyle

	// 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 OpenCodeClient added in v0.260910.1

type OpenCodeClient struct {
	*OpenAIClient
}

OpenCodeClient wraps OpenAIClient for OpenCode Zen. It embeds OpenAIClient to inherit the standard OpenAI API surface — Zen speaks plain OpenAI-compatible Chat Completions, and the only vendor requirement is the handshake header openCodeRoundTripper stamps.

OpenCode Zen requirements:

  • Every request must carry x-opencode-session, a stable per-conversation identifier, or the upstream answers 400 MissingSessionID (#1713)

Unlike the OAuth vendor clients (Codex, Kimi), the transport keeps the generic provider chain underneath: Zen providers are plain api_key providers, so the rule flags that gate on api_key — extra_headers — and the UA precedence must keep applying. The vendor layer is mounted below that chain and only fills a header nothing else supplied.

func NewOpenCodeClient added in v0.260910.1

func NewOpenCodeClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*OpenCodeClient, error)

NewOpenCodeClient creates an OpenCode Zen client over the standard provider transport chain with the vendor session layer underneath.

type QoderClient added in v1.261116.0

type QoderClient struct{ *OpenAIClient }

QoderClient uses the shared streamed-completion accumulator because Qoder only supplies streaming responses. Its transport implements the wire format.

func NewQoderClient added in v1.261116.0

func NewQoderClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*QoderClient, error)

func (*QoderClient) ChatCompletionsNew added in v1.261116.0

ChatCompletionsNew accumulates the upstream stream into a full completion.

func (*QoderClient) ListModels added in v1.261116.0

func (c *QoderClient) ListModels(context.Context) (*ModelListResult, error)

ListModels supplies a fallback list because Qoder stores its account-specific catalogue locally and does not expose a stable public models endpoint.

func (*QoderClient) ResponsesNew added in v1.261116.0

func (*QoderClient) ResponsesNewStreaming added in v1.261116.0

type RoutingCapture added in v0.260611.1

type RoutingCapture struct {
	Mu                   sync.Mutex
	SelectedProvider     string
	SelectedProviderUUID string
	SelectedModel        string
	RoutingSource        string
	MatchedSmartRule     string // raw header value; "-1" or index string

	// Execution-level facts (set at dispatch, after endpoint resolution).
	UpstreamAPI     string // e.g. "openai_chat", "openai_responses", "anthropic_v1"
	UpstreamURL     string // real upstream endpoint TB forwarded to
	MatchedRule     string // matched rule UUID (empty for synthetic provider probes)
	MatchedRuleDesc string // percent-encoded; decoded by the probe layer
	AppliedFlags    string // compact "endpoint=responses, thinking=high"
}

RoutingCapture holds routing-decision headers captured from a TB-loopback probe response. Fields mirror the X-Tingly-Selected-* / X-Tingly-Routing-Source headers set by SimpleSelector when X-Tingly-Debug-Routing: 1 is present.

func ApplyRoutingCaptureToClient added in v0.260611.1

func ApplyRoutingCaptureToClient(c interface{}) *RoutingCapture

ApplyRoutingCaptureToClient layers a captureRoutingRoundTripper on a probe client's transport chain. The capture pointer is populated after the SDK call completes. Returns the capture so the caller can read the result.

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)

type WorkBuddyClient added in v1.261022.1

type WorkBuddyClient struct {
	*OpenAIClient
	// contains filtered or unexported fields
}

WorkBuddyClient wraps OpenAIClient for WorkBuddy OAuth providers. The upstream is OpenAI chat completions at {origin}/v2/chat/completions, so the wrapper adds only the client identification headers (workbuddyRoundTripper) and the model list, which WorkBuddy serves from /v3/config rather than /models. See .design/workbuddy-oauth.md.

func NewWorkBuddyClient added in v1.261022.1

func NewWorkBuddyClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*WorkBuddyClient, error)

NewWorkBuddyClient creates a WorkBuddy client wrapper.

func (*WorkBuddyClient) ChatCompletionsNew added in v1.261022.1

ChatCompletionsNew answers a complete call from a stream: WorkBuddy refuses a chat that is not streamed, so the request is sent with stream: true and the chunks are assembled into the one ChatCompletion the caller expects. This is the same fallback CodexClient.ResponsesNew makes for the ChatGPT backend, kept at the client so every complete-call path (passthrough, cross-protocol, stage, tool engine) gets it. A stream that yields no answer is an EmptyResponseError, so failover can retry it.

func (*WorkBuddyClient) ListModels added in v1.261022.1

func (c *WorkBuddyClient) ListModels(ctx context.Context) (*ModelListResult, error)

ListModels reads the account's model list from GET {origin}/v3/config.

func (*WorkBuddyClient) ResponsesNew added in v1.261022.1

ResponsesNew is not served by WorkBuddy; Responses requests are converted to chat completions upstream of the client (endpoint mode chat).

func (*WorkBuddyClient) ResponsesNewStreaming added in v1.261022.1

ResponsesNewStreaming is not served by WorkBuddy.

type XAIClient added in v1.261001.1

type XAIClient struct {
	*OpenAIClient
}

XAIClient wraps OpenAIClient with xAI (Grok) OAuth specific behavior. The upstream is an OpenAI-compatible chat completions API, so the only thing this wrapper adds over the base client is the Grok CLI impersonation headers required by cli-chat-proxy.grok.com — see xaiRoundTripper.

func NewXAIClient added in v1.261001.1

func NewXAIClient(provider *typ.Provider, model string, sessionID typ.SessionID) (*XAIClient, error)

NewXAIClient creates a new xAI (Grok) client wrapper.

func (*XAIClient) APIStyle added in v1.261001.1

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

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

func (*XAIClient) Client added in v1.261001.1

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

Client returns the underlying OpenAI SDK client.

func (*XAIClient) Close added in v1.261001.1

func (c *XAIClient) Close() error

Close closes the client and releases resources.

func (*XAIClient) GetProvider added in v1.261001.1

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

GetProvider returns the provider configuration.

func (*XAIClient) ListModels added in v1.261001.1

func (c *XAIClient) ListModels(ctx context.Context) (*ModelListResult, error)

ListModels returns the list of available models.

func (*XAIClient) ResponsesNew added in v1.261001.1

ResponsesNew is not supported by xAI's Grok CLI proxy.

func (*XAIClient) ResponsesNewStreaming added in v1.261001.1

ResponsesNewStreaming is not supported by xAI's Grok CLI proxy.

Jump to

Keyboard shortcuts

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