Documentation
¶
Overview ¶
Package util provides utility functions for the CLI Proxy API server.
Package util provides utility functions used across the CLIProxyAPI application. These functions handle common tasks such as determining AI service providers from model names and managing HTTP proxies.
Package util provides utility functions for the CLI Proxy API server. It includes helper functions for proxy configuration, HTTP client setup, log level management, and other common operations used across the application.
Package util provides helper functions for SSH tunnel instructions and network-related tasks. This includes detecting the appropriate IP address and printing commands to help users connect to the local server from a remote machine.
Package util provides utility functions for the CLI Proxy API server. It includes helper functions for JSON manipulation, proxy configuration, and other common operations used across the application.
Package util provides utility functions for the CLI Proxy API server. It includes helper functions for logging configuration, file system operations, and other common utilities used throughout the application.
Index ¶
- Constants
- Variables
- func ApplyCustomHeadersFromAttrs(r *http.Request, attrs map[string]string, clientHeaders ...http.Header)
- func BuildGeminiFunctionDeclarations(root gjson.Result) ([][]byte, map[string]string, map[string]ResponsesToolIdentity)
- func CanonicalToolName(name string) string
- func ClaudeToolIsParameterless(toolName string, originalRequestRawJSON []byte) bool
- func CleanClaudeToolArguments(rawArgs string, toolName string, originalRequestRawJSON []byte) string
- func CleanClaudeToolArgumentsWithTranslated(rawArgs string, toolName string, originalRequestRawJSON []byte, ...) string
- func CleanJSONSchemaForAntigravity(jsonStr string) string
- func CleanJSONSchemaForAntigravityClaudeTool(jsonStr string, requirePlaceholder bool) string
- func CleanJSONSchemaForAntigravityResponse(jsonStr string) string
- func CleanJSONSchemaForAntigravityTool(jsonStr string, requirePlaceholder bool) string
- func CleanJSONSchemaForGemini(jsonStr string) string
- func CleanJSONSchemaForGeminiJSONSchema(jsonStr string) string
- func CollectResponsesToolWinners(root gjson.Result) map[string]ResponsesToolDescriptor
- func ConvertResponsesToolChoiceToGemini(toolChoice gjson.Result, forwardMap map[string]string) ([]byte, bool)
- func CountAuthFiles[T any](ctx context.Context, store interface{ ... }) int
- func CreateWhiteImageBase64(aspectRatio string) (string, error)
- func DeduplicateFunctionDeclarations(raw []byte) []byte
- func DisambiguatedToolNameMap(rawJSON []byte) map[string]string
- func FixJSON(input string) string
- func GeminiClaudeToolUseID(callID, name, argsRaw string) string
- func GetGJSONBytesNoCopy(data []byte, path string) gjson.Result
- func GetIPAddress() string
- func GetOpenAICompatibilityConfig(alias string, cfg *config.Config) (*config.OpenAICompatibility, *config.OpenAICompatibilityModel)
- func GetProviderName(modelName string) []string
- func HasExplicitSessionID(ctx context.Context) bool
- func HasUnsupportedUnicodePropertyEscape(pattern string) bool
- func HideAPIKey(apiKey string) string
- func InArray(hystack []string, needle string) bool
- func InlineLocalRefs(jsonStr string) string
- func IsClaudeCodeAttributionSystemText(text string) bool
- func IsClaudeModel(model string) bool
- func IsClaudeThinkingModel(model string) bool
- func IsCodexResponsesLiteRequest(body []byte, headers http.Header) bool
- func IsGeminiClaudeToolUseID(id string) bool
- func IsOpenAICompatibilityAlias(modelName string, cfg *config.Config) bool
- func IsResponsesClientToolSearchDeclaration(tool gjson.Result) bool
- func IsResponsesClientToolSearchItem(item gjson.Result) bool
- func MapClaudeToolName(toolNameMap map[string]string, originalRequestRawJSON []byte, name string) string
- func MapResponsesClientToolSearchName(forwardMap map[string]string) string
- func MapResponsesToolName(forwardMap map[string]string, name string) string
- func MapSanitizedFunctionName(nameMap map[string]string, name string) string
- func MapToolName(toolNameMap map[string]string, name string) string
- func MaskAuthorizationHeader(value string) string
- func MaskSensitiveHeaderValue(key, value string) string
- func MaskSensitiveQuery(raw string) string
- func NormalizeClaudeToolInputSchema(schema []byte) []byte
- func OpenAICompatibleProviderKey(name string) string
- func ParseGJSONBytesNoCopy(data []byte) gjson.Result
- func PrintSSHTunnelInstructions(port int)
- func QualifyResponsesNamespaceToolName(namespaceName, childName string) string
- func RenameKey(jsonStr, oldKeyPath, newKeyPath string) (string, error)
- func ResolveAuthDir(authDir string) (string, error)
- func ResolveAutoModel(modelName string) string
- func ResolveGitHubToken() string
- func ResponsesToolDescription(tool gjson.Result) string
- func ResponsesToolParameters(tool gjson.Result) gjson.Result
- func ResponsesToolReverseIdentityMap(rawJSON []byte) map[string]ResponsesToolIdentity
- func RestoreSanitizedToolName(toolNameMap map[string]string, sanitizedName string) string
- func SanitizeClaudeFunctionName(name string) string
- func SanitizeClaudeToolID(id string) string
- func SanitizeFunctionName(name string) string
- func SanitizedFunctionNameMap(rawJSON []byte) map[string]string
- func SanitizedToolNameMap(rawJSON []byte) map[string]string
- func SessionIDFromContext(ctx context.Context) string
- func SetLogLevel(cfg *config.Config)
- func SetProxy(cfg *config.SDKConfig, httpClient *http.Client) *http.Client
- func StripClaudeCodeAttributionSystem(payload []byte) []byte
- func ToolNameMapFromClaudeRequest(rawJSON []byte) map[string]string
- func UnwrapResponsesCustomToolInput(arguments string) string
- func Walk(value gjson.Result, path, field string, paths *[]string)
- func WalkSchema(value gjson.Result, path, field string, paths *[]string)
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WritablePath() string
- type ClaudeToolResult
- type ClaudeToolResultImage
- type ResponsesToolDescriptor
- type ResponsesToolIdentity
Constants ¶
const ( // ResponsesToolSearchType is the Responses tool type for deferred tool discovery. ResponsesToolSearchType = "tool_search" // ResponsesToolSearchExecutionClient marks a tool_search that the client executes itself. ResponsesToolSearchExecutionClient = "client" // ResponsesToolSearchFunctionName is the function name exposed to providers // that have no native tool_search support. ResponsesToolSearchFunctionName = "tool_search" // ResponsesClientToolSearchKey is the internal forwardMap key for the // client-executed tool_search shim. The leading NUL byte cannot appear in a // JSON identifier, preventing collisions with user-declared tool names. ResponsesClientToolSearchKey = "\x00client_tool_search" // ResponsesToolSearchCallType is the Responses item type for a tool_search invocation. ResponsesToolSearchCallType = "tool_search_call" // ResponsesToolSearchOutputType is the Responses input item carrying discovered tools. ResponsesToolSearchOutputType = "tool_search_output" // ResponsesDiscoveredToolPriority ranks tools loaded by tool_search_output after declared tools. ResponsesDiscoveredToolPriority = 2 )
Variables ¶
var SchemaMapKeywords = [...]string{
"properties",
"$defs",
"definitions",
"patternProperties",
"dependentSchemas",
"dependencies",
}
SchemaMapKeywords lists JSON Schema keywords whose values are maps of subschemas.
var SchemaValueKeywords = [...]string{
"items",
"prefixItems",
"contains",
"additionalProperties",
"propertyNames",
"unevaluatedProperties",
"unevaluatedItems",
"additionalItems",
"contentSchema",
"anyOf",
"oneOf",
"allOf",
"not",
"if",
"then",
"else",
}
SchemaValueKeywords lists JSON Schema keywords with a single nested subschema or a slice of subschemas.
SessionIDResolver is a pluggable resolver for extracting the internal session ID.
Functions ¶
func ApplyCustomHeadersFromAttrs ¶
func ApplyCustomHeadersFromAttrs(r *http.Request, attrs map[string]string, clientHeaders ...http.Header)
ApplyCustomHeadersFromAttrs applies user-defined headers stored in the provided attributes map. Custom headers override built-in defaults when conflicts occur. If clientHeaders is provided (or if the request context carries a Gin context), any custom header whose value starts with "$" (e.g. "$ABC" or "$X-Claude-Code-Session-Id") is dynamically resolved from the client's request headers. If the client did not provide that header, the custom header is omitted from the outgoing request. The magic variable $CPA-SESSION-ID expands to the internal session identifier used for session-affinity (regardless of whether session-affinity is enabled).
func BuildGeminiFunctionDeclarations ¶
func BuildGeminiFunctionDeclarations(root gjson.Result) ([][]byte, map[string]string, map[string]ResponsesToolIdentity)
BuildGeminiFunctionDeclarations builds Gemini function declarations, forward name mapping, and reverse identity mapping.
func CanonicalToolName ¶
func ClaudeToolIsParameterless ¶ added in v8.0.32
ClaudeToolIsParameterless reports whether the tool was declared in the original Claude request with an empty or missing object schema. Such tools had a placeholder "reason" property injected for Gemini/Antigravity schema validation, so any returned arguments must be normalized to "{}" before they reach the Claude client. Schemas that allow dynamic additional or pattern properties are never parameterless.
func CleanClaudeToolArguments ¶ added in v8.0.32
func CleanClaudeToolArguments(rawArgs string, toolName string, originalRequestRawJSON []byte) string
CleanClaudeToolArguments strips placeholder arguments ("reason" or "_") injected during schema normalization for empty object schemas when returning responses to Claude clients. If the tool was declared with empty or missing properties, the arguments are normalized to "{}". Placeholder fields are also stripped recursively from declared nested object properties when they were not declared there. Free-form nested schemas that do not declare an object type or properties are preserved because no placeholder is injected for them. Tools that legitimately declared those fields or use union schemas that cannot be resolved deterministically are left untouched. Deterministic allOf, single-branch unions, and local $ref schemas are resolved within the tool schema scope, matching request translation.
func CleanClaudeToolArgumentsWithTranslated ¶ added in v8.0.32
func CleanClaudeToolArgumentsWithTranslated(rawArgs string, toolName string, originalRequestRawJSON []byte, translatedRequestRawJSON []byte) string
CleanClaudeToolArgumentsWithTranslated strips placeholder arguments ("reason" or "_") only when the translated (actually-sent) tool schema shows that the placeholder was injected for that object (present in the translated schema with the placeholder description or marked required, while absent from the original declaration). When no translated schema is available it falls back to the original-schema inference used by CleanClaudeToolArguments. Parameterless tools are still normalized to "{}" because a strict Claude client rejects any argument for them.
func CleanJSONSchemaForAntigravity ¶
CleanJSONSchemaForAntigravity transforms a tool schema to be compatible with Antigravity API. It handles unsupported keywords, type flattening, and schema simplification while preserving semantic information as description hints and adding placeholders required by VALIDATED mode.
func CleanJSONSchemaForAntigravityClaudeTool ¶ added in v8.0.29
CleanJSONSchemaForAntigravityClaudeTool is the Antigravity tool cleaner for Claude models. It applies the same Antigravity schema cleanup, but flattens multi-branch anyOf/oneOf unions to a single strongest branch: the Antigravity Claude backend converts Gemini function declarations into Claude custom.input_schema and rejects nested multi-branch unions with "JSON schema is invalid", while the Gemini backends accept preserved unions (see Issue 3662 and its regression follow-up).
func CleanJSONSchemaForAntigravityResponse ¶
CleanJSONSchemaForAntigravityResponse transforms a response schema without applying tool-only compatibility rewrites that would alter the client's structured output contract.
Sanitization policy:
- Passthrough: type, properties, items, required, description, enum, nullable, and additionalProperties: false (which Antigravity natively enforces for response schemas).
- Description hints + deletion: unsupported or accepted-but-ignored constraints.
- Flattened: allOf merged into properties/required.
- Unions: multi-branch anyOf/oneOf unions are preserved; single-type nullable unions ([T, null]) project to T with nullable:true.
- Resolved: local $ref targets are inlined before $defs/definitions are removed.
- Dropped: unresolved $ref (after a hint), metadata, unsupported object-key constraints, conditional keywords (after non-conflicting properties are retained), and x-* extensions.
func CleanJSONSchemaForAntigravityTool ¶
CleanJSONSchemaForAntigravityTool transforms an Antigravity function schema. The private backend accepts enum members only as strings, but the declared type still controls the JSON type of generated function arguments, so numeric and boolean types must not be rewritten. requirePlaceholder is used only for Claude VALIDATED mode.
func CleanJSONSchemaForGemini ¶
CleanJSONSchemaForGemini transforms a JSON schema to be compatible with Gemini tool calling. It removes unsupported keywords and simplifies schemas, without adding empty-schema placeholders.
func CleanJSONSchemaForGeminiJSONSchema ¶
CleanJSONSchemaForGeminiJSONSchema transforms a JSON schema for Gemini tool calling when using the parametersJsonSchema carrier. It preserves standard JSON Schema constraints (such as pattern, minLength, maxLength) and additionalProperties (both boolean and schema-valued), while removing Gemini-incompatible metadata fields and cleaning required properties.
func CollectResponsesToolWinners ¶
func CollectResponsesToolWinners(root gjson.Result) map[string]ResponsesToolDescriptor
CollectResponsesToolWinners collects deduplicated winning descriptors for each qualified tool name.
func ConvertResponsesToolChoiceToGemini ¶
func ConvertResponsesToolChoiceToGemini(toolChoice gjson.Result, forwardMap map[string]string) ([]byte, bool)
ConvertResponsesToolChoiceToGemini translates Responses tool_choice into Gemini functionCallingConfig JSON.
func CountAuthFiles ¶
func CountAuthFiles[T any](ctx context.Context, store interface { List(context.Context) ([]T, error) }) int
CountAuthFiles returns the number of auth records available through the provided Store. For filesystem-backed stores, this reflects the number of JSON auth files under the configured directory.
func CreateWhiteImageBase64 ¶
func DeduplicateFunctionDeclarations ¶
DeduplicateFunctionDeclarations removes duplicate named declarations while preserving order.
func DisambiguatedToolNameMap ¶
DisambiguatedToolNameMap builds a sanitized-name → original-name map using the same collision-aware mapping as SanitizedFunctionNameMap.
func FixJSON ¶
FixJSON converts non-standard JSON that uses single quotes for strings into RFC 8259-compliant JSON by converting those single-quoted strings to double-quoted strings with proper escaping.
Examples:
{'a': 1, 'b': '2'} => {"a": 1, "b": "2"}
{"t": 'He said "hi"'} => {"t": "He said \"hi\""}
Rules:
- Existing double-quoted JSON strings are preserved as-is.
- Single-quoted strings are converted to double-quoted strings.
- Inside converted strings, any double quote is escaped (\").
- Common backslash escapes (\n, \r, \t, \b, \f, \\) are preserved.
- \' inside single-quoted strings becomes a literal ' in the output (no escaping needed inside double quotes).
- Unicode escapes (\uXXXX) inside single-quoted strings are forwarded.
- The function does not attempt to fix other non-JSON features beyond quotes.
func GeminiClaudeToolUseID ¶
GeminiClaudeToolUseID returns a stable Claude-facing ID for a provider-native Gemini function call. The opaque ID lets the executor recover the exact provider call from its replay ledger instead of trusting client-mutated args.
func GetGJSONBytesNoCopy ¶
GetGJSONBytesNoCopy returns a GJSON result that may reference data directly. Callers must not retain the result or mutate data while using it.
func GetIPAddress ¶
func GetIPAddress() string
GetIPAddress attempts to find the best-available IP address. It first tries to get the public IP address, and if that fails, it falls back to getting the local outbound IP address.
Returns:
- string: The determined IP address (preferring public IPv4)
func GetOpenAICompatibilityConfig ¶
func GetOpenAICompatibilityConfig(alias string, cfg *config.Config) (*config.OpenAICompatibility, *config.OpenAICompatibilityModel)
GetOpenAICompatibilityConfig returns the OpenAI compatibility configuration and model details for the given alias.
Parameters:
- alias: The model alias to find configuration for
- cfg: The application configuration containing OpenAI compatibility settings
Returns:
- *config.OpenAICompatibility: The matching compatibility configuration, or nil if not found
- *config.OpenAICompatibilityModel: The matching model configuration, or nil if not found
func GetProviderName ¶
GetProviderName determines all AI service providers capable of serving a registered model. It first queries the global model registry to retrieve the providers backing the supplied model name. When the model has not been registered yet, it falls back to legacy string heuristics to infer potential providers.
Supported providers include (but are not limited to):
- "gemini" for Google's Gemini family
- "codex" for OpenAI GPT-compatible providers
- "claude" for Anthropic models
- "openai-compatibility" for external OpenAI-compatible providers
Parameters:
- modelName: The name of the model to identify providers for.
- cfg: The application configuration containing OpenAI compatibility settings.
Returns:
- []string: All provider identifiers capable of serving the model, ordered by preference.
func HasExplicitSessionID ¶
HasExplicitSessionID returns true if ctx explicitly carries a session ID annotation (including an explicit empty string used to clear it).
func HasUnsupportedUnicodePropertyEscape ¶
HasUnsupportedUnicodePropertyEscape reports whether a regular expression string contains a construct that strict upstream JSON Schema validators reject when they compile "pattern" values on the way to a provider.
Two constructs are known to fail, both of which Anthropic's own API accepts verbatim (it does not validate pattern values), so they only surface after the request is translated or forwarded:
- Unicode property escapes (\p{...} or \P{...}): Python's built-in re module, and validators relying on it, fail with "bad escape \p".
- The octal NUL escape (\0): validators that re-serialize or normalize the schema reject it with "is not a 'regex'", while the equivalent \x00 spelling is accepted. Claude Code's built-in Artifact tool emits \0 in its NUL guards (e.g. "^[^\0]*$" on the upload_asset file_paths item).
Dropping the attribute is safe: the client validates its own input locally, so removing an upstream-side pattern constraint does not make a call succeed that would otherwise have been rejected by the tool.
func HideAPIKey ¶
HideAPIKey obscures an API key for logging purposes, showing only the first and last few characters.
Parameters:
- apiKey: The API key to hide.
Returns:
- string: The obscured API key.
func InArray ¶
InArray checks if a string exists in a slice of strings. It iterates through the slice and returns true if the target string is found, otherwise it returns false.
Parameters:
- hystack: The slice of strings to search in
- needle: The string to search for
Returns:
- bool: True if the string is found, false otherwise
func InlineLocalRefs ¶
InlineLocalRefs resolves JSON Pointer references against the original schema. Every reference receives its own copy as long as the expansion budget lasts, sibling keywords override the referenced definition, and cycles terminate as a typed hint instead of recursing forever.
func IsClaudeCodeAttributionSystemText ¶
IsClaudeCodeAttributionSystemText reports whether text is the Claude Code attribution block that carries per-request billing and prompt fingerprint data.
func IsClaudeModel ¶
IsClaudeModel reports whether the model name identifies a Claude model.
func IsClaudeThinkingModel ¶
IsClaudeThinkingModel checks if the model is a Claude thinking model that requires the interleaved-thinking beta header.
func IsCodexResponsesLiteRequest ¶
IsCodexResponsesLiteRequest recognizes the native header and its websocket metadata mirror.
func IsGeminiClaudeToolUseID ¶
IsGeminiClaudeToolUseID reports whether id belongs to the reserved Claude-facing Gemini provenance namespace.
func IsOpenAICompatibilityAlias ¶
IsOpenAICompatibilityAlias checks if the given model name is an alias configured for OpenAI compatibility routing.
Parameters:
- modelName: The model name to check
- cfg: The application configuration containing OpenAI compatibility settings
Returns:
- bool: True if the model name is an OpenAI compatibility alias, false otherwise
func IsResponsesClientToolSearchDeclaration ¶ added in v8.0.28
IsResponsesClientToolSearchDeclaration reports whether a tool declaration is a client-executed Responses tool_search.
func IsResponsesClientToolSearchItem ¶ added in v8.0.28
IsResponsesClientToolSearchItem reports whether a tool_search_call or tool_search_output input item belongs to client-executed tool search. Hosted server search explicitly sets execution to "server".
func MapClaudeToolName ¶ added in v8.0.32
func MapClaudeToolName(toolNameMap map[string]string, originalRequestRawJSON []byte, name string) string
MapClaudeToolName restores the client-facing tool name while preferring an exact declared name over canonical (case/leading-underscore-insensitive) restoration. This prevents distinct tools such as "Read" and "read" from being collapsed to the first declaration when the upstream already returned an exact name.
func MapResponsesClientToolSearchName ¶ added in v8.0.28
MapResponsesClientToolSearchName returns the mapped Gemini function name for the client-executed tool_search shim.
func MapResponsesToolName ¶
MapResponsesToolName returns the mapped Gemini function name if present in forwardMap, else sanitized name.
func MapSanitizedFunctionName ¶
MapSanitizedFunctionName returns the request-specific sanitized name when available.
func MaskAuthorizationHeader ¶
maskAuthorizationHeader masks the Authorization header value while preserving the auth type prefix. Common formats: "Bearer <token>", "Basic <credentials>", "ApiKey <key>", etc. It preserves the prefix (e.g., "Bearer ") and only masks the token/credential part.
Parameters:
- value: The Authorization header value
Returns:
- string: The masked Authorization value with prefix preserved
func MaskSensitiveHeaderValue ¶
MaskSensitiveHeaderValue masks sensitive header values while preserving expected formats.
Behavior by header key (case-insensitive):
- "Authorization": Preserve the auth type prefix (e.g., "Bearer ") and mask only the credential part.
- Headers containing "api-key": Mask the entire value using HideAPIKey.
- Others: Return the original value unchanged.
Parameters:
- key: The HTTP header name to inspect (case-insensitive matching).
- value: The header value to mask when sensitive.
Returns:
- string: The masked value according to the header type; unchanged if not sensitive.
func MaskSensitiveQuery ¶
MaskSensitiveQuery masks sensitive query parameters, e.g. auth_token, within the raw query string.
func NormalizeClaudeToolInputSchema ¶
NormalizeClaudeToolInputSchema makes a JSON Schema compatible with Claude's requirement that a tool input schema is an object without root-level unions.
func OpenAICompatibleProviderKey ¶
OpenAICompatibleProviderKey returns the internal provider key for an OpenAI-compatible provider.
func ParseGJSONBytesNoCopy ¶
ParseGJSONBytesNoCopy parses data into a GJSON result that references data directly. gjson.ParseBytes copies the whole document, which is prohibitive for multi-megabyte payloads. Callers must not retain the result or mutate data while using it.
func PrintSSHTunnelInstructions ¶
func PrintSSHTunnelInstructions(port int)
PrintSSHTunnelInstructions detects the IP address and prints SSH tunnel instructions for the user to connect to the local OAuth callback server from a remote machine.
Parameters:
- port: The local port number for the SSH tunnel
func QualifyResponsesNamespaceToolName ¶
QualifyResponsesNamespaceToolName qualifies a child tool name with its namespace.
func RenameKey ¶
RenameKey renames a key in a JSON string by moving its value to a new key path and then deleting the old key path.
Parameters:
- jsonStr: The JSON string to modify
- oldKeyPath: The dot-notation path to the key that should be renamed
- newKeyPath: The dot-notation path where the value should be moved to
Returns:
- string: The modified JSON string with the key renamed
- error: An error if the operation fails
The function performs the rename in two steps: 1. Sets the value at the new key path 2. Deletes the old key path
func ResolveAuthDir ¶
ResolveAuthDir normalizes the auth directory path for consistent reuse throughout the app. It expands a leading tilde (~) to the user's home directory and returns a cleaned path. If authDir is empty, it defaults to ~/.cli-proxy-api.
func ResolveAutoModel ¶
ResolveAutoModel resolves the "auto" model name to an actual available model. It uses an empty handler type to get any available model from the registry.
Parameters:
- modelName: The model name to check (should be "auto")
Returns:
- string: The resolved model name, or the original if not "auto" or resolution fails
func ResolveGitHubToken ¶
func ResolveGitHubToken() string
ResolveGitHubToken returns the GitHub API token in priority order: 1. server.github-token 2. GITHUB_TOKEN 3. github_token 4. GITSTORE_GIT_TOKEN (only if GITSTORE_GIT_URL points to github.com)
func ResponsesToolDescription ¶
ResponsesToolDescription extracts the description from a tool or function object.
func ResponsesToolParameters ¶
ResponsesToolParameters extracts the schema/parameters from a tool or function object.
func ResponsesToolReverseIdentityMap ¶
func ResponsesToolReverseIdentityMap(rawJSON []byte) map[string]ResponsesToolIdentity
ResponsesToolReverseIdentityMap builds a Gemini function name -> ResponsesToolIdentity map from a Responses request raw JSON.
func RestoreSanitizedToolName ¶
RestoreSanitizedToolName looks up a sanitized function name in the provided map and returns the original client-facing name. If no mapping exists, it returns the sanitized name unchanged.
func SanitizeClaudeFunctionName ¶
SanitizeClaudeFunctionName ensures a function or tool name conforms to Claude's requirements: ^[a-zA-Z0-9_-]{1,64}$. Non-conforming characters (including dots and colons commonly emitted by MCP tools) are replaced with '_'.
func SanitizeClaudeToolID ¶
SanitizeClaudeToolID ensures the given id conforms to Claude's tool_use.id regex ^[a-zA-Z0-9_-]+$. Non-conforming characters are replaced with '_'; an empty result gets a generated fallback.
func SanitizeFunctionName ¶
SanitizeFunctionName ensures a function name matches the requirements for Gemini/Vertex AI. It replaces invalid characters with underscores, ensures it starts with a letter or underscore, and truncates it to 64 characters if necessary. Regex Rule: [^a-zA-Z0-9_.:-] replaced with _.
func SanitizedFunctionNameMap ¶
SanitizedFunctionNameMap builds an original-name → sanitized-name map from request tools. Exact duplicate names share a mapping. Distinct names that sanitize to the same value receive deterministic hash suffixes so every declaration remains addressable within the 64-byte limit.
func SanitizedToolNameMap ¶
SanitizedToolNameMap builds the legacy sanitized-name → original-name map from top-level Claude-style tools. Collision-aware translators should use DisambiguatedToolNameMap instead.
func SessionIDFromContext ¶
SessionIDFromContext retrieves the internal session ID from the context if present.
func SetLogLevel ¶
SetLogLevel configures the logrus log level based on the configuration. It sets the log level to DebugLevel if debug mode is enabled, otherwise to InfoLevel.
func SetProxy ¶
SetProxy configures the provided HTTP client with proxy settings from the configuration. It supports SOCKS5, HTTP, and HTTPS proxies. The function modifies the client's transport to route requests through the configured proxy server.
func StripClaudeCodeAttributionSystem ¶
StripClaudeCodeAttributionSystem removes Claude Code billing/CCH attribution blocks from a Messages body. Other system content is kept. Providers such as Kimi and Antigravity may treat this block as prompt text, so callers use this helper when the active policy has not explicitly opted into a full CLI profile.
func ToolNameMapFromClaudeRequest ¶
ToolNameMapFromClaudeRequest returns a canonical-name -> original-name map extracted from a Claude request. It is used to restore exact tool name casing for clients that require strict tool name matching (e.g. Claude Code).
func UnwrapResponsesCustomToolInput ¶
UnwrapResponsesCustomToolInput extracts the raw input string from custom tool arguments JSON or plain string.
func Walk ¶
Walk recursively traverses a JSON structure to find all occurrences of a specific field. It builds paths to each occurrence and adds them to the provided paths slice.
Parameters:
- value: The gjson.Result object to traverse
- path: The current path in the JSON structure (empty string for root)
- field: The field name to search for
- paths: Pointer to a slice where found paths will be stored
The function works recursively, building dot-notation paths to each occurrence of the specified field throughout the JSON structure.
func WalkSchema ¶ added in v8.0.34
WalkSchema is Walk for JSON Schema documents: it records the field wherever a schema keyword may appear, but does not descend into literal values (default, example, examples, const, enum), whose contents are client data rather than subschemas. The literal keyword itself is still recorded when it is the searched field, and under a property-name map a key spelled like one is a property name whose subschema is still walked.
func WithSessionID ¶
WithSessionID returns a new context annotated with the internal session ID. Passing an empty sessionID explicitly clears/overrides any previous session ID in parent contexts.
func WritablePath ¶
func WritablePath() string
WritablePath returns the cleaned WRITABLE_PATH environment variable when it is set. It accepts both uppercase and lowercase variants for compatibility with existing conventions.
Types ¶
type ClaudeToolResult ¶
type ClaudeToolResult struct {
// Result is the value for functionResponse.response.result.
Result string
// ResultIsRaw reports whether Result holds raw JSON (write with sjson.SetRaw*)
// or a plain string (write with sjson.Set*). Writing raw JSON text through
// sjson.Set as a string value would double-encode it, so callers must honor
// this flag.
ResultIsRaw bool
// Images holds base64 image blocks separated out of the content.
Images []ClaudeToolResultImage
}
ClaudeToolResult is the normalized form of a Claude tool_result `content` field, ready to be written into a Gemini-style functionResponse.
func ConvertClaudeToolResultContent ¶
func ConvertClaudeToolResultContent(content gjson.Result) ClaudeToolResult
ConvertClaudeToolResultContent normalizes a Claude tool_result `content` field into a deterministic Gemini functionResponse result plus any extracted images.
Claude tool_result content may be a plain string, an array of mixed text/image blocks, a single object, or absent. Some Claude->Gemini translators previously wrote content.Raw straight through sjson.SetBytes, which double-encoded string content and flattened structured arrays (including base64 image data) into one opaque escaped string. This helper mirrors the Antigravity Claude translator, which already handles structured content correctly:
- string -> plain string result (no double-encoding)
- single non-image -> raw JSON result (structure preserved)
- multiple non-image -> raw JSON array result
- base64 image block -> separated into Images (emitted as inline data parts)
- object -> raw JSON result, or image -> Images with empty result
- absent/empty -> empty string result
Unlike Antigravity, image blocks without base64 data are dropped rather than emitted as empty inline data parts, matching the Gemini image part guards.
type ClaudeToolResultImage ¶
ClaudeToolResultImage represents a base64-encoded image extracted from a Claude tool_result content block. Callers emit it as a provider-specific inline data part so that image bytes do not bloat the textual function response result.
type ResponsesToolDescriptor ¶
type ResponsesToolDescriptor struct {
Name string // Qualified name (e.g. "functions__exec" or "exec")
LocalName string // Local name without namespace (e.g. "exec")
Namespace string // Namespace if any (e.g. "functions")
ToolType string // "function", "custom", etc.
Tool gjson.Result
SourcePriority int // 0 for top-level tools, 1 for additional_tools, 2 for tool_search_output
Direct bool // true if declared directly, false if declared as namespace child
Order int // original discovery order
ClientSearch bool // true for a client-executed tool_search declaration
}
ResponsesToolDescriptor is an internal representation of a tool declaration in a Responses request.
func CollectResponsesToolDescriptors ¶
func CollectResponsesToolDescriptors(root gjson.Result) []ResponsesToolDescriptor
CollectResponsesToolDescriptors extracts all tool descriptors from a Responses request root.
type ResponsesToolIdentity ¶
type ResponsesToolIdentity struct {
Name string
Namespace string
Custom bool
ApplyPatch bool // Resolved from the winning original declaration, never from the upstream name.
ToolSearch bool // Marks the function shim standing in for a client-executed tool_search declaration.
}
ResponsesToolIdentity represents the resolved identity of a tool in OpenAI Responses format.