transform

package
v0.260806.1 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: MPL-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlignToolMessagesForOpenAI

func AlignToolMessagesForOpenAI(req *openai.ChatCompletionNewParams)

AlignToolMessagesForOpenAI converts orphaned tool messages (those without a matching tool_call_id) to user messages. This prevents "role 'tool' must be a response to preceding message with 'tool_calls'" errors.

func PrintBetaMessage added in v0.260702.1

func PrintBetaMessage(req *anthropic.BetaMessageNewParams)

func PrintMessage added in v0.260702.1

func PrintMessage(req *anthropic.MessageNewParams)

func SetRequest

func SetRequest[T RequestUnionConstraint](ctx *TransformContext, req T)

SetRequest updates the request in the context. Only types satisfying RequestUnionConstraint are accepted — passing any other type will result in a compile-time error.

Types

type BaseTransform

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

BaseTransform handles protocol conversion from original format to target API style This is the first transform in the chain, converting the request format before consistency normalization and vendor-specific adjustments.

func NewBaseTransform

func NewBaseTransform(targetType protocol.APIType) *BaseTransform

NewBaseTransform creates a new BaseTransform with the specified target API style

func (*BaseTransform) Apply

func (t *BaseTransform) Apply(ctx *TransformContext) error

Apply converts the request to the target API style This transform detects the original request type and applies the appropriate conversion. For OpenAI Chat target, it converts Anthropic v1/beta requests to OpenAI Chat format. For OpenAI Responses target, it converts Anthropic v1/beta requests to Responses format. For Anthropic targets, it converts OpenAI requests to Anthropic format. If the input type already matches the target type, no conversion is performed.

func (*BaseTransform) Name

func (t *BaseTransform) Name() string

Name returns the name of this transform

type ClaudeCodeCompatTransform added in v0.260604.1

type ClaudeCodeCompatTransform struct{}

ClaudeCodeCompatTransform normalizes "system" roles in the inbound Anthropic messages array so the request is valid for third-party Anthropic-compatible providers. Claude Code sends mid-conversation system-role entries (a non-standard extension over the bare user/assistant message contract); this transform rewrites them before forwarding so providers that reject the role do not error.

Runs as a pre-Base stage; non-Anthropic inbound request types are left untouched. The transform is a thin shell — ops.ApplyClaudeCodeCompatRoleRewrite is the position-aware operation primitive (merge into the preceding user turn, or re-role to user) and this stage only decides when to invoke it based on the inbound request type.

func NewClaudeCodeCompatTransform added in v0.260604.1

func NewClaudeCodeCompatTransform() *ClaudeCodeCompatTransform

NewClaudeCodeCompatTransform returns a new ClaudeCodeCompatTransform.

func (*ClaudeCodeCompatTransform) Apply added in v0.260604.1

Apply normalizes system-role messages for Anthropic request types.

func (*ClaudeCodeCompatTransform) Name added in v0.260604.1

type ConsistencyTransform

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

ConsistencyTransform applies cross-provider normalization rules to requests. These rules apply to ALL providers, regardless of vendor.

Consistency Transform handles:

  • Tool Schema Normalization - Ensure type: "object", normalize properties
  • Scenario Flags - Disable stream usage, thinking mode if needed
  • Messages Normalization - Truncate tool_call_id to 40 chars
  • Validation - Check max_tokens, temperature ranges

func NewConsistencyTransform

func NewConsistencyTransform(targetAPIStyle protocol.APIType) *ConsistencyTransform

NewConsistencyTransform creates a new ConsistencyTransform for the given target API style.

func (*ConsistencyTransform) Apply

Apply executes the consistency normalization based on the target API style. Modifies ctx.Request in place and returns an error if transformation fails.

func (*ConsistencyTransform) Name

func (t *ConsistencyTransform) Name() string

Name returns the transform name for logging and tracking.

type OpenAICursorCompatTransform added in v0.260531.1

type OpenAICursorCompatTransform struct{}

OpenAICursorCompatTransform flattens rich content blocks in OpenAI Chat messages for Cursor-style clients that only accept plain string content.

It runs as a pre-Base stage so it sees the inbound request in its original shape — Cursor IDE always sends OpenAI Chat, so the type-switch matches and flattening happens before BaseTransform converts to the target shape. For non-Chat inbound shapes (Anthropic, Responses, Google) it is a no-op: Cursor compatibility is only meaningful when the source-of-truth message structure is OpenAI Chat.

The transform is a thin shell — ops.ApplyCursorCompatContentNormalization is the operation primitive; this stage only decides when to invoke it based on the inbound request type.

Only added to the chain when the rule's cursor_compat flag is enabled.

func NewOpenAICursorCompatTransform added in v0.260531.1

func NewOpenAICursorCompatTransform() *OpenAICursorCompatTransform

NewOpenAICursorCompatTransform creates a new pre-Base cursor compatibility transform.

func (*OpenAICursorCompatTransform) Apply added in v0.260531.1

Apply flattens rich content on OpenAI Chat requests. For any other shape (Anthropic v1/beta, Responses, Google) it is a no-op.

func (*OpenAICursorCompatTransform) Name added in v0.260531.1

type OpenAIMaxTokensRewriteTransform added in v0.260531.1

type OpenAIMaxTokensRewriteTransform struct {
	UseMaxCompletionTokens bool
	UseMaxTokens           bool
}

OpenAIMaxTokensRewriteTransform rewrites the OpenAI Chat `max_tokens` / `max_completion_tokens` field pair based on per-rule flags. It runs as a post-base stage so it sees the request in its target shape — protocol conversion (Anthropic ↔ OpenAI) has already happened by then.

Only added to the chain when at least one of the two flags is set.

func NewOpenAIMaxTokensRewriteTransform added in v0.260531.1

func NewOpenAIMaxTokensRewriteTransform(useMaxCompletionTokens, useMaxTokens bool) *OpenAIMaxTokensRewriteTransform

NewOpenAIMaxTokensRewriteTransform creates a new transform configured with the rule flags.

func (*OpenAIMaxTokensRewriteTransform) Apply added in v0.260531.1

Apply rewrites the token field on OpenAI Chat requests. For any other post-base shape (Anthropic, Responses, Google) it is a no-op.

func (*OpenAIMaxTokensRewriteTransform) Name added in v0.260531.1

type RequestUnionConstraint

RequestUnionConstraint defines the exact set of request types accepted by the transform chain. This is a compile-time type constraint enforced via generic functions. Any attempt to pass a type not in this union will fail at compile time.

type RuleThinkingTransform added in v0.260604.1

type RuleThinkingTransform struct {
	Effort string
}

RuleThinkingTransform applies the unified thinking_effort control at the rule level. It runs as a post-base stage so the type-switch sees the upstream-bound request shape after protocol conversion.

Effort semantics are documented on ops.ApplyThinkingEffort. Only added to the chain when Effort is non-default.

func NewRuleThinkingTransform added in v0.260604.1

func NewRuleThinkingTransform(effort string) *RuleThinkingTransform

NewRuleThinkingTransform returns a transform that applies the given effort.

func (*RuleThinkingTransform) Apply added in v0.260604.1

func (*RuleThinkingTransform) Name added in v0.260604.1

func (t *RuleThinkingTransform) Name() string

type ToolBlockTransform added in v0.260531.1

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

ToolBlockTransform strips a configured set of tools from the request's tool list. It runs as a pre-Base stage so it sees the request in its inbound shape — the names it matches are the ones the client actually sent, before any protocol conversion or vendor-specific tool renaming.

When no names are configured it is never added to the chain (see rulePreBaseTransforms).

func NewToolBlockTransform added in v0.260531.1

func NewToolBlockTransform(names []string) *ToolBlockTransform

NewToolBlockTransform builds a transform that blocks the given tool names. Names are matched exactly; empty entries are ignored.

func (*ToolBlockTransform) Apply added in v0.260531.1

func (t *ToolBlockTransform) Apply(ctx *TransformContext) error

Apply filters the tool list on whichever inbound request shape is present.

func (*ToolBlockTransform) Name added in v0.260531.1

func (t *ToolBlockTransform) Name() string

type Transform

type Transform interface {
	// Name returns the unique identifier for this transform
	Name() string

	// Apply applies the transformation to the context
	// Returns an error if the transformation fails
	Apply(ctx *TransformContext) error
}

Transform defines the interface for a single transformation step

type TransformChain

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

TransformChain manages an ordered sequence of transforms

func NewTransformChain

func NewTransformChain(transforms []Transform) *TransformChain

NewTransformChain creates a new TransformChain with the given transforms

func (*TransformChain) Add

func (c *TransformChain) Add(transform Transform)

Add appends a transform to the end of the chain

func (*TransformChain) Execute

Execute runs the transform chain on the provided context Transforms are executed in order, and each transform's name is recorded in TransformSteps. Returns the final TransformContext or an error if any transform fails with a descriptive error message.

func (*TransformChain) GetTransforms

func (c *TransformChain) GetTransforms() []Transform

GetTransforms returns a copy of the transforms in the chain

func (*TransformChain) Length

func (c *TransformChain) Length() int

Length returns the number of transforms in the chain

func (*TransformChain) SetTransforms added in v0.260414.2000

func (c *TransformChain) SetTransforms(ts []Transform)

SetTransforms help reset transforms

type TransformConfig added in v0.260402.2330

type TransformConfig struct {
	// MaxTokens is the maximum output tokens allowed for the request.
	// Used by base transform when converting between protocols.
	MaxTokens int64

	// UserID is the OAuth user ID for authenticated requests.
	UserID string

	// Device is the device identifier (e.g., Claude Code device ID).
	Device string

	// OpenAIConfig holds OpenAI-specific configuration populated during transforms.
	OpenAIConfig *protocol.OpenAIConfig

	// ResponsesConfig holds Responses API-specific configuration populated during transforms.
	ResponsesConfig *protocol.OpenAIConfig
}

TransformConfig holds structured, type-safe configuration for the transform chain. Use With* option constructors to set these values.

type TransformContext

type TransformContext struct {
	// Context carries the request-scoped context for cancellation and deadlines.
	// Transforms should use this instead of context.Background().
	Context context.Context

	SourceAPI protocol.APIType
	TargetAPI protocol.APIType

	RequestModel  string
	ResponseModel string

	// Request is the request being transformed.
	// Use SetRequest[T]() to update — only types satisfying RequestUnionConstraint are accepted.
	Request interface{}

	// ScenarioFlags contains configuration flags for the scenario
	ScenarioFlags *typ.ScenarioFlags

	// IsStreaming indicates if this is a streaming request
	IsStreaming bool

	// IsAdvisorRequest indicates if this is an advisor loopback request
	// Used to prevent recursive MCP tool injection
	IsAdvisorRequest bool

	// HasNativeAdvisor indicates Claude Code native advisor semantics are already
	// present in the request, so tingly-box must not inject or bridge a second advisor.
	HasNativeAdvisor bool

	// OriginalRequest stores the original request before any transformations
	OriginalRequest interface{}

	// TransformSteps records the names of transforms that have been applied
	TransformSteps []string

	// Config holds structured, type-safe configuration for the transform chain.
	Config TransformConfig

	// Provider is the canonical provider configuration for transforms that need
	// provider-aware behavior.
	Provider *typ.Provider

	// Extra allows transforms to pass arbitrary data through the chain
	Extra map[string]interface{}
}

TransformContext carries state through the transform chain

func NewTransformContext

func NewTransformContext[T RequestUnionConstraint](request T, opts ...TransformOption) *TransformContext

NewTransformContext creates a TransformContext with type-safe request validation. The generic type parameter T is constrained to RequestUnionConstraint, ensuring only valid request types can be used. Invalid types will cause a compile-time error.

Example:

ctx := transform.NewTransformContext(&anthropicReq,
    transform.WithProvider(provider),
    transform.WithStreaming(true),
)

func (*TransformContext) Release added in v0.260625.1

func (ctx *TransformContext) Release()

type TransformOption

type TransformOption func(*TransformContext)

TransformOption configures a TransformContext

func WithContext added in v0.260418.2200

func WithContext(c context.Context) TransformOption

WithContext sets the context in the transform context.

func WithDevice added in v0.260402.2330

func WithDevice(device string) TransformOption

WithDevice sets the device identifier in the transform config.

func WithExtra

func WithExtra(extra map[string]interface{}) TransformOption

WithExtra sets initial extra data in the transform context.

func WithIsAdvisorRequest added in v0.260507.1

func WithIsAdvisorRequest(isAdvisor bool) TransformOption

WithIsAdvisorRequest marks whether this is an advisor loopback request. This is used to prevent recursive MCP tool injection.

func WithMaxTokens added in v0.260402.2330

func WithMaxTokens(maxTokens int64) TransformOption

WithMaxTokens sets the maximum output tokens in the transform config.

func WithProvider added in v0.260709.1

func WithProvider(provider *typ.Provider) TransformOption

WithProvider sets the provider as the canonical upstream/provider context.

func WithScenarioFlags

func WithScenarioFlags(flags *typ.ScenarioFlags) TransformOption

WithScenarioFlags sets the scenario flags in the transform context.

func WithStreaming

func WithStreaming(isStreaming bool) TransformOption

WithStreaming sets the streaming flag in the transform context.

func WithUserID added in v0.260402.2330

func WithUserID(userID string) TransformOption

WithUserID sets the OAuth user ID in the transform config.

type ValidationError

type ValidationError struct {
	Field   string      `json:"field"`
	Message string      `json:"message"`
	Value   interface{} `json:"value,omitempty"`
}

ValidationError represents a validation error for request parameters.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type VendorTransform

type VendorTransform struct{}

VendorTransform applies provider-specific request adjustments. Per-shape dispatch is a flat strings.Contains chain — uniform across all request shapes so new vendors land in one place per shape. Provider data is read from TransformContext so this transform remains stateless and reusable.

func NewVendorTransform

func NewVendorTransform() *VendorTransform

NewVendorTransform creates a new vendor transform.

func (*VendorTransform) Apply

func (t *VendorTransform) Apply(ctx *TransformContext) error

Apply dispatches to the per-shape vendor logic. Unknown shapes are a no-op.

func (*VendorTransform) Name

func (t *VendorTransform) Name() string

Jump to

Keyboard shortcuts

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