helps

package
v6.9.9 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ClaudeDeviceProfileBeforeCandidateStore func(ClaudeDeviceProfile)
)

Functions

func APIKeyFromContext

func APIKeyFromContext(ctx context.Context) string

func AppendAPIResponseChunk

func AppendAPIResponseChunk(ctx context.Context, cfg *config.Config, chunk []byte)

AppendAPIResponseChunk appends an upstream response chunk to Gin context for request logging.

func AppendAPIWebsocketResponse added in v6.9.9

func AppendAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload []byte)

AppendAPIWebsocketResponse stores an upstream websocket response frame in Gin context.

func ApplyClaudeDeviceProfileHeaders

func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfile)

func ApplyClaudeLegacyDeviceHeaders

func ApplyClaudeLegacyDeviceHeaders(r *http.Request, ginHeaders http.Header, cfg *config.Config)

func ApplyPayloadConfigWithRoot

func ApplyPayloadConfigWithRoot(cfg *config.Config, model, protocol, root string, payload, original []byte, requestedModel string) []byte

ApplyPayloadConfigWithRoot behaves like applyPayloadConfig but treats all parameter paths as relative to the provided root path (for example, "request" for Gemini CLI) and restricts matches to the given protocol when supplied. Defaults are checked against the original payload when provided. requestedModel carries the client-visible model name before alias resolution so payload rules can target aliases precisely.

func BuildOpenAIUsageJSON

func BuildOpenAIUsageJSON(count int64) []byte

BuildOpenAIUsageJSON returns a minimal usage structure understood by downstream translators.

func CachedSessionID added in v6.9.9

func CachedSessionID(apiKey string) string

CachedSessionID returns a stable session UUID per apiKey, refreshing the TTL on each access.

func CachedUserID

func CachedUserID(apiKey string) string

func ClaudeDeviceProfileStabilizationEnabled

func ClaudeDeviceProfileStabilizationEnabled(cfg *config.Config) bool

func CountOpenAIChatTokens

func CountOpenAIChatTokens(enc tokenizer.Codec, payload []byte) (int64, error)

CountOpenAIChatTokens approximates prompt tokens for OpenAI chat completions payloads.

func DefaultClaudeVersion added in v6.9.9

func DefaultClaudeVersion(cfg *config.Config) string

DefaultClaudeVersion returns the version string (e.g. "2.1.63") from the current baseline device profile. It extracts the version from the User-Agent.

func FilterSSEUsageMetadata

func FilterSSEUsageMetadata(payload []byte) []byte

FilterSSEUsageMetadata removes usageMetadata from SSE events that are not terminal (finishReason != "stop"). Stop chunks are left untouched. This function is shared between aistudio and antigravity executors.

func GenerateFakeUserID

func GenerateFakeUserID() string

func IsValidUserID

func IsValidUserID(userID string) bool

func JSONPayload

func JSONPayload(line []byte) []byte

func LogWithRequestID

func LogWithRequestID(ctx context.Context) *log.Entry

logWithRequestID returns a logrus Entry with request_id field populated from context. If no request ID is found in context, it returns the standard logger.

func MapStainlessArch

func MapStainlessArch() string

func MapStainlessOS

func MapStainlessOS() string

func NewProxyAwareHTTPClient

func NewProxyAwareHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) *http.Client

NewProxyAwareHTTPClient creates an HTTP client with proper proxy configuration priority: 1. Use auth.ProxyURL if configured (highest priority) 2. Use cfg.ProxyURL if auth proxy is not configured 3. Use RoundTripper from context if neither are configured

Parameters:

  • ctx: The context containing optional RoundTripper
  • cfg: The application configuration
  • auth: The authentication information
  • timeout: The client timeout (0 means no timeout)

Returns:

  • *http.Client: An HTTP client with configured proxy or transport

func NewUtlsHTTPClient added in v6.9.9

func NewUtlsHTTPClient(cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) *http.Client

NewUtlsHTTPClient creates an HTTP client using utls Chrome TLS fingerprint. Use this for Claude API requests to match real Claude Code's TLS behavior. Falls back to standard transport for non-HTTPS requests.

func ObfuscateSensitiveWords

func ObfuscateSensitiveWords(payload []byte, matcher *SensitiveWordMatcher) []byte

ObfuscateSensitiveWords processes the payload and obfuscates sensitive words in system blocks and message content.

func ParseAntigravityStreamUsage

func ParseAntigravityStreamUsage(line []byte) (usage.Detail, bool)

func ParseAntigravityUsage

func ParseAntigravityUsage(data []byte) usage.Detail

func ParseClaudeStreamUsage

func ParseClaudeStreamUsage(line []byte) (usage.Detail, bool)

func ParseClaudeUsage

func ParseClaudeUsage(data []byte) usage.Detail

func ParseCodexUsage

func ParseCodexUsage(data []byte) (usage.Detail, bool)

func ParseGeminiCLIStreamUsage

func ParseGeminiCLIStreamUsage(line []byte) (usage.Detail, bool)

func ParseGeminiCLIUsage

func ParseGeminiCLIUsage(data []byte) usage.Detail

func ParseGeminiStreamUsage

func ParseGeminiStreamUsage(line []byte) (usage.Detail, bool)

func ParseGeminiUsage

func ParseGeminiUsage(data []byte) usage.Detail

func ParseOpenAIStreamUsage

func ParseOpenAIStreamUsage(line []byte) (usage.Detail, bool)

func ParseOpenAIUsage

func ParseOpenAIUsage(data []byte) usage.Detail

func PayloadRequestedModel

func PayloadRequestedModel(opts cliproxyexecutor.Options, fallback string) string

func RecordAPIRequest

func RecordAPIRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog)

RecordAPIRequest stores the upstream request metadata in Gin context for request logging.

func RecordAPIResponseError

func RecordAPIResponseError(ctx context.Context, cfg *config.Config, err error)

RecordAPIResponseError adds an error entry for the latest attempt when no HTTP response is available.

func RecordAPIResponseMetadata

func RecordAPIResponseMetadata(ctx context.Context, cfg *config.Config, status int, headers http.Header)

RecordAPIResponseMetadata captures upstream response status/header information for the latest attempt.

func RecordAPIWebsocketError added in v6.9.9

func RecordAPIWebsocketError(ctx context.Context, cfg *config.Config, stage string, err error)

RecordAPIWebsocketError stores an upstream websocket error event in Gin context.

func RecordAPIWebsocketHandshake added in v6.9.9

func RecordAPIWebsocketHandshake(ctx context.Context, cfg *config.Config, status int, headers http.Header)

RecordAPIWebsocketHandshake stores the upstream websocket handshake response metadata.

func RecordAPIWebsocketRequest added in v6.9.9

func RecordAPIWebsocketRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog)

RecordAPIWebsocketRequest stores an upstream websocket request event in Gin context.

func RecordAPIWebsocketUpgradeRejection added in v6.9.9

func RecordAPIWebsocketUpgradeRejection(ctx context.Context, cfg *config.Config, info UpstreamRequestLog, status int, headers http.Header, body []byte)

RecordAPIWebsocketUpgradeRejection stores a rejected websocket upgrade as an HTTP attempt.

func ResetClaudeDeviceProfileCache

func ResetClaudeDeviceProfileCache()

func SetCodexCache

func SetCodexCache(key string, cache CodexCache)

SetCodexCache stores a cache entry.

func ShouldCloak

func ShouldCloak(cloakMode string, userAgent string) bool

ShouldCloak determines if request should be cloaked based on config and client User-Agent. Returns true if cloaking should be applied.

func StripUsageMetadataFromJSON

func StripUsageMetadataFromJSON(rawJSON []byte) ([]byte, bool)

StripUsageMetadataFromJSON drops usageMetadata unless finishReason is present (terminal). It handles both formats: - Aistudio: candidates.0.finishReason - Antigravity: response.candidates.0.finishReason

func SummarizeErrorBody

func SummarizeErrorBody(contentType string, body []byte) string

func TokenizerForModel

func TokenizerForModel(model string) (tokenizer.Codec, error)

TokenizerForModel returns a tokenizer codec suitable for an OpenAI-style model id.

func WebsocketUpgradeRequestURL added in v6.9.9

func WebsocketUpgradeRequestURL(rawURL string) string

WebsocketUpgradeRequestURL converts a websocket URL back to its HTTP handshake URL for logging.

Types

type ClaudeDeviceProfile

type ClaudeDeviceProfile struct {
	UserAgent      string
	PackageVersion string
	RuntimeVersion string
	OS             string
	Arch           string
	// contains filtered or unexported fields
}

func ResolveClaudeDeviceProfile

func ResolveClaudeDeviceProfile(auth *cliproxyauth.Auth, apiKey string, headers http.Header, cfg *config.Config) ClaudeDeviceProfile

type CodexCache

type CodexCache struct {
	ID     string
	Expire time.Time
}

func GetCodexCache

func GetCodexCache(key string) (CodexCache, bool)

GetCodexCache retrieves a cached entry, returning ok=false if not found or expired.

type SensitiveWordMatcher

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

SensitiveWordMatcher holds the compiled regex for matching sensitive words.

func BuildSensitiveWordMatcher

func BuildSensitiveWordMatcher(words []string) *SensitiveWordMatcher

BuildSensitiveWordMatcher compiles a regex from the word list. Words are sorted by length (longest first) for proper matching.

type UpstreamRequestLog

type UpstreamRequestLog struct {
	URL       string
	Method    string
	Headers   http.Header
	Body      []byte
	Provider  string
	AuthID    string
	AuthLabel string
	AuthType  string
	AuthValue string
}

UpstreamRequestLog captures the outbound upstream request details for logging.

type UsageReporter

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

func NewUsageReporter

func NewUsageReporter(ctx context.Context, provider, model string, auth *cliproxyauth.Auth) *UsageReporter

func (*UsageReporter) EnsurePublished

func (r *UsageReporter) EnsurePublished(ctx context.Context)

ensurePublished guarantees that a usage record is emitted exactly once. It is safe to call multiple times; only the first call wins due to once.Do. This is used to ensure request counting even when upstream responses do not include any usage fields (tokens), especially for streaming paths.

func (*UsageReporter) Publish

func (r *UsageReporter) Publish(ctx context.Context, detail usage.Detail)

func (*UsageReporter) PublishFailure

func (r *UsageReporter) PublishFailure(ctx context.Context)

func (*UsageReporter) TrackFailure

func (r *UsageReporter) TrackFailure(ctx context.Context, errPtr *error)

Jump to

Keyboard shortcuts

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