config

package
v8.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Config file lifecycle

server.server-id identifies a deployment and is not emitted by Config JSON. An explicit value must be a nonzero hyphenated UUID; startup trims whitespace and persists lowercase. Missing, null, and blank values produce a random UUIDv4 on the first valid load. Adding the ID alone does not migrate a legacy file. If startup can read but not write the file, it uses a process-local ID for that file and reuses it on subsequent loads. If the same file becomes writable, the next load persists that ID. Set an explicit value when a read-only deployment needs a stable ID across process restarts.

The first YAML document supplies runtime configuration. The whole YAML stream must decode, and rewrites keep subsequent documents byte-for-byte. Optional startup treats missing files, directories, and YAML decoding failures (including empty/null documents and malformed credential weights) as standby, without an ID or source hash. Runtime validation errors such as a management secret longer than bcrypt's 72-byte limit still fail startup.

File operations

  • ReadConfigFile(path string) ([]byte, error) reads raw bytes under a shared lock.

  • ReadConfigFileSnapshot(path string) (*ConfigFileSnapshot, error) also captures the original file identity. Use snapshot.Bytes() to get an editable copy and snapshot.SourceHash() for an ETag or watcher comparison.

  • WriteConfigFileCAS(path string, expected *ConfigFileSnapshot, replacement []byte) (*ConfigFileSnapshot, error) compares file identity and the complete original bytes under an exclusive lock. The destination must already exist. On ErrConfigFileChanged, discard the prepared change or re-evaluate it against a fresh read; do not blindly retry the same replacement. The result describes the committed bytes, so there is no need to reopen the file to compute an ETag. CAS rejects a replacement that removes an identifying plaintext management setting but leaves a copy of its value. Callers still own general validation of the replacement.

  • CreateConfigFile(path string, data []byte) error publishes complete bytes at a missing path. It returns ErrConfigFileChanged if another writer created it.

  • RemoveConfigFileCAS(path string, expected *ConfigFileSnapshot) error removes a file only while it still matches the snapshot's identity and bytes.

  • EnsureServerIDInConfigBytesWithOptional(data []byte, optional bool) ([]byte, string, error) applies startup validation and sets only the first document's ID. The strict EnsureServerIDInConfigBytes variant omits the optional argument. This is a pure byte transformation, not a persistence or upload operation. Preserve an existing configured ID in a replacement document if the workflow requires the deployment to retain that identity. Optional standby returns (nil, "", nil).

  • PrepareConfigFileForUploadWithOptional(path string, optional bool) ([]byte, error) performs startup rewrites and validates the snapshot for upload. Candidates come from both management secret paths in every document, including shadowed merge definitions. The check looks for substrings in the complete YAML source and decoded scalars, including aliases, escaped and binary values, and environment expansions. Only recognized management setting names, bcrypt values at those paths, and YAML nulls are exempt where their source spelling can be identified. The check fails closed: even a coincidental match for a short key in other text can block upload or a save that would remove the only identifying setting. Use a longer unique key and remove conflicting copies before retrying. Startup retains that identifying setting if it cannot safely hash it on disk, so later uploads still reject the plaintext. Validation cannot identify unrelated secrets without an original plaintext candidate. Upload exactly the returned bytes; do not re-read the file after verification. (nil, nil) is optional standby and must not be uploaded. A required rewrite on a read-only file is an error.

  • PrepareConfigBytesForUploadWithOptional(data []byte, optional bool) ([]byte, error) performs the same preparation on remote or template bytes without writing a speculative change to the mirror. VerifyConfigBytesForUpload(data []byte) error validates an immutable artifact, such as a Git commit blob, without changing it.

  • ParsePreparedConfigBytes(data []byte) (*Config, error) loads the prepared snapshot without reopening its backing file and records its source hash. It returns the standby configuration if the prepared snapshot is nil.

ComputeSourceHash(data []byte) string is lowercase hex SHA-256 of the exact bytes, including any separator, trailing document, BOM, or newline. A successful LoadConfigOptional records the committed snapshot's hash (the original hash if read-only), not the hash from before a successful startup rewrite.

Management v8 validates the full YAML stream before editing the first document with DecodeFirstConfigDocument and ReplaceFirstConfigDocument. The read view uses ProjectConfigServerID to include an available ephemeral identity without writing the file. A persisted identity, or a valid explicit identity accepted on load, retires the ephemeral entry. Unlike startup, a v8 write uses EnsureManagementServerID to replace an invalid identity before validation and commit; other configuration errors still reject the write.

Existing files are updated in place through an O_RDWR descriptor without replacing the inode. Writers check path identity before and after the write, sync, and attempt to restore the original snapshot on failure. Process-local and OS locks are cooperative; callers must use these helpers rather than truncating, renaming, or independently reading the file mid-transaction. This matters on AIX and Solaris in particular, where closing another descriptor for that same inode in the process can release its fcntl lock. No lock protects against an editor or another program that ignores the locking protocol.

Remote mirrors

PostgreSQL and S3 seed missing configs conditionally. Each instance uses the exact body (PostgreSQL) or the strong response ETag (S3) from its last successful sync or publish to guard the next save. The S3 endpoint must return a strong ETag on GET and successful PUT responses. If another instance has changed the remote config, a stale save reports a conflict instead of overwriting it. Keep a copy of the local edits, resynchronize, and reapply the edits before saving again.

Startup reloads the winner after a rejected conditional write. If another instance already wrote the exact winning bytes to a shared mirror, startup accepts it without rewriting. If a concurrent local edit differs from the winner, even in a trailing YAML document, startup reports the conflict and leaves the file untouched.

PostgreSQL keeps the config column as TEXT. It accepts only UTF-8 YAML without NUL bytes and rejects incompatible bytes before publishing. Convert UTF-16 YAML to UTF-8 before using it with the PostgreSQL store. The store does not transcode files because the published config and its source hash identify exact bytes.

Git performs startup rewrites only after synchronizing and verifies the actual candidate commit blob before publishing. A rejected startup candidate never touches the working config. The runtime config's source hash identifies the exact winning bytes, not a re-read of a potentially edited file.

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"
	DefaultKVStorePath           = "kv.db"
)
View Source
const (
	ClaudeClientRequestIDOn          = "on"
	ClaudeClientRequestIDOff         = "off"
	ClaudeClientRequestIDPassthrough = "passthrough"
)

Supported ClaudeHeaderDefaults.ClientRequestID values. An empty value means ClaudeClientRequestIDOn.

View Source
const (
	DefaultInFlightMaxPartBytes       = 256 * 1024
	DefaultInFlightMaxPartCount       = 64
	DefaultInFlightMaxRevisionBytes   = 16 * 1024 * 1024
	DefaultInFlightMaxAggregateGroups = 100000
	DefaultInFlightMaxDetails         = 10000
	DefaultInFlightMaxStringBytes     = 256
)
View Source
const (
	// DefaultCodexWebSearchResultCacheTTL is the default lifetime of cached web search results.
	DefaultCodexWebSearchResultCacheTTL = 24 * time.Hour

	// DefaultCodexWebSearchResultCacheLimit is the default maximum number of cached web search result entries.
	DefaultCodexWebSearchResultCacheLimit = 1024
)
View Source
const DefaultClaudeSessionDatePinDays = 7

DefaultClaudeSessionDatePinDays is the session date pin retention applied when session-date-pin-days is not configured.

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 DefaultSignInWithChatGPTIdentifier = "CLIProxyAPI"

DefaultSignInWithChatGPTIdentifier is the default identifier (agent_name_hint and User-Agent prefix) used for Codex Sign in with ChatGPT (SIWC) OAuth authorization and API requests.

View Source
const MaxCredentialWeight = int(credentialweight.Max)

MaxCredentialWeight is the largest positive credential routing weight.

Variables

View Source
var ErrConfigFileChanged = errors.New("config file changed")

ErrConfigFileChanged indicates that a path no longer refers to the inode or complete contents observed by a config operation. Retrying a write with the same replacement would risk losing another writer's changes.

View Source
var ErrConfigFileDirectory = errors.New("config file is a directory")

ErrConfigFileDirectory indicates that the config path refers to a directory.

Functions

func ApplyRootedConfigFileCAS added in v8.1.0

func ApplyRootedConfigFileCAS(root *os.Root, path string, expected *ConfigFileSnapshot, data []byte) error

ApplyRootedConfigFileCAS checks the original snapshot and applies a rooted create, replacement, or deletion (nil data).

func ComputeSourceHash added in v8.0.30

func ComputeSourceHash(data []byte) string

ComputeSourceHash returns the lowercase hex SHA-256 of the exact file bytes.

func CreateConfigFile added in v8.1.0

func CreateConfigFile(path string, data []byte) error

CreateConfigFile publishes a complete snapshot only if the destination does not exist, without exposing a partially written configuration to readers.

func DecodeFirstConfigDocument added in v8.1.0

func DecodeFirstConfigDocument(data []byte) (*yaml.Node, error)

DecodeFirstConfigDocument validates the complete YAML stream before returning its first document. Runtime settings come only from the first document.

func EnsureManagementServerID added in v8.1.0

func EnsureManagementServerID(root *yaml.Node) (string, error)

EnsureManagementServerID canonicalizes the candidate identity or allocates a new UUID when it is missing or invalid. Startup intentionally remains strict.

func EnsureServerIDInConfigBytes added in v8.1.0

func EnsureServerIDInConfigBytes(data []byte) ([]byte, string, error)

EnsureServerIDInConfigBytes validates the complete stream and sets only the first document's identity. Other startup rewrites are deliberately not applied.

func EnsureServerIDInConfigBytesWithOptional added in v8.1.0

func EnsureServerIDInConfigBytesWithOptional(data []byte, optional bool) ([]byte, string, error)

EnsureServerIDInConfigBytesWithOptional returns updated bytes and their ID. On optional standby it returns (nil, "", nil); no identifier has been allocated.

func FormatConnectionPoolDedupID added in v8.0.52

func FormatConnectionPoolDedupID(pool *ProxyConnectionPoolConfig) string

FormatConnectionPoolDedupID serializes a per-credential connection-pool override deterministically for credential deduplication and auth-index mapping.

func FormatSortedHeaders

func FormatSortedHeaders(headers map[string]string) string

FormatSortedHeaders serializes headers deterministically with null byte separators.

func IsPreparedConfigFromSeed added in v8.1.0

func IsPreparedConfigFromSeed(seed, prepared []byte) bool

IsPreparedConfigFromSeed reports whether prepared differs from seed only by the automatic startup rewrites, including a generated ID and salted hash.

func IsV8ConfigLayout added in v8.0.11

func IsV8ConfigLayout(root *yaml.Node) bool

IsV8ConfigLayout identifies a validated document by its version or v8 paths. Roots shared with the legacy runtime schema do not alone indicate v8.

func NormalizeClaudeFingerprintProfile

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 NormalizeCollectionNodeStyles added in v8.0.21

func NormalizeCollectionNodeStyles(node *yaml.Node)

NormalizeCollectionNodeStyles forces YAML collections to use block notation, keeping lists and maps readable. Empty sequences retain flow style ([]) so empty list markers remain compact. It also clears double quotes from string mapping keys so JSON-derived keys render as standard unquoted YAML keys.

func NormalizeCommentIndentation

func NormalizeCommentIndentation(data []byte) []byte

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

func NormalizeConfigLayout

func NormalizeConfigLayout(data []byte, migrate bool) ([]byte, bool, error)

NormalizeConfigLayout removes conflicting legacy fields. migrate also moves legacy-only fields; callers use it only for an explicit v8 configuration write.

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

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 NormalizeSensitiveWordsReplace added in v8.0.65

func NormalizeSensitiveWordsReplace(in map[string]string) map[string]string

NormalizeSensitiveWordsReplace trims replacement target keys, drops blank keys, and preserves replacement values (including empty strings for phrase deletion).

func NormalizeV8ConfigAliases added in v8.0.11

func NormalizeV8ConfigAliases(root *yaml.Node) error

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 PrepareConfigBytesForUploadWithOptional added in v8.1.0

func PrepareConfigBytesForUploadWithOptional(data []byte, optional bool) ([]byte, error)

PrepareConfigBytesForUploadWithOptional validates and rewrites remote or template bytes without changing any file. A nil result and no error means optional standby.

func PrepareConfigFileForUpload added in v8.0.30

func PrepareConfigFileForUpload(configFile string) error

PrepareConfigFileForUpload applies startup rewrites and verifies that no plaintext management secret would be uploaded. Prefer the variant returning the verified bytes to avoid racing another write.

func PrepareConfigFileForUploadWithOptional added in v8.1.0

func PrepareConfigFileForUploadWithOptional(configFile string, optional bool) ([]byte, error)

PrepareConfigFileForUploadWithOptional returns the verified bytes from the same locked transaction that performed startup rewrites. Upload these bytes directly, not a later read. A nil slice with no error means optional standby and must not be uploaded. A required rewrite on a read-only file is an error.

func ProjectConfigServerID added in v8.1.0

func ProjectConfigServerID(root *yaml.Node, fallback string) (string, error)

ProjectConfigServerID canonicalizes an explicit identity in a read-only YAML view. If no identity was persisted, it can project the runtime's ephemeral ID.

func ProjectV8ConfigAliases added in v8.0.11

func ProjectV8ConfigAliases(root *yaml.Node, path string)

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 ReadConfigFile added in v8.1.0

func ReadConfigFile(path string) ([]byte, error)

ReadConfigFile is a shared-locked read of the complete file, without validation.

func RemoveConfigFileCAS added in v8.1.0

func RemoveConfigFileCAS(path string, expected *ConfigFileSnapshot) error

RemoveConfigFileCAS removes the path only if it still describes expected.

func ReplaceFirstConfigDocument added in v8.1.0

func ReplaceFirstConfigDocument(original []byte, doc *yaml.Node) ([]byte, error)

ReplaceFirstConfigDocument encodes the edited document and copies the rest of the original YAML stream byte-for-byte.

func ResolvePluginsDir

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, migrateV8 ...bool) 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. Existing v8 documents are saved in the latest layout. Successful migration also synchronizes cfg's OAuth scope for runtime snapshots.

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 SetV8MigrationWarnFunc added in v8.0.3

func SetV8MigrationWarnFunc(fn func(section, msg string))

SetV8MigrationWarnFunc sets a custom warning handler (e.g. from logging package).

func ValidateClaudeFingerprintProfile

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 ValidateConfigSave added in v8.1.0

func ValidateConfigSave(original, replacement []byte) error

ValidateConfigSave prevents a rewrite from orphaning known plaintext in a copy or comment. An unchanged plaintext setting remains identifiable and will still be checked (and, if safe, rewritten) by upload preparation.

func ValidateCredentialConcurrency

func ValidateCredentialConcurrency(cfg CredentialConcurrencyConfig) error

ValidateCredentialConcurrency validates values intrinsic to a credential concurrency configuration.

func ValidateCredentialConcurrencyLifecycle

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

ValidateCredentialConcurrencyLifecycle verifies the Home lifecycle timing safety invariant.

func ValidateCredentialWeight

func ValidateCredentialWeight(weight *int) error

ValidateCredentialWeight validates one optional config credential weight.

func ValidateV8Config

func ValidateV8Config(data []byte) error

ValidateV8Config accepts only the v8 layout in management writes. Plugin-owned configuration remains extensible through its existing decoder.

func ValidateV8ConfigArchives added in v8.1.0

func ValidateV8ConfigArchives(data []byte, sections []ArchivedV8Section) error

ValidateV8ConfigArchives rejects secret-bearing archives from a temporary projection if the edited file would keep them.

func VerifyConfigBytesForUpload added in v8.1.0

func VerifyConfigBytesForUpload(data []byte) error

VerifyConfigBytesForUpload verifies immutable bytes without rewriting them.

func WarnUnrecognizedV8Sections added in v8.0.78

func WarnUnrecognizedV8Sections(sections []ArchivedV8Section)

WarnUnrecognizedV8Sections logs migration warnings for configuration sections that were commented out during v8 migration.

func WithConfigFileOpenGate added in v8.1.0

func WithConfigFileOpenGate(scan func() error) error

WithConfigFileOpenGate serializes raw filesystem scans with in-process config transactions. The callback must not call a config file API itself.

Types

type AntigravityConfig

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

	// SensitiveWordsReplace maps sensitive words or phrases to literal replacements 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"`

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

	// TOSPauseWindow controls the pool-wide protective pause armed after the first
	// 403 TOS_VIOLATION. Defaults to "0" (disabled), so only the violating
	// credential is deactivated unless a positive Go duration string (e.g. "6h")
	// is explicitly configured. Set to "0", "off", "false", "none", or
	// "disabled" to explicitly disable the pause.
	TOSPauseWindow string `yaml:"tos-pause-window,omitempty" json:"tos-pause-window,omitempty"`
}

AntigravityConfig configures provider-wide Antigravity request behavior.

type AntigravityConnectionPoolConfig

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. Zero or negative values disable idle pooling (short-lived connection mode).
	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 ArchivedV8Section added in v8.0.78

type ArchivedV8Section struct {
	Section string
	Comment string
	// contains filtered or unexported fields
}

ArchivedV8Section records an unrecognized configuration section name together with the exact commented YAML block produced for it.

func FilterArchivedV8Sections added in v8.0.78

func FilterArchivedV8Sections(data []byte, sections []ArchivedV8Section) []ArchivedV8Section

FilterArchivedV8Sections returns the subset of sections whose exact root-level archived comment block is preserved in data.

func NormalizeConfigLayoutSilent added in v8.0.78

func NormalizeConfigLayoutSilent(data []byte, migrate bool) ([]byte, bool, []ArchivedV8Section, error)

NormalizeConfigLayoutSilent normalizes a config for saving without emitting migration warnings. Callers may report the archived sections once saved.

func ProjectV8ConfigLayout added in v8.1.0

func ProjectV8ConfigLayout(data []byte) ([]byte, []ArchivedV8Section, error)

ProjectV8ConfigLayout allows archives in a temporary view so that an explicit edit can discard an unsafe archive. Check retained archives before saving.

type ClaudeClientConfig added in v8.0.49

type ClaudeClientConfig struct {
	// ShowCodexCommentary mirrors public Codex progress into visible Claude text.
	// Default false preserves the existing hidden-commentary behavior.
	ShowCodexCommentary bool `yaml:"show-codex-commentary" json:"show-codex-commentary"`
}

ClaudeClientConfig controls client-facing Claude protocol compatibility.

type ClaudeCodeConfig

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

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 enables Codex client tool_search on Claude Responses routes:
	// Anthropic native tool search where the credential supports it, a pre-tool_search
	// translation elsewhere, and per-credential search advertising in the Codex
	// catalog. Default false keeps the translation that predates tool_search support.
	ToolSearch bool `yaml:"tool-search" json:"tool-search"`
	// ServerSideFallback opts cloaked Claude requests into Anthropic server-side
	// refusal fallback injection (claude-opus-5-5 -> claude-opus-4-8 and
	// claude-fable-5-1 -> claude-opus-5) when the request body does not already
	// specify fallbacks. Default false leaves cross-model fallbacks omitted unless
	// explicitly configured by the caller or payload rules.
	ServerSideFallback bool `yaml:"server-side-fallback" json:"server-side-fallback"`
	// SessionDatePinDays retains the cloaked currentDate pin per session for
	// this many days in in-memory mode (server.kv-store.disabled: true without
	// Home), independently of continuity expiry and credential switches. A nil
	// value (unset) defaults to 7 days; an explicit 0 keeps the
	// continuity-scoped pin (1h lifetime). When a KV store (local bbolt or Home
	// KV) is active, session date pins are persisted permanently and
	// session-date-pin-days is ignored.
	SessionDatePinDays *int `yaml:"session-date-pin-days" json:"session-date-pin-days"`
	// OAuthIncludeCreateAPIKey controls whether new Claude OAuth authorization
	// URLs request the org:create_api_key scope in addition to ClaudeOAuthScope.
	// Nil defaults to true to match native Claude Code.
	OAuthIncludeCreateAPIKey *bool `yaml:"oauth-include-create-api-key,omitempty" json:"oauth-include-create-api-key,omitempty"`
}

ClaudeConfig configures provider-wide Claude request behavior.

func (*ClaudeConfig) OAuthIncludeCreateAPIKeyEnabled added in v8.0.78

func (c *ClaudeConfig) OAuthIncludeCreateAPIKeyEnabled() bool

OAuthIncludeCreateAPIKeyEnabled reports whether Claude OAuth authorization requests should include the org:create_api_key scope.

func (ClaudeConfig) SessionDatePinRetention added in v8.0.32

func (c ClaudeConfig) SessionDatePinRetention() time.Duration

SessionDatePinRetention returns the configured session date pin retention. An unset value defaults to 7 days; an explicit zero keeps the legacy continuity-scoped behavior. Days are clamped so the duration cannot overflow.

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"`
	NativeEntrypoints      []string `yaml:"native-entrypoints,omitempty" json:"native-entrypoints,omitempty"`
	AnthropicBetaStrip     []string `yaml:"anthropic-beta-strip,omitempty" json:"anthropic-beta-strip,omitempty"`
	AnthropicBetaAppend    []string `yaml:"anthropic-beta-append,omitempty" json:"anthropic-beta-append,omitempty"`
	InjectDiagnostics      *bool    `yaml:"inject-diagnostics,omitempty" json:"inject-diagnostics,omitempty"`
	ClientRequestID        string   `yaml:"client-request-id,omitempty" json:"client-request-id,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. NativeEntrypoints extends the built-in native Claude Code entrypoint allowlist. AnthropicBetaStrip and AnthropicBetaAppend are exact-name operator overrides applied to the final Anthropic-Beta set; InjectDiagnostics and ClientRequestID tune the first-party Claude Code CLI request shape.

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"`

	// ConnectionPool configures upstream connection reuse for this credential.
	// Omitted disables pooling (preserving the fresh-transport-per-request default);
	// pools stay per credential, so opting in never shares connections with another key.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,omitempty"`

	// 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"`

	// NativeToolSearch trusts a custom base URL with Anthropic native tool search
	// (defer_loading tools and tool_reference results) for Codex tool_search.
	// Official api.anthropic.com credentials use native tool search without it.
	NativeToolSearch bool `yaml:"native-tool-search,omitempty" json:"native-tool-search,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

func (k ClaudeKey) GetPrefix() string

func (ClaudeKey) GetProxyURL

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

func (m ClaudeModel) GetDisplayName() string

func (ClaudeModel) GetForceMapping

func (m ClaudeModel) GetForceMapping() bool

func (ClaudeModel) GetIsCompat

func (m ClaudeModel) GetIsCompat() bool

func (ClaudeModel) GetMaxContextLength

func (m ClaudeModel) GetMaxContextLength() int

func (ClaudeModel) GetName

func (m ClaudeModel) GetName() string

func (ClaudeModel) GetThinking

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

type ClientConfig added in v8.0.9

type ClientConfig struct {
	Codex  CodexClientConfig  `yaml:"codex" json:"codex"`
	Claude ClaudeClientConfig `yaml:"claude" json:"claude"`
}

ClientConfig configures client-facing compatibility behavior.

type CloakConfig

type CloakConfig struct {
	// Mode controls cloaking behavior: "auto" (default), "always", "never", or "uncloak".
	// 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" / "uncloak": never apply cloaking; on non-CLI API keys, also strip incoming Claude Code identity and billing attribution
	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"`

	// SensitiveWordsReplace maps sensitive words or phrases to literal replacements.
	SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"`

	// SensitivePatternsReplace defines ordered Go RE2 regex replacement rules.
	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

func NormalizeCloakConfig(cloak *CloakConfig) *CloakConfig

NormalizeCloakConfig trims strings and removes blank sensitive words.

type CodexClientConfig added in v8.0.9

type CodexClientConfig struct {
	// OptimizeMultiAgentV2 optimizes official Codex multi-agent requests across providers.
	// Default false leaves the client's multi-agent behavior unchanged.
	OptimizeMultiAgentV2 bool `yaml:"optimize-multi-agent-v2" json:"optimize-multi-agent-v2"`

	// EnableApplyPatch advertises freeform apply_patch only for supported models.
	// Default false clears the capability regardless of template metadata.
	EnableApplyPatch bool `yaml:"enable-apply-patch" json:"enable-apply-patch"`

	// WebSearchResultCache configures caching of upstream web search results for
	// Codex Responses clients that drop search results from replayed history.
	WebSearchResultCache CodexWebSearchResultCacheConfig `yaml:"web-search-result-cache" json:"web-search-result-cache"`
}

CodexClientConfig configures Codex client compatibility and the model catalog.

type CodexConfig

type CodexConfig struct {
	// WebsocketCompression controls upstream and downstream permessage-deflate; unset means enabled.
	WebsocketCompression *bool `yaml:"websocket-compression,omitempty" json:"websocket-compression,omitempty"`
	// UpstreamRequestCompression enables zstd request bodies for the ChatGPT Codex backend.
	UpstreamRequestCompression bool `yaml:"upstream-request-compression" json:"upstream-request-compression"`
	// UpstreamRequestCompressionMinBytes defaults to 1024 when zero or negative.
	UpstreamRequestCompressionMinBytes int `yaml:"upstream-request-compression-min-bytes,omitempty" json:"upstream-request-compression-min-bytes,omitempty"`
	// 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"`
	// 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"`
	// SignInWithChatGPTIdentifier configures the identifier (agent_name_hint and User-Agent prefix)
	// for Codex Sign in with ChatGPT (SIWC) OAuth authorization and API requests.
	// Defaults to "CLIProxyAPI".
	SignInWithChatGPTIdentifier string `yaml:"signin-with-chatgpt-identifier,omitempty" json:"signin-with-chatgpt-identifier,omitempty"`
}

CodexConfig configures provider-wide Codex request behavior.

func (CodexConfig) EffectiveSignInWithChatGPTIdentifier added in v8.0.25

func (c CodexConfig) EffectiveSignInWithChatGPTIdentifier() string

EffectiveSignInWithChatGPTIdentifier returns the configured Sign in with ChatGPT identifier, or DefaultSignInWithChatGPTIdentifier when unset or blank.

func (*CodexConfig) RequestCompressionMinBytes added in v8.0.44

func (c *CodexConfig) RequestCompressionMinBytes() int

RequestCompressionMinBytes returns the minimum request size eligible for compression.

func (*CodexConfig) StreamBootstrapTimeoutDuration

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.

func (*CodexConfig) WebsocketCompressionEnabled added in v8.0.44

func (c *CodexConfig) WebsocketCompressionEnabled() bool

WebsocketCompressionEnabled reports whether WebSocket compression is enabled.

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"`

	// ConnectionPool configures upstream connection reuse for this credential.
	// Omitted disables pooling (preserving the fresh-transport-per-request default);
	// pools stay per credential, so opting in never shares connections with another key.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,omitempty"`

	// 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

func (k CodexKey) GetPrefix() string

func (CodexKey) GetProxyURL

func (k CodexKey) GetProxyURL() string

type CodexLiveICEServer

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

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

func (c CodexLiveMediaRelayConfig) EffectiveMaxSessions() int

EffectiveMaxSessions returns the configured media session limit.

func (*CodexLiveMediaRelayConfig) UnmarshalYAML

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

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 client.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.
	// When enabled, compaction_trigger items also use local summary compaction.
	IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"`

	// SupportConfigurationUpdate enables configuration_update for this API-key model.
	// It defaults to false, independently of the built-in OAuth model catalog.
	SupportConfigurationUpdate bool `yaml:"support-configuration-update,omitempty" json:"support-configuration-update,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

func (m CodexModel) GetDisplayName() string

func (CodexModel) GetForceMapping

func (m CodexModel) GetForceMapping() bool

func (CodexModel) GetIsCompat

func (m CodexModel) GetIsCompat() bool

func (CodexModel) GetMaxContextLength

func (m CodexModel) GetMaxContextLength() int

func (CodexModel) GetName

func (m CodexModel) GetName() string

func (CodexModel) GetThinking

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

type CodexWebSearchResultCacheConfig added in v8.0.34

type CodexWebSearchResultCacheConfig struct {
	// Enabled controls whether web search results are cached and restored for Codex Responses requests.
	// Default is false (disabled).
	Enabled bool `yaml:"enabled" json:"enabled"`

	// TTL specifies how long cached web search results remain valid (e.g. 1800, "30m", "24h").
	// Pure numbers are interpreted as seconds. Defaults to "24h" when unset.
	TTL string `yaml:"ttl" json:"ttl"`

	// Limit specifies the maximum number of entries retained in the web search result cache.
	// Defaults to 1024 when unset or zero.
	Limit int `yaml:"limit" json:"limit"`
}

CodexWebSearchResultCacheConfig configures the session-scoped web search result cache.

func (CodexWebSearchResultCacheConfig) EffectiveLimit added in v8.0.34

func (c CodexWebSearchResultCacheConfig) EffectiveLimit() int

EffectiveLimit returns the configured entry limit, or DefaultCodexWebSearchResultCacheLimit when unset or non-positive.

func (CodexWebSearchResultCacheConfig) EffectiveTTL added in v8.0.34

EffectiveTTL returns the parsed cache TTL, or DefaultCodexWebSearchResultCacheTTL when unset or zero.

func (*CodexWebSearchResultCacheConfig) UnmarshalJSON added in v8.0.34

func (c *CodexWebSearchResultCacheConfig) UnmarshalJSON(data []byte) error

func (*CodexWebSearchResultCacheConfig) UnmarshalYAML added in v8.0.34

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

func (CodexWebSearchResultCacheConfig) Validate added in v8.0.34

Validate checks that the configured TTL and entry limit are valid.

type Config

type Config struct {
	// ServerResponseCompression is the JSON-visible mirror of the downstream
	// response compression settings (YAML: server.response-compression).
	ServerResponseCompression ResponseCompressionConfig `yaml:"-" json:"response-compression"`
	// 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 network port on which the API server will listen.
	Port int `yaml:"port" json:"-"`

	// ServerID is the stable deployment UUID from server.server-id, or a
	// process-local identity when the file cannot be written. It is not public JSON.
	ServerID string `yaml:"-" json:"-"`

	// GitHubToken is the global token for GitHub requests, taking precedence over GITHUB_TOKEN.
	GitHubToken string `yaml:"github-token" 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"`

	// ShutdownTimeoutSeconds controls how long the API server waits for in-flight
	// requests to finish during shutdown before forcibly closing connections.
	// 0 (the default) keeps the legacy behavior of closing immediately without draining.
	// Values are in seconds.
	ShutdownTimeoutSeconds int `yaml:"shutdown-timeout" json:"shutdown-timeout"`

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

	// SourceHash is runtime-only: the SHA-256 of the exact config file snapshot after startup
	// rewrites, or empty when the config was not loaded from a file.
	SourceHash string `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"`

	// KVStore configures the local bbolt key-value store.
	KVStore KVStoreConfig `yaml:"kv-store" json:"kv-store"`

	// 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"`

	// ProxyPoolPublisher identifies the runtime that published this snapshot, so a
	// reload in one runtime never retires another runtime's snapshots.
	ProxyPoolPublisher uint64 `yaml:"-" json:"-"`

	// ProxyPoolGeneration fences obsolete runtime snapshots from the shared transport cache.
	ProxyPoolGeneration uint64 `yaml:"-" json:"-"`

	// 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,
	// including vertex, aistudio, antigravity, claude, codex, kimi, xai, meta, and copilot.
	//
	// 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, copilot, 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"`

	// OAuthSettings defines per-channel model settings (such as max-context-length) applied to OAuth/file-backed auth entries.
	OAuthSettings map[string][]OAuthModelSetting `yaml:"oauth-settings,omitempty" json:"oauth-settings,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 loads the configuration and applies startup file rewrites.

func LoadConfigOptional

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

LoadConfigOptional loads the config or returns the optional standby defaults for missing files, directories, empty input and YAML decoding failures. A valid read-only config can use a process-local generated server identity.

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 ParsePreparedConfigBytes added in v8.1.0

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

ParsePreparedConfigBytes loads the exact snapshot returned by upload preparation and records its hash without reopening or rewriting the local mirror. A nil snapshot is the optional standby result returned by upload preparation.

func (*Config) CloneForRuntime

func (cfg *Config) CloneForRuntime() *Config

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

func (*Config) EffectiveKVStorePath added in v8.0.55

func (cfg *Config) EffectiveKVStorePath() string

EffectiveKVStorePath returns the configured KVStore.Path or "<auth-dir>/kv.db" when empty.

func (*Config) EffectiveResponseCompression added in v8.0.44

func (cfg *Config) EffectiveResponseCompression() ResponseCompressionConfig

EffectiveResponseCompression returns the downstream response compression settings from their canonical storage (SDKConfig.ResponseCompression, YAML server.response-compression), falling back to the JSON/programmatic mirror on the outer Config when the canonical value was never populated.

func (*Config) ForAPIKey

func (cfg *Config) ForAPIKey() *Config

ForAPIKey returns a request-local configuration view without v8 OAuth-only overrides. Legacy global settings and explicit API-key settings keep their existing semantics. The shared configuration is never modified.

func (Config) MarshalYAML

func (cfg Config) MarshalYAML() (any, error)

MarshalYAML preserves OAuth scope across watcher/server YAML snapshots. A legacy-only Config still produces its original layout. Persistence explicitly marshals legacyConfig before reconciling the on-disk layout.

func (*Config) NormalizeClaudeConfig added in v8.0.32

func (cfg *Config) NormalizeClaudeConfig()

NormalizeClaudeConfig applies default Claude provider configuration values.

func (*Config) NormalizePluginsConfig

func (cfg *Config) NormalizePluginsConfig()

NormalizePluginsConfig applies default plugin configuration values.

func (*Config) ResolvePluginsDir

func (cfg *Config) ResolvePluginsDir() error

ResolvePluginsDir resolves and stores the effective plugin directory.

func (*Config) SanitizeAntigravity added in v8.0.65

func (cfg *Config) SanitizeAntigravity()

SanitizeAntigravity normalizes Antigravity sensitive-word settings.

func (*Config) SanitizeClaudeHeaderDefaults

func (cfg *Config) SanitizeClaudeHeaderDefaults()

SanitizeClaudeHeaderDefaults trims surrounding whitespace from the configured Claude fingerprint baseline values, normalizes the native entrypoint and beta override lists, and resets an unknown client-request-id mode to the default.

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) SanitizeDevin added in v8.0.65

func (cfg *Config) SanitizeDevin()

SanitizeDevin normalizes Devin sensitive-word settings.

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

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

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

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) SanitizeOAuthSettings added in v8.0.5

func (cfg *Config) SanitizeOAuthSettings()

SanitizeOAuthSettings normalizes and deduplicates global OAuth model settings. It trims whitespace, normalizes channel keys to lower-case, drops empty entries, and ensures entries 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 drops invalid rules and skips invalid regex entries individually.

func (*Config) SanitizeVertexCompatKeys

func (cfg *Config) SanitizeVertexCompatKeys()

SanitizeVertexCompatKeys deduplicates and normalizes Vertex-compatible API key credentials.

func (*Config) SanitizeXAIKeys

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) SyncServerResponseCompression added in v8.0.44

func (cfg *Config) SyncServerResponseCompression()

SyncServerResponseCompression copies the canonical response compression settings into the JSON-visible mirror on the outer Config.

func (*Config) UnmarshalYAML

func (cfg *Config) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML accepts both layouts, including partially migrated documents. Presence, rather than Go zero values, determines which setting wins.

func (*Config) ValidateCredentialWeights

func (cfg *Config) ValidateCredentialWeights() error

ValidateCredentialWeights validates weights for every API-key family.

type ConfigFileSnapshot added in v8.1.0

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

ConfigFileSnapshot is an immutable view of an existing config file. It may contain unvalidated YAML; use PrepareConfigFileForUploadWithOptional for upload.

func ReadConfigFileSnapshot added in v8.1.0

func ReadConfigFileSnapshot(path string) (snapshot *ConfigFileSnapshot, err error)

ReadConfigFileSnapshot reads the complete bytes and file identity under a shared lock.

func ReadRootedConfigFileSnapshot added in v8.1.0

func ReadRootedConfigFileSnapshot(root *os.Root, path string) (*ConfigFileSnapshot, error)

ReadRootedConfigFileSnapshot reads a repository-relative config without allowing symbolic links in any path component.

func WriteConfigFileCAS added in v8.1.0

func WriteConfigFileCAS(path string, expected *ConfigFileSnapshot, replacement []byte) (snapshot *ConfigFileSnapshot, err error)

WriteConfigFileCAS replaces an existing file in place under an exclusive lock. It compares both the identity and ALL bytes with expected and never retries on conflict. The returned snapshot reflects the committed bytes; it is safe to use for a response ETag without reopening the file. It guards against orphaned plaintext but does not otherwise validate or normalize replacement.

func (*ConfigFileSnapshot) Bytes added in v8.1.0

func (s *ConfigFileSnapshot) Bytes() []byte

Bytes returns a copy of the complete file contents, safe to edit independently.

func (*ConfigFileSnapshot) SourceHash added in v8.1.0

func (s *ConfigFileSnapshot) SourceHash() string

SourceHash returns the SHA-256 of the complete file bytes in lowercase hex.

type CredentialConcurrencyConfig

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

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

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

func (CredentialConcurrencyConfig) WithDefaults

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

type CredentialInFlightConfig

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

func DefaultCredentialInFlightConfig() CredentialInFlightConfig

DefaultCredentialInFlightConfig returns the in-flight observation defaults.

func (CredentialInFlightConfig) Durations

Durations parses and validates the in-flight observation durations.

func (CredentialInFlightConfig) Validate

func (c CredentialInFlightConfig) Validate() error

Validate verifies the in-flight observation bounds.

type DevinConfig

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 sensitive words or phrases to literal replacements 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"`
}

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

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 is deprecated and ignored. Management endpoints are never
	// advertised over DNS-SD; the field remains so existing config files still load.
	AdvertiseManagement bool `yaml:"advertise-management" json:"advertise-management"`
}

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

type DiscoveryInterfacesConfig

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"`

	// ConnectionPool configures upstream connection reuse for this credential.
	// Omitted disables pooling (preserving the fresh-transport-per-request default);
	// pools stay per credential, so opting in never shares connections with another key.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,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

func (k GeminiKey) GetPrefix() string

func (GeminiKey) GetProxyURL

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

func (m GeminiModel) GetDisplayName() string

func (GeminiModel) GetForceMapping

func (m GeminiModel) GetForceMapping() bool

func (GeminiModel) GetIsCompat

func (m GeminiModel) GetIsCompat() bool

func (GeminiModel) GetMaxContextLength

func (m GeminiModel) GetMaxContextLength() int

func (GeminiModel) GetName

func (m GeminiModel) GetName() string

func (GeminiModel) GetThinking

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

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 KVStoreConfig added in v8.0.55

type KVStoreConfig struct {
	// Disabled turns off the local bbolt KV store when true (fallback to in-memory).
	// Defaults to false (bbolt enabled by default in non-Home mode).
	Disabled bool `yaml:"disabled" json:"disabled"`

	// Path is the file system path to the bbolt database file.
	// When empty, it defaults to "<auth-dir>/kv.db".
	Path string `yaml:"path,omitempty" json:"path,omitempty"`
}

KVStoreConfig holds configuration for the local persistent bbolt KV store.

func (KVStoreConfig) EffectivePath added in v8.0.55

func (c KVStoreConfig) EffectivePath() string

EffectivePath returns the trimmed Path or DefaultKVStorePath ("kv.db") when empty.

func (KVStoreConfig) EffectivePathForAuthDir added in v8.0.55

func (c KVStoreConfig) EffectivePathForAuthDir(authDir string) string

EffectivePathForAuthDir returns the trimmed Path when explicitly configured, or joins the given authDir (falling back to DefaultAuthDir when authDir is empty) with DefaultKVStorePath ("<auth-dir>/kv.db").

type MetaKey

type MetaKey = CodexKey

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

type MetaModel

type MetaModel = CodexModel

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

type ModelCatalogs added in v8.0.14

type ModelCatalogs = registry.CatalogSources

ModelCatalogs selects optional sources for the process-wide model catalogs.

type OAuthModelAlias

type OAuthModelAlias struct {
	// OpenAPI overrides Vertex endpoint selection for this model.
	OpenAPI *bool `yaml:"openapi,omitempty" json:"openapi,omitempty"`

	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 OAuthModelSetting added in v8.0.5

type OAuthModelSetting struct {
	// OpenAPI overrides Vertex endpoint selection for this model.
	OpenAPI *bool `yaml:"openapi,omitempty" json:"openapi,omitempty"`

	Name  string `yaml:"name" json:"name"`
	Alias string `yaml:"alias,omitempty" json:"alias,omitempty"`

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

OAuthModelSetting defines provider/channel model settings (such as context window overrides) for OAuth credentials.

func ResolveOAuthModelSetting added in v8.0.5

func ResolveOAuthModelSetting(settings []OAuthModelSetting, modelID, metadataModelID, modelName string) *OAuthModelSetting

ResolveOAuthModelSetting finds the best matching OAuthModelSetting for a given model. An exact Alias match on the model ID takes precedence over a general Name match. Within the same match specificity, later entries in the slice override earlier ones.

func (OAuthModelSetting) GetMaxContextLength added in v8.0.5

func (s OAuthModelSetting) GetMaxContextLength() int

GetMaxContextLength returns the configured maximum context length override.

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"`

	// ConnectionPool is the provider-group default for upstream connection reuse.
	// A per-key connection-pool entry overrides it field by field; omitted disables pooling.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,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"`

	// ConnectionPool configures upstream connection reuse for this key, overriding
	// the provider-group default field by field. Pools stay per credential, so
	// opting in never shares connections with another key.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,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

func (m OpenAICompatibilityModel) GetDisplayName() string

func (OpenAICompatibilityModel) GetForceMapping

func (m OpenAICompatibilityModel) GetForceMapping() bool

func (OpenAICompatibilityModel) GetIsCompat

func (m OpenAICompatibilityModel) GetIsCompat() bool

func (OpenAICompatibilityModel) GetMaxContextLength

func (m OpenAICompatibilityModel) GetMaxContextLength() int

func (OpenAICompatibilityModel) GetName

func (m OpenAICompatibilityModel) GetName() string

func (OpenAICompatibilityModel) GetThinking

func (OpenAICompatibilityModel) GetUseMaxCompletionTokens

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"`
	// Replace defines ordered literal and Go RE2 regex replacements in selected strings.
	Replace []PayloadReplaceRule `yaml:"replace" json:"replace"`
	// Filter defines rules that remove parameters from the payload by JSON path.
	Filter []PayloadFilterRule `yaml:"filter" json:"filter"`
}

PayloadConfig defines parameter and text mutation 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 PayloadReplaceRule added in v8.0.75

type PayloadReplaceRule struct {
	Models       []PayloadModelRule   `yaml:"models" json:"models"`
	Target       PayloadReplaceTarget `yaml:"target" json:"target"`
	Replacements []PayloadReplacement `yaml:"replacements" json:"replacements"`
}

PayloadReplaceRule applies ordered literal and Go RE2 regex replacements to existing strings.

func (PayloadReplaceRule) Validate added in v8.0.75

func (r PayloadReplaceRule) Validate() error

Validate rejects unsafe implicit targets and ambiguous replacement entries. Invalid regexes are skipped individually during sanitization and execution.

type PayloadReplaceTarget added in v8.0.75

type PayloadReplaceTarget struct {
	Role      string   `yaml:"role" json:"role"`
	Positions []int    `yaml:"positions" json:"positions"`
	All       bool     `yaml:"all" json:"all"`
	Paths     []string `yaml:"paths,omitempty" json:"paths,omitempty"`
}

PayloadReplaceTarget selects either JSON paths or one-based positions of a role in the final upstream body. Paths are mutually exclusive with role selectors. Messages without editable text still count; a top-level system field counts as one message.

func (*PayloadReplaceTarget) UnmarshalYAML added in v8.0.75

func (t *PayloadReplaceTarget) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML rejects fractional positions and non-string paths instead of allowing YAML coercion.

type PayloadReplacement added in v8.0.75

type PayloadReplacement map[string]string

PayloadReplacement is either a single literal source-to-destination mapping ({"from": "to"}) or a Go RE2 regex rule ({"pattern": "...", "replacement": "..."}). The enclosing slice, not map iteration order, determines replacement order.

func (PayloadReplacement) Resolve added in v8.0.77

func (r PayloadReplacement) Resolve() (source, replacement string, isRegex bool, err error)

Resolve classifies a replacement entry as a literal ("from": "to") or Go RE2 pattern ({"pattern": "...", "replacement": "..."}) pair.

func (*PayloadReplacement) UnmarshalJSON added in v8.0.75

func (r *PayloadReplacement) UnmarshalJSON(data []byte) error

UnmarshalJSON enforces the same string-only mapping contract as YAML.

func (*PayloadReplacement) UnmarshalYAML added in v8.0.75

func (r *PayloadReplacement) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML prevents YAML from coercing numeric or boolean operands to strings.

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

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

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

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

func (*PluginInstanceConfig) UnmarshalYAML

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

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

type PluginsConfig

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 ProxyConnectionPoolConfig added in v8.0.50

type ProxyConnectionPoolConfig struct {
	// Enabled controls whether connection reuse is active for this credential.
	// Writing the connection-pool block is the opt-in, so an omitted or true
	// value enables pooling; an explicit false opts a key out of its group pool.
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`

	// IdleConnTimeout is how long an idle pooled connection survives before it
	// is closed. Defaults to "300s". Measured against ollama.com, an idle
	// connection was still reused after 600s, so 300s sits inside the upstream
	// window while covering the multi-minute gaps between interactive requests.
	// Zero or a negative value disables keep-alives, so every request dials
	// afresh.
	IdleConnTimeout string `yaml:"idle-conn-timeout,omitempty" json:"idle-conn-timeout,omitempty"`

	// MaxIdleConnsPerHost caps idle connections kept per upstream host.
	// Defaults to 2, matching net/http's DefaultMaxIdleConnsPerHost. Zero or a
	// negative value disables keep-alives as well.
	MaxIdleConnsPerHost *int `yaml:"max-idle-conns-per-host,omitempty" json:"max-idle-conns-per-host,omitempty"`
}

ProxyConnectionPoolConfig configures upstream connection reuse for one api-key credential (group level or per key).

Pools are per credential: two API keys never share a connection, and OAuth credentials are not poolable at all (Antigravity keeps its own switch). The transport cache is bounded, so a deployment with very many keys degrades to the historical one-transport-per-request behavior instead of growing without limit.

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"`
	// BaseURL specifies the base URL of the remote management API for TUI client mode (e.g. "https://proxy.example.com").
	BaseURL string `yaml:"base-url,omitempty" json:"base-url,omitempty"`
}

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

type RequestScopedErrorRule

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 ResponseCompressionConfig added in v8.0.44

type ResponseCompressionConfig struct {
	// Enabled defaults to true when unset.
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
	// MinBytes defaults to 1024 when zero or negative.
	MinBytes int `yaml:"min-bytes" json:"min-bytes"`
}

ResponseCompressionConfig controls downstream HTTP response compression.

func (ResponseCompressionConfig) EffectiveMinBytes added in v8.0.44

func (c ResponseCompressionConfig) EffectiveMinBytes() int

EffectiveMinBytes returns the minimum non-streaming response size to compress.

func (ResponseCompressionConfig) IsEnabled added in v8.0.44

func (c ResponseCompressionConfig) IsEnabled() bool

IsEnabled reports whether negotiated response compression is enabled.

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, pi, and generic (X-Session-ID) session headers
	// are preferred, followed by prompt_cache_key, Responses conversation IDs, legacy body IDs,
	// execution session identity, Merkle LCP prefix/compaction matching, derived session
	// identity, and the existing message-content hash fallback.
	// LCP compaction matching requires at least 2 shared trailing turns; clients whose
	// compaction replaces all earlier turns with a summary should send X-Session-ID (or
	// another explicit session ID), or affinity starts a new binding at every compaction.
	// 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"`

	// SessionAffinityRebindOn controls which credential failures rebind an established session
	// to the failover credential.
	// Supported values:
	//   - "any" (default): any credential-attributed failure unbinds and rebinds on failover.
	//   - "quota": transient errors (408, 5xx, empty stream, buffer limit) fail over for that
	//     request only while keeping the session bound to its original credential; quota and
	//     auth errors (429, 401/402/403, 404/model support, invalid_grant) rebind as normal.
	//   - "never": never move or fail over an established session to another credential;
	//     keep the binding and return the error (or retry the same credential) instead.
	// Ignored when SessionAffinity is false.
	SessionAffinityRebindOn string `yaml:"session-affinity-rebind-on,omitempty" json:"session-affinity-rebind-on,omitempty"`
}

RoutingConfig configures how credentials are selected for requests.

type SDKConfig

type SDKConfig struct {
	// MaxRequestBodyBytes limits the size (in bytes) of incoming HTTP request bodies.
	// Values <= 0 disable the limit (default).
	MaxRequestBodyBytes int64 `yaml:"max-request-body-bytes" json:"max-request-body-bytes"`

	// ResponseCompression controls negotiated compression of downstream HTTP responses.
	// It is configured under server.response-compression. Config.ServerResponseCompression
	// mirrors it for JSON and programmatic access; read the effective value via
	// Config.EffectiveResponseCompression.
	ResponseCompression ResponseCompressionConfig `yaml:"response-compression" json:"-"`

	// Client configures client-facing compatibility behavior.
	Client ClientConfig `yaml:"client" json:"client"`

	// OAuthOnlyFields records v8 provider settings that must wait for credential
	// selection and must not affect API-key credentials. Config YAML snapshots
	// preserve the corresponding v8 paths instead of serializing this metadata.
	OAuthOnlyFields map[string]bool `yaml:"-" json:"-"`

	// 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"`

	// TLSHandshakeTimeoutSeconds bounds upstream TLS handshakes made by the
	// shared uTLS client, in seconds. It applies to both the Claude Code
	// Anthropic transport and the Chrome ChatGPT/Codex transport; the
	// standard fallback transport is unaffected. It starts after TCP or
	// proxy connection establishment returns and does not bound dialing or
	// proxy CONNECT. Those uTLS paths use custom TLS dialing, for which Go
	// ignores http.Transport.TLSHandshakeTimeout, so a peer that accepts the
	// connection but never answers the ClientHello would otherwise block the
	// request indefinitely and request-retry could never engage. The bound
	// applies only during the TLS handshake and is removed once it succeeds,
	// so inference and long-running streams are unaffected. The default 0
	// disables the bound (previous behavior); negative values are treated as
	// 0, and values beyond the representable duration range saturate.
	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.
	//   - "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"`

	// 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.

func (*SDKConfig) TLSHandshakeTimeout added in v8.0.29

func (c *SDKConfig) TLSHandshakeTimeout() time.Duration

TLSHandshakeTimeout returns the configured upstream TLS handshake bound for requests using the shared uTLS client. A non-positive configured value disables the bound and yields 0.

type SensitivePatternRule added in v8.0.70

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 v8.0.70

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 ServerResponseCompression added in v8.0.44

type ServerResponseCompression = ResponseCompressionConfig

ServerResponseCompression mirrors SDKConfig.ResponseCompression on the outer Config so JSON and YAML round trips preserve server.response-compression. The canonical storage remains SDKConfig.ResponseCompression; read the effective value via EffectiveResponseCompression.

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"`

	// 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 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.
	// When it contains a "/publishers/" segment it is used as the full resource
	// prefix (e.g. "https://aiplatform.googleapis.com/v1/projects/{p}/locations/{l}/publishers/google/models")
	// and the executor only appends "/{model}:{action}". Otherwise "/v1" is
	// inserted if absent, then "/publishers/google/models" is appended; a
	// trailing version segment like "/v1" or "/v1beta1" is never duplicated.
	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"`

	// ConnectionPool configures upstream connection reuse for this credential.
	// Omitted disables pooling (preserving the fresh-transport-per-request default);
	// pools stay per credential, so opting in never shares connections with another key.
	ConnectionPool *ProxyConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,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"`

	// Interactions optionally enables native Vertex Interactions API routing for this key.
	Interactions *bool `yaml:"interactions,omitempty" json:"interactions,omitempty"`

	// OpenAPI overrides automatic OpenAI-compatible endpoint selection.
	OpenAPI *bool `yaml:"openapi,omitempty" json:"openapi,omitempty"`

	// OpenAPILocation overrides the location used for OpenAPI requests.
	OpenAPILocation string `yaml:"openapi-location,omitempty" json:"openapi-location,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

func (k VertexCompatKey) GetPrefix() string

func (VertexCompatKey) GetProxyURL

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"`

	// OpenAPI overrides endpoint selection for this model.
	OpenAPI *bool `yaml:"openapi,omitempty" json:"openapi,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

func (m VertexCompatModel) GetDisplayName() string

func (VertexCompatModel) GetForceMapping

func (m VertexCompatModel) GetForceMapping() bool

func (VertexCompatModel) GetName

func (m VertexCompatModel) GetName() string

func (VertexCompatModel) GetOpenAPI added in v8.0.37

func (m VertexCompatModel) GetOpenAPI() *bool

func (VertexCompatModel) GetThinking

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

type XAIConfig

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

type XAIKey = CodexKey

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

type XAIModel

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