config

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: Apache-2.0 Imports: 10 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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID             string     `yaml:"id,omitempty" json:"id,omitempty"`
	Name           string     `yaml:"name" json:"name"`
	Adapter        string     `yaml:"adapter,omitempty" json:"adapter,omitempty"`
	BaseURL        string     `yaml:"base_url" json:"base_url"`
	APIKey         string     `yaml:"api_key,omitempty" json:"api_key,omitempty"`
	Credential     Credential `yaml:"credential,omitempty" json:"credential,omitempty"`
	Enabled        bool       `yaml:"enabled" json:"enabled"`
	Priority       int        `yaml:"priority" json:"priority"`
	Weight         int        `yaml:"weight" json:"weight"`
	MaxConcurrency int        `yaml:"max_concurrency" json:"max_concurrency"`
	Cost           float64    `yaml:"cost" json:"cost"`
	// Proxy is an upstream proxy for THIS account (any format, list allowed).
	// Empty = fall back to the global pool, then direct/HTTP_PROXY.
	Proxy string `yaml:"proxy,omitempty" json:"proxy,omitempty"`
}

type Config

type Config struct {
	Version      int          `yaml:"version" json:"version"`
	Server       Server       `yaml:"server" json:"server"`
	Secret       string       `yaml:"secret" json:"secret"`
	VirtualKeys  []VirtualKey `yaml:"virtual_keys" json:"virtual_keys"`
	Models       []Model      `yaml:"models" json:"models"`
	Accounts     []Account    `yaml:"accounts" json:"accounts"`
	Routing      Routing      `yaml:"routing" json:"routing"`
	Resilience   Resilience   `yaml:"resilience" json:"resilience"`
	Optimization Optimization `yaml:"optimization,omitempty" json:"optimization,omitempty"`
	Webhook      Webhook      `yaml:"webhook,omitempty" json:"webhook,omitempty"`
	// Proxies is the global upstream proxy pool (any format: one entry per
	// line, commas/semicolons, JSON array; http/https/socks4/4a/5/5h).
	// Accounts without their own proxy use this pool; accounts with one use
	// their own. Empty = direct connections (HTTP_PROXY env still applies).
	Proxies []string `yaml:"proxies,omitempty" json:"proxies,omitempty"`
	// Plugins lists sidecar/config plugins (like dsh plugins but HTTP sidecars).
	// Each becomes a plugin.Registry entry wired on runtime start.
	Plugins []PluginConfig `yaml:"plugins,omitempty" json:"plugins,omitempty"`
	// MCPServers exposes upstream Model Context Protocol endpoints through
	// the gateway (/v1/mcp/<name>) behind virtual-key auth.
	MCPServers []McpServer `yaml:"mcp_servers,omitempty" json:"mcp_servers,omitempty"`
	// Guardrails enables request-content checking (G5): PII regexes and
	// prompt-injection heuristics in off|log|redact|block mode.
	Guardrails GuardrailsConfig `yaml:"guardrails,omitempty" json:"guardrails,omitempty"`
}

type Credential

type Credential struct {
	Kind             string `yaml:"kind,omitempty" json:"kind,omitempty"`
	APIKey           string `yaml:"api_key,omitempty" json:"api_key,omitempty"`
	AccessToken      string `yaml:"access_token,omitempty" json:"access_token,omitempty"`
	RefreshToken     string `yaml:"refresh_token,omitempty" json:"refresh_token,omitempty"`
	IDToken          string `yaml:"id_token,omitempty" json:"id_token,omitempty"`
	Cookies          string `yaml:"cookies,omitempty" json:"cookies,omitempty"`
	OrganizationID   string `yaml:"organization_id,omitempty" json:"organization_id,omitempty"`
	ExpiresAt        string `yaml:"expires_at,omitempty" json:"expires_at,omitempty"`
	ClientID         string `yaml:"client_id,omitempty" json:"client_id,omitempty"`
	ChatGPTAccountID string `yaml:"chatgpt_account_id,omitempty" json:"chatgpt_account_id,omitempty"`
	Revision         int64  `yaml:"revision,omitempty" json:"revision,omitempty"`
}

type GuardrailsConfig

type GuardrailsConfig struct {
	// Mode: "" | "off" | "log" | "redact" | "block".
	Mode string `yaml:"mode,omitempty" json:"mode,omitempty"`
	// PII toggles; empty = all PII detectors on when Mode is set.
	PII GuardrailsPII `yaml:"pii,omitempty" json:"pii,omitempty"`
	// Injection enables prompt-injection heuristics (zero = inherit/off).
	Injection *bool `yaml:"injection,omitempty" json:"injection,omitempty"`
}

GuardrailsConfig mirrors internal/guardrails.Config.

type GuardrailsPII

type GuardrailsPII struct {
	Email  *bool `yaml:"email,omitempty" json:"email,omitempty"`
	Phone  *bool `yaml:"phone,omitempty" json:"phone,omitempty"`
	Card   *bool `yaml:"card,omitempty" json:"card,omitempty"`
	APIKey *bool `yaml:"api_key,omitempty" json:"api_key,omitempty"`
}

type McpServer

type McpServer struct {
	Name    string            `yaml:"name" json:"name"`
	URL     string            `yaml:"url" json:"url"`
	Enabled *bool             `yaml:"enabled,omitempty" json:"enabled,omitempty"` // omitted = enabled
	Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
	// PinTools (G2) enables rug-pull detection for the tool surface: the
	// first tools/list response is pinned (hash + tool names) and any later
	// change is BLOCKED with 409 (otherwise it is only audited). The gateway
	// always records a telemetry outcome (mcp_tools_registered/changed/blocked).
	PinTools bool `yaml:"pin_tools,omitempty" json:"pin_tools,omitempty"`
}

McpServer is an upstream Model Context Protocol endpoint exposed through the gateway at /v1/mcp/<name> behind virtual-key auth. Headers carry the upstream credentials (same trust level as account api_key in file config).

func (McpServer) IsEnabled

func (m McpServer) IsEnabled() bool

IsEnabled reports whether the server accepts traffic; file configs may omit the flag, in which case the server is enabled.

type Model

type Model struct {
	Alias             string        `yaml:"alias" json:"alias"`
	UpstreamModel     string        `yaml:"upstream_model" json:"upstream_model"`
	Accounts          []string      `yaml:"accounts" json:"accounts"`
	RoutingStrategy   string        `yaml:"routing_strategy,omitempty" json:"routing_strategy,omitempty"`
	Fallbacks         []string      `yaml:"fallbacks,omitempty" json:"fallbacks,omitempty"`
	InputCostPerMtok  float64       `yaml:"input_cost_per_mtok,omitempty" json:"input_cost_per_mtok,omitempty"`
	OutputCostPerMtok float64       `yaml:"output_cost_per_mtok,omitempty" json:"output_cost_per_mtok,omitempty"`
	Optimization      *Optimization `yaml:"optimization,omitempty" json:"optimization,omitempty"`
	// Cache (G4) enables the per-model exact-match response cache:
	// "" = inherit (off unless the client sends X-Gateway-Cache: true),
	// "exact" = non-streaming responses are cached with no opt-in header.
	// CacheTTL overrides the default 5m window (Go duration string).
	Cache    string `yaml:"cache,omitempty" json:"cache,omitempty"`
	CacheTTL string `yaml:"cache_ttl,omitempty" json:"cache_ttl,omitempty"`
	// Sources (шаг 5 хребта): per-account overrides for multi-provider
	// aliases — one public name served by different providers with their own
	// upstream model names, weights and prices. Empty = legacy 1:1 behavior.
	Sources []ModelSource `yaml:"sources,omitempty" json:"sources,omitempty"`
}

func (Model) ResolvedFor

func (m Model) ResolvedFor(account string) Model

ResolvedFor returns an attempt-scoped copy of the model with the source's upstream name and costs applied — adapters and response rewriting need no changes to honor per-provider overrides.

func (Model) UpstreamFor

func (m Model) UpstreamFor(account string) string

UpstreamFor resolves the upstream model for an attempt against account: the source override wins over the alias default.

func (Model) WeightFor

func (m Model) WeightFor(account string) (int, bool)

WeightFor reports the per-source ordering weight for an account within this alias, when the source defines one.

type ModelSource

type ModelSource struct {
	Account           string  `yaml:"account" json:"account"`
	UpstreamModel     string  `yaml:"upstream_model,omitempty" json:"upstream_model,omitempty"`
	Weight            int     `yaml:"weight,omitempty" json:"weight,omitempty"` // ordering within THIS alias; overrides account.Weight
	InputCostPerMtok  float64 `yaml:"input_cost_per_mtok,omitempty" json:"input_cost_per_mtok,omitempty"`
	OutputCostPerMtok float64 `yaml:"output_cost_per_mtok,omitempty" json:"output_cost_per_mtok,omitempty"`
}

type Optimization

type Optimization struct {
	// RTKCompression compresses large tool_result content (saves 20-40% input tokens).
	RTKCompression bool `yaml:"rtk_compression" json:"rtk_compression"`
	// Caveman injects a terse "caveman" system directive so the model replies
	// with fewer output tokens (up to ~65%), while keeping technical substance.
	Caveman bool `yaml:"caveman" json:"caveman"`
	// Headroom reserves output space by pruning old tool history when the
	// estimated input tokens exceed the headroom window (like 9Router).
	Headroom bool `yaml:"headroom" json:"headroom"`
	// HeadroomReserve is the max estimated input tokens before pruning. 0 = 120k default.
	HeadroomReserve int `yaml:"headroom_reserve,omitempty" json:"headroom_reserve,omitempty"`
	// HeadroomKeep is how many recent turns to keep when pruning. 0 = 8 default.
	HeadroomKeep int `yaml:"headroom_keep,omitempty" json:"headroom_keep,omitempty"`
	// Mode presets. Empty string = legacy behavior (standard/full/balanced).
	// Valid values: rtk_mode light|standard|aggressive|auto,
	// caveman_mode lite|full|auto, headroom_profile conservative|balanced|aggressive|auto.
	RTKMode         string `yaml:"rtk_mode,omitempty" json:"rtk_mode,omitempty"`
	CavemanMode     string `yaml:"caveman_mode,omitempty" json:"caveman_mode,omitempty"`
	HeadroomProfile string `yaml:"headroom_profile,omitempty" json:"headroom_profile,omitempty"`
	// Squoze enables the experimental squoze engine (github.com/Rethinger/squoze)
	// as the ONLY request-body optimizer: content-routed head/tail squeezing
	// with never-elide, decision memo and reversible marker refs. Exclusive:
	// when set, rtk/caveman/headroom must be empty or Build() fails.
	Squoze bool `yaml:"squoze,omitempty" json:"squoze,omitempty"`
}

Optimization carries global request-optimization flags applied by the gateway to every request, mirroring 9Router's token savers. Individual requests can still opt in with X-Gateway-* headers even when disabled.

type Org

type Org struct {
	ID        string  `yaml:"id" json:"id"`
	BudgetUSD float64 `yaml:"budget_usd" json:"budget_usd"` // caps team budgets, 0 = unlimited
}

Org carries only what policy enforcement needs from organizations.

type PluginConfig

type PluginConfig struct {
	Name     string `yaml:"name" json:"name"`
	Endpoint string `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
	Enabled  bool   `yaml:"enabled,omitempty" json:"enabled,omitempty"`
}

PluginConfig declares a gateway plugin: HTTP sidecar endpoint or in-process enabled flag.

type Resilience

type Resilience struct {
	Cooldown        string `yaml:"cooldown" json:"cooldown"`
	CircuitFailures int    `yaml:"circuit_failures" json:"circuit_failures"`
	CircuitReset    string `yaml:"circuit_reset" json:"circuit_reset"`
	LockoutFailures int    `yaml:"lockout_failures,omitempty" json:"lockout_failures,omitempty"`
	LockoutDuration string `yaml:"lockout_duration,omitempty" json:"lockout_duration,omitempty"`
}

type Routing

type Routing struct {
	Strategy    string `yaml:"strategy" json:"strategy"`
	StickyTTL   string `yaml:"sticky_ttl" json:"sticky_ttl"`
	MaxAttempts int    `yaml:"max_attempts" json:"max_attempts"`
}

type Server

type Server struct {
	Addr         string `yaml:"addr" json:"addr"`
	ReadTimeout  string `yaml:"read_timeout" json:"read_timeout"`
	WriteTimeout string `yaml:"write_timeout" json:"write_timeout"`
	// Gzip compresses buffered non-streaming JSON responses >= 1 KiB when
	// the client advertises Accept-Encoding: gzip (LiteLLM parity).
	Gzip bool `yaml:"gzip,omitempty" json:"gzip,omitempty"`
}

type Snapshot

type Snapshot struct {
	Config
	KeyHashes                         map[string][]byte
	ModelsByAlias                     map[string]Model
	VirtualKeysByName                 map[string]VirtualKey
	AccountsByName                    map[string]Account
	MCPServersByName                  map[string]McpServer
	GlobalProxies                     []proxylib.Entry            // parsed from Config.Proxies
	AccountProxies                    map[string][]proxylib.Entry // parsed per account (nil = unset)
	StickyTTL, Cooldown, CircuitReset time.Duration
	Lockout                           time.Duration
	ReadTimeout, WriteTimeout         time.Duration
}

func Build

func Build(c Config) (*Snapshot, error)

func Load

func Load(path string) (*Snapshot, error)

func (*Snapshot) HashPresented

func (s *Snapshot) HashPresented(key string) []byte

func (*Snapshot) KeyHashHex

func (s *Snapshot) KeyHashHex(name string) string

type Team

type Team struct {
	ID        string  `yaml:"id" json:"id"`
	BudgetUSD float64 `yaml:"budget_usd" json:"budget_usd"`                   // shared daily team budget, 0 = unlimited
	ShareUSD  float64 `yaml:"share_usd,omitempty" json:"share_usd,omitempty"` // per-key fair share = budget / key count
	// BalanceUSD is the prepaid credit remaining (шаг 6, Cloud). It caps the
	// effective team budget (owner formula: min(budget, balance)). Precision
	// is bounded by snapshot freshness — control-plane decrements balance per
	// request_event and a nightly reconcile keeps it honest.
	BalanceUSD float64 `yaml:"balance_usd,omitempty" json:"balance_usd,omitempty"`
	// Org is the enterprise organization owning this team (migration 015).
	// Its budget is an upper bound on every team budget under it.
	Org *Org `yaml:"org,omitempty" json:"org,omitempty"`
}

type VirtualKey

type VirtualKey struct {
	Name           string   `yaml:"name" json:"name"`
	ID             string   `yaml:"id,omitempty" json:"id,omitempty"`
	Key            string   `yaml:"key,omitempty" json:"key,omitempty"`
	KeyHash        string   `yaml:"key_hash,omitempty" json:"key_hash,omitempty"`
	Models         []string `yaml:"models" json:"models"`
	RPM            int      `yaml:"rpm" json:"rpm"`
	TPM            int      `yaml:"tpm,omitempty" json:"tpm,omitempty"`
	MaxConcurrency int      `yaml:"max_concurrency,omitempty" json:"max_concurrency,omitempty"`
	BudgetUSD      float64  `yaml:"budget_usd,omitempty" json:"budget_usd,omitempty"` // daily by default, 0 = unlimited
	// BudgetDuration is the reset window for BudgetUSD: "" | "day" (default)
	// | "month". A monthly window keeps the same allowance but resets at the
	// first of the month (G1 gap — Cloud self-serve blocker).
	BudgetDuration string        `yaml:"budget_duration,omitempty" json:"budget_duration,omitempty"`
	Team           *Team         `yaml:"team,omitempty" json:"team,omitempty"`
	Optimization   *Optimization `yaml:"optimization,omitempty" json:"optimization,omitempty"`
	// contains filtered or unexported fields
}

type Webhook

type Webhook struct {
	Enabled bool   `yaml:"enabled" json:"enabled"`
	URL     string `yaml:"url,omitempty" json:"url,omitempty"`
	Secret  string `yaml:"secret,omitempty" json:"secret,omitempty"`
}

Webhook delivers gateway alerts (account lockout, budget exceeded) to an external endpoint. Requests are signed with HMAC-SHA256 of the body using Secret when set.

Jump to

Keyboard shortcuts

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