util

package
v8.0.61 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 34 Imported by: 0

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

View Source
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

View Source
var SchemaMapKeywords = [...]string{
	"properties",
	"$defs",
	"definitions",
	"patternProperties",
	"dependentSchemas",
	"dependencies",
}

SchemaMapKeywords lists JSON Schema keywords whose values are maps of subschemas.

View Source
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.

View Source
var SessionIDResolver func(ctx context.Context, clientHeaders http.Header) string

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 ojson.Result) ([][]byte, map[string]string, map[string]ResponsesToolIdentity)

BuildGeminiFunctionDeclarations builds Gemini function declarations, forward name mapping, and reverse identity mapping.

func CanonicalToolName

func CanonicalToolName(name string) string

func ClaudeToolIsParameterless added in v8.0.32

func ClaudeToolIsParameterless(toolName string, originalRequestRawJSON []byte) bool

ClaudeToolIsParameterless reports whether the tool was declared in the original Claude request with a missing schema or an explicitly closed empty object schema (additionalProperties: false). Schemas that allow dynamic additional or pattern properties, including objects that omit additionalProperties, are not 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 and additionalProperties: false, 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

func CleanJSONSchemaForAntigravity(jsonStr string) string

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

func CleanJSONSchemaForAntigravityClaudeTool(jsonStr string, requirePlaceholder bool) string

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

func CleanJSONSchemaForAntigravityResponse(jsonStr string) string

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

func CleanJSONSchemaForAntigravityTool(jsonStr string, requirePlaceholder bool) string

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

func CleanJSONSchemaForGemini(jsonStr string) string

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

func CleanJSONSchemaForGeminiJSONSchema(jsonStr string) string

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 ojson.Result) map[string]ResponsesToolDescriptor

CollectResponsesToolWinners collects deduplicated winning descriptors for each qualified tool name.

func CollectResponsesToolWinnersDoc added in v8.0.52

func CollectResponsesToolWinnersDoc(doc *ojson.Doc) map[string]ResponsesToolDescriptor

CollectResponsesToolWinnersDoc collects deduplicated winning descriptors from doc.

func ConvertResponsesToolChoiceToGemini

func ConvertResponsesToolChoiceToGemini(toolChoice ojson.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 CreateWhiteImageBase64(aspectRatio string) (string, error)

func DeduplicateFunctionDeclarations

func DeduplicateFunctionDeclarations(raw []byte) []byte

DeduplicateFunctionDeclarations removes duplicate named declarations while preserving order.

func DeleteJSONBytesIfExists added in v8.0.45

func DeleteJSONBytesIfExists(data []byte, path string) ([]byte, error)

DeleteJSONBytesIfExists behaves like ojson.DeleteBytes but returns data unchanged when path is absent. ojson.DeleteBytes copies the document at least once even when there is nothing to delete (a partial prefix copy is built and discarded, then the whole input is copied again before sjson returns the original slice), which dominates allocation when callers defensively delete alias spellings that are usually missing. path must be a nonempty literal dotted path (gjson-compatible escapes like \. are supported); sjson's "-1" last-element delete and ":" forced-object-key syntax are not supported here. Behavior otherwise matches ojson.DeleteBytes.

func DeleteJSONDocIfExists added in v8.0.52

func DeleteJSONDocIfExists(doc *ojson.Doc, path string) error

DeleteJSONDocIfExists deletes path from doc only when the path exists.

func DisambiguatedToolNameMap

func DisambiguatedToolNameMap(rawJSON []byte) map[string]string

DisambiguatedToolNameMap builds a sanitized-name → original-name map using the same collision-aware mapping as SanitizedFunctionNameMap.

func FixJSON

func FixJSON(input string) string

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

func GeminiClaudeToolUseID(callID, name, argsRaw string) string

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

func GetGJSONBytesNoCopy(data []byte, path string) gjson.Result

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

func GetProviderName(modelName string) []string

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

func HasExplicitSessionID(ctx context.Context) bool

HasExplicitSessionID returns true if ctx explicitly carries a session ID annotation (including an explicit empty string used to clear it).

func HasUnsupportedUnicodePropertyEscape

func HasUnsupportedUnicodePropertyEscape(pattern string) bool

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

func HideAPIKey(apiKey string) string

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

func InArray(hystack []string, needle string) bool

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

func InlineLocalRefs(jsonStr string) string

InlineLocalRefs resolves JSON Pointer references against the original schema. Every reference receives its own copy as long as the expansion budget lasts, conflicting sibling assertions remain conjunctive, and cycles terminate as a typed hint instead of recursing forever.

func IsClaudeCodeAttributionSystemText

func IsClaudeCodeAttributionSystemText(text string) bool

IsClaudeCodeAttributionSystemText reports whether text is the Claude Code attribution block that carries per-request billing and prompt fingerprint data.

func IsClaudeLegacySystemReminderModel added in v8.0.59

func IsClaudeLegacySystemReminderModel(model string) bool

IsClaudeLegacySystemReminderModel reports whether model is a known Claude model that rejects a mid-conversation role=system message. Matching ignores case, surrounding whitespace and any provider prefix. Unknown and future IDs are not listed, so callers treat them as accepting the turn.

func IsClaudeModel

func IsClaudeModel(model string) bool

IsClaudeModel reports whether the model name identifies a Claude model.

func IsClaudeThinkingModel

func IsClaudeThinkingModel(model string) bool

IsClaudeThinkingModel checks if the model is a Claude thinking model that requires the interleaved-thinking beta header.

func IsCodexResponsesLiteRequest

func IsCodexResponsesLiteRequest(body []byte, headers http.Header) bool

IsCodexResponsesLiteRequest recognizes the native header and its websocket metadata mirror.

func IsGeminiClaudeToolUseID

func IsGeminiClaudeToolUseID(id string) bool

IsGeminiClaudeToolUseID reports whether id belongs to the reserved Claude-facing Gemini provenance namespace.

func IsOpenAICompatibilityAlias

func IsOpenAICompatibilityAlias(modelName string, cfg *config.Config) bool

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

func IsResponsesClientToolSearchDeclaration(tool ojson.Result) bool

IsResponsesClientToolSearchDeclaration reports whether a tool declaration is a client-executed Responses tool_search.

func IsResponsesClientToolSearchItem added in v8.0.28

func IsResponsesClientToolSearchItem(item ojson.Result) bool

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. It re-scans the request body on every call; hot paths should precompute with UnambiguousToolNameMapFromClaudeRequest and use MapToolName instead. 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

func MapResponsesClientToolSearchName(forwardMap map[string]string) string

MapResponsesClientToolSearchName returns the mapped Gemini function name for the client-executed tool_search shim.

func MapResponsesToolName

func MapResponsesToolName(forwardMap map[string]string, name string) string

MapResponsesToolName returns the mapped Gemini function name if present in forwardMap, else sanitized name.

func MapSanitizedFunctionName

func MapSanitizedFunctionName(nameMap map[string]string, name string) string

MapSanitizedFunctionName returns the request-specific sanitized name when available.

func MapToolName

func MapToolName(toolNameMap map[string]string, name string) string

func MaskAuthorizationHeader

func MaskAuthorizationHeader(value string) string

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

func MaskSensitiveHeaderValue(key, value string) string

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

func MaskSensitiveQuery(raw string) string

MaskSensitiveQuery masks sensitive query parameters, e.g. auth_token, within the raw query string.

func NormalizeClaudeToolInputSchema

func NormalizeClaudeToolInputSchema(schema []byte) []byte

NormalizeClaudeToolInputSchema makes a JSON Schema compatible with Claude's requirement that a tool input schema is an object without root-level unions.

func NormalizeJSONSchemaNumericConstraints added in v8.0.51

func NormalizeJSONSchemaNumericConstraints(jsonStr string) string

NormalizeJSONSchemaNumericConstraints converts string-encoded integer values on JSON Schema numeric constraint keywords (minLength, maxLength, minItems, maxItems, minProperties, maxProperties) to JSON numbers. Google's Protobuf Schema format represents these int64 fields as strings, whereas standard JSON Schema carriers (such as parametersJsonSchema) require numeric values.

func OpenAICompatibleProviderKey

func OpenAICompatibleProviderKey(name string) string

OpenAICompatibleProviderKey returns the internal provider key for an OpenAI-compatible provider.

func ParseGJSONBytesNoCopy

func ParseGJSONBytesNoCopy(data []byte) gjson.Result

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

func QualifyResponsesNamespaceToolName(namespaceName, childName string) string

QualifyResponsesNamespaceToolName qualifies a child tool name with its namespace.

func RenameKey

func RenameKey(jsonStr, oldKeyPath, newKeyPath string) (string, error)

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

func ResolveAuthDir(authDir string) (string, error)

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

func ResolveAutoModel(modelName string) string

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 ResolveClientHeaders added in v8.0.36

func ResolveClientHeaders(r *http.Request, clientHeaders ...http.Header) http.Header

ResolveClientHeaders returns the client request headers from the provided slice or falls back to the Gin request headers in r.Context() when available.

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

func ResponsesToolDescription(tool ojson.Result) string

ResponsesToolDescription extracts the description from a tool or function object.

func ResponsesToolParameters

func ResponsesToolParameters(tool ojson.Result) ojson.Result

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

func RestoreSanitizedToolName(toolNameMap map[string]string, sanitizedName string) string

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

func SanitizeClaudeFunctionName(name string) string

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

func SanitizeClaudeToolID(id string) string

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

func SanitizeFunctionName(name string) string

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

func SanitizedFunctionNameMap(rawJSON []byte) map[string]string

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

func SanitizedToolNameMap(rawJSON []byte) map[string]string

SanitizedToolNameMap builds the legacy sanitized-name → original-name map from top-level Claude-style tools. Collision-aware translators should use DisambiguatedToolNameMap instead.

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext retrieves the internal session ID from the context if present.

func SetLogLevel

func SetLogLevel(cfg *config.Config)

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

func SetProxy(cfg *config.SDKConfig, httpClient *http.Client) *http.Client

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

func StripClaudeCodeAttributionSystem(payload []byte) []byte

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

func ToolNameMapFromClaudeRequest(rawJSON []byte) map[string]string

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 UnambiguousToolNameMapFromClaudeRequest added in v8.0.37

func UnambiguousToolNameMapFromClaudeRequest(rawJSON []byte) map[string]string

UnambiguousToolNameMapFromClaudeRequest precomputes the legacy Claude mapper's collision policy so response chunks only need MapToolName, not the request body. Ambiguous canonical keys are stored with an empty value, so the returned map is only meaningful with MapToolName (which keeps the upstream name for empty values); do not index it directly.

func UnwrapResponsesCustomToolInput

func UnwrapResponsesCustomToolInput(arguments string) string

UnwrapResponsesCustomToolInput extracts the raw input string from custom tool arguments JSON or plain string.

func Walk

func Walk(value ojson.Result, path, field string, paths *[]string)

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 ojson.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

func WalkSchema(value ojson.Result, path, field string, paths *[]string)

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

func WithSessionID(ctx context.Context, sessionID string) context.Context

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 or .error.
	Result string
	// ResultIsRaw reports whether Result holds raw JSON (write with ojson.SetRaw*)
	// or a plain string (write with ojson.Set*). Writing raw JSON text through
	// ojson.Set as a string value would double-encode it, so callers must honor
	// this flag.
	ResultIsRaw bool
	// IsError preserves an explicit tool_result.is_error failure flag.
	IsError bool
	// Images holds base64 image blocks separated out of the content.
	Images []ClaudeToolResultImage
}

ClaudeToolResult is the normalized form of a Claude tool_result block, ready to be written into a Gemini-style functionResponse.

func ConvertClaudeToolResult added in v8.0.48

func ConvertClaudeToolResult(block ojson.Result) ClaudeToolResult

ConvertClaudeToolResult normalizes a complete Claude tool_result block while preserving its success/failure semantics.

func ConvertClaudeToolResultContent

func ConvertClaudeToolResultContent(content ojson.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 ojson.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

type ClaudeToolResultImage struct {
	MimeType string
	Data     string
}

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           ojson.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 ojson.Result) []ResponsesToolDescriptor

CollectResponsesToolDescriptors extracts all tool descriptors from a Responses request root.

func CollectResponsesToolDescriptorsDoc added in v8.0.52

func CollectResponsesToolDescriptorsDoc(doc *ojson.Doc) []ResponsesToolDescriptor

CollectResponsesToolDescriptorsDoc extracts all tool descriptors from a Responses request doc.

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.

Jump to

Keyboard shortcuts

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