config

package
v7.3.16 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package config provides configuration management for the CLI Proxy API server. It handles loading and parsing YAML configuration files, and provides structured access to application settings including server port, authentication directory, debug settings, proxy configuration, and API keys.

Package config provides configuration management for the CLI Proxy API server. It handles loading and parsing YAML configuration files, and provides structured access to application settings including server port, authentication directory, debug settings, proxy configuration, and API keys.

Index

Constants

View Source
const (
	// ClaudeFingerprintProfileDefault keeps the caller-owned request fingerprint.
	ClaudeFingerprintProfileDefault = ""
	// ClaudeFingerprintProfileClaudeCodeCLI opts into the Claude Code CLI Messages fingerprint.
	ClaudeFingerprintProfileClaudeCodeCLI = "claude-code-cli"
)

Claude fingerprint profile values for ClaudeKey.FingerprintProfile and for the matching auth-file / auth-attribute field. This is the single source of truth: the runtime, the config sanitizer and the Management API all resolve a raw value through NormalizeClaudeFingerprintProfile so an operator cannot end up with a value that one layer accepts and another silently ignores.

View Source
const (
	DefaultPanelGitHubRepository = "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
	DefaultPprofAddr             = "127.0.0.1:8316"
	DefaultAuthDir               = "~/.cli-proxy-api"
	DefaultDiscoveryServiceType  = "_ai-gateway._tcp"
)
View Source
const (
	DefaultInFlightMaxPartBytes       = 256 * 1024
	DefaultInFlightMaxPartCount       = 64
	DefaultInFlightMaxRevisionBytes   = 16 * 1024 * 1024
	DefaultInFlightMaxAggregateGroups = 100000
	DefaultInFlightMaxDetails         = 10000
	DefaultInFlightMaxStringBytes     = 256
)
View Source
const DefaultCodexLiveMediaMaxSessions = 32

DefaultCodexLiveMediaMaxSessions is the default in-process media session limit.

View Source
const DefaultCodexStreamBootstrapTimeout = 0

DefaultCodexStreamBootstrapTimeout is the default maximum duration to buffer bootstrap events. By default, it is 0 (unlimited time, relying purely on the 48-frame and 1MB byte bounds).

View Source
const MaxCredentialWeight = int(credentialweight.Max)

MaxCredentialWeight is the largest positive credential routing weight.

Variables

This section is empty.

Functions

func FormatSortedHeaders added in v7.2.138

func FormatSortedHeaders(headers map[string]string) string

FormatSortedHeaders serializes headers deterministically with null byte separators.

func NormalizeClaudeFingerprintProfile added in v7.2.136

func NormalizeClaudeFingerprintProfile(raw string) (string, bool)

NormalizeClaudeFingerprintProfile maps a raw configured value to its canonical form. The second result reports whether the value is recognized; an unrecognized value normalizes to the default (caller-owned) profile.

func NormalizeCommentIndentation

func NormalizeCommentIndentation(data []byte) []byte

NormalizeCommentIndentation removes indentation from standalone YAML comment lines to keep them left aligned.

func NormalizeExcludedModels

func NormalizeExcludedModels(models []string) []string

NormalizeExcludedModels trims, lowercases, and deduplicates model exclusion patterns. It preserves the order of first occurrences and drops empty entries.

func NormalizeHeaders

func NormalizeHeaders(headers map[string]string) map[string]string

NormalizeHeaders trims header keys and values and removes empty pairs.

func NormalizeHomePort added in v7.2.146

func NormalizeHomePort(port int) int

NormalizeHomePort ensures that the CPA server port received from Home is valid, defaulting to 8317 when omitted or non-positive.

func NormalizeOAuthExcludedModels

func NormalizeOAuthExcludedModels(entries map[string][]string) map[string][]string

NormalizeOAuthExcludedModels cleans provider -> excluded models mappings by normalizing provider keys and applying model exclusion normalization to each entry.

func ResolvePluginsDir added in v7.2.78

func ResolvePluginsDir(pluginsDir string) (string, error)

ResolvePluginsDir normalizes the plugin directory for consistent use throughout the app. It expands a leading tilde (~) to the user's home directory and defaults empty values to plugins.

func SaveConfigPreserveComments

func SaveConfigPreserveComments(configFile string, cfg *Config) error

SaveConfigPreserveComments writes the config back to YAML while preserving existing comments and key ordering by loading the original file into a yaml.Node tree and updating values in-place.

func SaveConfigPreserveCommentsUpdateNestedScalar

func SaveConfigPreserveCommentsUpdateNestedScalar(configFile string, path []string, value string) error

SaveConfigPreserveCommentsUpdateNestedScalar updates a nested scalar key path like ["a","b"] while preserving comments and positions.

func ValidateClaudeFingerprintProfile added in v7.2.136

func ValidateClaudeFingerprintProfile(raw string) error

ValidateClaudeFingerprintProfile reports an error for values that would be silently ignored at request time. Write paths (Management API) use it to reject a typo instead of letting it reach the request path.

func ValidateCredentialConcurrency added in v7.2.96

func ValidateCredentialConcurrency(cfg CredentialConcurrencyConfig) error

ValidateCredentialConcurrency validates values intrinsic to a credential concurrency configuration.

func ValidateCredentialConcurrencyLifecycle added in v7.2.96

func ValidateCredentialConcurrencyLifecycle(nodeHeartbeatTimeout time.Duration, cfg CredentialConcurrencyConfig) error

ValidateCredentialConcurrencyLifecycle verifies the Home lifecycle timing safety invariant.

func ValidateCredentialWeight added in v7.2.104

func ValidateCredentialWeight(weight *int) error

ValidateCredentialWeight validates one optional config credential weight.

Types

type AntigravityConfig added in v7.2.118

type AntigravityConfig struct {
	// SensitiveWords is a list of words to obfuscate with zero-width characters in system instructions.
	SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"`

	// ConnectionPool configures upstream HTTP connection pooling behavior for Antigravity.
	ConnectionPool AntigravityConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,omitempty"`
}

AntigravityConfig configures provider-wide Antigravity request behavior.

type AntigravityConnectionPoolConfig added in v7.2.154

type AntigravityConnectionPoolConfig struct {
	// Enabled controls whether upstream connection pooling is enabled.
	// Defaults to false (short-lived connection mode). Set to true to enable connection pooling.
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`

	// IdleConnTimeout specifies how long an idle connection stays in the pool before expiring.
	// Defaults to "30s". Capped at 210s to prevent exceeding Google Frontend (GFE) 240s cutoff.
	IdleConnTimeout string `yaml:"idle-conn-timeout,omitempty" json:"idle-conn-timeout,omitempty"`

	// MaxIdleConnsPerHost specifies the maximum number of idle connections to retain per host per credential.
	// Defaults to 2.
	MaxIdleConnsPerHost *int `yaml:"max-idle-conns-per-host,omitempty" json:"max-idle-conns-per-host,omitempty"`
}

AntigravityConnectionPoolConfig controls upstream HTTP/1.1 connection pooling behavior for Antigravity.

type ClaudeCodeConfig added in v7.2.103

type ClaudeCodeConfig struct {
	// DisableCloakingModelList disables model ID cloaking in Anthropic model list responses.
	DisableCloakingModelList bool `yaml:"disable-cloaking-model-list" json:"disable-cloaking-model-list"`
}

ClaudeCodeConfig configures Claude Code compatibility behavior.

type ClaudeConfig added in v7.3.7

type ClaudeConfig struct {
	// ModelLevelCooling scopes Claude quota cooldowns to the requested model
	// rather than cooling down the entire credential across all sibling models.
	ModelLevelCooling bool `yaml:"model-level-cooling" json:"model-level-cooling"`
}

ClaudeConfig configures provider-wide Claude request behavior.

type ClaudeHeaderDefaults

type ClaudeHeaderDefaults struct {
	UserAgent              string `yaml:"user-agent" json:"user-agent"`
	PackageVersion         string `yaml:"package-version" json:"package-version"`
	RuntimeVersion         string `yaml:"runtime-version" json:"runtime-version"`
	OS                     string `yaml:"os" json:"os"`
	Arch                   string `yaml:"arch" json:"arch"`
	Timeout                string `yaml:"timeout" json:"timeout"`
	Timezone               string `yaml:"timezone" json:"timezone"`
	StabilizeDeviceProfile *bool  `yaml:"stabilize-device-profile,omitempty" json:"stabilize-device-profile,omitempty"`
}

ClaudeHeaderDefaults configures the measured Claude Code software baseline. Verified native requests preserve their entrypoint and software shape only when their Claude Code, package, and runtime versions exactly match this baseline; unmeasured versions use the configured values. Timeout remains a fallback. Stabilized profiles also pin OS and Arch and never learn newer software versions automatically.

type ClaudeKey

type ClaudeKey struct {
	// APIKey is the authentication key for accessing Claude API services.
	APIKey string `yaml:"api-key" json:"api-key"`

	// Priority controls selection preference when multiple credentials match.
	// Higher values are preferred; defaults to 0.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`

	// Weight controls proportional selection under weighted-round-robin.
	// An omitted value defaults to 1; non-positive values exclude this credential; maximum 1,000,000.
	Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`

	// Prefix optionally namespaces models for this credential (e.g., "teamA/claude-sonnet-4").
	Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`

	// BaseURL is the base URL for the Claude API endpoint.
	// If empty, the default Claude API URL will be used.
	BaseURL string `yaml:"base-url" json:"base-url"`

	// ProxyURL overrides the global proxy setting for this API key if provided.
	ProxyURL string `yaml:"proxy-url" json:"proxy-url"`

	// Models defines upstream model names and aliases for request routing.
	Models []ClaudeModel `yaml:"models" json:"models"`

	// Headers optionally adds extra HTTP headers for requests sent with this key.
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`

	// ExcludedModels lists model IDs that should be excluded for this provider.
	ExcludedModels []string `yaml:"excluded-models,omitempty" json:"excluded-models,omitempty"`

	// RebuildMidSystemMessage moves Claude messages with role "system" into the top-level system field.
	RebuildMidSystemMessage bool `yaml:"rebuild-mid-system-message,omitempty" json:"rebuild-mid-system-message,omitempty"`

	// DisableCooling overrides the global cooling policy for this credential when set.
	// True disables auth/model cooldowns; false explicitly enables them.
	DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`

	// RequestRetry optionally overrides the global request-retry for this credential.
	// Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds.
	RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`

	// RequestScopedErrors configures custom classification rules for upstream errors.
	RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`

	// Cloak configures request cloaking for non-Claude-Code clients.
	Cloak *CloakConfig `yaml:"cloak,omitempty" json:"cloak,omitempty"`

	// FingerprintProfile selects the Claude Code request fingerprint for this
	// credential on Anthropic Messages. Empty/default keeps the caller request
	// fingerprint and headers, including first-party api.anthropic.com API keys.
	// "claude-code-cli" opts official Anthropic API keys, custom gateways, and
	// delegated providers such as Kimi into the Claude Code OAuth CLI Messages
	// shape (OAuth betas, CCH signing, stable CLI identity) without treating the
	// credential as a real OAuth token for refresh/profile/runtime semantics.
	// CCH is a per-request hash and follows the native gate: it is emitted only on
	// api.anthropic.com and Vertex, so an opt-in on any other gateway sends the
	// billing block unsigned and cannot bust that gateway's prompt cache. Kimi
	// strips the attribution entirely by default and keeps it, unsigned, after an
	// explicit opt-in. count_tokens keeps the native model/messages/tools shape.
	// Recognized values are defined by NormalizeClaudeFingerprintProfile.
	FingerprintProfile string `yaml:"fingerprint-profile,omitempty" json:"fingerprint-profile,omitempty"`

	// ExperimentalCCHSigning is retained for configuration compatibility.
	// CCH signing is automatic for Claude OAuth and supported direct upstreams.
	ExperimentalCCHSigning bool `yaml:"experimental-cch-signing,omitempty" json:"experimental-cch-signing,omitempty"`
}

ClaudeKey represents the configuration for a Claude API key, including the API key itself and an optional base URL for the API endpoint.

func (ClaudeKey) GetAPIKey

func (k ClaudeKey) GetAPIKey() string

func (ClaudeKey) GetBaseURL

func (k ClaudeKey) GetBaseURL() string

func (ClaudeKey) GetPrefix added in v7.2.105

func (k ClaudeKey) GetPrefix() string

func (ClaudeKey) GetProxyURL added in v7.2.105

func (k ClaudeKey) GetProxyURL() string

type ClaudeModel

type ClaudeModel struct {
	// Name is the upstream model identifier used when issuing requests.
	Name string `yaml:"name" json:"name"`

	// Alias is the client-facing model name that maps to Name.
	Alias string `yaml:"alias" json:"alias"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	// MaxContextLength overrides the context window advertised to Codex clients.
	MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`

	// ForceMapping rewrites upstream response model fields back to Alias.
	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`

	// IsCompat preserves thinking blocks with empty signatures for compatible upstreams
	// and enables provider-aware signed-thinking replay for Claude-compatible API-key models.
	// Default false keeps the normal signature validation behavior.
	IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`

	// Thinking configures the thinking/reasoning capability for this model.
	Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}

ClaudeModel describes a mapping between an alias and the actual upstream model name.

func (ClaudeModel) GetAlias

func (m ClaudeModel) GetAlias() string

func (ClaudeModel) GetDisplayName added in v7.2.70

func (m ClaudeModel) GetDisplayName() string

func (ClaudeModel) GetForceMapping added in v7.2.40

func (m ClaudeModel) GetForceMapping() bool

func (ClaudeModel) GetIsCompat added in v7.2.121

func (m ClaudeModel) GetIsCompat() bool

func (ClaudeModel) GetMaxContextLength added in v7.2.115

func (m ClaudeModel) GetMaxContextLength() int

func (ClaudeModel) GetName

func (m ClaudeModel) GetName() string

func (ClaudeModel) GetThinking added in v7.2.105

func (m ClaudeModel) GetThinking() *registry.ThinkingSupport

type CloakConfig

type CloakConfig struct {
	// Mode controls cloaking behavior: "auto" (default), "always", or "never".
	// Supplying this CloakConfig explicitly enables cloaking for an unprofiled API key.
	// - "auto": cloak unless strong request signals identify a verified native entrypoint
	// - "always": cloak every unconfirmed client; confirmed native Claude Code remains passthrough
	// - "never": never apply cloaking
	Mode string `yaml:"mode,omitempty" json:"mode,omitempty"`

	// StrictMode controls how caller system prompts are handled when cloaking.
	// - false (default): legacy-model whitelist uses a user reminder; all other models use a mid-conversation system message
	// - true: strip caller system prompts and keep only the Claude Code billing and identity blocks
	StrictMode bool `yaml:"strict-mode,omitempty" json:"strict-mode,omitempty"`

	// SensitiveWords is a list of words to obfuscate with zero-width characters.
	// This can help bypass certain content filters.
	SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"`

	// CacheUserID controls whether Claude user_id values are cached per API key.
	// When false, a fresh random user_id is generated for every request.
	CacheUserID *bool `yaml:"cache-user-id,omitempty" json:"cache-user-id,omitempty"`
}

CloakConfig configures request cloaking for non-Claude-Code clients. Cloaking disguises API requests to appear as originating from the official Claude Code CLI.

func NormalizeCloakConfig added in v7.3.8

func NormalizeCloakConfig(cloak *CloakConfig) *CloakConfig

NormalizeCloakConfig trims strings and removes blank sensitive words.

type CodexConfig added in v7.1.34

type CodexConfig struct {
	IdentityConfuse bool `yaml:"identity-confuse" json:"identity-confuse"`
	// DisableCodexCloaking disables forcing the official Codex identity headers on HTTP/SSE and WebSocket requests.
	DisableCodexCloaking bool `yaml:"disable-codex-cloaking" json:"disable-codex-cloaking"`
	// StreamBootstrapBuffering holds back the frames that arrive before generation starts, none of
	// which the client has seen anything from - the handshake (response.created, response.in_progress,
	// the websocket metadata frames), keepalive heartbeats, and the *.added announcements of an item
	// or part that is still empty - until the first generated event arrives. The upstream delivers
	// server_is_overloaded rejections inside an HTTP 200 stream right after those frames instead of
	// returning 503 on the wire, so buffering them keeps the downstream response headers uncommitted
	// long enough to retry on another credential. Trade-off: the response headers are delayed until
	// the upstream starts generating, which on a slow reasoning turn now means several heartbeat
	// intervals rather than one, and can trip client or reverse-proxy read timeouts. The hold is
	// bounded by a frame and a byte budget, not by wall-clock time, and neither budget is advanced
	// by a websocket peer that sends only control frames or by an upstream that never terminates an
	// SSE line. Only overload and rate-limit rejections fail over deliberately. A stream that ends
	// while the bootstrap is still holding ends the attempt rather than reaching the client, and
	// what follows is pre-existing but now far more likely, since the hold can span the whole
	// reasoning phase instead of ending at the first keepalive: a clean end with no terminal event
	// is request-scoped on SSE and stops there, while a websocket close or a transport error on
	// either transport is not, so the request may be retried on another credential.
	// Default is false.
	StreamBootstrapBuffering bool `yaml:"stream-bootstrap-buffering" json:"stream-bootstrap-buffering"`
	// StreamBootstrapTimeout specifies an optional maximum duration to hold back uncommitted response
	// headers during bootstrap buffering before releasing the stream to the client.
	// Defaults to "0" (unlimited time, relying purely on the 48-frame and 1MB byte bounds).
	// When set (e.g. "20s"), the stream is released once the time ceiling is reached, avoiding
	// reverse-proxy timeouts (e.g. Nginx 60s proxy_read_timeout).
	StreamBootstrapTimeout string `yaml:"stream-bootstrap-timeout,omitempty" json:"stream-bootstrap-timeout,omitempty"`
	// OptimizeMultiAgentV2 optimizes official Codex multi-agent requests.
	OptimizeMultiAgentV2 bool `yaml:"optimize-multi-agent-v2" json:"optimize-multi-agent-v2"`
	// OrphanDelegationCompatibility enables opt-in compatibility for orphan Codex delegation outputs.
	OrphanDelegationCompatibility bool `yaml:"orphan-delegation-compatibility" json:"orphan-delegation-compatibility"`
	// ModelLevelCooling scopes Codex usage_limit_reached quota cooldowns to the requested model
	// rather than cooling down the entire credential across all sibling models.
	ModelLevelCooling bool `yaml:"model-level-cooling" json:"model-level-cooling"`
	// LiveMediaRelay terminates and relays Codex Live WebRTC media in this process.
	LiveMediaRelay CodexLiveMediaRelayConfig `yaml:"live-media-relay" json:"live-media-relay"`
	// ResponseSteering enables full-duplex Codex WebSockets, bound to one
	// upstream model/account/socket for their entire lifetime. Default is false.
	ResponseSteering bool `yaml:"response-steering" json:"response-steering"`
}

CodexConfig configures provider-wide Codex request behavior.

func (*CodexConfig) StreamBootstrapTimeoutDuration added in v7.3.3

func (c *CodexConfig) StreamBootstrapTimeoutDuration() time.Duration

StreamBootstrapTimeoutDuration returns the maximum duration to buffer bootstrap events. Defaults to 0 (unlimited time, relying purely on the 48-frame and 1MB byte bounds). If explicitly set to a positive duration (e.g. "10s", "500ms", "15"), returns that duration. If set to "0", "0s", "none", "unlimited", "disabled", "off", "never", or invalid strings, returns 0.

type CodexHeaderDefaults

type CodexHeaderDefaults struct {
	UserAgent    string `yaml:"user-agent" json:"user-agent"`
	BetaFeatures string `yaml:"beta-features" json:"beta-features"`
}

CodexHeaderDefaults configures fallback header values injected into Codex model requests for OAuth/file-backed auth when the client omits them. UserAgent applies to HTTP and websocket requests; BetaFeatures only applies to websockets.

type CodexKey

type CodexKey struct {
	// APIKey is the authentication key for accessing Codex API services.
	APIKey string `yaml:"api-key" json:"api-key"`

	// Priority controls selection preference when multiple credentials match.
	// Higher values are preferred; defaults to 0.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`

	// Weight controls proportional selection under weighted-round-robin.
	// An omitted value defaults to 1; non-positive values exclude this credential; maximum 1,000,000.
	Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`

	// Prefix optionally namespaces models for this credential (e.g., "teamA/gpt-5-codex").
	Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`

	// BaseURL is the base URL for the Codex API endpoint.
	// If empty, the default Codex API URL will be used.
	BaseURL string `yaml:"base-url" json:"base-url"`

	// Websockets enables the Responses API websocket transport for this credential.
	Websockets bool `yaml:"websockets,omitempty" json:"websockets,omitempty"`

	// AlphaSearch allows this Codex API key to serve the Alpha Search endpoint.
	AlphaSearch bool `yaml:"alpha-search,omitempty" json:"alpha-search,omitempty"`

	// ProxyURL overrides the global proxy setting for this API key if provided.
	ProxyURL string `yaml:"proxy-url" json:"proxy-url"`

	// Models defines upstream model names and aliases for request routing.
	Models []CodexModel `yaml:"models" json:"models"`

	// Headers optionally adds extra HTTP headers for requests sent with this key.
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`

	// ExcludedModels lists model IDs that should be excluded for this provider.
	ExcludedModels []string `yaml:"excluded-models,omitempty" json:"excluded-models,omitempty"`

	// DisableCooling overrides the global cooling policy for this credential when set.
	// True disables auth/model cooldowns; false explicitly enables them.
	DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`

	// DisableCodexCloaking optionally overrides the global codex.disable-codex-cloaking for this credential.
	// True disables cloaking; false explicitly enables cloaking; omitted inherits global codex.disable-codex-cloaking.
	DisableCodexCloaking *bool `yaml:"disable-codex-cloaking,omitempty" json:"disable-codex-cloaking,omitempty"`

	// RequestRetry optionally overrides the global request-retry for this credential.
	// Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds.
	RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`

	// RequestScopedErrors configures custom classification rules for upstream errors.
	RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`
}

CodexKey represents the configuration for a Codex API key, including the API key itself and an optional base URL for the API endpoint.

func (CodexKey) GetAPIKey

func (k CodexKey) GetAPIKey() string

func (CodexKey) GetBaseURL

func (k CodexKey) GetBaseURL() string

func (CodexKey) GetPrefix added in v7.2.105

func (k CodexKey) GetPrefix() string

func (CodexKey) GetProxyURL added in v7.2.105

func (k CodexKey) GetProxyURL() string

type CodexLiveICEServer added in v7.2.99

type CodexLiveICEServer struct {
	URLs       []string `yaml:"urls" json:"urls"`
	Username   string   `yaml:"username" json:"-"`
	Credential string   `yaml:"credential" json:"-"`
}

CodexLiveICEServer configures a STUN or TURN server for the media relay.

type CodexLiveMediaRelayConfig added in v7.2.99

type CodexLiveMediaRelayConfig struct {
	Enabled                 bool                 `yaml:"enabled" json:"enabled"`
	MaxSessions             int                  `yaml:"max-sessions" json:"max-sessions"`
	DisablePrivateRemoteIPs bool                 `yaml:"disable-private-remote-ips" json:"disable-private-remote-ips"`
	PublicIP                string               `yaml:"public-ip" json:"public-ip"`
	UDPPortMin              uint16               `yaml:"udp-port-min" json:"udp-port-min"`
	UDPPortMax              uint16               `yaml:"udp-port-max" json:"udp-port-max"`
	ICEServers              []CodexLiveICEServer `yaml:"ice-servers" json:"ice-servers"`
}

CodexLiveMediaRelayConfig configures the in-process Codex Live WebRTC gateway.

func (CodexLiveMediaRelayConfig) EffectiveMaxSessions added in v7.2.99

func (c CodexLiveMediaRelayConfig) EffectiveMaxSessions() int

EffectiveMaxSessions returns the configured media session limit.

func (*CodexLiveMediaRelayConfig) UnmarshalYAML added in v7.2.99

func (c *CodexLiveMediaRelayConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML supports the deprecated allow-private-remote-ips setting while preserving the default behavior of allowing private downstream candidates.

func (CodexLiveMediaRelayConfig) Validate added in v7.2.99

func (c CodexLiveMediaRelayConfig) Validate() error

Validate verifies the Codex Live media relay configuration.

type CodexModel

type CodexModel struct {
	// Name is the upstream model identifier used when issuing requests.
	Name string `yaml:"name" json:"name"`

	// Alias is the client-facing model name that maps to Name.
	Alias string `yaml:"alias" json:"alias"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	// MaxContextLength overrides the context window advertised to Codex clients.
	MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`

	// ForceMapping rewrites upstream response model fields back to Alias.
	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`

	// IsCompat converts Codex MultiAgentV2 agent_message items into portable
	// Responses message/user input when codex.optimize-multi-agent-v2 is also true.
	// Use this for third-party Responses-compatible endpoints that do not accept
	// native agent_message items or empty-signature thinking blocks. Default false
	// keeps the native behavior unchanged.
	IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`

	// Thinking configures the thinking/reasoning capability for this model.
	Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}

CodexModel describes a mapping between an alias and the actual upstream model name.

func (CodexModel) GetAlias

func (m CodexModel) GetAlias() string

func (CodexModel) GetDisplayName added in v7.2.70

func (m CodexModel) GetDisplayName() string

func (CodexModel) GetForceMapping added in v7.2.40

func (m CodexModel) GetForceMapping() bool

func (CodexModel) GetIsCompat added in v7.2.121

func (m CodexModel) GetIsCompat() bool

func (CodexModel) GetMaxContextLength added in v7.2.115

func (m CodexModel) GetMaxContextLength() int

func (CodexModel) GetName

func (m CodexModel) GetName() string

func (CodexModel) GetThinking added in v7.2.105

func (m CodexModel) GetThinking() *registry.ThinkingSupport

type Config

type Config struct {
	SDKConfig `yaml:",inline"`
	// Host is the network host/interface on which the API server will bind.
	// Default is empty ("") to bind all interfaces (IPv4 + IPv6). Use "127.0.0.1" or "localhost" for local-only access.
	Host string `yaml:"host" json:"-"`
	// Port is the network port on which the API server will listen.
	Port int `yaml:"port" json:"-"`

	// TrustedProxies lists the IPs or CIDRs allowed to provide forwarded client IP headers.
	// The server applies this list at startup; changing it requires a restart.
	TrustedProxies []string `yaml:"trusted-proxies" json:"trusted-proxies"`

	// TLS config controls HTTPS server settings.
	TLS TLSConfig `yaml:"tls" json:"tls"`

	// Home config is runtime-only and is populated from -home-jwt.
	Home HomeConfig `yaml:"-" json:"-"`

	// CredentialConcurrency contains Home-authoritative credential lifecycle settings.
	CredentialConcurrency CredentialConcurrencyConfig `yaml:"credential-concurrency" json:"credential-concurrency"`

	// CredentialInFlight configures credential observation snapshots.
	CredentialInFlight CredentialInFlightConfig `yaml:"credential-in-flight" json:"credential-in-flight"`

	// RemoteManagement nests management-related options under 'remote-management'.
	RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`

	// Plugins configures dynamic plugin discovery and per-plugin settings.
	Plugins PluginsConfig `yaml:"plugins" json:"plugins"`

	// AuthDir is the directory where authentication token files are stored.
	AuthDir string `yaml:"auth-dir" json:"-"`

	// Debug enables or disables debug-level logging and other debug features.
	Debug bool `yaml:"debug" json:"debug"`

	// Pprof config controls the optional pprof HTTP debug server.
	Pprof PprofConfig `yaml:"pprof" json:"pprof"`

	// Discovery configures local network mDNS / DNS-SD service advertising.
	Discovery DiscoveryConfig `yaml:"discovery" json:"discovery"`

	// CommercialMode disables high-overhead request logging and HTTP middleware features to minimize per-request memory usage.
	CommercialMode bool `yaml:"commercial-mode" json:"commercial-mode"`

	// LoggingToFile controls whether application logs are written to rotating files or stdout.
	LoggingToFile bool `yaml:"logging-to-file" json:"logging-to-file"`

	// LogsMaxTotalSizeMB limits the total size (in MB) of log files under the logs directory.
	// When exceeded, the oldest log files are deleted until within the limit. Set to 0 to disable.
	LogsMaxTotalSizeMB int `yaml:"logs-max-total-size-mb" json:"logs-max-total-size-mb"`

	// ErrorLogsMaxFiles limits the number of error log files retained when request logging is disabled.
	// When exceeded, the oldest error log files are deleted. Default is 10. Set to 0 to disable cleanup.
	ErrorLogsMaxFiles int `yaml:"error-logs-max-files" json:"error-logs-max-files"`

	// UsageStatisticsEnabled toggles in-memory usage aggregation; when false, usage data is discarded.
	UsageStatisticsEnabled bool `yaml:"usage-statistics-enabled" json:"usage-statistics-enabled"`

	// RedisUsageQueueRetentionSeconds controls how long usage queue items are retained
	// in memory for Management API consumers.
	// Default: 60. Max: 3600.
	RedisUsageQueueRetentionSeconds int `yaml:"redis-usage-queue-retention-seconds" json:"redis-usage-queue-retention-seconds"`

	// DisableCooling disables auth/model cooldown scheduling when true unless a credential or provider overrides it.
	DisableCooling bool `yaml:"disable-cooling" json:"disable-cooling"`

	// SaveCooldownStatus persists runtime cooldown status next to auth files when true.
	SaveCooldownStatus bool `yaml:"save-cooldown-status" json:"save-cooldown-status"`

	// TransientErrorCooldownSeconds controls cooldowns for transient upstream errors (408/500/502/503/504/520-526).
	// 0 keeps the legacy default cooldown. Negative values disable these cooldowns.
	TransientErrorCooldownSeconds int `yaml:"transient-error-cooldown-seconds" json:"transient-error-cooldown-seconds"`

	// AuthAutoRefreshWorkers overrides the size of the core auth auto-refresh and manual refresh-all worker pool.
	// When <= 0, the default worker count is used.
	AuthAutoRefreshWorkers int `yaml:"auth-auto-refresh-workers" json:"auth-auto-refresh-workers"`

	// RequestRetry defines the number of additional credential retry rounds after
	// the first round has exhausted its eligible credentials.
	RequestRetry int `yaml:"request-retry" json:"request-retry"`
	// MaxRetryCredentials defines the maximum number of different credentials to
	// try in each credential retry round.
	// Set to 0 or a negative value to keep trying all available credentials (legacy behavior).
	MaxRetryCredentials int `yaml:"max-retry-credentials" json:"max-retry-credentials"`
	// MaxRetryInterval defines the maximum positive cooldown wait, in seconds,
	// allowed before starting another credential retry round. A non-positive value
	// forbids positive cooldown waits; it does not disable same-round credential
	// failover or immediate additional rounds allowed by RequestRetry.
	MaxRetryInterval int `yaml:"max-retry-interval" json:"max-retry-interval"`

	// QuotaExceeded defines the behavior when a quota is exceeded.
	QuotaExceeded QuotaExceeded `yaml:"quota-exceeded" json:"quota-exceeded"`

	// Routing controls credential selection behavior.
	Routing RoutingConfig `yaml:"routing" json:"routing"`

	// WebsocketAuth enables or disables authentication for the WebSocket API.
	WebsocketAuth bool `yaml:"ws-auth" json:"ws-auth"`

	// AntigravitySignatureCacheEnabled controls whether signature cache validation is enabled for thinking blocks.
	// When true (default), cached signatures are preferred and validated.
	// When false, client signatures are used directly after normalization (bypass mode).
	AntigravitySignatureCacheEnabled *bool `yaml:"antigravity-signature-cache-enabled,omitempty" json:"antigravity-signature-cache-enabled,omitempty"`

	AntigravitySignatureBypassStrict *bool `yaml:"antigravity-signature-bypass-strict,omitempty" json:"antigravity-signature-bypass-strict,omitempty"`

	// Antigravity configures provider-wide Antigravity request behavior.
	Antigravity AntigravityConfig `yaml:"antigravity" json:"antigravity"`

	// Devin configures provider-wide Devin request behavior.
	Devin DevinConfig `yaml:"devin" json:"devin"`

	// GeminiKey defines Gemini API key configurations with optional routing overrides.
	GeminiKey []GeminiKey `yaml:"gemini-api-key" json:"gemini-api-key"`

	// InteractionsKey defines native Google Interactions API key configurations.
	InteractionsKey []GeminiKey `yaml:"interactions-api-key" json:"interactions-api-key"`

	// Codex defines a list of Codex API key configurations as specified in the YAML configuration file.
	CodexKey []CodexKey `yaml:"codex-api-key" json:"codex-api-key"`

	// XAIKey defines xAI API key configurations using the same structure as Codex API keys.
	XAIKey []XAIKey `yaml:"xai-api-key" json:"xai-api-key"`

	// MetaKey defines Meta API key configurations using the same structure as Codex API keys.
	MetaKey []MetaKey `yaml:"meta-api-key" json:"meta-api-key"`

	// XAI configures provider-wide xAI request behavior.
	XAI XAIConfig `yaml:"xai" json:"xai"`

	// Codex configures provider-wide Codex request behavior.
	Codex CodexConfig `yaml:"codex" json:"codex"`

	// CodexHeaderDefaults configures fallback headers for Codex OAuth model requests.
	// These are used only when the client does not send its own headers.
	CodexHeaderDefaults CodexHeaderDefaults `yaml:"codex-header-defaults" json:"codex-header-defaults"`

	// Claude configures provider-wide Claude request behavior.
	Claude ClaudeConfig `yaml:"claude" json:"claude"`

	// ClaudeKey defines a list of Claude API key configurations as specified in the YAML configuration file.
	ClaudeKey []ClaudeKey `yaml:"claude-api-key" json:"claude-api-key"`

	// ClaudeHeaderDefaults configures default header values for Claude API requests.
	// These are used as fallbacks when the client does not send its own headers.
	ClaudeHeaderDefaults ClaudeHeaderDefaults `yaml:"claude-header-defaults" json:"claude-header-defaults"`

	// DisableClaudeCloakMode globally disables Claude request cloaking when true.
	// Cloaking disguises requests as the official Claude Code CLI and replaces the
	// system prompt. When true, every Claude credential defaults to no cloaking
	// ("never"); a specific credential can still re-enable or override it via its own
	// cloak settings (the per claude-api-key "cloak" block, or a "cloak_mode" value in
	// the auth/OAuth token file). Default false preserves the per-client "auto" behavior.
	DisableClaudeCloakMode bool `yaml:"disable-claude-cloak-mode" json:"disable-claude-cloak-mode"`

	// OpenAICompatibility defines OpenAI API compatibility configurations for external providers.
	OpenAICompatibility []OpenAICompatibility `yaml:"openai-compatibility" json:"openai-compatibility"`

	// VertexCompatAPIKey defines Vertex AI-compatible API key configurations for third-party providers.
	// Used for services that use Vertex AI-style paths but with simple API key authentication.
	VertexCompatAPIKey []VertexCompatKey `yaml:"vertex-api-key" json:"vertex-api-key"`

	// OAuthExcludedModels defines per-provider global model exclusions applied to OAuth/file-backed auth entries.
	OAuthExcludedModels map[string][]string `yaml:"oauth-excluded-models,omitempty" json:"oauth-excluded-models,omitempty"`

	// OAuthModelAlias defines global model name aliases for OAuth/file-backed auth channels.
	// These aliases affect both model listing and model routing for supported channels:
	// vertex, aistudio, antigravity, claude, codex, kimi, xai, meta.
	//
	// NOTE: This does not apply to existing per-credential model alias features under:
	// gemini-api-key, interactions-api-key, codex-api-key, xai-api-key, meta-api-key, claude-api-key, openai-compatibility, and vertex-api-key.
	OAuthModelAlias map[string][]OAuthModelAlias `yaml:"oauth-model-alias,omitempty" json:"oauth-model-alias,omitempty"`

	// OAuthRequestScopedErrors defines per-provider request-scoped error rules applied to OAuth/file-backed auth entries.
	// Supported channels include: vertex, aistudio, antigravity, claude, codex, kimi, xai, meta, and OAuth plugin provider keys.
	//
	// NOTE: This applies only to OAuth credentials and does not affect per-credential request-scoped-errors under *-api-key.
	OAuthRequestScopedErrors map[string][]RequestScopedErrorRule `yaml:"oauth-request-scoped-errors,omitempty" json:"oauth-request-scoped-errors,omitempty"`

	// Payload defines default and override rules for provider payload parameters.
	Payload PayloadConfig `yaml:"payload" json:"payload"`
}

Config represents the application's configuration, loaded from a YAML file.

func LoadConfig

func LoadConfig(configFile string) (*Config, error)

LoadConfig reads a YAML configuration file from the given path, unmarshals it into a Config struct, applies environment variable overrides, and returns it.

Parameters:

  • configFile: The path to the YAML configuration file

Returns:

  • *Config: The loaded configuration
  • error: An error if the configuration could not be loaded

func LoadConfigOptional

func LoadConfigOptional(configFile string, optional bool) (*Config, error)

LoadConfigOptional reads YAML from configFile. If optional is true and the file is missing, it returns an empty Config. If optional is true and the file is empty or invalid, it returns an empty Config.

func ParseConfigBytes

func ParseConfigBytes(data []byte) (*Config, error)

ParseConfigBytes parses a YAML configuration payload into Config and applies the same in-memory normalizations as LoadConfigOptional, without persisting any changes to disk.

func (*Config) CloneForRuntime added in v7.2.12

func (cfg *Config) CloneForRuntime() *Config

CloneForRuntime returns an independent in-memory snapshot of the full config.

func (*Config) NormalizePluginsConfig added in v7.1.47

func (cfg *Config) NormalizePluginsConfig()

NormalizePluginsConfig applies default plugin configuration values.

func (*Config) ResolvePluginsDir added in v7.2.78

func (cfg *Config) ResolvePluginsDir() error

ResolvePluginsDir resolves and stores the effective plugin directory.

func (*Config) SanitizeClaudeHeaderDefaults

func (cfg *Config) SanitizeClaudeHeaderDefaults()

SanitizeClaudeHeaderDefaults trims surrounding whitespace from the configured Claude fingerprint baseline values.

func (*Config) SanitizeClaudeKeys

func (cfg *Config) SanitizeClaudeKeys()

SanitizeClaudeKeys normalizes headers for Claude credentials.

func (*Config) SanitizeCodexHeaderDefaults

func (cfg *Config) SanitizeCodexHeaderDefaults()

SanitizeCodexHeaderDefaults trims surrounding whitespace from the configured Codex header fallback values.

func (*Config) SanitizeCodexKeys

func (cfg *Config) SanitizeCodexKeys()

SanitizeCodexKeys removes Codex API key entries missing a BaseURL. It trims whitespace and preserves order for remaining entries.

func (*Config) SanitizeGeminiKeys

func (cfg *Config) SanitizeGeminiKeys()

SanitizeGeminiKeys deduplicates and normalizes Gemini credentials. It uses API key, base URL, proxy URL, prefix, and custom headers as the uniqueness key.

func (*Config) SanitizeInteractionsKeys added in v7.2.51

func (cfg *Config) SanitizeInteractionsKeys()

SanitizeInteractionsKeys deduplicates and normalizes native Interactions credentials. It uses API key, base URL, proxy URL, prefix, and custom headers as the uniqueness key.

func (*Config) SanitizeMetaKeys added in v7.3.4

func (cfg *Config) SanitizeMetaKeys()

SanitizeMetaKeys normalizes Meta API key entries, defaulting BaseURL to https://api.meta.ai/v1 if empty.

func (*Config) SanitizeOAuthModelAlias

func (cfg *Config) SanitizeOAuthModelAlias()

SanitizeOAuthModelAlias normalizes and deduplicates global OAuth model name aliases. It trims whitespace, normalizes channel keys to lower-case, drops empty entries, allows multiple aliases per upstream name, and ensures aliases are unique within each channel.

func (*Config) SanitizeOAuthRequestScopedErrors added in v7.2.138

func (cfg *Config) SanitizeOAuthRequestScopedErrors()

SanitizeOAuthRequestScopedErrors normalizes and validates global OAuth request-scoped error rules. It trims whitespace, normalizes channel keys to lower-case, validates status/action, and drops invalid rules.

func (*Config) SanitizeOpenAICompatibility

func (cfg *Config) SanitizeOpenAICompatibility()

SanitizeOpenAICompatibility removes OpenAI-compatibility provider entries that are not actionable, specifically those missing a BaseURL. It trims whitespace before evaluation and preserves the relative order of remaining entries.

func (*Config) SanitizePayloadRules

func (cfg *Config) SanitizePayloadRules()

SanitizePayloadRules validates raw JSON payload rule params and drops invalid rules.

func (*Config) SanitizeVertexCompatKeys

func (cfg *Config) SanitizeVertexCompatKeys()

SanitizeVertexCompatKeys deduplicates and normalizes Vertex-compatible API key credentials.

func (*Config) SanitizeXAIKeys added in v7.2.73

func (cfg *Config) SanitizeXAIKeys()

SanitizeXAIKeys removes xAI API key entries missing a BaseURL. It applies the same normalization rules as codex-api-key.

func (*Config) ValidateCredentialWeights added in v7.2.104

func (cfg *Config) ValidateCredentialWeights() error

ValidateCredentialWeights validates weights for every API-key family.

type CredentialConcurrencyConfig added in v7.2.96

type CredentialConcurrencyConfig struct {
	LifecycleConfigRevision    int64         `yaml:"lifecycle-config-revision" json:"lifecycle-config-revision"`
	ObservationBarrierRevision int64         `yaml:"observation-barrier-revision" json:"observation-barrier-revision"`
	CPAHeartbeatTimeout        time.Duration `yaml:"cpa-heartbeat-timeout" json:"cpa-heartbeat-timeout"`
	CPACancelBound             time.Duration `yaml:"cpa-cancel-bound" json:"cpa-cancel-bound"`
	ReclaimGrace               time.Duration `yaml:"reclaim-grace" json:"reclaim-grace"`
	CleanupInterval            time.Duration `yaml:"cleanup-interval" json:"cleanup-interval"`
	ReleaseFlushInterval       time.Duration `yaml:"release-flush-interval" json:"release-flush-interval"`
	ReleaseMaxBackoff          time.Duration `yaml:"release-max-backoff" json:"release-max-backoff"`
	BusyRetryMin               time.Duration `yaml:"busy-retry-min" json:"busy-retry-min"`
	BusyRetryMax               time.Duration `yaml:"busy-retry-max" json:"busy-retry-max"`
	MaxLimit                   int64         `yaml:"max-limit" json:"max-limit"`
	// contains filtered or unexported fields
}

CredentialConcurrencyConfig controls the credential concurrency lifecycle managed by Home.

func (*CredentialConcurrencyConfig) UnmarshalYAML added in v7.2.96

func (c *CredentialConcurrencyConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML preserves field presence so only absent lifecycle values receive legacy defaults.

func (CredentialConcurrencyConfig) WithDefaults added in v7.2.96

WithDefaults applies the lifecycle defaults required for compatibility with older Home versions.

type CredentialInFlightConfig added in v7.2.96

type CredentialInFlightConfig struct {
	SnapshotInterval   string `yaml:"snapshot-interval" json:"snapshot-interval"`
	StaleAfter         string `yaml:"stale-after" json:"stale-after"`
	MaxPartBytes       int    `yaml:"max-part-bytes" json:"max-part-bytes"`
	MaxPartCount       int    `yaml:"max-part-count" json:"max-part-count"`
	MaxRevisionBytes   int    `yaml:"max-revision-bytes" json:"max-revision-bytes"`
	MaxAggregateGroups int    `yaml:"max-aggregate-groups" json:"max-aggregate-groups"`
	MaxDetails         int    `yaml:"max-details" json:"max-details"`
	MaxStringBytes     int    `yaml:"max-string-bytes" json:"max-string-bytes"`
	StagingRetention   string `yaml:"staging-retention" json:"staging-retention"`
}

CredentialInFlightConfig controls in-flight credential observation snapshots.

func DefaultCredentialInFlightConfig added in v7.2.96

func DefaultCredentialInFlightConfig() CredentialInFlightConfig

DefaultCredentialInFlightConfig returns the in-flight observation defaults.

func (CredentialInFlightConfig) Durations added in v7.2.96

Durations parses and validates the in-flight observation durations.

func (CredentialInFlightConfig) Validate added in v7.2.96

func (c CredentialInFlightConfig) Validate() error

Validate verifies the in-flight observation bounds.

type DevinConfig added in v7.3.0

type DevinConfig struct {
	// SensitiveWords is a list of words to obfuscate with zero-width characters in system prompts and messages.
	SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"`
}

DevinConfig configures provider-wide Devin request behavior.

type DisableImageGenerationMode

type DisableImageGenerationMode int

DisableImageGenerationMode is a four-state config value for disable-image-generation.

It supports:

  • false: enabled
  • true: disabled everywhere (including /v1/images/* endpoints)
  • "chat": disabled for all non-images endpoints, but enabled for /v1/images/generations and /v1/images/edits
  • "passthrough": never inject and never strip image_generation on non-images endpoints (the client payload is forwarded unchanged); on /v1/images/* endpoints behave like "chat"
const (
	DisableImageGenerationOff DisableImageGenerationMode = iota
	DisableImageGenerationAll
	DisableImageGenerationChat
	DisableImageGenerationPassthrough
)

func (DisableImageGenerationMode) MarshalJSON

func (m DisableImageGenerationMode) MarshalJSON() ([]byte, error)

func (DisableImageGenerationMode) MarshalYAML

func (m DisableImageGenerationMode) MarshalYAML() (any, error)

func (DisableImageGenerationMode) String

func (*DisableImageGenerationMode) UnmarshalJSON

func (m *DisableImageGenerationMode) UnmarshalJSON(data []byte) error

func (*DisableImageGenerationMode) UnmarshalYAML

func (m *DisableImageGenerationMode) UnmarshalYAML(value *yaml.Node) error

type DiscoveryConfig added in v7.3.3

type DiscoveryConfig struct {
	// Enabled toggles mDNS service advertising on the local network (default: false).
	Enabled bool `yaml:"enabled" json:"enabled"`

	// ServiceName is the optional custom instance name. When empty, defaults to CPA-<ShortID>.
	ServiceName string `yaml:"service-name" json:"service-name"`

	// ServiceType is the DNS-SD service type (default: _ai-gateway._tcp).
	ServiceType string `yaml:"service-type" json:"service-type"`

	// Subtypes specifies DNS-SD API protocol subtypes to advertise (e.g. _responses, _messages, _generate-content).
	Subtypes []string `yaml:"subtypes" json:"subtypes"`

	// Interfaces specifies network interface filtering rules.
	Interfaces DiscoveryInterfacesConfig `yaml:"interfaces" json:"interfaces"`

	// AuthRequired indicates whether authentication is required for client calls (default: true).
	AuthRequired *bool `yaml:"auth-required" json:"auth-required"`

	// AdvertiseManagement explicitly controls whether management endpoints are exposed (default: false).
	AdvertiseManagement bool `yaml:"advertise-management" json:"advertise-management"`
}

DiscoveryConfig controls local network mDNS / DNS-SD service advertising.

type DiscoveryInterfacesConfig added in v7.3.3

type DiscoveryInterfacesConfig struct {
	Include []string `yaml:"include" json:"include"`
	Exclude []string `yaml:"exclude" json:"exclude"`
}

DiscoveryInterfacesConfig specifies interface inclusion and exclusion rules.

type GeminiKey

type GeminiKey struct {
	// APIKey is the authentication key for accessing Gemini API services.
	APIKey string `yaml:"api-key" json:"api-key"`

	// Priority controls selection preference when multiple credentials match.
	// Higher values are preferred; defaults to 0.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`

	// Weight controls proportional selection under weighted-round-robin.
	// An omitted value defaults to 1; non-positive values exclude this credential; maximum 1,000,000.
	Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`

	// Prefix optionally namespaces models for this credential (e.g., "teamA/gemini-3-pro-preview").
	Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`

	// BaseURL optionally overrides the Gemini API endpoint.
	BaseURL string `yaml:"base-url,omitempty" json:"base-url,omitempty"`

	// ProxyURL optionally overrides the global proxy for this API key.
	ProxyURL string `yaml:"proxy-url,omitempty" json:"proxy-url,omitempty"`

	// Models defines upstream model names and aliases for request routing.
	Models []GeminiModel `yaml:"models,omitempty" json:"models,omitempty"`

	// Headers optionally adds extra HTTP headers for requests sent with this key.
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`

	// ExcludedModels lists model IDs that should be excluded for this provider.
	ExcludedModels []string `yaml:"excluded-models,omitempty" json:"excluded-models,omitempty"`

	// DisableCooling overrides the global cooling policy for this credential when set.
	// True disables auth/model cooldowns; false explicitly enables them.
	DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`

	// RequestRetry optionally overrides the global request-retry for this credential.
	// Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds.
	RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`

	// RequestScopedErrors configures custom classification rules for upstream errors.
	RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`
}

GeminiKey represents the configuration for a Gemini API key, including optional overrides for upstream base URL, proxy routing, and headers.

func (GeminiKey) GetAPIKey

func (k GeminiKey) GetAPIKey() string

func (GeminiKey) GetBaseURL

func (k GeminiKey) GetBaseURL() string

func (GeminiKey) GetPrefix added in v7.2.105

func (k GeminiKey) GetPrefix() string

func (GeminiKey) GetProxyURL added in v7.2.105

func (k GeminiKey) GetProxyURL() string

type GeminiModel

type GeminiModel struct {
	// Name is the upstream model identifier used when issuing requests.
	Name string `yaml:"name" json:"name"`

	// Alias is the client-facing model name that maps to Name.
	Alias string `yaml:"alias" json:"alias"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	// MaxContextLength overrides the context window advertised to Codex clients.
	MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`

	// ForceMapping rewrites upstream response model fields back to Alias.
	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`

	// IsCompat preserves thinking blocks with empty signatures for compatible upstreams.
	// Default false keeps the normal signature validation behavior.
	IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`

	// Thinking configures the thinking/reasoning capability for this model.
	Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}

GeminiModel describes a mapping between an alias and the actual upstream model name.

func (GeminiModel) GetAlias

func (m GeminiModel) GetAlias() string

func (GeminiModel) GetDisplayName added in v7.2.70

func (m GeminiModel) GetDisplayName() string

func (GeminiModel) GetForceMapping added in v7.2.40

func (m GeminiModel) GetForceMapping() bool

func (GeminiModel) GetIsCompat added in v7.2.121

func (m GeminiModel) GetIsCompat() bool

func (GeminiModel) GetMaxContextLength added in v7.2.115

func (m GeminiModel) GetMaxContextLength() int

func (GeminiModel) GetName

func (m GeminiModel) GetName() string

func (GeminiModel) GetThinking added in v7.2.105

func (m GeminiModel) GetThinking() *registry.ThinkingSupport

type HomeConfig

type HomeConfig struct {
	Enabled                 bool          `yaml:"enabled" json:"enabled"`
	NodeID                  string        `yaml:"-" json:"-"`
	Host                    string        `yaml:"host" json:"-"`
	Port                    int           `yaml:"port" json:"-"`
	DisableClusterDiscovery bool          `yaml:"disable-cluster-discovery" json:"-"`
	TLS                     HomeTLSConfig `yaml:"tls" json:"-"`
}

HomeConfig stores runtime-only Home control plane settings from -home-jwt.

type HomeTLSConfig added in v7.0.10

type HomeTLSConfig struct {
	Enable              bool   `yaml:"enable" json:"-"`
	ServerName          string `yaml:"server-name" json:"-"`
	InsecureSkipVerify  bool   `yaml:"insecure-skip-verify" json:"-"`
	CACert              string `yaml:"ca-cert" json:"-"`
	ClientCert          string `yaml:"-" json:"-"`
	ClientKey           string `yaml:"-" json:"-"`
	UseTargetServerName bool   `yaml:"-" json:"-"`
}

HomeTLSConfig configures client-side TLS for the home Redis connection.

type MetaKey added in v7.3.4

type MetaKey = CodexKey

MetaKey uses the Codex API key structure for native Meta Muse execution.

type MetaModel added in v7.3.4

type MetaModel = CodexModel

MetaModel uses the Codex model mapping structure for Meta Muse models.

type OAuthModelAlias

type OAuthModelAlias struct {
	Name  string `yaml:"name" json:"name"`
	Alias string `yaml:"alias" json:"alias"`
	Fork  bool   `yaml:"fork,omitempty" json:"fork,omitempty"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
}

OAuthModelAlias defines a model ID alias for a specific channel. It maps the upstream model name (Name) to the client-visible alias (Alias). When Fork is true, the alias is added as an additional model in listings while keeping the original model ID available.

type OpenAICompatibility

type OpenAICompatibility struct {
	// Name is the identifier for this OpenAI compatibility configuration.
	Name string `yaml:"name" json:"name"`

	// Priority controls selection preference when multiple providers or credentials match.
	// Higher values are preferred; defaults to 0.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`

	// Disabled prevents this provider from being used for routing.
	Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"`

	// Prefix optionally namespaces model aliases for this provider (e.g., "teamA/kimi-k2").
	Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`

	// BaseURL is the base URL for the external OpenAI-compatible API endpoint.
	BaseURL string `yaml:"base-url" json:"base-url"`

	// APIKeyEntries defines API keys with optional per-key proxy configuration.
	APIKeyEntries []OpenAICompatibilityAPIKey `yaml:"api-key-entries,omitempty" json:"api-key-entries,omitempty"`

	// Models defines the model configurations including aliases for routing.
	Models []OpenAICompatibilityModel `yaml:"models" json:"models"`

	// Headers optionally adds extra HTTP headers for requests sent to this provider.
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`

	// SupportPromptCacheKey enables derived prompt_cache_key injection for supported requests.
	SupportPromptCacheKey bool `yaml:"support-prompt-cache-key,omitempty" json:"support-prompt-cache-key,omitempty"`

	// DisableCooling overrides the global cooling policy for this provider when set.
	// True disables auth/model cooldowns; false explicitly enables them.
	DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`

	// RequestRetry optionally overrides the global request-retry for this provider.
	// Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds.
	RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`

	// RequestScopedErrors configures custom classification rules for upstream errors.
	RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`
}

OpenAICompatibility represents the configuration for OpenAI API compatibility with external providers, allowing model aliases to be routed through OpenAI API format.

type OpenAICompatibilityAPIKey

type OpenAICompatibilityAPIKey struct {
	// APIKey is the authentication key for accessing the external API services.
	APIKey string `yaml:"api-key" json:"api-key"`

	// Weight controls proportional selection under weighted-round-robin.
	// An omitted value defaults to 1; non-positive values exclude this credential; maximum 1,000,000.
	Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`

	// ProxyURL overrides the global proxy setting for this API key if provided.
	ProxyURL string `yaml:"proxy-url,omitempty" json:"proxy-url,omitempty"`
}

OpenAICompatibilityAPIKey represents an API key configuration with optional proxy setting.

type OpenAICompatibilityModel

type OpenAICompatibilityModel struct {
	// Name is the actual model name used by the external provider.
	Name string `yaml:"name" json:"name"`

	// Alias is the model name alias that clients will use to reference this model.
	Alias string `yaml:"alias" json:"alias"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	// MaxContextLength overrides the context window advertised to Codex clients.
	MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`

	// ForceMapping rewrites upstream response model fields back to Alias.
	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`

	// Image marks this model as callable through /v1/images/generations and /v1/images/edits.
	Image bool `yaml:"image,omitempty" json:"image,omitempty"`

	// InputModalities declares chat/responses input capabilities (e.g. text, image) for Codex and other clients.
	// This is separate from Image, which only enables /v1/images/* endpoints.
	InputModalities []string `yaml:"input-modalities,omitempty" json:"input-modalities,omitempty"`

	// OutputModalities declares supported output modalities when known (e.g. text, image).
	OutputModalities []string `yaml:"output-modalities,omitempty" json:"output-modalities,omitempty"`

	// IsCompat preserves Claude thinking blocks for compatible upstreams.
	// Default false keeps the normal signature validation behavior.
	IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`

	// UseMaxCompletionTokens emits max_completion_tokens instead of legacy max_tokens for this model.
	// Default false preserves max_tokens for older compatible upstreams.
	UseMaxCompletionTokens bool `yaml:"use-max-completion-tokens,omitempty" json:"use-max-completion-tokens,omitempty"`

	// Thinking configures the thinking/reasoning capability for this model.
	// If nil, the model defaults to level-based reasoning with levels ["low", "medium", "high"].
	Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}

OpenAICompatibilityModel represents a model configuration for OpenAI compatibility, including the actual model name and its alias for API routing.

func (OpenAICompatibilityModel) GetAlias

func (m OpenAICompatibilityModel) GetAlias() string

func (OpenAICompatibilityModel) GetDisplayName added in v7.2.70

func (m OpenAICompatibilityModel) GetDisplayName() string

func (OpenAICompatibilityModel) GetForceMapping added in v7.2.40

func (m OpenAICompatibilityModel) GetForceMapping() bool

func (OpenAICompatibilityModel) GetIsCompat added in v7.2.122

func (m OpenAICompatibilityModel) GetIsCompat() bool

func (OpenAICompatibilityModel) GetMaxContextLength added in v7.2.115

func (m OpenAICompatibilityModel) GetMaxContextLength() int

func (OpenAICompatibilityModel) GetName

func (m OpenAICompatibilityModel) GetName() string

func (OpenAICompatibilityModel) GetThinking added in v7.2.105

func (OpenAICompatibilityModel) GetUseMaxCompletionTokens added in v7.3.8

func (m OpenAICompatibilityModel) GetUseMaxCompletionTokens() bool

type PayloadConfig

type PayloadConfig struct {
	// Default defines rules that only set parameters when they are missing in the payload.
	Default []PayloadRule `yaml:"default" json:"default"`
	// DefaultRaw defines rules that set raw JSON values only when they are missing.
	DefaultRaw []PayloadRule `yaml:"default-raw" json:"default-raw"`
	// Override defines rules that always set parameters, overwriting any existing values.
	Override []PayloadRule `yaml:"override" json:"override"`
	// OverrideRaw defines rules that always set raw JSON values, overwriting any existing values.
	OverrideRaw []PayloadRule `yaml:"override-raw" json:"override-raw"`
	// Filter defines rules that remove parameters from the payload by JSON path.
	Filter []PayloadFilterRule `yaml:"filter" json:"filter"`
}

PayloadConfig defines default and override parameter rules applied to provider payloads.

type PayloadFilterRule

type PayloadFilterRule struct {
	// Models lists model entries with name pattern and protocol constraint.
	Models []PayloadModelRule `yaml:"models" json:"models"`
	// Params lists JSON paths (gjson/sjson syntax) to remove from the payload.
	Params []string `yaml:"params" json:"params"`
}

PayloadFilterRule describes a rule to remove specific JSON paths from matching model payloads.

type PayloadModelRule

type PayloadModelRule struct {
	// Name is the model name or wildcard pattern (e.g., "gpt-*", "*-5", "gemini-*-pro").
	Name string `yaml:"name" json:"name"`
	// Protocol restricts the rule to a specific translator format (e.g., "gemini", "responses").
	Protocol string `yaml:"protocol" json:"protocol"`
	// Headers restricts the rule to requests whose headers match all configured wildcard patterns.
	Headers map[string]string `yaml:"headers" json:"headers"`
	// FromProtocol restricts the rule to a specific source protocol (e.g., "gemini", "responses").
	FromProtocol string `yaml:"from-protocol" json:"from-protocol"`
	// Match requires payload JSON paths to equal the configured values.
	Match []map[string]any `yaml:"match" json:"match"`
	// NotMatch requires payload JSON paths to not equal the configured values.
	NotMatch []map[string]any `yaml:"not-match" json:"not-match"`
	// Exist requires payload JSON paths to exist and not be null.
	Exist []string `yaml:"exist" json:"exist"`
	// NotExist requires payload JSON paths to be missing or null.
	NotExist []string `yaml:"not-exist" json:"not-exist"`
}

PayloadModelRule ties a model name pattern to a specific translator protocol.

type PayloadRule

type PayloadRule struct {
	// Models lists model entries with name pattern and protocol constraint.
	Models []PayloadModelRule `yaml:"models" json:"models"`
	// Params maps JSON paths (gjson/sjson syntax) to values written into the payload.
	// For *-raw rules, values are treated as raw JSON fragments (strings are used as-is).
	Params map[string]any `yaml:"params" json:"params"`
}

PayloadRule describes a single rule targeting a list of models with parameter updates.

type PluginInstanceConfig added in v7.1.47

type PluginInstanceConfig struct {
	// Enabled toggles this plugin instance. Nil is normalized to false during YAML parsing.
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
	// Priority controls plugin startup and routing order.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`
	// Raw preserves the full original plugin configuration YAML subtree.
	Raw yaml.Node `yaml:"-" json:"-"`
}

PluginInstanceConfig stores host-owned plugin settings and the original plugin YAML subtree.

func (PluginInstanceConfig) MarshalYAML added in v7.1.47

func (c PluginInstanceConfig) MarshalYAML() (any, error)

MarshalYAML returns the preserved raw plugin YAML subtree for lossless config output.

func (*PluginInstanceConfig) UnmarshalYAML added in v7.1.47

func (c *PluginInstanceConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML extracts host-owned fields while preserving the full original YAML node.

type PluginsConfig added in v7.1.47

type PluginsConfig struct {
	// Enabled toggles dynamic plugin loading.
	Enabled bool `yaml:"enabled" json:"enabled"`
	// Dir is the plugin discovery directory.
	Dir string `yaml:"dir" json:"dir"`
	// StoreSources appends third-party plugin store registries to the built-in official source.
	StoreSources []string `yaml:"store-sources,omitempty" json:"store-sources,omitempty"`
	// StoreAuth defines optional auth rules for plugin store registry, metadata, and artifact requests.
	StoreAuth []sdkpluginstore.AuthConfig `yaml:"store-auth,omitempty" json:"store-auth,omitempty"`
	// AuthRevision changes when Home-managed plugin credentials change.
	AuthRevision int64 `yaml:"auth-revision,omitempty" json:"auth-revision,omitempty"`
	// Configs stores per-plugin instance configuration by plugin ID.
	Configs map[string]PluginInstanceConfig `yaml:"configs" json:"configs"`
}

PluginsConfig holds dynamic plugin system settings.

type PprofConfig

type PprofConfig struct {
	// Enable toggles the pprof HTTP debug server.
	Enable bool `yaml:"enable" json:"enable"`
	// Addr is the host:port address for the pprof HTTP server.
	Addr string `yaml:"addr" json:"addr"`
}

PprofConfig holds pprof HTTP server settings.

type QuotaExceeded

type QuotaExceeded struct {
	// SwitchProject indicates whether to automatically switch to another project when a quota is exceeded.
	SwitchProject bool `yaml:"switch-project" json:"switch-project"`

	// SwitchPreviewModel indicates whether to automatically switch to a preview model when a quota is exceeded.
	SwitchPreviewModel bool `yaml:"switch-preview-model" json:"switch-preview-model"`

	// AntigravityCredits enables credits-based last-resort fallback for Claude models.
	// When all free-tier auths are exhausted (429/503), the conductor retries with
	// an auth that has available Google One AI credits.
	AntigravityCredits bool `yaml:"antigravity-credits" json:"antigravity-credits"`
}

QuotaExceeded defines the behavior when API quota limits are exceeded. It provides configuration options for automatic failover mechanisms.

type RemoteManagement

type RemoteManagement struct {
	// AllowRemote toggles remote (non-localhost) access to management API.
	AllowRemote bool `yaml:"allow-remote"`
	// SecretKey is the management key (plaintext or bcrypt hashed). YAML key intentionally 'secret-key'.
	SecretKey string `yaml:"secret-key"`
	// DisableControlPanel skips serving and syncing the bundled management UI when true.
	DisableControlPanel bool `yaml:"disable-control-panel"`
	// DisableAutoUpdatePanel disables automatic periodic background updates of the management panel asset from GitHub.
	// When false (the default), the background updater remains enabled; when true, the panel is only downloaded on first access if missing.
	DisableAutoUpdatePanel bool `yaml:"disable-auto-update-panel"`
	// PanelGitHubRepository overrides the GitHub repository used to fetch the management panel asset.
	// Accepts either a repository URL (https://github.com/org/repo) or an API releases endpoint.
	PanelGitHubRepository string `yaml:"panel-github-repository"`
}

RemoteManagement holds management API configuration under 'remote-management'.

type RequestScopedErrorRule added in v7.2.134

type RequestScopedErrorRule struct {
	// Status matches the HTTP status code of the upstream response (e.g. 400).
	Status int `yaml:"status,omitempty" json:"status,omitempty"`
	// Match matches substrings in the upstream error body.
	Match []string `yaml:"match,omitempty" json:"match,omitempty"`
	// MatchRegexr matches regular expressions in the upstream error body.
	MatchRegexr []string `yaml:"match-regexr,omitempty" json:"match-regexr,omitempty"`
	// Action specifies the handling behavior: "stop", "stop-and-cooldown", "continue", "continue-and-cooldown".
	Action string `yaml:"action,omitempty" json:"action,omitempty"`
}

RequestScopedErrorRule configures custom classification and handling for upstream errors.

type RoutingConfig

type RoutingConfig struct {
	// Strategy selects the credential selection strategy.
	// Supported values: "round-robin" (default), "weighted-round-robin", "fill-first".
	Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`

	// SessionAffinity enables universal session-sticky routing for all clients.
	// Explicit Claude Code, Codex, OpenCode, and pi session headers are preferred,
	// followed by prompt_cache_key, Responses conversation IDs, legacy body IDs,
	// execution or derived session identity, and the existing message-content hash fallback.
	// Automatic failover is always enabled when bound auth becomes unavailable.
	SessionAffinity bool `yaml:"session-affinity,omitempty" json:"session-affinity,omitempty"`

	// SessionAffinityTTL specifies how long session-to-auth bindings are retained.
	// Default: 1h. Accepts duration strings like "30m", "1h", "2h30m".
	SessionAffinityTTL string `yaml:"session-affinity-ttl,omitempty" json:"session-affinity-ttl,omitempty"`

	// SessionAffinitySubagents controls whether subagents (child sessions with parent references)
	// inherit and bind to the parent's upstream credential across all providers (Claude, Codex,
	// Antigravity, Gemini), maximizing prompt and KV cache reuse.
	// When false, subagents are distributed across the credential pool via the fallback selector.
	// Default: true. Ignored when SessionAffinity is false.
	SessionAffinitySubagents *bool `yaml:"session-affinity-subagents,omitempty" json:"session-affinity-subagents,omitempty"`
}

RoutingConfig configures how credentials are selected for requests.

type SDKConfig

type SDKConfig struct {
	// CodexResponseSteering mirrors the provider-wide runtime setting for API handlers.
	CodexResponseSteering bool `yaml:"-" json:"-"`

	// ProxyURL is the URL of an optional proxy server to use for outbound requests.
	ProxyURL string `yaml:"proxy-url" json:"proxy-url"`

	// DisableImageGeneration controls whether the built-in image_generation tool is injected/allowed.
	//
	// Supported values:
	//   - false (default): image_generation is enabled everywhere (normal behavior).
	//   - true: image_generation is disabled everywhere. The server stops injecting it, removes it from request payloads,
	//     and returns 404 for /v1/images/generations and /v1/images/edits.
	//   - "chat": disable image_generation injection for all non-images endpoints (e.g. /v1/responses, /v1/chat/completions),
	//     while keeping /v1/images/generations and /v1/images/edits enabled and preserving image_generation there.
	//   - "passthrough": do not modify the tool list on non-images endpoints — keep image_generation if the client
	//     sent it and do not inject it otherwise; on /v1/images/generations and /v1/images/edits behave like "chat".
	DisableImageGeneration DisableImageGenerationMode `yaml:"disable-image-generation" json:"disable-image-generation"`

	// GPTImage2BaseModel sets the base (mainline) model used by the legacy hosted
	// image_generation tool path when a Codex image request is not proxied directly
	// through the Image API.
	//
	// The value must start with "gpt-" (case-insensitive). If empty or invalid, the
	// default base model ("gpt-5.4-mini") is used.
	GPTImage2BaseModel string `yaml:"gpt-image-2-base-model,omitempty" json:"gpt-image-2-base-model,omitempty"`

	// VideoResultAuthCacheTTL controls how long video IDs stay pinned to the credential
	// that created them. Accepts duration strings like "30m" or "3h".
	// Empty or invalid values use the default 3h.
	VideoResultAuthCacheTTL string `yaml:"video-result-auth-cache-ttl,omitempty" json:"video-result-auth-cache-ttl,omitempty"`

	// ForceModelPrefix requires explicit model prefixes (e.g., "teamA/gemini-3-pro-preview")
	// to target prefixed credentials. When false, unprefixed model requests may use prefixed
	// credentials as well.
	ForceModelPrefix bool `yaml:"force-model-prefix" json:"force-model-prefix"`

	// RequestLog enables or disables detailed request logging functionality.
	RequestLog bool `yaml:"request-log" json:"request-log"`

	// CodexOptimizeMultiAgentV2 mirrors the provider-wide runtime setting for API handlers.
	CodexOptimizeMultiAgentV2 bool `yaml:"-" json:"-"`

	// CodexOrphanDelegationCompatibility mirrors the provider-wide runtime setting for API handlers.
	CodexOrphanDelegationCompatibility bool `yaml:"-" json:"-"`

	// ClaudeCode configures Claude Code compatibility behavior.
	ClaudeCode ClaudeCodeConfig `yaml:"claude-code" json:"claude-code"`

	// APIKeys is a list of keys for authenticating clients to this proxy server.
	APIKeys []string `yaml:"api-keys" json:"api-keys"`

	// PassthroughHeaders controls whether upstream response headers are forwarded to downstream clients.
	// Default is false (disabled).
	PassthroughHeaders bool `yaml:"passthrough-headers" json:"passthrough-headers"`

	// Streaming configures server-side streaming behavior (keep-alives and safe bootstrap retries).
	Streaming StreamingConfig `yaml:"streaming" json:"streaming"`

	// NonStreamKeepAliveInterval controls how often blank lines are emitted for non-streaming responses.
	// <= 0 disables keep-alives. Value is in seconds.
	NonStreamKeepAliveInterval int `yaml:"nonstream-keepalive-interval,omitempty" json:"nonstream-keepalive-interval,omitempty"`
}

SDKConfig represents the application's configuration, loaded from a YAML file.

type StreamingConfig

type StreamingConfig struct {
	// KeepAliveSeconds controls how often the server emits SSE heartbeats (": keep-alive\n\n")
	// or WebSocket Ping control frames.
	// <= 0 disables keep-alives. Default is 0.
	KeepAliveSeconds int `yaml:"keepalive-seconds,omitempty" json:"keepalive-seconds,omitempty"`

	// BootstrapRetries controls how many times the server may retry a streaming request before any bytes are sent,
	// to allow auth rotation / transient recovery.
	// <= 0 disables bootstrap retries. Default is 0.
	BootstrapRetries int `yaml:"bootstrap-retries,omitempty" json:"bootstrap-retries,omitempty"`
}

StreamingConfig holds server streaming behavior configuration.

type TLSConfig

type TLSConfig struct {
	// Enable toggles HTTPS server mode.
	Enable bool `yaml:"enable" json:"enable"`
	// Cert is the path to the TLS certificate file.
	Cert string `yaml:"cert" json:"cert"`
	// Key is the path to the TLS private key file.
	Key string `yaml:"key" json:"key"`
}

TLSConfig holds HTTPS server settings.

type VertexCompatKey

type VertexCompatKey struct {
	// APIKey is the authentication key for accessing the Vertex-compatible API.
	// Maps to the x-goog-api-key header.
	APIKey string `yaml:"api-key" json:"api-key"`

	// Priority controls selection preference when multiple credentials match.
	// Higher values are preferred; defaults to 0.
	Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`

	// Weight controls proportional selection under weighted-round-robin.
	// An omitted value defaults to 1; non-positive values exclude this credential; maximum 1,000,000.
	Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`

	// Prefix optionally namespaces model aliases for this credential (e.g., "teamA/vertex-pro").
	Prefix string `yaml:"prefix,omitempty" json:"prefix,omitempty"`

	// BaseURL optionally overrides the Vertex-compatible API endpoint.
	// The executor will append "/v1/publishers/google/models/{model}:action" to this.
	// When empty, requests fall back to the default Vertex API base URL.
	BaseURL string `yaml:"base-url,omitempty" json:"base-url,omitempty"`

	// ProxyURL optionally overrides the global proxy for this API key.
	ProxyURL string `yaml:"proxy-url,omitempty" json:"proxy-url,omitempty"`

	// Headers optionally adds extra HTTP headers for requests sent with this key.
	// Commonly used for cookies, user-agent, and other authentication headers.
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`

	// Models defines the model configurations including aliases for routing.
	Models []VertexCompatModel `yaml:"models,omitempty" json:"models,omitempty"`

	// ExcludedModels lists model IDs that should be excluded for this provider.
	ExcludedModels []string `yaml:"excluded-models,omitempty" json:"excluded-models,omitempty"`

	// DisableCooling overrides the global cooling policy for this credential when set.
	// True disables auth/model cooldowns; false explicitly enables them.
	DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`

	// RequestRetry optionally overrides the global request-retry for this credential.
	// Nil or a negative value means "use the global request-retry". 0 disables additional retry rounds.
	RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
}

VertexCompatKey represents the configuration for Vertex AI-compatible API keys. This supports third-party services that use Vertex AI-style endpoint paths (/publishers/google/models/{model}:streamGenerateContent) but authenticate with simple API keys instead of Google Cloud service account credentials.

Example services: zenmux.ai and similar Vertex-compatible providers.

func (VertexCompatKey) GetAPIKey

func (k VertexCompatKey) GetAPIKey() string

func (VertexCompatKey) GetBaseURL

func (k VertexCompatKey) GetBaseURL() string

func (VertexCompatKey) GetPrefix added in v7.2.105

func (k VertexCompatKey) GetPrefix() string

func (VertexCompatKey) GetProxyURL added in v7.2.105

func (k VertexCompatKey) GetProxyURL() string

type VertexCompatModel

type VertexCompatModel struct {
	// Name is the actual model name used by the external provider.
	Name string `yaml:"name" json:"name"`

	// Alias is the model name alias that clients will use to reference this model.
	Alias string `yaml:"alias" json:"alias"`

	// DisplayName is the optional human-readable name shown in model catalogs.
	DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`

	// ForceMapping rewrites upstream response model fields back to Alias.
	ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`

	// Thinking configures the thinking/reasoning capability for this model.
	Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}

VertexCompatModel represents a model configuration for Vertex compatibility, including the actual model name and its alias for API routing.

func (VertexCompatModel) GetAlias

func (m VertexCompatModel) GetAlias() string

func (VertexCompatModel) GetDisplayName added in v7.2.70

func (m VertexCompatModel) GetDisplayName() string

func (VertexCompatModel) GetForceMapping added in v7.2.40

func (m VertexCompatModel) GetForceMapping() bool

func (VertexCompatModel) GetName

func (m VertexCompatModel) GetName() string

func (VertexCompatModel) GetThinking added in v7.2.105

func (m VertexCompatModel) GetThinking() *registry.ThinkingSupport

type XAIConfig added in v7.2.102

type XAIConfig struct {
	// InjectXSearch injects xAI's native x_search tool when the request does not declare it.
	InjectXSearch bool `yaml:"inject-x-search" json:"inject-x-search"`
}

XAIConfig configures provider-wide xAI request behavior.

type XAIKey added in v7.2.73

type XAIKey = CodexKey

XAIKey uses the Codex API key structure for native xAI execution.

type XAIModel added in v7.2.73

type XAIModel = CodexModel

XAIModel uses the Codex model mapping structure for xAI models.

Jump to

Keyboard shortcuts

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