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
- Variables
- func ApplyDownstreamHomeModeScalars(root map[string]any)
- func ApplyHomeRuntimeScalars(root map[string]any)
- func CredentialConfigFromOptions(entry, options any) (map[string]any, error)
- func CredentialExecutionOptions(entry any) (map[string]any, error)
- func ForceHomeRuntimeConfig(cfg *Config)
- func FormatSortedHeaders(headers map[string]string) string
- func IsOAuthProviderRoot(key string) bool
- func LegacyConfigRoot(cfg *Config) (map[string]any, error)
- func NormalizeCommentIndentation(data []byte) []byte
- func NormalizeConfigLayout(data []byte, migrate bool) ([]byte, bool, error)
- func NormalizeConfigRoot(root map[string]any) (map[string]any, error)
- func NormalizeExcludedModels(models []string) []string
- func NormalizeHeaders(headers map[string]string) map[string]string
- func NormalizeOAuthExcludedModels(entries map[string][]string) map[string][]string
- func NormalizeRemoteManagementSecret(secret string) (string, bool, error)
- func NormalizeSensitiveWordsReplace(in map[string]string) map[string]string
- func NormalizeV8ConfigAliases(root *yaml.Node) error
- func ProjectV8ConfigAliases(root *yaml.Node, path string)
- func SaveConfigPreserveCommentsUpdateNestedScalar(configFile string, path []string, value string) error
- func UpdateOAuthScope(oauth any, key string, value any) (any, bool, error)
- func ValidateCredentialConcurrencyConfig(cfg CredentialConcurrencyConfig) error
- func ValidateCredentialWeight(weight *int) error
- func ValidateTrustedProxies(values []string) error
- func ValidateV8Config(data []byte) error
- type AntigravityConfig
- type AntigravityConnectionPoolConfig
- type ClaudeCodeConfig
- type ClaudeConfig
- type ClaudeHeaderDefaults
- type ClaudeKey
- type ClaudeModel
- type CloakConfig
- type CodexConfig
- type CodexHeaderDefaults
- type CodexKey
- type CodexLiveICEServer
- type CodexLiveMediaRelayConfig
- type CodexModel
- type Config
- func (cfg Config) MarshalYAML() (any, error)
- func (cfg *Config) NormalizePluginsConfig()
- func (cfg *Config) NormalizeProviderCredentialIDs() error
- func (cfg *Config) NormalizeTrustedProxies()
- func (cfg *Config) NormalizeUserEmailConfig()
- func (cfg *Config) SanitizeAntigravity()
- func (cfg *Config) SanitizeClaudeHeaderDefaults()
- func (cfg *Config) SanitizeClaudeKeys()
- func (cfg *Config) SanitizeCodexHeaderDefaults()
- func (cfg *Config) SanitizeCodexKeys()
- func (cfg *Config) SanitizeDevin()
- func (cfg *Config) SanitizeGeminiKeys()
- func (cfg *Config) SanitizeInteractionsKeys()
- func (cfg *Config) SanitizeMetaKeys()
- func (cfg *Config) SanitizeOAuthModelAlias()
- func (cfg *Config) SanitizeOpenAICompatibility()
- func (cfg *Config) SanitizePayloadRules()
- func (cfg *Config) SanitizeVertexCompatKeys()
- func (cfg *Config) SanitizeXAIKeys()
- func (cfg *Config) UnmarshalYAML(node *yaml.Node) error
- func (cfg *Config) ValidateCredentialWeights() error
- func (cfg *Config) ValidateHomePolicies() error
- type CredentialConcurrencyConfig
- type CredentialConfig
- type CredentialInFlightConfig
- type DevinConfig
- type DisableImageGenerationMode
- func (m DisableImageGenerationMode) MarshalJSON() ([]byte, error)
- func (m DisableImageGenerationMode) MarshalYAML() (any, error)
- func (m DisableImageGenerationMode) String() string
- func (m *DisableImageGenerationMode) UnmarshalJSON(data []byte) error
- func (m *DisableImageGenerationMode) UnmarshalYAML(value *yaml.Node) error
- type DiscoveryConfig
- type DiscoveryInterfacesConfig
- type GeminiKey
- type GeminiModel
- type MetaKey
- type MetaModel
- type ModelCatalogs
- type OAuthModelAlias
- type OAuthModelSetting
- type OpenAICompatibility
- type OpenAICompatibilityAPIKey
- type OpenAICompatibilityModel
- type PayloadConfig
- type PayloadFilterRule
- type PayloadModelRule
- type PayloadRule
- type PluginInstanceConfig
- type PluginsConfig
- type PprofConfig
- type QuotaExceeded
- type RemoteManagement
- type RequestScopedErrorRule
- type RoutingConfig
- type SDKConfig
- type SensitivePatternRule
- type StreamingConfig
- type TLSConfig
- type UserEmailConfig
- type UserEmailSMTPConfig
- type UserEmailSenderConfig
- type VertexCompatKey
- type VertexCompatModel
- type XAIConfig
- type XAIKey
- type XAIModel
Constants ¶
const ( DefaultPanelGitHubRepository = "https://github.com/router-for-me/Home-Management-Center" DefaultPprofAddr = "127.0.0.1:8316" DefaultCPAPort = 8317 )
const ( DefaultCPAHeartbeatTimeout = 3 * time.Second DefaultCPACancelBound = 5 * time.Second DefaultReclaimGrace = 5 * time.Second DefaultCleanupInterval = 5 * time.Second )
const ( DefaultInFlightMaxPartBytes = 256 * 1024 DefaultInFlightMaxPartCount = 64 DefaultInFlightMaxRevisionBytes = 16 * 1024 * 1024 DefaultInFlightMaxAggregateGroups = 100000 DefaultInFlightMaxDetails = 10000 DefaultInFlightMaxStringBytes = 256 )
const ( DefaultUserEmailVerificationTokenTTL = "24h" DefaultUserEmailResetTokenTTL = "30m" DefaultUserEmailSMTPPort = 587 )
const HomeCredentialConfigMetadataKey = "home_config"
HomeCredentialConfigMetadataKey is private persistence data, never a CPA payload.
const MaxCredentialWeight = 1_000_000
MaxCredentialWeight is the largest positive credential routing weight.
Variables ¶
var ErrInvalidProviderCredentialID = errors.New("provider credential id must be a canonical UUID")
var HomeCredentialFields = [...]string{"id", "uuid", "api-key", "base-url", "proxy-url", "prefix", "priority", "headers", "excluded-models", "disable-cooling", "request-retry", "name", "disabled"}
These fields are stored authoritatively on auth records, not in CPA options.
Functions ¶
func ApplyDownstreamHomeModeScalars ¶ added in v1.0.34
ApplyDownstreamHomeModeScalars only applies scalar Home-mode overrides. It does not remove sensitive or Home-local roots such as api-keys, remote-management, auth-dir, tls, or credential roots. Callers that build downstream CPA YAML must filter those roots separately first.
func ApplyHomeRuntimeScalars ¶ added in v1.0.67
ApplyHomeRuntimeScalars applies scalar invariants owned by Home.
func CredentialConfigFromOptions ¶ added in v1.1.10
CredentialConfigFromOptions upgrades older records that only retained the CPA JSON projection. New records always export their original credential tree. Seed the SDK view with recoverable auth fields before applying retained options.
func CredentialExecutionOptions ¶ added in v1.1.10
CredentialExecutionOptions translates YAML to CPA JSON using SDK types. This projection is not used to reconstruct newly stored configuration.
func ForceHomeRuntimeConfig ¶ added in v1.0.67
func ForceHomeRuntimeConfig(cfg *Config)
ForceHomeRuntimeConfig applies invariants owned by the Home runtime.
func FormatSortedHeaders ¶ added in v1.0.70
FormatSortedHeaders serializes headers deterministically with null byte separators.
func IsOAuthProviderRoot ¶ added in v1.0.75
IsOAuthProviderRoot identifies legacy roots that contain OAuth-scoped fields.
func LegacyConfigRoot ¶ added in v1.0.75
LegacyConfigRoot materializes effective runtime fields for v0 field updates. Scope is retained in the persisted document by UpdateOAuthScope.
func NormalizeCommentIndentation ¶
NormalizeCommentIndentation removes indentation from standalone YAML comment lines to keep them left aligned.
func NormalizeConfigLayout ¶ added in v1.0.75
NormalizeConfigLayout removes conflicting legacy fields. migrate also moves legacy-only fields; callers use it only for an explicit v8 configuration write.
func NormalizeConfigRoot ¶ added in v1.0.75
NormalizeConfigRoot keeps the database's legacy roots while retaining OAuth provider paths as scope information. Both layouts describe the same values. Keeping the legacy projection also lets older CPA nodes consume the snapshot.
func NormalizeExcludedModels ¶
NormalizeExcludedModels trims, lowercases, and deduplicates model exclusion patterns. It preserves the order of first occurrences and drops empty entries.
func NormalizeHeaders ¶
NormalizeHeaders trims header keys and values and removes empty pairs.
func NormalizeOAuthExcludedModels ¶
NormalizeOAuthExcludedModels cleans provider -> excluded models mappings by normalizing provider keys and applying model exclusion normalization to each entry.
func NormalizeRemoteManagementSecret ¶ added in v1.0.2
NormalizeRemoteManagementSecret normalizes a remote management secret.
func NormalizeSensitiveWordsReplace ¶ added in v1.1.10
NormalizeSensitiveWordsReplace trims replacement target keys, drops blank keys, and preserves replacement values (including empty strings for phrase deletion).
func NormalizeV8ConfigAliases ¶ added in v1.1.0
NormalizeV8ConfigAliases accepts historical v8 paths without discarding unknown fields. Callers still validate the canonical document before saving. Normalize request bodies before merging so an alias update can replace a canonical value already present in the stored configuration.
func ProjectV8ConfigAliases ¶ added in v1.1.0
ProjectV8ConfigAliases moves canonical fields into a requested historical subtree. Moving, rather than copying, preserves PUT and DELETE semantics when the subtree contains both shared settings and OAuth-only fields.
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 UpdateOAuthScope ¶ added in v1.0.75
UpdateOAuthScope applies a legacy root edit to any existing v8 OAuth paths. A nil value removes the corresponding scoped settings as well as their root.
func ValidateCredentialConcurrencyConfig ¶ added in v1.0.61
func ValidateCredentialConcurrencyConfig(cfg CredentialConcurrencyConfig) error
ValidateCredentialConcurrencyConfig validates limiter timing and configured bounds.
func ValidateCredentialWeight ¶ added in v1.0.75
ValidateCredentialWeight validates one optional config credential weight.
func ValidateTrustedProxies ¶ added in v1.0.60
ValidateTrustedProxies accepts only explicit IP addresses and CIDRs, and rejects trust-all networks that would let direct clients spoof their source.
func ValidateV8Config ¶ added in v1.0.75
ValidateV8Config accepts only the v8 layout in management writes. Plugin-owned configuration remains extensible through its existing decoder.
Types ¶
type AntigravityConfig ¶ added in v1.0.72
type AntigravityConfig struct {
TOSPauseWindow string `yaml:"tos-pause-window,omitempty" json:"tos-pause-window,omitempty"`
// SensitiveWords is a list of words to obfuscate in system instructions.
SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"`
// SensitiveWordsReplace maps target substrings to literal replacement text in system instructions.
SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"`
// SensitivePatternsReplace defines ordered Go RE2 regex replacement rules for system instructions.
SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,omitempty"`
// Settings shared with CPA V8.
ConnectionPool AntigravityConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,omitempty"`
}
AntigravityConfig configures provider-wide Antigravity request behavior.
type AntigravityConnectionPoolConfig ¶ added in v1.0.75
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"`
}
type ClaudeCodeConfig ¶ added in v1.0.75
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 v1.0.75
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"`
// ToolSearch is a CPA option (upstream.claude.tool-search) that enables Codex
// client tool_search on Claude Responses routes. Home forwards it to CPA.
ToolSearch bool `yaml:"tool-search" json:"tool-search"`
}
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"`
StabilizeDeviceProfile *bool `yaml:"stabilize-device-profile,omitempty" json:"stabilize-device-profile,omitempty"`
// Settings shared with CPA V8.
Timezone string `yaml:"timezone" json:"timezone"`
}
ClaudeHeaderDefaults configures default header values injected into Claude API requests. In legacy mode, UserAgent/PackageVersion/RuntimeVersion/Timeout act as fallbacks when the client omits them, while OS/Arch remain runtime-derived. When stabilized device profiles are enabled, OS/Arch become the pinned platform baseline, while UserAgent/PackageVersion/RuntimeVersion seed the upgradeable software fingerprint.
type ClaudeKey ¶
type ClaudeKey struct {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable credential identity.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// 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"`
// 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"`
// DisableCooling overrides the global cooling policy for this credential when set.
// True disables request-error and quota cooldowns; false explicitly enables them.
DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`
// RequestRetry optionally overrides the global number of additional retry rounds.
// Nil or a negative value inherits the global setting; zero disables additional rounds.
RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
// Cloak configures request cloaking for non-Claude-Code clients.
Cloak *CloakConfig `yaml:"cloak,omitempty" json:"cloak,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"`
// Settings shared with CPA V8.
Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`
RebuildMidSystemMessage bool `yaml:"rebuild-mid-system-message,omitempty" json:"rebuild-mid-system-message,omitempty"`
RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`
FingerprintProfile string `yaml:"fingerprint-profile,omitempty" json:"fingerprint-profile,omitempty"`
// NativeToolSearch trusts a custom base URL with Anthropic native tool search
// (defer_loading tools and tool_reference results) for Codex tool_search.
NativeToolSearch bool `yaml:"native-tool-search,omitempty" json:"native-tool-search,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) GetProxyURL ¶ added in v1.0.70
GetProxyURL returns a proxy url.
func (ClaudeKey) MarshalYAML ¶ added in v1.1.10
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"`
// Settings shared with CPA V8.
DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`
MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`
ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`
Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}
ClaudeModel describes a mapping between an alias and the actual upstream model name.
func (ClaudeModel) GetDisplayName ¶ added in v1.0.75
func (m ClaudeModel) GetDisplayName() string
GetDisplayName returns a display name.
func (ClaudeModel) GetForceMapping ¶ added in v1.0.75
func (m ClaudeModel) GetForceMapping() bool
GetForceMapping returns whether response model fields should be rewritten.
func (ClaudeModel) GetMaxContextLength ¶ added in v1.0.75
func (m ClaudeModel) GetMaxContextLength() int
GetMaxContextLength returns the configured context limit.
func (ClaudeModel) GetThinking ¶ added in v1.0.75
func (m ClaudeModel) GetThinking() *registry.ThinkingSupport
GetThinking returns configured reasoning capabilities.
type CloakConfig ¶
type CloakConfig struct {
// Mode controls cloaking behavior: "auto" (default), "always", or "never".
// - "auto": cloak only when client is not Claude Code (based on User-Agent)
// - "always": always apply cloaking regardless of client
// - "never": never apply cloaking
Mode string `yaml:"mode,omitempty" json:"mode,omitempty"`
// StrictMode controls how system prompts are handled when cloaking.
// - false (default): prepend Claude Code prompt to user system messages
// - true: strip all user system messages, keep only Claude Code prompt
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"`
// SensitiveWordsReplace maps target substrings to literal replacement text when cloaking.
SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"`
// SensitivePatternsReplace defines ordered Go RE2 regex replacement rules when cloaking.
SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,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 v1.1.10
func NormalizeCloakConfig(cloak *CloakConfig) *CloakConfig
NormalizeCloakConfig trims strings and removes blank sensitive words.
type CodexConfig ¶ added in v1.0.75
type CodexConfig struct {
// 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"`
}
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 {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable credential identity.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// 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"`
// 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 request-error and quota cooldowns; false explicitly enables them.
DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`
// RequestRetry optionally overrides the global number of additional retry rounds.
// Nil or a negative value inherits the global setting; zero disables additional rounds.
RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
// Settings shared with CPA V8.
Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`
DisableCodexCloaking *bool `yaml:"disable-codex-cloaking,omitempty" json:"disable-codex-cloaking,omitempty"`
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) GetProxyURL ¶ added in v1.0.70
GetProxyURL returns a proxy url.
func (CodexKey) MarshalYAML ¶ added in v1.1.10
type CodexLiveICEServer ¶ added in v1.0.75
type CodexLiveMediaRelayConfig ¶ added in v1.0.75
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"`
}
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"`
// SupportConfigurationUpdate enables Responses configuration updates for this model.
SupportConfigurationUpdate bool `yaml:"support-configuration-update,omitempty" json:"support-configuration-update,omitempty"`
// 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"`
// Settings shared with CPA V8.
MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`
IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`
Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}
CodexModel describes a mapping between an alias and the actual upstream model name.
func (CodexModel) GetDisplayName ¶ added in v1.0.55
func (m CodexModel) GetDisplayName() string
GetDisplayName returns a display name.
func (CodexModel) GetForceMapping ¶ added in v1.0.55
func (m CodexModel) GetForceMapping() bool
GetForceMapping returns whether response model fields should be rewritten.
func (CodexModel) GetMaxContextLength ¶ added in v1.0.75
func (m CodexModel) GetMaxContextLength() int
GetMaxContextLength returns the configured context limit.
func (CodexModel) GetThinking ¶ added in v1.0.75
func (m CodexModel) GetThinking() *registry.ThinkingSupport
GetThinking returns configured reasoning capabilities.
type Config ¶
type Config struct {
// RawConfig is the complete submitted configuration, not an execution-field remainder.
// Runtime fields below are a read projection; configuration writes update the tree.
RawConfig map[string]any `yaml:"-" json:"-"`
// Models selects optional catalog sources independently for each catalog.
Models ModelCatalogs `yaml:"models" json:"models"`
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 CPA server port distributed by Home.
Port int `yaml:"port" json:"-"`
// OAuth model capabilities are owned and published by Home.
OAuthSettings map[string][]OAuthModelSetting `yaml:"oauth-settings,omitempty" json:"oauth-settings,omitempty"`
// AllowHost limits RESP client connections to the listed IP addresses.
// Empty means all client hosts are allowed.
AllowHost []string `yaml:"allow-host" json:"-"`
// TLS config controls HTTPS server settings.
TLS TLSConfig `yaml:"tls" json:"tls"`
// TrustedProxies lists reverse-proxy IPs or CIDRs whose forwarded client
// address headers the HTTP server may trust. Empty disables forwarded headers.
TrustedProxies []string `yaml:"trusted-proxies" json:"trusted-proxies"`
// RemoteManagement nests management-related options under 'remote-management'.
RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`
// Plugins configures dynamic plugin distribution for downstream CPA nodes.
Plugins PluginsConfig `yaml:"plugins" json:"plugins"`
// UserEmail configures verified user emails and password-recovery delivery.
UserEmail UserEmailConfig `yaml:"user-email" json:"-"`
// CredentialConcurrency controls Home credential concurrency lifecycle behavior.
CredentialConcurrency CredentialConcurrencyConfig `yaml:"credential-concurrency" json:"credential-concurrency"`
// CredentialInFlight configures credential observation snapshots.
CredentialInFlight CredentialInFlightConfig `yaml:"credential-in-flight" json:"credential-in-flight"`
// 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"`
// CommercialMode disables high-overhead 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 local log files independently on each Home and downstream CPA node.
// When exceeded, the oldest log files are deleted until within the limit (in MB). 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 before database-backed persistence consumes them.
// Default: 60. Max: 3600.
RedisUsageQueueRetentionSeconds int `yaml:"redis-usage-queue-retention-seconds" json:"redis-usage-queue-retention-seconds"`
// DisableCooling disables Home request-error and quota cooldown scheduling when true.
DisableCooling bool `yaml:"disable-cooling" json:"disable-cooling"`
// WebsocketAuth enables or disables authentication for the WebSocket API.
WebsocketAuth bool `yaml:"ws-auth" json:"ws-auth"`
// AuthAutoRefreshWorkers overrides the size of the core auth auto-refresh 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 for
// downstream CPA execution after the first round exhausts its 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"`
// 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"`
// 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"`
// 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"`
// 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"`
// 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, antigravity, claude, codex, kimi, xai, meta, devin.
//
// 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"`
// Payload defines default and override rules for provider payload parameters.
Payload PayloadConfig `yaml:"payload" json:"payload"`
// Settings shared with CPA V8.
Discovery DiscoveryConfig `yaml:"discovery" json:"discovery"`
SaveCooldownStatus bool `yaml:"save-cooldown-status" json:"save-cooldown-status"`
TransientErrorCooldownSeconds int `yaml:"transient-error-cooldown-seconds" json:"transient-error-cooldown-seconds"`
Devin DevinConfig `yaml:"devin" json:"devin"`
XAI XAIConfig `yaml:"xai" json:"xai"`
Codex CodexConfig `yaml:"codex" json:"codex"`
Claude ClaudeConfig `yaml:"claude" json:"claude"`
DisableClaudeCloakMode bool `yaml:"disable-claude-cloak-mode" json:"disable-claude-cloak-mode"`
OAuthRequestScopedErrors map[string][]RequestScopedErrorRule `yaml:"oauth-request-scoped-errors,omitempty" json:"oauth-request-scoped-errors,omitempty"`
}
Config represents the application's configuration, loaded from a YAML file.
func LoadConfigOptional ¶
LoadConfigOptional reads YAML from configFile. If optional is true and the file is missing, it returns a Config with credential defaults. If optional is true and the file is empty or invalid, it returns a Config with credential defaults.
func (Config) MarshalYAML ¶ added in v1.0.75
MarshalYAML returns the complete source tree without rebuilding it from runtime fields. Programmatically constructed configs retain the legacy fallback below. Legacy field updates explicitly use LegacyConfigRoot instead.
func (*Config) NormalizePluginsConfig ¶ added in v1.0.39
func (cfg *Config) NormalizePluginsConfig()
NormalizePluginsConfig applies default plugin configuration values.
func (*Config) NormalizeProviderCredentialIDs ¶ added in v1.0.61
NormalizeProviderCredentialIDs normalizes legacy UUID input to immutable IDs.
func (*Config) NormalizeTrustedProxies ¶ added in v1.0.60
func (cfg *Config) NormalizeTrustedProxies()
NormalizeTrustedProxies trims, removes empty values, and de-duplicates the explicit reverse-proxy allowlist while preserving its configured order.
func (*Config) NormalizeUserEmailConfig ¶ added in v1.0.60
func (cfg *Config) NormalizeUserEmailConfig()
NormalizeUserEmailConfig applies stable defaults without deciding whether the feature is usable.
func (*Config) SanitizeAntigravity ¶ added in v1.0.72
func (cfg *Config) SanitizeAntigravity()
SanitizeAntigravity trims surrounding whitespace and drops empty entries from Antigravity sensitive-word settings.
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 and cloak settings 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) SanitizeDevin ¶ added in v1.1.10
func (cfg *Config) SanitizeDevin()
SanitizeDevin trims surrounding whitespace and drops empty entries from Devin sensitive-word settings.
func (*Config) SanitizeGeminiKeys ¶
func (cfg *Config) SanitizeGeminiKeys()
SanitizeGeminiKeys deduplicates and normalizes Gemini credentials. Distinct scheduling, model, and CPA execution options remain separate credentials.
func (*Config) SanitizeInteractionsKeys ¶ added in v1.0.70
func (cfg *Config) SanitizeInteractionsKeys()
SanitizeInteractionsKeys deduplicates and normalizes native Interactions credentials.
func (*Config) SanitizeMetaKeys ¶ added in v1.0.73
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) 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 v1.0.55
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) UnmarshalYAML ¶ added in v1.0.75
UnmarshalYAML accepts both layouts, including partially migrated documents. Presence, rather than Go zero values, determines which setting wins.
func (*Config) ValidateCredentialWeights ¶ added in v1.0.75
ValidateCredentialWeights validates weights for every API-key family.
func (*Config) ValidateHomePolicies ¶ added in v1.1.10
ValidateHomePolicies validates only policies that Home actually executes.
type CredentialConcurrencyConfig ¶ added in v1.0.61
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 string `yaml:"release-flush-interval" json:"release-flush-interval"`
ReleaseMaxBackoff string `yaml:"release-max-backoff" json:"release-max-backoff"`
BusyRetryMin string `yaml:"busy-retry-min" json:"busy-retry-min"`
BusyRetryMax string `yaml:"busy-retry-max" json:"busy-retry-max"`
MaxLimit int64 `yaml:"max-limit" json:"max-limit"`
}
CredentialConcurrencyConfig controls Home credential concurrency lifecycle behavior.
func DefaultCredentialConcurrencyConfig ¶ added in v1.0.61
func DefaultCredentialConcurrencyConfig() CredentialConcurrencyConfig
DefaultCredentialConcurrencyConfig returns the lifecycle and limiter defaults.
type CredentialConfig ¶ added in v1.1.10
CredentialConfig retains the complete credential subtree, including models and cloak settings. Home's typed credential fields are scheduling projections only.
func (*CredentialConfig) SetConfigTree ¶ added in v1.1.10
func (c *CredentialConfig) SetConfigTree(tree map[string]any)
type CredentialInFlightConfig ¶ added in v1.0.61
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 v1.0.61
func DefaultCredentialInFlightConfig() CredentialInFlightConfig
DefaultCredentialInFlightConfig returns the in-flight observation defaults.
func (CredentialInFlightConfig) Durations ¶ added in v1.0.61
Durations parses and validates the in-flight observation durations.
func (CredentialInFlightConfig) Validate ¶ added in v1.0.61
func (c CredentialInFlightConfig) Validate() error
Validate verifies the in-flight observation bounds.
type DevinConfig ¶ added in v1.0.75
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"`
// SensitiveWordsReplace maps target substrings to literal replacement text in system prompts.
SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"`
// SensitivePatternsReplace defines ordered Go RE2 regex replacement rules for system prompts.
SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,omitempty"`
}
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 (m DisableImageGenerationMode) String() 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 v1.0.75
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"`
}
type DiscoveryInterfacesConfig ¶ added in v1.0.75
type GeminiKey ¶
type GeminiKey struct {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable credential identity.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// 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"`
// 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 request-error and quota cooldowns; false explicitly enables them.
DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`
// RequestRetry optionally overrides the global number of additional retry rounds.
// Nil or a negative value inherits the global setting; zero disables additional rounds.
RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
// Settings shared with CPA V8.
Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`
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) GetProxyURL ¶ added in v1.0.70
GetProxyURL returns a proxy url.
func (GeminiKey) MarshalYAML ¶ added in v1.1.10
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"`
// ForceMapping rewrites upstream response model fields back to Alias.
ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
// Settings shared with CPA V8.
MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`
IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`
Thinking *registry.ThinkingSupport `yaml:"thinking,omitempty" json:"thinking,omitempty"`
}
GeminiModel describes a mapping between an alias and the actual upstream model name.
func (GeminiModel) GetDisplayName ¶ added in v1.0.70
func (m GeminiModel) GetDisplayName() string
GetDisplayName returns a display name.
func (GeminiModel) GetForceMapping ¶ added in v1.0.70
func (m GeminiModel) GetForceMapping() bool
GetForceMapping returns whether response model fields should be rewritten.
func (GeminiModel) GetMaxContextLength ¶ added in v1.0.75
func (m GeminiModel) GetMaxContextLength() int
GetMaxContextLength returns the configured context limit.
func (GeminiModel) GetThinking ¶ added in v1.0.75
func (m GeminiModel) GetThinking() *registry.ThinkingSupport
GetThinking returns configured reasoning capabilities.
type MetaKey ¶ added in v1.0.73
type MetaKey = CodexKey
MetaKey uses the Codex API key structure for native Meta Muse execution.
type MetaModel ¶ added in v1.0.73
type MetaModel = CodexModel
MetaModel uses the Codex model mapping structure for Meta Muse models.
type ModelCatalogs ¶ added in v1.1.3
type ModelCatalogs = registry.CatalogSources
ModelCatalogs selects optional sources for the process-wide model catalogs.
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"`
ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
// Settings shared with CPA V8.
DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`
// OpenAPI selects the Vertex execution endpoint without changing Home alias resolution.
OpenAPI *bool `yaml:"openapi,omitempty" json:"openapi,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 OAuthModelSetting ¶ added in v1.1.10
type OAuthModelSetting = cpaconfig.OAuthModelSetting
OAuthModelSetting remains typed because Home publishes the authoritative model catalog.
type OpenAICompatibility ¶
type OpenAICompatibility struct {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable identity of the fallback credential when no API key entries exist.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// 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"`
// DisableCooling overrides the global cooling policy for this provider when set.
// True disables request-error and quota cooldowns; false explicitly enables them.
DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`
// RequestRetry optionally overrides the global number of additional retry rounds.
// Nil or a negative value inherits the global setting; zero disables additional rounds.
RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
// Settings shared with CPA V8.
SupportPromptCacheKey bool `yaml:"support-prompt-cache-key,omitempty" json:"support-prompt-cache-key,omitempty"`
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.
func (OpenAICompatibility) MarshalYAML ¶ added in v1.1.10
func (c OpenAICompatibility) MarshalYAML() (any, error)
type OpenAICompatibilityAPIKey ¶
type OpenAICompatibilityAPIKey struct {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable credential identity.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// APIKey is the authentication key for accessing the external API services.
APIKey string `yaml:"api-key" json:"api-key"`
// ProxyURL overrides the global proxy setting for this API key if provided.
ProxyURL string `yaml:"proxy-url,omitempty" json:"proxy-url,omitempty"`
// Settings shared with CPA V8.
Weight *int `yaml:"weight,omitempty" json:"weight,omitempty"`
}
OpenAICompatibilityAPIKey represents an API key configuration with optional proxy setting.
func (OpenAICompatibilityAPIKey) MarshalYAML ¶ added in v1.1.10
func (c OpenAICompatibilityAPIKey) MarshalYAML() (any, error)
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"`
// 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"`
// Settings shared with CPA V8.
DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`
MaxContextLength int `yaml:"max-context-length,omitempty" json:"max-context-length,omitempty"`
ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
Image bool `yaml:"image,omitempty" json:"image,omitempty"`
InputModalities []string `yaml:"input-modalities,omitempty" json:"input-modalities,omitempty"`
OutputModalities []string `yaml:"output-modalities,omitempty" json:"output-modalities,omitempty"`
IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`
UseMaxCompletionTokens bool `yaml:"use-max-completion-tokens,omitempty" json:"use-max-completion-tokens,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
GetAlias returns an alias.
func (OpenAICompatibilityModel) GetMaxContextLength ¶ added in v1.0.75
func (m OpenAICompatibilityModel) GetMaxContextLength() int
GetMaxContextLength returns the configured context limit.
func (OpenAICompatibilityModel) GetName ¶
func (m OpenAICompatibilityModel) GetName() string
GetName returns a name.
func (OpenAICompatibilityModel) GetThinking ¶ added in v1.0.75
func (m OpenAICompatibilityModel) GetThinking() *registry.ThinkingSupport
GetThinking returns configured reasoning capabilities.
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 v1.0.39
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) MarshalJSON ¶ added in v1.0.39
func (c PluginInstanceConfig) MarshalJSON() ([]byte, error)
MarshalJSON returns the preserved raw plugin subtree for lossless Management API output.
func (PluginInstanceConfig) MarshalYAML ¶ added in v1.0.39
func (c PluginInstanceConfig) MarshalYAML() (any, error)
MarshalYAML returns the preserved raw plugin YAML subtree for lossless config output.
func (*PluginInstanceConfig) UnmarshalYAML ¶ added in v1.0.39
func (c *PluginInstanceConfig) UnmarshalYAML(value *yaml.Node) error
UnmarshalYAML extracts host-owned fields while preserving the full original YAML node.
type PluginsConfig ¶ added in v1.0.39
type PluginsConfig struct {
// Enabled toggles dynamic plugin loading on downstream CPA nodes.
Enabled bool `yaml:"enabled" json:"enabled"`
// Dir is the downstream 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"`
// Configs stores per-plugin instance configuration by plugin ID.
Configs map[string]PluginInstanceConfig `yaml:"configs" json:"configs"`
}
PluginsConfig holds dynamic plugin distribution settings for downstream CPA nodes.
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 is retained for configuration compatibility with older deployments.
// Embedded bundle mode serves local assets at build time and does not perform runtime remote updates.
DisableAutoUpdatePanel bool `yaml:"disable-auto-update-panel"`
// PanelGitHubRepository is retained for legacy compatibility and version tracking.
// Embedded bundle mode does not fetch control panel assets from GitHub at runtime.
PanelGitHubRepository string `yaml:"panel-github-repository"`
// Settings shared with CPA V8.
BaseURL string `yaml:"base-url,omitempty" json:"base-url,omitempty"`
}
RemoteManagement holds management API configuration under 'remote-management'.
type RequestScopedErrorRule ¶ added in v1.0.75
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"`
}
type RoutingConfig ¶
type RoutingConfig struct {
// SessionAffinityRebindOn controls failover binding changes: any, quota, or never.
SessionAffinityRebindOn string `yaml:"session-affinity-rebind-on,omitempty" json:"session-affinity-rebind-on,omitempty"`
// Strategy selects the credential selection strategy.
// Supported values: "round-robin" (default), "fill-first".
Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`
// SessionAffinity enables universal session-sticky routing for all clients.
// Session IDs are extracted from multiple sources:
// metadata.user_id (Claude Code session format), X-Session-ID, Session_id (Codex),
// X-Client-Request-Id (PI), metadata.user_id, conversation_id, or message hash.
// 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 initial parent-credential inheritance for child sessions.
// Guardian children may inherit the parent's latest eligible selection across models.
// Defaults to true; ignored when SessionAffinity is false. Existing child bindings,
// conversational forks, compaction, and content-hash fallbacks are unaffected.
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 {
// OAuthOnlyFields preserves the scope of v8 provider settings.
OAuthOnlyFields map[string]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"`
// TLSHandshakeTimeoutSeconds is a CPA option that bounds upstream TLS
// handshakes made by CPA's shared uTLS client, in seconds. CPA applies
// it to both its Claude Code Anthropic transport and its Chrome
// ChatGPT/Codex transport. Home only stores and forwards the value;
// the default 0 disables it in CPA.
TLSHandshakeTimeoutSeconds int `yaml:"tls-handshake-timeout-seconds" json:"tls-handshake-timeout-seconds"`
// 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.
DisableImageGeneration DisableImageGenerationMode `yaml:"disable-image-generation" json:"disable-image-generation"`
// 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"`
// 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"`
// Settings shared with CPA V8.
GPTImage2BaseModel string `yaml:"gpt-image-2-base-model,omitempty" json:"gpt-image-2-base-model,omitempty"`
VideoResultAuthCacheTTL string `yaml:"video-result-auth-cache-ttl,omitempty" json:"video-result-auth-cache-ttl,omitempty"`
ClaudeCode ClaudeCodeConfig `yaml:"claude-code" json:"claude-code"`
}
SDKConfig represents the application's configuration, loaded from a YAML file.
type SensitivePatternRule ¶ added in v1.1.10
type SensitivePatternRule struct {
// Pattern is the Go RE2 regular expression to match.
Pattern string `yaml:"pattern" json:"pattern"`
// Replacement is the substitution string (empty string deletes matches).
Replacement string `yaml:"replacement" json:"replacement"`
}
SensitivePatternRule defines a Go RE2 regular expression replacement rule.
func NormalizeSensitivePatternsReplace ¶ added in v1.1.10
func NormalizeSensitivePatternsReplace(in []SensitivePatternRule) []SensitivePatternRule
NormalizeSensitivePatternsReplace validates Go RE2 regex rules, logs and drops invalid or blank patterns, and preserves replacement values (including empty strings).
type StreamingConfig ¶
type StreamingConfig struct {
// KeepAliveSeconds controls how often the server emits SSE heartbeats (": keep-alive\n\n").
// <= 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"`
// SendKeepAliveBeforeFT controls whether SSE heartbeats are sent before the first token arrives
// when KeepAliveSeconds > 0. Default is false.
SendKeepAliveBeforeFT bool `yaml:"send-keepalive-before-ft,omitempty" json:"send-keepalive-before-ft,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 UserEmailConfig ¶ added in v1.0.60
type UserEmailConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
PublicUserURL string `yaml:"public-user-url" json:"public-user-url"`
FromAddress string `yaml:"from-address" json:"from-address"`
FromName string `yaml:"from-name" json:"from-name"`
Sender UserEmailSenderConfig `yaml:"sender" json:"sender"`
VerificationTokenTTL string `yaml:"verification-token-ttl" json:"verification-token-ttl"`
ResetTokenTTL string `yaml:"reset-token-ttl" json:"reset-token-ttl"`
}
UserEmailConfig controls optional verified-email and password-recovery behavior.
type UserEmailSMTPConfig ¶ added in v1.0.60
type UserEmailSMTPConfig struct {
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Username string `yaml:"username" json:"username"`
PasswordEnv string `yaml:"password-env" json:"password-env"`
StartTLS bool `yaml:"starttls" json:"starttls"`
}
UserEmailSMTPConfig configures SMTP delivery without persisting the password itself.
type UserEmailSenderConfig ¶ added in v1.0.60
type UserEmailSenderConfig struct {
Type string `yaml:"type" json:"type"`
SMTP UserEmailSMTPConfig `yaml:"smtp" json:"smtp"`
}
UserEmailSenderConfig selects the configured mail transport.
type VertexCompatKey ¶
type VertexCompatKey struct {
CredentialConfig `yaml:",inline" json:"-"`
// ID is the immutable credential identity.
ID string `yaml:"id,omitempty" json:"id,omitempty"`
// UUID is accepted for backward-compatible input and normalized to ID.
UUID string `yaml:"uuid,omitempty" json:"uuid,omitempty"`
// 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"`
// 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 request-error and quota cooldowns; false explicitly enables them.
DisableCooling *bool `yaml:"disable-cooling,omitempty" json:"disable-cooling,omitempty"`
// RequestRetry optionally overrides the global number of additional retry rounds.
// Nil or a negative value inherits the global setting; zero disables additional rounds.
RequestRetry *int `yaml:"request-retry,omitempty" json:"request-retry,omitempty"`
// Settings shared with CPA V8.
Weight *int `yaml:"weight,omitempty" json:"weight,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
GetAPIKey returns an api key.
func (VertexCompatKey) GetBaseURL ¶
func (k VertexCompatKey) GetBaseURL() string
GetBaseURL returns a base url.
func (VertexCompatKey) GetPrefix ¶ added in v1.0.70
func (k VertexCompatKey) GetPrefix() string
GetPrefix returns a model prefix.
func (VertexCompatKey) GetProxyURL ¶ added in v1.0.70
func (k VertexCompatKey) GetProxyURL() string
GetProxyURL returns a proxy url.
func (VertexCompatKey) MarshalYAML ¶ added in v1.1.10
func (c VertexCompatKey) MarshalYAML() (any, error)
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"`
// Settings shared with CPA V8.
DisplayName string `yaml:"display-name,omitempty" json:"display-name,omitempty"`
ForceMapping bool `yaml:"force-mapping,omitempty" json:"force-mapping,omitempty"`
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
GetAlias returns an alias.
func (VertexCompatModel) GetDisplayName ¶ added in v1.0.75
func (m VertexCompatModel) GetDisplayName() string
GetDisplayName returns a display name.
func (VertexCompatModel) GetForceMapping ¶ added in v1.0.75
func (m VertexCompatModel) GetForceMapping() bool
GetForceMapping returns whether response model fields should be rewritten.
func (VertexCompatModel) GetName ¶
func (m VertexCompatModel) GetName() string
GetName returns a name.
func (VertexCompatModel) GetThinking ¶ added in v1.0.75
func (m VertexCompatModel) GetThinking() *registry.ThinkingSupport
GetThinking returns configured reasoning capabilities.
type XAIConfig ¶ added in v1.0.75
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"`
}
type XAIKey ¶ added in v1.0.55
type XAIKey = CodexKey
XAIKey uses the Codex API key structure for native xAI execution.
type XAIModel ¶ added in v1.0.55
type XAIModel = CodexModel
XAIModel uses the Codex model mapping structure for xAI models.
Source Files
¶
- config.go
- config_layout.go
- config_schema.go
- config_tree.go
- config_types.go
- config_v8.go
- config_v8_api.go
- cpa_execution.go
- credential_concurrency.go
- credential_in_flight.go
- credential_tree.go
- disable_image_generation_mode.go
- home_mode.go
- model_catalogs.go
- oauth_scope.go
- plugin_config.go
- sdk_config.go
- trusted_proxies.go
- user_email.go
- vertex_compat.go
- weight.go