helps

package
v7.2.116 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 57 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ClaudeCodeSessionHeader = "X-Claude-Code-Session-Id"
	ClaudeCodeAgentHeader   = "X-Claude-Code-Agent-Id"
	ClaudeCodeMainAgentID   = "main"
)

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

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

AppendAPIWebsocketResponse stores an upstream websocket response frame in Gin context.

func ApplyClaudeCredentialMetadata added in v7.2.116

func ApplyClaudeCredentialMetadata(payload []byte, auth *cliproxyauth.Auth, sessionID string) ([]byte, string, error)

ApplyClaudeCredentialMetadata rewrites the identity exception shared by native and cloaked OAuth requests.

func ApplyClaudeDefaultDeviceProfileHeaders added in v7.2.116

func ApplyClaudeDefaultDeviceProfileHeaders(r *http.Request, cfg *config.Config)

func ApplyClaudeDeviceProfileHeaders

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

func ApplyClaudeLegacyDeviceHeaders

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

func ApplyPayloadConfigWithRequest added in v7.1.8

func ApplyPayloadConfigWithRequest(cfg *config.Config, model, protocol, fromProtocol, root string, payload, original []byte, requestedModel string, requestPath string, headers http.Header) []byte

ApplyPayloadConfigWithRequest applies payload config using source protocol and request header gates.

func ApplyPayloadConfigWithRoot

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

ApplyPayloadConfigWithRoot behaves like applyPayloadConfig but treats all parameter paths as relative to the provided root path 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. requestPath is the inbound HTTP request path (when available) used for endpoint-scoped gates.

func ApplyRequestThinking added in v7.2.105

func ApplyRequestThinking(body []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, fromFormat, toFormat, provider string) ([]byte, error)

ApplyRequestThinking preserves the registry lookup path unless the auth manager bound an exact configured API-key model definition to this attempt.

func ApplyThinkingWithSourcePayload added in v7.2.112

func ApplyThinkingWithSourcePayload(body, currentSourcePayload, originalSourcePayload []byte, model, fromFormat, toFormat, providerKey string) ([]byte, error)

ApplyThinkingWithSourcePayload preserves summary visibility from the original client payload while applying thinking configuration to its translated target payload. currentSourcePayload is the payload that was translated, while originalSourcePayload retains intent removed by an earlier interceptor.

func AugmentClaudeBuiltinToolRegistry

func AugmentClaudeBuiltinToolRegistry(body []byte, registry map[string]bool) map[string]bool

func BeginClaudeDiagnostics added in v7.2.116

func BeginClaudeDiagnostics(credentialIdentity, sessionID string) (key string, sequence uint64, previousMessageID string)

BeginClaudeDiagnostics starts one request generation for a stable credential identity and Claude conversation. It returns the last successfully completed upstream message ID, if any. Only a SHA-256 digest of the credential identity and session is retained as the cache key, so access-token rotation does not interrupt continuity.

func BuildOpenAIUsageJSON

func BuildOpenAIUsageJSON(count int64) []byte

BuildOpenAIUsageJSON returns a minimal usage structure understood by downstream translators.

func CachedSessionID

func CachedSessionID(apiKey string) string

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

func CachedSessionIDRequired added in v7.2.0

func CachedSessionIDRequired(ctx context.Context, apiKey string) (string, error)

CachedSessionIDRequired returns a stable session UUID per apiKey for request-time paths.

func CachedUserID

func CachedUserID(apiKey string) string

func CachedUserIDRequired added in v7.2.0

func CachedUserIDRequired(ctx context.Context, apiKey string) (string, error)

CachedUserIDRequired returns a stable fake user ID per apiKey for request-time paths.

func ClaudeAgentSessionUUID added in v7.2.116

func ClaudeAgentSessionUUID(headers http.Header, originalPayload, translatedPayload []byte, metadataSets ...map[string]any) string

ClaudeAgentSessionUUID maps the downstream agent conversation to one stable UUID, preserving native Claude Code session signals.

func ClaudeAgentSessionUUIDForRequest added in v7.2.116

func ClaudeAgentSessionUUIDForRequest(headers http.Header, originalPayload, translatedPayload []byte, confirmedClaudeCode bool, metadataSets ...map[string]any) string

ClaudeAgentSessionUUIDForRequest preserves Claude-specific session signals only for a confirmed native caller. Other callers use protocol session fields, execution metadata, or the stable derived conversation root.

func ClaudeCodeExecutionScope added in v7.2.85

func ClaudeCodeExecutionScope(ctx context.Context, payload []byte, headers http.Header) (string, bool)

ClaudeCodeExecutionScope returns the stable root-session and agent identity used by Codex execution state.

func ClaudeCredentialAccountUUID added in v7.2.116

func ClaudeCredentialAccountUUID(auth *cliproxyauth.Auth) string

ClaudeCredentialAccountUUID returns the selected upstream credential's account UUID.

func ClaudeDeviceProfileStabilizationEnabled

func ClaudeDeviceProfileStabilizationEnabled(cfg *config.Config) bool

func ClaudeMCPToolAlias added in v7.2.116

func ClaudeMCPToolAlias(secret, original string, attempt uint32) string

ClaudeMCPToolAlias derives a Claude Code-style MCP tool name. Aliases from one caller share a virtual server component. The tool component combines a stable keyed ID with a truncated semantic suffix so the model can distinguish tools by name while the request-local symbol table restores the exact original. A higher attempt changes the stable ID when a collision must be avoided.

func CodexPromptCacheKey added in v7.2.0

func CodexPromptCacheKey(modelName string, userScope string) string

CodexPromptCacheKey builds the Home KV key for a model/user prompt cache.

func CommitClaudeDiagnostics added in v7.2.116

func CommitClaudeDiagnostics(key string, sequence uint64, messageID string)

CommitClaudeDiagnostics advances continuity only after a response completes. A response from an older concurrently-started request cannot overwrite a newer committed generation, including after TTL expiry or capacity eviction.

func CountClaudeInputTokens added in v7.2.102

func CountClaudeInputTokens(payload []byte) (int64, error)

CountClaudeInputTokens estimates tokens for a Claude request with the O200kBase tokenizer.

func CountOpenAIChatTokens

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

CountOpenAIChatTokens approximates prompt tokens for OpenAI chat completions payloads.

func CreditsUsed

func CreditsUsed(ctx context.Context) bool

CreditsUsed returns true if the request used AI credits.

func DefaultClaudeVersion

func DefaultClaudeVersion(cfg *config.Config) string

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

func DeleteJSONField added in v7.2.20

func DeleteJSONField(body []byte, key string) []byte

DeleteJSONField removes a top-level or nested JSON field from a payload.

func DerivedAntigravitySessionID added in v7.2.101

func DerivedAntigravitySessionID(metadataSets ...map[string]any) string

DerivedAntigravitySessionID maps a derived session identity to Antigravity's negative decimal format.

func DerivedSessionID added in v7.2.101

func DerivedSessionID(metadataSets ...map[string]any) string

DerivedSessionID returns the first context-derived session identity in metadata order.

func DerivedSessionUUID added in v7.2.101

func DerivedSessionUUID(provider string, metadataSets ...map[string]any) string

DerivedSessionUUID maps a derived session identity to a provider-scoped stable UUID.

func EnsureClaudeCredentialDevicePoolRequired added in v7.2.116

func EnsureClaudeCredentialDevicePoolRequired(ctx context.Context, auth *cliproxyauth.Auth) ([]string, error)

EnsureClaudeCredentialDevicePoolRequired initializes a credential pool locally, or coordinates it through Home KV when the selected auth is a remote dispatch clone.

func ExecutorTypeName added in v7.1.38

func ExecutorTypeName(executor any) string

func ExtractClaudeCodeAgentID added in v7.2.85

func ExtractClaudeCodeAgentID(ctx context.Context, headers http.Header) string

ExtractClaudeCodeAgentID resolves the Claude Code agent ID and uses a stable sentinel for the root agent.

func ExtractClaudeCodeSessionID added in v7.2.30

func ExtractClaudeCodeSessionID(ctx context.Context, payload []byte, headers http.Header) string

ExtractClaudeCodeSessionID resolves a Claude Code session ID, preferring X-Claude-Code-Session-Id over payload metadata.

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 GenerateFakeUserIDWithSessionID added in v7.2.116

func GenerateFakeUserIDWithSessionID(sessionID string) string

func IsAnthropicUpstreamURL added in v7.2.116

func IsAnthropicUpstreamURL(u *url.URL) bool

IsAnthropicUpstreamURL reports whether a resolved request targets Anthropic's first-party API origin. Claude-specific body, header, HTTP, and TLS behavior must all use this gate so they cannot drift onto custom ports or userinfo URLs.

func IsClaudeMCPToolName added in v7.2.116

func IsClaudeMCPToolName(name string) bool

IsClaudeMCPToolName reports whether name follows Claude Code's MCP tool convention and contains only characters accepted by Anthropic tool names.

func IsClaudeServerToolType added in v7.2.116

func IsClaudeServerToolType(toolType string) bool

IsClaudeServerToolType reports whether a typed declaration is a recognized Anthropic-operated tool. Client-defined type:"custom" declarations are not server tools and must remain eligible for MCP aliasing.

func IsValidUserID

func IsValidUserID(userID string) bool

func JSONPayload

func JSONPayload(line []byte) []byte

func JoinRawJSONArray added in v7.2.92

func JoinRawJSONArray(items [][]byte) []byte

JoinRawJSONArray joins validated raw JSON array items without re-encoding them.

func JoinRawJSONStrings added in v7.2.92

func JoinRawJSONStrings(items []string) []byte

JoinRawJSONStrings joins raw JSON array items held as strings.

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 MarkCreditsUsed

func MarkCreditsUsed(ctx context.Context)

MarkCreditsUsed flags the request as having used AI credits for billing.

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

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

NewUtlsHTTPClient creates an HTTP client using provider-specific TLS fingerprints for protected hosts. It uses Claude Code's Node/OpenSSL profile for Anthropic and a Chrome profile for ChatGPT, with a standard-transport fallback for other hosts.

func NormalizeOpenAIToolResultsTextOnly added in v7.2.115

func NormalizeOpenAIToolResultsTextOnly(payload []byte) []byte

NormalizeOpenAIToolResultsTextOnly converts tool message content to strings. Text parts are preserved and image parts are replaced with a short marker.

func ObfuscateSensitiveWords

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

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

func OptimizeCodexMultiAgentV2Request added in v7.2.98

func OptimizeCodexMultiAgentV2Request(ctx context.Context, headers http.Header, payload []byte, cfg *config.Config) ([]byte, bool)

OptimizeCodexMultiAgentV2Request rewrites an eligible spawn_agent request and reports whether the collaboration namespace was renamed for upstream use.

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 ParseCodexImageToolUsage

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

func ParseCodexUsage

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

func ParseGeminiStreamUsage

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

func ParseGeminiUsage

func ParseGeminiUsage(data []byte) usage.Detail

func ParseInteractionsStreamUsage added in v7.2.51

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

func ParseInteractionsUsage added in v7.2.51

func ParseInteractionsUsage(data []byte) usage.Detail

func ParseOpenAIStreamUsage

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

func ParseOpenAIUsage

func ParseOpenAIUsage(data []byte) usage.Detail

func ParseRetryDelay added in v7.2.20

func ParseRetryDelay(errorBody []byte) (*time.Duration, error)

ParseRetryDelay extracts the retry delay from a Google API 429 error response.

func PayloadRequestPath

func PayloadRequestPath(opts cliproxyexecutor.Options) string

func PayloadRequestedModel

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

func ProviderSessionUUID added in v7.2.101

func ProviderSessionUUID(provider string, metadataSets ...map[string]any) string

ProviderSessionUUID prefers a long-lived execution session and falls back to the derived identity.

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

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

RecordAPIWebsocketError stores an upstream websocket error event in Gin context.

func RecordAPIWebsocketHandshake

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

RecordAPIWebsocketHandshake stores the upstream websocket handshake response metadata.

func RecordAPIWebsocketRequest

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

RecordAPIWebsocketRequest stores an upstream websocket request event in Gin context.

func RecordAPIWebsocketUpgradeRejection

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 RefreshAuthViaHome

func RefreshAuthViaHome(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, bool, error)

RefreshAuthViaHome replaces local refresh logic when home control plane integration is enabled. It returns (updatedAuth, true, nil) when home refresh succeeds; (nil, true, err) when home is enabled but refresh fails; and (nil, false, nil) when home is disabled.

func ResetClaudeDeviceProfileCache

func ResetClaudeDeviceProfileCache()

func ResolveAntigravityGroundingURLs added in v7.1.74

func ResolveAntigravityGroundingURLs(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, payload []byte) []byte

ResolveAntigravityGroundingURLs replaces Vertex Search redirect URLs in grounding chunks with their target URLs.

func RestoreCodexMultiAgentV2Response added in v7.2.98

func RestoreCodexMultiAgentV2Response(payload []byte, optimized bool) []byte

RestoreCodexMultiAgentV2Response restores optimized collaboration namespace values before an upstream response is translated and returned to the client.

func RewriteCodexMultiAgentV2Input added in v7.2.98

func RewriteCodexMultiAgentV2Input(ctx context.Context, headers http.Header, payload []byte, cfg *config.Config) []byte

RewriteCodexMultiAgentV2Input converts official Codex multi-agent input into standard Responses API messages when multi-agent v2 optimization is enabled.

func RewriteCodexSpawnAgentDescription added in v7.2.98

func RewriteCodexSpawnAgentDescription(ctx context.Context, headers http.Header, payload []byte, cfg *config.Config) []byte

RewriteCodexSpawnAgentDescription optimizes spawn_agent definitions for official Codex clients when multi-agent v2 optimization is enabled.

func SanitizeCodexInputItemIDs added in v7.2.84

func SanitizeCodexInputItemIDs(body []byte) []byte

SanitizeCodexInputItemIDs normalizes message IDs for Codex, removes encrypted reasoning items whose IDs exceed the Codex limit, and deterministically shortens other overlong input item IDs.

func SetBoolIfDifferent added in v7.2.92

func SetBoolIfDifferent(payload []byte, path string, value bool) []byte

SetBoolIfDifferent updates path only when its value is not already the canonical JSON boolean. Values with another JSON type are still normalized.

func SetCodexCache

func SetCodexCache(key string, cache CodexCache)

SetCodexCache stores a cache entry.

func SetCodexCacheBestEffort added in v7.2.0

func SetCodexCacheBestEffort(ctx context.Context, key string, cache CodexCache) bool

SetCodexCacheBestEffort stores a cache entry without failing completed responses.

func SetCodexCacheRequired added in v7.2.0

func SetCodexCacheRequired(ctx context.Context, key string, cache CodexCache) error

SetCodexCacheRequired stores a cache entry for request-time paths.

func SetRawIfDifferent added in v7.2.92

func SetRawIfDifferent(payload []byte, path string, value []byte) []byte

SetRawIfDifferent updates path only when the existing raw JSON is identical.

func SetStringIfDifferent added in v7.2.92

func SetStringIfDifferent(payload []byte, path, value string) []byte

SetStringIfDifferent updates path only when its value is not already the canonical JSON string. Values with another JSON type are still normalized.

func ShouldNormalizeOpenAIToolResultsForModel added in v7.2.115

func ShouldNormalizeOpenAIToolResultsForModel(compat *config.OpenAICompatibility, upstreamModel, requestedModel string) bool

ShouldNormalizeOpenAIToolResultsForModel reports whether the selected model explicitly excludes image input through its input-modalities configuration.

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 StripVertexOpenAIResponsesToolCallIDs

func StripVertexOpenAIResponsesToolCallIDs(payload []byte, sourceFormat string) []byte

StripVertexOpenAIResponsesToolCallIDs removes OpenAI Responses call IDs that Vertex rejects in Gemini functionCall/functionResponse payloads.

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 TranslateRequestWithCodexMultiAgentV2 added in v7.2.98

func TranslateRequestWithCodexMultiAgentV2(ctx context.Context, headers http.Header, cfg *config.Config, from, to sdktranslator.Format, model string, payload []byte, stream bool) []byte

TranslateRequestWithCodexMultiAgentV2 normalizes official Codex multi-agent input before translating it to a non-Codex target protocol.

func TranslateStreamWithClaudeInputTokens added in v7.2.95

func TranslateStreamWithClaudeInputTokens(
	ctx context.Context,
	upstreamFormat, responseFormat sdktranslator.Format,
	model string,
	originalRequestRawJSON, requestRawJSON, rawJSON []byte,
	param *any,
	state *ClaudeInputTokenState,
) [][]byte

TranslateStreamWithClaudeInputTokens translates a stream chunk and estimates Claude message_start input usage once.

func WebsocketUpgradeRequestURL

func WebsocketUpgradeRequestURL(rawURL string) string

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

Types

type ClaudeCodeRequestDetection added in v7.2.116

type ClaudeCodeRequestDetection struct {
	Confirmed       bool
	StrongSignals   bool
	NativeClient    bool
	XAppCLI         bool
	UserAgent       bool
	BetasPresent    bool
	MetadataUserID  bool
	Entrypoint      string
	Subclient       string
	AgentSDKVersion string
}

ClaudeCodeRequestDetection records the strong signals and first-party subclient identity used to distinguish an official Claude Code request from a client that only copied its User-Agent.

func DetectClaudeCodeRequest added in v7.2.116

func DetectClaudeCodeRequest(headers http.Header, payload []byte, countTokens bool, configs ...*config.Config) ClaudeCodeRequestDetection

DetectClaudeCodeRequest first mirrors CCH's strong-signal contract, then applies CPA's native-client policy. Messages requests require all four strong signals; count_tokens omits metadata.user_id and uses the three header signals. Only Anthropic first-party product entrypoints are confirmed for pass-through. Generic sdk-ts/sdk-py Agent SDK entrypoints remain unconfirmed and receive CLI cloaking; native Claude Code print mode keeps its original sdk-cli identity.

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

func ResolveClaudeDeviceProfileRequired added in v7.2.0

func ResolveClaudeDeviceProfileRequired(ctx context.Context, auth *cliproxyauth.Auth, apiKey string, headers http.Header, cfg *config.Config) (ClaudeDeviceProfile, error)

ResolveClaudeDeviceProfileRequired resolves a stable Claude Code device profile for request-time paths.

type ClaudeInputTokenState added in v7.2.95

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

ClaudeInputTokenState tracks the one-time input token update for a translated Claude stream.

func NewClaudeInputTokenState added in v7.2.95

func NewClaudeInputTokenState(sourceFormat, upstreamFormat, responseFormat sdktranslator.Format, originalRequest []byte) *ClaudeInputTokenState

NewClaudeInputTokenState creates request-scoped state for translated Claude input token usage.

type CodexCache

type CodexCache struct {
	ID     string
	Expire time.Time
}

func ClaudeCodePromptCache added in v7.2.30

func ClaudeCodePromptCache(ctx context.Context, modelName string, payload []byte, headers http.Header) (CodexCache, bool, error)

ClaudeCodePromptCache derives a deterministic upstream prompt_cache_key for one Claude Code agent.

func GetCodexCache

func GetCodexCache(key string) (CodexCache, bool)

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

func GetCodexCacheRequired added in v7.2.0

func GetCodexCacheRequired(ctx context.Context, key string) (CodexCache, bool, error)

GetCodexCacheRequired retrieves a cached entry for request-time paths.

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 StreamUsageBuffer added in v7.2.52

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

StreamUsageBuffer keeps the latest usage detail observed in a stream.

func (*StreamUsageBuffer) Detail added in v7.2.52

func (b *StreamUsageBuffer) Detail() (usage.Detail, bool)

Detail returns the latest observed usage detail.

func (*StreamUsageBuffer) Observe added in v7.2.52

func (b *StreamUsageBuffer) Observe(detail usage.Detail, ok bool)

Observe records detail when ok is true, allowing the final stream usage to win.

func (*StreamUsageBuffer) ObserveOpenAIStream added in v7.2.65

func (b *StreamUsageBuffer) ObserveOpenAIStream(line []byte)

ObserveOpenAIStream records response-tier state and the latest usage from an OpenAI-style stream while avoiding JSON parsing for irrelevant chunks.

func (*StreamUsageBuffer) Publish added in v7.2.52

func (b *StreamUsageBuffer) Publish(ctx context.Context, reporter *UsageReporter) bool

Publish emits the latest observed usage detail, if any.

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 NewExecutorUsageReporter added in v7.1.38

func NewExecutorUsageReporter(ctx context.Context, executor usageExecutor, model string, auth *cliproxyauth.Auth) *UsageReporter

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) MarkFirstResponseByte added in v7.1.24

func (r *UsageReporter) MarkFirstResponseByte()

func (*UsageReporter) ObserveResponse added in v7.1.24

func (r *UsageReporter) ObserveResponse(resp *http.Response)

func (*UsageReporter) Publish

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

func (*UsageReporter) PublishAdditionalModel

func (r *UsageReporter) PublishAdditionalModel(ctx context.Context, model string, detail usage.Detail)

func (*UsageReporter) PublishFailure

func (r *UsageReporter) PublishFailure(ctx context.Context, errs ...error)

func (*UsageReporter) SetTranslatedReasoningEffort added in v7.1.24

func (r *UsageReporter) SetTranslatedReasoningEffort(payload []byte, format string)

func (*UsageReporter) StartResponseTTFT added in v7.1.24

func (r *UsageReporter) StartResponseTTFT()

func (*UsageReporter) TrackFailure

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

func (*UsageReporter) TrackHTTPClient added in v7.1.24

func (r *UsageReporter) TrackHTTPClient(client *http.Client) *http.Client

func (*UsageReporter) UpdateAccessTokenFingerprint added in v7.2.116

func (r *UsageReporter) UpdateAccessTokenFingerprint(auth *cliproxyauth.Auth)

UpdateAccessTokenFingerprint records the token version actually used upstream.

Jump to

Keyboard shortcuts

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