common

package
v8.0.71 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GeminiClaudeCarrierPrefix     = "cpa-gemini-carrier-v1:"
	GeminiClaudeCarrierNext       = "next"
	GeminiClaudeCarrierPrevious   = "previous"
	GeminiClaudeCarrierStandalone = "standalone"
	GeminiClaudeCarrierText       = "text"
	GeminiClaudeCarrierFunction   = "function"
	GeminiClaudeCarrierAny        = "any"
)

Gemini Claude carriers encode direction and semantic target on the client-facing wire.

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 ojson.Result, toolUseIDs []string) ojson.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. Escape the entire prefix chain ending in an intrinsic name so real external_ names remain distinguishable.

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 ApplyPatchFailure added in v8.0.9

func ApplyPatchFailure(responseID string, sequence int) []byte

ApplyPatchFailure builds a terminal Responses failure without exposing upstream arguments.

func ApplyPatchInputDelta added in v8.0.9

func ApplyPatchInputDelta(s *ApplyPatchCallState, delta string, sequence int) []byte

ApplyPatchInputDelta builds a Responses custom-tool input delta without SSE framing.

func ApplyPatchInputDone added in v8.0.9

func ApplyPatchInputDone(s *ApplyPatchCallState, input string, sequence int) []byte

ApplyPatchInputDone builds a Responses custom-tool input completion without SSE framing.

func AttachCacheControl

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

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

func AttachMessageCacheControl

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

AttachMessageCacheControl applies message-level cache_control onto the last eligible non-empty content block. Part-level cache_control wins when the target 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 ojson.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 BuildClaudeFallbackMetadata added in v8.0.66

func BuildClaudeFallbackMetadata(contentBlock ojson.Result, defaultFromModel, defaultToModel, boundaryKey string, boundaryIndex *int) []byte

BuildClaudeFallbackMetadata serializes a structured fallback metadata object preserving upstream from/to/trigger objects and an optional boundary index.

func BuildClaudeStructuredOutputInstruction

func BuildClaudeStructuredOutputInstruction(format ojson.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 ojson.Result) (string, bool)

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

func ClaudeMessagesJSONToSSE added in v8.0.14

func ClaudeMessagesJSONToSSE(rawJSON []byte) ([]byte, string)

ClaudeMessagesJSONToSSE adapts a native Messages response for the existing SSE aggregators and returns its model. SSE and other payloads pass through unchanged.

func ClaudeModelSameOrSnapshot added in v8.0.66

func ClaudeModelSameOrSnapshot(primaryModel, upstreamModel string) bool

ClaudeModelSameOrSnapshot reports whether primaryModel and upstreamModel refer to the same Anthropic model or an 8-digit YYYYMMDD snapshot thereof.

func ClaudePreTokenFallbackModels added in v8.0.66

func ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON []byte, fallbackRequestedModel, upstreamModel string) (fromModel, toModel string, ok bool)

ClaudePreTokenFallbackModels detects when an Anthropic message_start model already switched to a fallback model (including array fallbacks, fallbacks: "default", and sticky-routing turns).

func CodexReplaySignatureForTarget added in v8.0.34

func CodexReplaySignatureForTarget(modelName, rawSignature string) (string, bool)

CodexReplaySignatureForTarget returns the exact value that may be written as a Responses reasoning encrypted_content for the Codex-format upstream serving modelName, or false when rawSignature must not replay there. Positively detected families must match the target family exactly (an unmapped target defaults to the Codex GPT family, mirroring the Codex translators' purpose) and go through the shared compatibility normalization, so cache-prefixed values such as "gpt#..." are stripped to their native payload instead of being forwarded verbatim. Grok has no detectable envelope, so it falls back to its shape inspector keyed on the target.

func ContainsJSONRef

func ContainsJSONRef(value ojson.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 CountSendableGeminiParts added in v8.0.20

func CountSendableGeminiParts(parts [][]byte) int

CountSendableGeminiParts counts the parts for which GeminiPartIsSendable holds.

func DecodeGeminiClaudeCarrierSignature added in v8.0.68

func DecodeGeminiClaudeCarrierSignature(rawSignature string) (signatureValue, direction, targetKind string, marked, ok bool)

DecodeGeminiClaudeCarrierSignature validates and unwraps a marked carrier, or returns a legacy raw signature.

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 EncodeGeminiClaudeCarrierSignature added in v8.0.68

func EncodeGeminiClaudeCarrierSignature(rawSignature, direction, targetKind string) string

EncodeGeminiClaudeCarrierSignature marks the native part a Claude-facing signature belongs to.

func ExtractResponsesCallID

func ExtractResponsesCallID(node ojson.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 GeminiPartFunctionCall added in v8.0.52

func GeminiPartFunctionCall(part ojson.Result) ojson.Result

GeminiPartFunctionCall returns the functionCall or snake_case function_call object from a Gemini part.

func GeminiPartFunctionResponse added in v8.0.52

func GeminiPartFunctionResponse(part ojson.Result) ojson.Result

GeminiPartFunctionResponse returns the functionResponse or snake_case function_response object from a Gemini part.

func GeminiPartIsSendable added in v8.0.20

func GeminiPartIsSendable(part []byte) bool

GeminiPartIsSendable reports whether a Gemini part gives the model something to read. A text part that is empty or only whitespace does not.

func GeminiPartsHaveFunctionCall added in v8.0.52

func GeminiPartsHaveFunctionCall(parts ojson.Result) bool

GeminiPartsHaveFunctionCall reports whether a parsed Gemini parts array contains any functionCall part without copying or re-parsing the enclosing content raw bytes.

func GeminiPartsHaveFunctionResponse added in v8.0.52

func GeminiPartsHaveFunctionResponse(parts ojson.Result) bool

GeminiPartsHaveFunctionResponse reports whether a parsed Gemini parts array contains any functionResponse part without copying or re-parsing the enclosing content raw bytes.

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 InteractionsAttachmentType added in v8.0.20

func InteractionsAttachmentType(part ojson.Result) string

InteractionsAttachmentType names the type of an Interactions content part that carries an attachment, or returns "" for text and for parts that name nothing. It is the type reported when a translation cannot send the part.

func InteractionsUsage

func InteractionsUsage(root ojson.Result) ojson.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 ojson.Result) bool

IsGeminiThoughtPart reports whether a Gemini part contains hidden model thought.

func IsHTTPURL added in v8.0.20

func IsHTTPURL(value string) bool

IsHTTPURL reports whether value is an absolute http or https URL with a host.

func IsInteractionsInstructionStep added in v8.0.20

func IsInteractionsInstructionStep(step ojson.Result, inherited bool) bool

IsInteractionsInstructionStep reports whether an Interactions step carries developer or system content rather than user content. The step's own role decides, falling back to its type; a step that names neither inherits the answer from the wrapper it sits in. Instruction content is still sent, but it closes the open user turn and never keeps an emptied one alive.

func IsVertexStreamingFunctionCall added in v8.0.45

func IsVertexStreamingFunctionCall(fc ojson.Result) bool

IsVertexStreamingFunctionCall reports whether a Gemini/Vertex functionCall object uses streaming arguments (partialArgs or willContinue).

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 NormalizeApplyPatchResponsesRequest added in v8.0.9

func NormalizeApplyPatchResponsesRequest(raw []byte) ([]byte, error)

NormalizeApplyPatchResponsesRequest adapts declarations and explicit custom patch history. Winners are collected before rewriting: normalization must not change declaration precedence.

func NormalizeGeminiTurnRole added in v8.0.52

func NormalizeGeminiTurnRole(rawRole string, parts ojson.Result, previousRole string) string

NormalizeGeminiTurnRole maps a Gemini content role to "user" or "assistant", inferring missing or unrecognized roles from functionCall/functionResponse parts or alternating from previousRole (matching Gemini ingress normalization).

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 []ojson.Result) []ojson.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 ResolveCodexReplayTargetModel added in v8.0.34

func ResolveCodexReplayTargetModel(modelName string, rawPayload []byte) string

ResolveCodexReplayTargetModel returns the model name to use for reasoning signature family checks, falling back to the client-supplied "model" field in rawPayload when modelName is an unmapped upstream deployment alias for a Responses-native model family (Meta Muse, Grok, or GPT).

func SSEEventData

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

SSEEventData builds one complete SSE frame. Each frame carries its own blank-line terminator so concatenated frames stay separable downstream.

func SanitizeDevinToolDescription

func SanitizeDevinToolDescription(_ string, desc string) string

SanitizeDevinToolDescription applies description obfuscation for Devin function tools. Clients may embed exec_command or write_stdin descriptions inside another tool (such as the Codex code-mode "exec" tool), and Devin rejects those phrases regardless of the tool name.

func SanitizeOrphanResponsesToolOutputsDoc added in v8.0.61

func SanitizeOrphanResponsesToolOutputsDoc(doc *ojson.Doc) bool

SanitizeOrphanResponsesToolOutputsDoc rewrites standalone function_call_output and custom_tool_call_output items that carry no call_id into user message items. Codex Desktop Companion Page context is injected as function_call_output items without call_id, which strict Responses upstreams reject with HTTP 400 ("responses function_call_output call_id is required").

func SanitizeOrphanResponsesToolOutputsInputDoc added in v8.0.61

func SanitizeOrphanResponsesToolOutputsInputDoc(inputResult ojson.Result, ensureDoc func() *ojson.Doc) bool

SanitizeOrphanResponsesToolOutputsInputDoc pairs tool outputs missing call_id with preceding unmatched tool calls when possible, and rewrites remaining standalone function_call_output and custom_tool_call_output items without call_id into user message items in-place on the document returned by ensureDoc.

func SetGeminiFunctionResponseRaw

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

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

func SetGeminiFunctionResponseRawDoc added in v8.0.52

func SetGeminiFunctionResponseRawDoc(doc *ojson.Doc, path string, rawJSON string)

SetGeminiFunctionResponseRawDoc is a convenience wrapper around SetGeminiFunctionResponseResultDoc for raw JSON strings.

func SetGeminiFunctionResponseResult

func SetGeminiFunctionResponseResult(part []byte, path string, result ojson.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 ojson.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 SetGeminiFunctionResponseResultDoc added in v8.0.52

func SetGeminiFunctionResponseResultDoc(doc *ojson.Doc, path string, result ojson.Result)

SetGeminiFunctionResponseResultDoc sets the Gemini functionResponse result or response field on doc.

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 SetRawArrayItemsDoc added in v8.0.52

func SetRawArrayItemsDoc(doc *ojson.Doc, path string, items [][]byte)

SetRawArrayItemsDoc replaces a JSON array at path in doc with raw items.

func SetResponsesToolCallIdentity

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

SetResponsesToolCallIdentity writes a resolved Responses tool name and namespace.

func SetResponsesToolCallIdentityDoc added in v8.0.52

func SetResponsesToolCallIdentityDoc(doc *ojson.Doc, name, namespace, itemPath string)

SetResponsesToolCallIdentityDoc writes a resolved Responses tool name and namespace into doc.

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 ojson.Set/SetBytes delegates string values containing quotes or special characters to encoding/json.Marshal, which unconditionally escapes <, >, & to \u003c, \u003e, \u0026.

func SetStringWithoutHTMLEscapeDoc added in v8.0.52

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

SetStringWithoutHTMLEscapeDoc sets a string field in an ojson.Doc without escaping HTML characters (<, >, &).

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.

func VertexFunctionCallWillContinue added in v8.0.45

func VertexFunctionCallWillContinue(fc ojson.Result) bool

VertexFunctionCallWillContinue reports whether a functionCall chunk indicates that subsequent chunks will follow for the same function call.

func VisibleCodexCommentary added in v8.0.49

func VisibleCodexCommentary(ctx context.Context) bool

VisibleCodexCommentary reports the per-request display policy. The environment fallback supports SDK-only users and existing deployments of the opt-in mode.

func WithVisibleCodexCommentary added in v8.0.49

func WithVisibleCodexCommentary(ctx context.Context, enabled bool) context.Context

WithVisibleCodexCommentary snapshots the display policy for one request.

Types

type ApplyPatchCallState added in v8.0.9

type ApplyPatchCallState struct {
	ItemID      string
	CallID      string
	Name        string
	Namespace   string
	OutputIndex int
	Decoder     ApplyPatchInputDecoder
}

ApplyPatchCallState owns the input decoder and identity of one tool call.

func (*ApplyPatchCallState) FinishArguments added in v8.0.9

func (s *ApplyPatchCallState) FinishArguments(arguments string) (string, string, error)

FinishArguments returns any unsent suffix and the complete decoded input.

func (*ApplyPatchCallState) PushArguments added in v8.0.9

func (s *ApplyPatchCallState) PushArguments(fragment string) (string, error)

PushArguments decodes the next arguments fragment for this call.

type ApplyPatchErrorState added in v8.0.9

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

ApplyPatchErrorState retains a conversion error for the caller.

func (*ApplyPatchErrorState) SetToolInputError added in v8.0.9

func (s *ApplyPatchErrorState) SetToolInputError(err error)

SetToolInputError stores the original conversion error for executor handling.

func (*ApplyPatchErrorState) ToolInputError added in v8.0.9

func (s *ApplyPatchErrorState) ToolInputError() error

ToolInputError returns the original conversion error, if any.

type ApplyPatchInputDecoder added in v8.0.9

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

ApplyPatchInputDecoder decodes the input string from streamed function arguments. A decoder belongs to one call and must not be copied after use.

func (*ApplyPatchInputDecoder) Finish added in v8.0.9

func (d *ApplyPatchInputDecoder) Finish(arguments string) (string, error)

Finish validates the final wrapper and emits only the previously unsent suffix.

func (*ApplyPatchInputDecoder) Input added in v8.0.9

func (d *ApplyPatchInputDecoder) Input() string

Input returns the decoded input, preserving its original whitespace.

func (*ApplyPatchInputDecoder) Push added in v8.0.9

func (d *ApplyPatchInputDecoder) Push(fragment string) (string, error)

Push scans each fragment once, emitting only complete, validated characters.

type ApplyPatchResponsesBridge added in v8.0.9

type ApplyPatchResponsesBridge struct {
	ApplyPatchErrorState
	// contains filtered or unexported fields
}

ApplyPatchResponsesBridge handles JSON event payloads, without SSE framing. Identity evidence is retained even before a call receives its name. A bridge is local to one response and must not be shared between goroutines.

func NewApplyPatchResponsesBridge added in v8.0.9

func NewApplyPatchResponsesBridge(originalRequest []byte) *ApplyPatchResponsesBridge

NewApplyPatchResponsesBridge resolves original declarations before any normalization.

func (*ApplyPatchResponsesBridge) CheckIdentity added in v8.0.9

func (b *ApplyPatchResponsesBridge) CheckIdentity(event []byte) error

CheckIdentity retains every supplied key before a folded dispatcher reveals its child. Names are deliberately withheld: a dispatcher name is not the selected child name.

func (*ApplyPatchResponsesBridge) Fail added in v8.0.9

func (b *ApplyPatchResponsesBridge) Fail(err error) ([][]byte, error)

Fail terminates an executor-owned bridge with the same one-shot failure contract.

func (*ApplyPatchResponsesBridge) Finish added in v8.0.9

func (b *ApplyPatchResponsesBridge) Finish() error

Finish rejects acquired calls whose final arguments have not been validated.

func (*ApplyPatchResponsesBridge) Transform added in v8.0.9

func (b *ApplyPatchResponsesBridge) Transform(event []byte) ([][]byte, error)

Transform converts one payload. A failure is terminal and is emitted only once.

func (*ApplyPatchResponsesBridge) TransformNonStream added in v8.0.9

func (b *ApplyPatchResponsesBridge) TransformNonStream(response []byte) ([]byte, error)

TransformNonStream accepts either a bare response or a terminal event envelope.

type ClaudeFallbackChain added in v8.0.66

type ClaudeFallbackChain struct {
	Entries [][]byte
	// contains filtered or unexported fields
}

ClaudeFallbackChain accumulates ordered Anthropic fallback hops across pre-token message_start switches, mid-stream fallback content blocks, and usage.iterations fallback_message entries without losing earlier boundaries.

func (*ClaudeFallbackChain) ArrayBytes added in v8.0.66

func (c *ClaudeFallbackChain) ArrayBytes() []byte

ArrayBytes serializes all ordered fallback hops as a JSON array, or nil when empty.

func (*ClaudeFallbackChain) Latest added in v8.0.66

func (c *ClaudeFallbackChain) Latest() []byte

Latest returns the most recent fallback hop metadata, or nil when none occurred.

func (*ClaudeFallbackChain) RecordBlock added in v8.0.66

func (c *ClaudeFallbackChain) RecordBlock(contentBlock ojson.Result, defaultFromModel, defaultToModel, boundaryKey string, boundaryIndex *int) []byte

RecordBlock records an explicit Anthropic content_block of type "fallback". If the first explicit block describes the same transition already inferred at message_start, it upgrades that entry with trigger/boundary details; otherwise it appends a new hop in order.

func (*ClaudeFallbackChain) RecordIterations added in v8.0.66

func (c *ClaudeFallbackChain) RecordIterations(iterations ojson.Result, defaultFromModel, boundaryKey string, boundaryIndex *int) (finalModel string, newEntries [][]byte)

RecordIterations reconciles usage.iterations fallback_message entries, returning the final fallback serving model and any newly discovered hop metadata when explicit fallback content blocks were absent.

func (*ClaudeFallbackChain) RecordPreToken added in v8.0.66

func (c *ClaudeFallbackChain) RecordPreToken(fromModel, toModel, boundaryKey string, boundaryIndex *int) []byte

RecordPreToken records a pre-token or sticky fallback detected at message_start.

func (*ClaudeFallbackChain) Reset added in v8.0.66

func (c *ClaudeFallbackChain) Reset()

Reset clears all accumulated fallback state for a new message.

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.

type UnsupportedPartError added in v8.0.20

type UnsupportedPartError struct {
	Type string
}

UnsupportedPartError is a request-scoped rejection. The part type was present and this translation has no equivalent, so the request must not be sent with that part removed.

func (*UnsupportedPartError) Error added in v8.0.20

func (e *UnsupportedPartError) Error() string

func (*UnsupportedPartError) IsRequestScoped added in v8.0.20

func (e *UnsupportedPartError) IsRequestScoped() bool

func (*UnsupportedPartError) StatusCode added in v8.0.20

func (e *UnsupportedPartError) StatusCode() int

type UserRun added in v8.0.20

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

UserRun follows the consecutive user content that a target merges into one user turn. Add records content that keeps the turn alive, Drop records a part that could not be sent, and End closes the turn when model content starts or the input ends. Every method is a no-op on a nil receiver, so callers can pass nil for content that is not user content.

func (*UserRun) Add added in v8.0.20

func (r *UserRun) Add()

Add records one sendable item in the current user turn.

func (*UserRun) Drop added in v8.0.20

func (r *UserRun) Drop(partType string)

Drop records a part of the current user turn that cannot be sent.

func (*UserRun) End added in v8.0.20

func (r *UserRun) End()

End closes the current user turn.

func (*UserRun) Err added in v8.0.20

func (r *UserRun) Err() error

Err returns the refusal for the first emptied user turn, or nil.

type UserTurnDrops added in v8.0.20

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

UserTurnDrops is the shared policy for a part a translation cannot send: text or any other sendable part beside it still goes out, but a user turn left with nothing to send is refused rather than forwarded empty. The decision is made per user turn, so earlier or later turns, system prompts and developer prompts can never hide an emptied user turn.

func (*UserTurnDrops) Drop added in v8.0.20

func (d *UserTurnDrops) Drop(partType string)

Drop records a part of the current user turn that cannot be sent. The first type recorded within a turn is the one reported.

func (*UserTurnDrops) EndTurn added in v8.0.20

func (d *UserTurnDrops) EndTurn(sendable int)

EndTurn closes the current user turn. sendable is the number of parts the turn contributed to the translated request. A turn that dropped a part and contributed nothing is remembered; a later turn never clears it.

func (*UserTurnDrops) Err added in v8.0.20

func (d *UserTurnDrops) Err() error

Err returns the refusal for the first emptied user turn, or nil.

type VertexPartialArgsAssembler added in v8.0.45

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

VertexPartialArgsAssembler incrementally reconstructs a JSON value from Vertex AI streaming functionCall.partialArgs fragments and emits valid JSON deltas that can be concatenated directly by downstream OpenAI and Claude clients.

func NewVertexPartialArgsAssembler added in v8.0.45

func NewVertexPartialArgsAssembler() *VertexPartialArgsAssembler

NewVertexPartialArgsAssembler creates a new assembler for a single streaming function call.

func (*VertexPartialArgsAssembler) CanAcceptContinuation added in v8.0.45

func (a *VertexPartialArgsAssembler) CanAcceptContinuation(fc ojson.Result) bool

CanAcceptContinuation reports whether fc's partialArgs can continue the current in-progress argument tree without overwriting any already-completed leaf value.

func (*VertexPartialArgsAssembler) Err added in v8.0.45

Err returns the first structural or limits error encountered while assembling partialArgs.

func (*VertexPartialArgsAssembler) FullArguments added in v8.0.45

func (a *VertexPartialArgsAssembler) FullArguments() string

FullArguments returns the concatenated JSON arguments emitted so far.

func (*VertexPartialArgsAssembler) PushFunctionCall added in v8.0.45

func (a *VertexPartialArgsAssembler) PushFunctionCall(fc ojson.Result) (string, bool)

PushFunctionCall processes one functionCall chunk and returns the newly emitted JSON argument delta and whether the function call has completed cleanly.

func (*VertexPartialArgsAssembler) SetArgumentCleaner added in v8.0.45

func (a *VertexPartialArgsAssembler) SetArgumentCleaner(cleaner func(string) string)

SetArgumentCleaner configures an optional JSON argument cleaner (such as Claude schema placeholder stripping) applied before potentially removable placeholder fields ("reason", "_", or closed empty object fields) are emitted.

type VertexStreamingToolCall added in v8.0.45

type VertexStreamingToolCall struct {
	RawName    string
	Name       string
	UpstreamID string
	ID         string
	Index      int
	Assembler  *VertexPartialArgsAssembler
}

VertexStreamingToolCall tracks an in-progress Vertex streaming function call across SSE chunks for a single candidate or stream.

func NewVertexStreamingToolCall added in v8.0.45

func NewVertexStreamingToolCall(rawName, name, upstreamID, id string, index int) *VertexStreamingToolCall

NewVertexStreamingToolCall creates a new active streaming tool call tracker.

func (*VertexStreamingToolCall) CanContinueWith added in v8.0.45

func (c *VertexStreamingToolCall) CanContinueWith(fc ojson.Result) bool

CanContinueWith reports whether fc belongs to this in-progress streaming tool call.

Jump to

Keyboard shortcuts

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