common

package
v8.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const ExternalToolPrefix = "external_"

Antigravity agents (Interactions API) ship intrinsic sandbox tools such as read_file / write_file / execute_code. When a client-defined function re-declares one of those names, Google returns 500 "Unknown Error". The proxy therefore renames colliding client tools with the ExternalToolPrefix on the way upstream and strips the prefix again on every response path, so the client keeps seeing its original names.

Variables

This section is empty.

Functions

func AlignClaudeToolResults

func AlignClaudeToolResults(content gjson.Result, toolUseIDs []string) gjson.Result

AlignClaudeToolResults orders tool_result blocks by the preceding tool_use IDs, preserving non-result content blocks at their existing indexes. If a complete one-to-one match is unavailable, the original content is returned.

func AlignOpenAIToolCallMessages

func AlignOpenAIToolCallMessages(messages [][]byte, extraAmbiguousIDs ...string) [][]byte

AlignOpenAIToolCallMessages reorders tool result messages to immediately follow the assistant message that issued their matching tool_calls by tool_call_id. It preserves original message order, content parts, reasoning fields, and numeric precision, while leaving ambiguous, orphan, and incomplete histories untouched.

func AntigravityToolNameToUpstream

func AntigravityToolNameToUpstream(name string) string

AntigravityToolNameToUpstream maps a client-facing tool name to the name sent to the antigravity Interactions API. Names that do not collide are returned unchanged.

func AntigravityUpstreamToolNameToClient

func AntigravityUpstreamToolNameToClient(name string) string

AntigravityUpstreamToolNameToClient strips the external prefix from an upstream tool name before it reaches the client, provided that the base name is an intrinsic tool that was prefixed to avoid collisions. Non-colliding or non-prefixed names pass through unchanged.

func AppendSSEEventBytes

func AppendSSEEventBytes(out []byte, event string, payload []byte, trailingNewlines int) []byte

func AppendSSEEventString

func AppendSSEEventString(out []byte, event, payload string, trailingNewlines int) []byte

func AttachCacheControl

func AttachCacheControl(dst []byte, src gjson.Result) []byte

AttachCacheControl copies a Claude-compatible cache_control object from src onto dst. Returns dst unchanged when cache_control is missing or not an object.

func AttachMessageCacheControl

func AttachMessageCacheControl(msg []byte, src gjson.Result) []byte

AttachMessageCacheControl applies message-level cache_control onto the last content block. Part-level cache_control wins when the last block already has one. String content is promoted to a content array so Claude can accept cache_control.

func AttachToolMessageCacheControl

func AttachToolMessageCacheControl(msg []byte, src gjson.Result) []byte

AttachToolMessageCacheControl hoists part-level or message-level cache_control onto the tool_result content block in msg. Part-level cache_control from src content takes precedence over message-level cache_control.

func BuildClaudeStructuredOutputInstruction

func BuildClaudeStructuredOutputInstruction(format gjson.Result) string

BuildClaudeStructuredOutputInstruction formats structured output settings (from Chat Completions response_format or Responses text.format) as explicit instructions to inject into Claude's system prompt.

func ClaudeInputTokensJSON

func ClaudeInputTokensJSON(count int64) []byte

func ClaudeMessageSystemReminderText

func ClaudeMessageSystemReminderText(content gjson.Result) (string, bool)

ClaudeMessageSystemReminderText converts a Claude message-level system value into ordinary user-visible reminder text for non-Claude upstream formats.

func ContainsJSONRef

func ContainsJSONRef(value gjson.Result) bool

ContainsJSONRef reports whether value (recursively) contains a string-valued "$ref" property.

func ContentHasGeminiFunctionCall

func ContentHasGeminiFunctionCall(content []byte) bool

ContentHasGeminiFunctionCall reports whether a Gemini content turn contains any functionCall part.

func ContentHasGeminiFunctionResponse

func ContentHasGeminiFunctionResponse(content []byte) bool

ContentHasGeminiFunctionResponse reports whether a Gemini content turn contains any functionResponse part.

func DeriveClaudeUserID

func DeriveClaudeUserID(rawJSON []byte) string

DeriveClaudeUserID returns a stable value for the Claude request field metadata.user_id. It preserves any caller-supplied metadata.user_id or OpenAI Chat Completions user field, then derives a deterministic value from stable client signals (prompt_cache_key, session_id, conversation_id, first user message content, and model/system instructions). The same conversation therefore gets the same user_id on every worker and every turn, while different conversations get different values.

func ExtractResponsesCallID

func ExtractResponsesCallID(node gjson.Result) string

ExtractResponsesCallID extracts the tool call ID from a Responses API item, prioritizing dedicated tool call references over generic item IDs: call_id -> tool_call_id -> callId -> id (excluding fco_ output item IDs)

func GeminiTokenCountJSON

func GeminiTokenCountJSON(count int64) []byte

func GenerateClaudeToolCallID

func GenerateClaudeToolCallID() string

GenerateClaudeToolCallID generates a random tool use ID prefixed with toolu_ using rejection sampling to guarantee a uniform distribution across the 62 alphanumeric characters.

func InteractionsUsage

func InteractionsUsage(root gjson.Result) gjson.Result

func IsDevinCodexAppAutomationUpdate

func IsDevinCodexAppAutomationUpdate(namespace, toolName string) bool

IsDevinCodexAppAutomationUpdate reports whether a tool declaration corresponds to the automation_update method within the mcp__codex_app namespace.

func IsGeminiThoughtPart

func IsGeminiThoughtPart(part gjson.Result) bool

IsGeminiThoughtPart reports whether a Gemini part contains hidden model thought.

func JoinRawArray

func JoinRawArray(items [][]byte) []byte

func MergeAdjacentGeminiContents

func MergeAdjacentGeminiContents(contents [][]byte) [][]byte

MergeAdjacentGeminiContents merges consecutive user Content turns. Mid-conversation system messages in Claude requests are downgraded to user reminder turns. When followed or preceded by other user turns or tool results, their parts are merged into a single user turn. Consecutive model turns are strictly kept unmerged to avoid shifting part indices and breaking cryptographic thought signatures and reasoning replay.

func MergeAdjacentGeminiUserContents

func MergeAdjacentGeminiUserContents(contents [][]byte) [][]byte

MergeAdjacentGeminiUserContents merges consecutive user Content turns, but leaves turns containing functionResponse unmerged to preserve tool-call/response boundaries.

func NewRawArrayItems

func NewRawArrayItems(capacity int64) [][]byte

NewRawArrayItems creates a raw item slice sized for the expected input.

func NormalizeOpenAIFileData

func NormalizeOpenAIFileData(filename, fallbackMIMEType, fileData string) (mimeType, data string, ok bool)

NormalizeOpenAIFileData returns the MIME type and raw base64 payload for OpenAI file content.

func NormalizeResponsesToolCallOutputs

func NormalizeResponsesToolCallOutputs(items []gjson.Result) []gjson.Result

NormalizeResponsesToolCallOutputs scans a slice of Responses input items, pairs function_call_output / custom_tool_call_output with preceding pending tool calls, and assigns missing call_ids to tool outputs using a multi-pass matching strategy: 1. Exact explicit call ID match (reserving calls for outputs that explicitly reference them across the entire conversation). 2. Function name match for outputs that omit a call ID (skipping pending calls reserved by future explicit outputs). 3. FIFO queue fallback for remaining outputs that omit a call ID (skipping pending calls reserved by future explicit outputs). Outputs that already carry an explicit call ID that does not match any pending call are never rewritten or stolen.

func ObfuscateExecCommandDescription

func ObfuscateExecCommandDescription(desc string) string

ObfuscateExecCommandDescription replaces "returning output or a session ID for ongoing interaction" with "returning output or an session ID for ongoing interaction".

func ObfuscateWriteStdinDescription

func ObfuscateWriteStdinDescription(desc string) string

ObfuscateWriteStdinDescription replaces "Writes characters to an existing unified exec session and returns recent output." with "Writes characters to a existing unified exec session and returns recent output.".

func ReorderGeminiUserParts

func ReorderGeminiUserParts(parts [][]byte) [][]byte

ReorderGeminiUserParts reorders parts within a Gemini user turn so that text parts (such as prompt text and system reminders) precede functionResponse parts. This resolves upstream provider validation failures (such as Google Cloud Vertex AI returning 400 "Requests ending with a model turn are not supported" when functionResponse is followed by text in the same turn).

func RequestModelName

func RequestModelName(originalRequestRawJSON, requestRawJSON []byte) string

RequestModelName returns the model name from the original request, falling back to the translated request when the original request is unavailable.

func SSEEventData

func SSEEventData(event string, payload []byte) []byte

func SanitizeDevinToolDescription

func SanitizeDevinToolDescription(toolName, desc string) string

SanitizeDevinToolDescription applies description obfuscation for Devin function tools.

func SetGeminiFunctionResponseRaw

func SetGeminiFunctionResponseRaw(part []byte, path string, rawJSON string) []byte

SetGeminiFunctionResponseRaw is a convenience wrapper around SetGeminiFunctionResponseResult for raw JSON strings.

func SetGeminiFunctionResponseResult

func SetGeminiFunctionResponseResult(part []byte, path string, result gjson.Result) []byte

SetGeminiFunctionResponseResult sets the Gemini functionResponse result or response field. If the result contains a JSON Schema or OpenAPI "$ref" property with a string value, it is preserved as opaque JSON text with sjson.SetBytes. This prevents Gemini/Vertex AI from interpreting "$ref" as a reference to a media part in function_response.parts and rejecting the request with HTTP 400. If path points to "functionResponse.response" or "response", a stringified result is placed under the ".result" child object to satisfy Gemini's requirement that "response" is an object.

func SetRawArrayItems

func SetRawArrayItems(data []byte, path string, items [][]byte) []byte

SetRawArrayItems replaces an empty JSON array at path with raw items. The single-item path avoids allocating an intermediate joined array.

func SetResponsesToolCallIdentity

func SetResponsesToolCallIdentity(item []byte, name, namespace, itemPath string) []byte

SetResponsesToolCallIdentity writes a resolved Responses tool name and namespace.

func SetStringWithoutHTMLEscape

func SetStringWithoutHTMLEscape(data []byte, path, value string) ([]byte, error)

SetStringWithoutHTMLEscape sets a string field in a JSON payload without escaping HTML characters (<, >, &). Standard sjson.Set/SetBytes delegates string values containing quotes or special characters to encoding/json.Marshal, which unconditionally escapes <, >, & to \u003c, \u003e, \u0026.

func SplitGeminiFunctionResponseTurns

func SplitGeminiFunctionResponseTurns(contents [][]byte) [][]byte

SplitGeminiFunctionResponseTurns separates functionResponse parts from other user parts. Gemini/Antigravity requires a function response turn to immediately follow the model turn containing the corresponding call; text or reminders in the same user turn or intervening reminder turns can otherwise make the response appear orphaned to the upstream validator.

func SystemReminderText

func SystemReminderText(text string) string

SystemReminderText wraps text in the <system-reminder> envelope so non-Claude upstream formats treat demoted mid-session system or developer instructions as system directives rather than user speech.

Types

type ClaudeMessageAccumulator

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

ClaudeMessageAccumulator groups consecutive Claude messages by role.

func NewClaudeMessageAccumulator

func NewClaudeMessageAccumulator(capacity int) *ClaudeMessageAccumulator

NewClaudeMessageAccumulator creates an accumulator sized for the expected messages.

func (*ClaudeMessageAccumulator) Append

func (a *ClaudeMessageAccumulator) Append(message []byte)

Append adds one Claude-shaped message to the current role turn.

func (*ClaudeMessageAccumulator) Flush

func (a *ClaudeMessageAccumulator) Flush()

Flush closes the current role turn while keeping accumulated messages.

func (*ClaudeMessageAccumulator) Messages

func (a *ClaudeMessageAccumulator) Messages() [][]byte

Messages flushes the final turn and returns all accumulated messages.

Jump to

Keyboard shortcuts

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