Documentation
¶
Index ¶
- Constants
- Variables
- func APIKeyFromContext(ctx context.Context) string
- func AppendAPIResponseChunk(ctx context.Context, cfg *config.Config, chunk []byte)
- func AppendAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload []byte)
- func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfile)
- func ApplyClaudeLegacyDeviceHeaders(r *http.Request, ginHeaders http.Header, cfg *config.Config)
- func ApplyPayloadConfigWithRequest(cfg *config.Config, model, protocol, fromProtocol, root string, ...) []byte
- func ApplyPayloadConfigWithRoot(cfg *config.Config, model, protocol, root string, payload, original []byte, ...) []byte
- func AugmentClaudeBuiltinToolRegistry(body []byte, registry map[string]bool) map[string]bool
- func BuildOpenAIUsageJSON(count int64) []byte
- func CachedSessionID(apiKey string) string
- func CachedSessionIDRequired(ctx context.Context, apiKey string) (string, error)
- func CachedUserID(apiKey string) string
- func CachedUserIDRequired(ctx context.Context, apiKey string) (string, error)
- func ClaudeCodeExecutionScope(ctx context.Context, payload []byte, headers http.Header) (string, bool)
- func ClaudeDeviceProfileStabilizationEnabled(cfg *config.Config) bool
- func CodexPromptCacheKey(modelName string, userScope string) string
- func CountOpenAIChatTokens(enc tokenizer.Codec, payload []byte) (int64, error)
- func DefaultClaudeVersion(cfg *config.Config) string
- func DeleteJSONField(body []byte, key string) []byte
- func ExecutorTypeName(executor any) string
- func ExtractClaudeCodeAgentID(ctx context.Context, headers http.Header) string
- func ExtractClaudeCodeSessionID(ctx context.Context, payload []byte, headers http.Header) string
- func FilterSSEUsageMetadata(payload []byte) []byte
- func GenerateFakeUserID() string
- func IsValidUserID(userID string) bool
- func JSONPayload(line []byte) []byte
- func LogWithRequestID(ctx context.Context) *log.Entry
- func MapStainlessArch() string
- func MapStainlessOS() string
- func NewProxyAwareHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, ...) *http.Client
- func NewUtlsHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, ...) *http.Client
- func ObfuscateSensitiveWords(payload []byte, matcher *SensitiveWordMatcher) []byte
- func ParseAntigravityStreamUsage(line []byte) (usage.Detail, bool)
- func ParseAntigravityUsage(data []byte) usage.Detail
- func ParseClaudeStreamUsage(line []byte) (usage.Detail, bool)
- func ParseClaudeUsage(data []byte) usage.Detail
- func ParseCodexImageToolUsage(data []byte) (usage.Detail, bool)
- func ParseCodexUsage(data []byte) (usage.Detail, bool)
- func ParseGeminiCLIStreamUsage(line []byte) (usage.Detail, bool)
- func ParseGeminiCLIUsage(data []byte) usage.Detail
- func ParseGeminiStreamUsage(line []byte) (usage.Detail, bool)
- func ParseGeminiUsage(data []byte) usage.Detail
- func ParseInteractionsStreamUsage(line []byte) (usage.Detail, bool)
- func ParseInteractionsUsage(data []byte) usage.Detail
- func ParseOpenAIStreamUsage(line []byte) (usage.Detail, bool)
- func ParseOpenAIUsage(data []byte) usage.Detail
- func ParseRetryDelay(errorBody []byte) (*time.Duration, error)
- func PayloadRequestPath(opts cliproxyexecutor.Options) string
- func PayloadRequestedModel(opts cliproxyexecutor.Options, fallback string) string
- func RecordAPIRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog)
- func RecordAPIResponseError(ctx context.Context, cfg *config.Config, err error)
- func RecordAPIResponseMetadata(ctx context.Context, cfg *config.Config, status int, headers http.Header)
- func RecordAPIWebsocketError(ctx context.Context, cfg *config.Config, stage string, err error)
- func RecordAPIWebsocketHandshake(ctx context.Context, cfg *config.Config, status int, headers http.Header)
- func RecordAPIWebsocketRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog)
- func RecordAPIWebsocketUpgradeRejection(ctx context.Context, cfg *config.Config, info UpstreamRequestLog, status int, ...)
- func RefreshAuthViaHome(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, bool, error)
- func ResetClaudeDeviceProfileCache()
- func ResolveAntigravityGroundingURLs(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, ...) []byte
- func SanitizeCodexInputItemIDs(body []byte) []byte
- func SetCodexCache(key string, cache CodexCache)
- func SetCodexCacheBestEffort(ctx context.Context, key string, cache CodexCache) bool
- func SetCodexCacheRequired(ctx context.Context, key string, cache CodexCache) error
- func ShouldCloak(cloakMode string, userAgent string) bool
- func StripUsageMetadataFromJSON(rawJSON []byte) ([]byte, bool)
- func StripVertexOpenAIResponsesToolCallIDs(payload []byte, sourceFormat string) []byte
- func SummarizeErrorBody(contentType string, body []byte) string
- func TokenizerForModel(model string) (tokenizer.Codec, error)
- func WebsocketUpgradeRequestURL(rawURL string) string
- type ClaudeDeviceProfile
- type CodexCache
- type SensitiveWordMatcher
- type StreamUsageBuffer
- type UpstreamRequestLog
- type UsageReporter
- func (r *UsageReporter) EnsurePublished(ctx context.Context)
- func (r *UsageReporter) MarkFirstResponseByte()
- func (r *UsageReporter) ObserveResponse(resp *http.Response)
- func (r *UsageReporter) Publish(ctx context.Context, detail usage.Detail)
- func (r *UsageReporter) PublishAdditionalModel(ctx context.Context, model string, detail usage.Detail)
- func (r *UsageReporter) PublishFailure(ctx context.Context, errs ...error)
- func (r *UsageReporter) SetTranslatedReasoningEffort(payload []byte, format string)
- func (r *UsageReporter) StartResponseTTFT()
- func (r *UsageReporter) TrackFailure(ctx context.Context, errPtr *error)
- func (r *UsageReporter) TrackHTTPClient(client *http.Client) *http.Client
Constants ¶
const ( // ClaudeCodeSessionHeader 是 Claude Code 根会话 ID 请求头。 // 同一个对话窗口内的主 agent / 子 agent 通常共享该值。 ClaudeCodeSessionHeader = "X-Claude-Code-Session-Id" // ClaudeCodeAgentHeader 是 Claude Code 当前 agent 身份请求头。 // 子代理会带独立 agent-id;缺失时按主 agent(main)处理。 ClaudeCodeAgentHeader = "X-Claude-Code-Agent-Id" // ClaudeCodeMainAgentID 是未声明 agent 头时的稳定哨兵值。 // 保证“根会话主代理”始终落在固定分桶,而不是空字符串导致 key 漂移。 ClaudeCodeMainAgentID = "main" )
const ClaudeCodeDoingTasks = `` /* 3327-byte string literal not displayed */
ClaudeCodeDoingTasks is the task guidance section. Corresponds to getSimpleDoingTasksSection() (non-ant version) in prompts.ts.
const ClaudeCodeIntro = `` /* 373-byte string literal not displayed */
ClaudeCodeIntro is the first system block after billing header and agent identifier. Corresponds to getSimpleIntroSection() in prompts.ts.
const ClaudeCodeOutputEfficiency = `` /* 732-byte string literal not displayed */
ClaudeCodeOutputEfficiency is the output efficiency section. Corresponds to getOutputEfficiencySection() (non-ant version) in prompts.ts.
const ClaudeCodeSystem = `` /* 1255-byte string literal not displayed */
ClaudeCodeSystem is the system instructions section. Corresponds to getSimpleSystemSection() in prompts.ts.
const ClaudeCodeSystemReminderSection = `` /* 347-byte string literal not displayed */
ClaudeCodeSystemReminderSection corresponds to getSystemRemindersSection() in prompts.ts.
const ClaudeCodeToneAndStyle = `` /* 551-byte string literal not displayed */
ClaudeCodeToneAndStyle is the tone and style guidance section. Corresponds to getSimpleToneAndStyleSection() in prompts.ts.
Variables ¶
var (
ClaudeDeviceProfileBeforeCandidateStore func(ClaudeDeviceProfile)
)
Functions ¶
func APIKeyFromContext ¶
func AppendAPIResponseChunk ¶
AppendAPIResponseChunk appends an upstream response chunk to Gin context for request logging.
func AppendAPIWebsocketResponse ¶
AppendAPIWebsocketResponse stores an upstream websocket response frame in Gin context.
func ApplyClaudeDeviceProfileHeaders ¶
func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfile)
func ApplyPayloadConfigWithRequest ¶
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 BuildOpenAIUsageJSON ¶
BuildOpenAIUsageJSON returns a minimal usage structure understood by downstream translators.
func CachedSessionID ¶
CachedSessionID returns a stable session UUID per apiKey, refreshing the TTL on each access.
func CachedSessionIDRequired ¶ added in v7.2.49
CachedSessionIDRequired returns a stable session UUID per apiKey for request-time paths.
func CachedUserID ¶
func CachedUserIDRequired ¶ added in v7.2.49
CachedUserIDRequired returns a stable fake user ID per apiKey for request-time paths.
func ClaudeCodeExecutionScope ¶ added in v7.2.61
func ClaudeCodeExecutionScope(ctx context.Context, payload []byte, headers http.Header) (string, bool)
ClaudeCodeExecutionScope 生成“根会话 + agent”执行作用域。 返回形如:claude:{sessionID}:agent:{agentID}
用途链路:
- ClaudeCodePromptCache 用它生成上游 prompt_cache_key,避免子 agent 复用主 agent 缓存;
- codex reasoning replay 用它作为 sessionKey,避免多 agent 回放串台;
- 同 session 不同 agent 并行时,两边状态分桶隔离。
func CodexPromptCacheKey ¶ added in v7.2.49
CodexPromptCacheKey builds the Home KV key for a model/user prompt cache.
func CountOpenAIChatTokens ¶
CountOpenAIChatTokens approximates prompt tokens for OpenAI chat completions payloads.
func DefaultClaudeVersion ¶
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 DeleteJSONField ¶ added in v7.2.49
DeleteJSONField removes a top-level or nested JSON field from a payload.
func ExecutorTypeName ¶ added in v7.2.49
func ExtractClaudeCodeAgentID ¶ added in v7.2.61
ExtractClaudeCodeAgentID 解析 Claude Code agent ID。 有头用头;无头回落 main,确保同会话不同 agent 能被稳定区分。
func ExtractClaudeCodeSessionID ¶ added in v7.2.49
ExtractClaudeCodeSessionID 解析 Claude Code 会话 ID。 优先顺序:显式请求头 X-Claude-Code-Session-Id -> gin 请求头 -> payload metadata.user_id。
func FilterSSEUsageMetadata ¶
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 JSONPayload ¶
func LogWithRequestID ¶
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 ¶
func NewUtlsHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) *http.Client
NewUtlsHTTPClient creates an HTTP client using utls Chrome TLS fingerprint. Use this for provider requests that need a Chrome-like TLS fingerprint. 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 ParseAntigravityUsage ¶
func ParseClaudeUsage ¶
func ParseGeminiCLIUsage ¶
func ParseGeminiUsage ¶
func ParseInteractionsStreamUsage ¶ added in v7.2.53
func ParseInteractionsUsage ¶ added in v7.2.53
func ParseOpenAIUsage ¶
func ParseRetryDelay ¶ added in v7.2.49
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 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 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 ¶
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 the Home control plane is enabled.
func ResetClaudeDeviceProfileCache ¶
func ResetClaudeDeviceProfileCache()
func ResolveAntigravityGroundingURLs ¶ added in v7.2.49
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 SanitizeCodexInputItemIDs ¶ added in v7.2.61
SanitizeCodexInputItemIDs 把 body.input[*].id 中超长 ID 确定性缩短到 64 字符内。 链路: 1) 先收集未超长 ID,占用集合 occupied 2) 对超长 ID 用 sha256 后缀缩短;若冲突则 attempt++ 再哈希 3) 同一原始 ID 在本请求内映射到同一个 shortened,保证引用一致
func SetCodexCache ¶
func SetCodexCache(key string, cache CodexCache)
SetCodexCache stores a cache entry.
func SetCodexCacheBestEffort ¶ added in v7.2.49
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.49
func SetCodexCacheRequired(ctx context.Context, key string, cache CodexCache) error
SetCodexCacheRequired stores a cache entry for request-time paths.
func ShouldCloak ¶
ShouldCloak determines if request should be cloaked based on config and client User-Agent. Returns true if cloaking should be applied.
func StripUsageMetadataFromJSON ¶
StripUsageMetadataFromJSON drops usageMetadata unless finishReason is present (terminal). It handles both formats: - Aistudio: candidates.0.finishReason - Antigravity: response.candidates.0.finishReason
func StripVertexOpenAIResponsesToolCallIDs ¶
StripVertexOpenAIResponsesToolCallIDs removes OpenAI Responses call IDs that Vertex rejects in Gemini functionCall/functionResponse payloads.
func SummarizeErrorBody ¶
func TokenizerForModel ¶
TokenizerForModel returns a tokenizer codec suitable for an OpenAI-style model id.
func WebsocketUpgradeRequestURL ¶
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
func ResolveClaudeDeviceProfileRequired ¶ added in v7.2.49
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 CodexCache ¶
func ClaudeCodePromptCache ¶ added in v7.2.49
func ClaudeCodePromptCache(ctx context.Context, modelName string, payload []byte, headers http.Header) (CodexCache, bool, error)
ClaudeCodePromptCache 为单个 Claude Code agent 生成确定性的上游 prompt_cache_key。
旧实现只按 session 分桶,同会话子 agent 会撞同一 cache; 现在改为 session+agent 作用域 + SHA1 确定性 ID:
- 同 agent 多次请求稳定复用;
- 不同 agent 天然隔离;
- 不再依赖进程内随机 UUID 缓存表。
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.49
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.54
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.54
func (b *StreamUsageBuffer) Detail() (usage.Detail, bool)
Detail returns the latest observed usage detail.
func (*StreamUsageBuffer) Observe ¶ added in v7.2.54
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) Publish ¶ added in v7.2.54
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.2.49
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.2.49
func (r *UsageReporter) MarkFirstResponseByte()
func (*UsageReporter) ObserveResponse ¶ added in v7.2.49
func (r *UsageReporter) ObserveResponse(resp *http.Response)
func (*UsageReporter) Publish ¶
func (r *UsageReporter) Publish(ctx context.Context, detail usage.Detail)
func (*UsageReporter) PublishAdditionalModel ¶
func (*UsageReporter) PublishFailure ¶
func (r *UsageReporter) PublishFailure(ctx context.Context, errs ...error)
func (*UsageReporter) SetTranslatedReasoningEffort ¶ added in v7.2.49
func (r *UsageReporter) SetTranslatedReasoningEffort(payload []byte, format string)
func (*UsageReporter) StartResponseTTFT ¶ added in v7.2.49
func (r *UsageReporter) StartResponseTTFT()
func (*UsageReporter) TrackFailure ¶
func (r *UsageReporter) TrackFailure(ctx context.Context, errPtr *error)
func (*UsageReporter) TrackHTTPClient ¶ added in v7.2.49
func (r *UsageReporter) TrackHTTPClient(client *http.Client) *http.Client
Source Files
¶
- antigravity_grounding_urls.go
- cache_helpers.go
- claude_builtin_tools.go
- claude_code_session.go
- claude_device_profile.go
- claude_system_prompt.go
- cloak_obfuscate.go
- cloak_utils.go
- codex_input_ids.go
- home_refresh.go
- json_retry_helpers.go
- logging_helpers.go
- payload_helpers.go
- proxy_helpers.go
- session_id_cache.go
- thinking_providers.go
- token_helpers.go
- usage_helpers.go
- user_id_cache.go
- utls_client.go
- vertex_payload_helpers.go