Documentation
¶
Index ¶
- func EstimateTokens(s string) int64
- func Run()
- func SaverSnapshot() map[string]interface{}
- func ValidPromptMode(m string) bool
- type APIKey
- type Config
- type CustomProvider
- type DeviceGrant
- type HourBucket
- type LogEntry
- type ModelStat
- type Provider
- type ProviderKind
- type ProviderStat
- type Registry
- func (r *Registry) Catalog() ([]map[string]interface{}, bool)
- func (r *Registry) Combos() map[string][]string
- func (r *Registry) Cooldown(providerID string, seconds int64)
- func (r *Registry) Cooling(providerID string) bool
- func (r *Registry) DeleteCombo(name string) bool
- func (r *Registry) OwnerOf(model string) string
- func (r *Registry) Providers() []Provider
- func (r *Registry) RefreshModels(ctx context.Context)
- func (r *Registry) Resolve(model string) []*Provider
- func (r *Registry) SetAliases(providerID string, m map[string]string) bool
- func (r *Registry) SetBridgeEnabled(id string, enabled bool)
- func (r *Registry) SetBridgeURL(id, baseURL string)
- func (r *Registry) SetCombo(name string, chain []string)
- func (r *Registry) SetInternalToken(tok string)
- type Router
- type Stats
- type Store
- func (s *Store) AddProvider(p CustomProvider) error
- func (s *Store) ConnectionKeys() []APIKey
- func (s *Store) CreateDeviceGrant(deviceCode, userCode, client string) DeviceGrant
- func (s *Store) CreateKey(name string, maxReq int64, allowedModels []string) APIKey
- func (s *Store) DeleteCombo(name string) bool
- func (s *Store) DeleteDeviceGrant(deviceCode string)
- func (s *Store) DeleteKey(key string) bool
- func (s *Store) DeleteProvider(name string) bool
- func (s *Store) EnsureSeedKey(routerKey string) (string, bool)
- func (s *Store) Flush(force bool)
- func (s *Store) ListCombos() map[string][]string
- func (s *Store) ListFreebuffTokens() []string
- func (s *Store) ListKeys() []APIKey
- func (s *Store) ListProviders() []CustomProvider
- func (s *Store) LookupDeviceGrant(deviceCode string) (DeviceGrant, bool)
- func (s *Store) LookupKey(key string) (APIKey, bool)
- func (s *Store) LookupUserGrant(userCode string) (DeviceGrant, bool)
- func (s *Store) PendingGrants() []DeviceGrant
- func (s *Store) RecordStat(provider, model string, in, out int64, failed bool)
- func (s *Store) RecordUsage(key string, inTok, outTok int64, failed bool)
- func (s *Store) ResolveDeviceGrant(userCode, decision string) (DeviceGrant, bool)
- func (s *Store) SetCombo(name string, chain []string)
- func (s *Store) SetFreebuffTokens(tokens []string)
- func (s *Store) SnapshotStats() Stats
- func (s *Store) ToggleKey(key string, enabled bool) bool
- func (s *Store) ToggleProvider(name string, enabled bool) bool
- func (s *Store) TopModels(n int) []string
- func (s *Store) UpdateKey(key string, maxReq *int64, allowed *[]string) bool
- func (s *Store) UpdateProvider(p CustomProvider) error
- func (s *Store) ValidateKey(key string) bool
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EstimateTokens ¶ added in v1.1.0
EstimateTokens exposes the rough char/4 estimator for count_tokens.
func SaverSnapshot ¶ added in v1.2.0
func SaverSnapshot() map[string]interface{}
SaverSnapshot is the admin/dashboard view of the saver state.
func ValidPromptMode ¶ added in v1.2.0
ValidPromptMode reports whether a mode id is supported.
Types ¶
type APIKey ¶
type APIKey struct {
Key string `json:"key"`
Name string `json:"name"`
CreatedAt int64 `json:"created_at"`
Enabled bool `json:"enabled"`
Requests int64 `json:"requests"`
Errors int64 `json:"errors"`
TokensIn int64 `json:"tokens_in"`
TokensOut int64 `json:"tokens_out"`
LastUsedAt int64 `json:"last_used_at"`
// Client identifies the OAuth device-flow connection that minted this
// key ("cline", "kilo", "hermes", …). Empty = created by hand.
Client string `json:"client,omitempty"`
// UserCode is the device-flow code the user approved for this key.
UserCode string `json:"user_code,omitempty"`
// MaxRequests caps total requests for this key (0 = unlimited).
MaxRequests int64 `json:"max_requests,omitempty"`
// AllowedModels restricts which models this key may request.
// Entries are exact model ids or provider wildcards like "qwen/*".
// Empty = all models allowed.
AllowedModels []string `json:"allowed_models,omitempty"`
}
type Config ¶
type Config struct {
Host string
Port int
// AdminPassword guards the dashboard + /admin/api.
AdminPassword string
// RouterKey seeds the first client API key (ROUTER_KEY). When empty a
// random sk- key is generated and stored.
RouterKey string
// InternalToken is the shared bridge secret (AUTH_TOKEN from .env). The
// embedded bridges were configured from the very same env at package
// init, so core and bridges always agree.
InternalToken string
DataDir string
LogLevel string
// RetryPerProvider: attempts against one provider before failing over.
RetryPerProvider int
// CooldownSeconds: after a provider exhausts its retries it is benched
// for this long so later requests prefer healthier candidates.
CooldownSeconds int64
// RequestTimeoutSec: hard upstream timeout for NON-stream requests
// (streams are unbounded — reasoning models think for minutes).
RequestTimeoutSec int64
}
type CustomProvider ¶
type CustomProvider struct {
Name string `json:"name"` // unique slug, used as prefix "name/model"
BaseURL string `json:"base_url"` // OpenAI-compatible root (…/v1)
APIKey string `json:"api_key"` // upstream key (Bearer)
Models []string `json:"models"` // advertised models (or fetched live)
Enabled bool `json:"enabled"`
CreatedAt int64 `json:"created_at"`
// ModelMap maps public model names → the upstream model id actually
// sent to this provider (aliasing, yolorouter-style).
ModelMap map[string]string `json:"model_map,omitempty"`
}
type DeviceGrant ¶ added in v1.4.0
type DeviceGrant struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
Client string `json:"client"` // client id (cline, kilo, hermes, …)
Status string `json:"status"` // pending | approved | denied
Key string `json:"key,omitempty"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
}
DeviceGrant is one OAuth Device Authorization Grant (RFC 8628): an agent asks for a code, the user approves it in the dashboard/consent page, and polling returns a freshly minted virtual API key.
type HourBucket ¶ added in v1.1.0
type LogEntry ¶
type LogEntry struct {
Time int64 `json:"time"`
Key string `json:"key"`
Model string `json:"model"`
Provider string `json:"provider"`
Status int `json:"status"`
Stream bool `json:"stream"`
LatencyMS int64 `json:"latency_ms"`
TokensIn int64 `json:"tokens_in,omitempty"`
TokensOut int64 `json:"tokens_out,omitempty"`
Saved int64 `json:"saved,omitempty"` // bytes shaved by the Token Saver
Err string `json:"error,omitempty"`
}
func RecentLogs ¶
func RecentLogs() []LogEntry
type Provider ¶
type Provider struct {
ID string `json:"id"` // "glm" | "qwen" | "ds" | "gemini" | "custom:<name>"
Kind ProviderKind `json:"kind"`
BaseURL string `json:"base_url"` // internal listener or external root
APIKey string `json:"-"` // custom only
Label string `json:"label"`
Enabled bool `json:"enabled"`
Models []string `json:"models"`
Healthy bool `json:"healthy"`
LastErr string `json:"last_error,omitempty"`
// Aliases: public model name → upstream model id for THIS provider.
Aliases map[string]string `json:"aliases,omitempty"`
}
type ProviderKind ¶
type ProviderKind string
const ( KindBridge ProviderKind = "bridge" KindCustom ProviderKind = "custom" )
type ProviderStat ¶ added in v1.1.0
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
func NewRegistry ¶
func NewRegistry(internalToken string, customs []CustomProvider) *Registry
func (*Registry) Cooldown ¶ added in v1.1.0
Cooldown marks a provider unhealthy for the next `seconds` so failover prefers other candidates.
func (*Registry) Cooling ¶ added in v1.1.0
Cooling reports whether a provider is currently on cooldown.
func (*Registry) DeleteCombo ¶ added in v1.2.0
DeleteCombo removes a named chain; returns false when it did not exist.
func (*Registry) OwnerOf ¶ added in v1.1.0
OwnerOf returns the provider id that owns a model id in the catalog (used by per-key allowlist checks).
func (*Registry) RefreshModels ¶
RefreshModels re-fetches /v1/models from every enabled provider.
func (*Registry) Resolve ¶
Resolve maps a client model id to an ordered candidate chain:
"auto" → AUTO chain (env AUTO_CHAIN or a sane default across
enabled providers, best-first)
"provider/model" → exactly that provider (single candidate)
"model" → catalog owner + (optionally) other providers serving it
Each candidate's Models[0] is the upstream model id to send (alias applied).
func (*Registry) SetAliases ¶ added in v1.1.0
SetAliases installs/updates the public→upstream alias map of a provider (bridge id or custom name) and rebuilds the catalog immediately.
func (*Registry) SetBridgeEnabled ¶
SetBridgeEnabled marks an embedded bridge enabled/disabled (e.g. no tokens).
func (*Registry) SetBridgeURL ¶
SetBridgeURL assigns the internal listener address of an embedded bridge.
func (*Registry) SetCombo ¶ added in v1.2.0
SetCombo installs/updates a named failover chain and rebuilds the catalog.
func (*Registry) SetInternalToken ¶ added in v1.2.0
SetInternalToken records the shared bridge secret for models fetching.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router bundles the live state of the whole service.
type Stats ¶ added in v1.1.0
type Stats struct {
TotalRequests int64 `json:"total_requests"`
TotalErrors int64 `json:"total_errors"`
TokensIn int64 `json:"tokens_in"`
TokensOut int64 `json:"tokens_out"`
Providers map[string]*ProviderStat `json:"providers"`
Models map[string]*ModelStat `json:"models"`
Hourly []HourBucket `json:"hourly"`
StartedAt int64 `json:"started_at"`
}
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
func (*Store) AddProvider ¶
func (s *Store) AddProvider(p CustomProvider) error
func (*Store) ConnectionKeys ¶ added in v1.4.0
ConnectionKeys returns the keys minted through OAuth connections.
func (*Store) CreateDeviceGrant ¶ added in v1.4.0
func (s *Store) CreateDeviceGrant(deviceCode, userCode, client string) DeviceGrant
CreateDeviceGrant registers a new pending grant for a client.
func (*Store) DeleteCombo ¶ added in v1.2.0
DeleteCombo removes a named chain; false when it did not exist.
func (*Store) DeleteDeviceGrant ¶ added in v1.4.0
DeleteDeviceGrant removes a consumed grant record (after successful poll).
func (*Store) DeleteProvider ¶
func (*Store) EnsureSeedKey ¶
EnsureSeedKey creates the first key if none exists: ROUTER_KEY when set, else a random sk- key. Returns the key material for the boot banner.
func (*Store) Flush ¶ added in v1.1.0
Flush persists dirty state (stats) at most once per 5 seconds. Called by a background ticker and before shutdown.
func (*Store) ListCombos ¶ added in v1.2.0
ListCombos returns the persisted named chains.
func (*Store) ListFreebuffTokens ¶ added in v1.4.0
ListFreebuffTokens returns the dashboard-connected Freebuff auth tokens.
func (*Store) ListProviders ¶
func (s *Store) ListProviders() []CustomProvider
func (*Store) LookupDeviceGrant ¶ added in v1.4.0
func (s *Store) LookupDeviceGrant(deviceCode string) (DeviceGrant, bool)
LookupDeviceGrant fetches a grant by its long device code.
func (*Store) LookupKey ¶ added in v1.1.0
LookupKey returns a copy of the key record (quota + allowlist checks).
func (*Store) LookupUserGrant ¶ added in v1.4.0
func (s *Store) LookupUserGrant(userCode string) (DeviceGrant, bool)
LookupUserGrant fetches the most recent grant for a user code.
func (*Store) PendingGrants ¶ added in v1.4.0
func (s *Store) PendingGrants() []DeviceGrant
PendingGrants returns live pending grants (for the dashboard panel).
func (*Store) RecordStat ¶ added in v1.1.0
RecordStat bumps global + per-provider + per-model + hourly counters.
func (*Store) RecordUsage ¶
RecordUsage updates per-key counters (called by the forwarder once the upstream attempt settled).
func (*Store) ResolveDeviceGrant ¶ added in v1.4.0
func (s *Store) ResolveDeviceGrant(userCode, decision string) (DeviceGrant, bool)
ResolveDeviceGrant approves/denies a pending grant and, on approve, mints the linked virtual key (named after the client + user code). Returns the updated grant.
func (*Store) SetFreebuffTokens ¶ added in v1.4.0
SetFreebuffTokens persists the token list (empty slice disconnects).
func (*Store) SnapshotStats ¶ added in v1.1.0
func (*Store) UpdateProvider ¶ added in v1.1.0
func (s *Store) UpdateProvider(p CustomProvider) error
UpdateProvider replaces an existing provider record (keeps CreatedAt).
func (*Store) ValidateKey ¶
ValidateKey checks a client key and bumps its request counter.