Documentation
¶
Overview ¶
Package service contains the business logic layer: checkin, balance, notify, OAuth, and backup services.
Package service provides time and date formatting utilities that mirror the TS localTimeService.ts behavior.
Package service hosts the SQL-backed routing store that feeds the token router (moved from app/proxy_upstream.go so the app layer stays pure wiring). The channel/account/site join columns used by several loaders are kept in the channelAccountSiteSelect fragment so a store schema change is a one-line edit here instead of a silent drift across three queries.
Index ¶
- Constants
- func AccountFor(account *store.Account, site *store.Site) string
- func ApplyRedirectFixes(ctx context.Context, db *sqlx.DB, candidates []RedirectFixCandidate) (int, error)
- func ApplySiteStatusSideEffects(db *sqlx.DB, siteID int64, siteName string, newStatus string) error
- func BuildMergedSub2ApiAuth(existingExtraConfig *string, refreshToken *string, tokenExpiresAt *int64, ...) map[string]any
- func BuildPlatformProxyConfig(cfg *config.Config, account *store.Account, site *store.Site) *platform.ProxyConfig
- func BuildPlatformProxyConfigForToken(cfg *config.Config, site *store.Site, rawToken string) *platform.ProxyConfig
- func BuildPlatformProxyConfigForTokenWithProxyURL(cfg *config.Config, site *store.Site, rawToken, proxyURL string) *platform.ProxyConfig
- func BuildStoredSub2ApiSubscriptionSummary(summary any) map[string]any
- func BuildTimeFootnote(t time.Time) string
- func CanonicalFromActual(actual string, candidates []string) (canonical string, ok bool)
- func CanonicalizeSiteURL(rawURL string) string
- func ClearResinLeasesForTest()
- func CreateEvent(db *sqlx.DB, eventType string, title string, message string, level string, ...) error
- func CreateSite(db *sqlx.DB, siteData map[string]any) (int64, error)
- func DecryptAccountPassword(cfg *config.Config, cipherText string) string
- func DecryptPassword(cfg *config.Config, cipherText string) string
- func DeleteAccount(db *sqlx.DB, id int64) error
- func DeleteSite(db *sqlx.DB, siteID int64) error
- func DeleteTokenByID(db *sqlx.DB, tokenID int64) error
- func DeriveVertexEndpoints(config store.DirectEndpoints, baseURL, project string) (store.DirectEndpoints, error)
- func EncryptAccountPassword(cfg *config.Config, password string) (string, error)
- func EncryptPassword(cfg *config.Config, password string) (string, error)
- func EnsureDefaultTokenForAccount(db *sqlx.DB, accountID int64, tokenValue string, ...) (int64, error)
- func EstimateRewardWithTodayIncomeFallback(input EstimateRewardInput) float64
- func FormatLocalDate(t time.Time) string
- func FormatLocalDateTime(t time.Time) string
- func FormatUtcSqlDateTime(t time.Time) string
- func ForwardProxyURL(cfg *config.Config, platform, account string) (string, bool)
- func GenerateModelRedirects(ctx context.Context, db *sqlx.DB, accountID int64, actualModels []string) (int, error)
- func GetAccountByID(db *sqlx.DB, id int64) (*store.Account, error)
- func GetDefaultTokenForAccount(db *sqlx.DB, accountID int64) (*store.AccountToken, error)
- func GetLocalTokenGroups(db *sqlx.DB, accountID int64) ([]string, error)
- func GetNextAccountSortOrder(db *sqlx.DB) (int64, error)
- func GetPlatformUserIdFromExtraConfig(extraConfig *string) (int64, bool)
- func GetProxyURLFromExtraConfig(extraConfig *string) string
- func GetResolvedTimeZone() string
- func GetSub2ApiAuthFromExtraConfig(extraConfig *string) map[string]any
- func GetTodayIncomeDelta(extraConfig *string, day string) float64
- func GetTodayIncomeValue(extraConfig *string, day string) float64
- func GetTodayUnixSecondsRange(t time.Time) (start, end int64)
- func GetTokenByID(db *sqlx.DB, id int64) (*store.AccountToken, error)
- func GetTokenGroups(ctx context.Context, db *sqlx.DB, accountID int64, ...) ([]string, error)
- func GetUseSystemProxyFromExtraConfig(extraConfig *string) bool
- func GuessPlatformUserIdFromUsername(username *string) int64
- func HasSessionToken(accessToken string) bool
- func InsertAccount(db *sqlx.DB, account map[string]any) (int64, error)
- func InvalidateSiteCaches()
- func InvalidateSiteProxyCache()
- func InvalidateTokenRouterCache()
- func IsAPIKeyConnection(account *store.Account) bool
- func IsForbiddenPublicTargetURL(raw string) bool
- func IsForbiddenSiteTargetURL(raw string) bool
- func IsManagedSub2ApiTokenDue(tokenExpiresAt any) bool
- func IsMaskedPendingAccountToken(token *store.AccountToken) bool
- func IsMaskedTokenValue(token string) bool
- func IsSub2ApiPlatform(platform string) bool
- func IsUnsupportedCheckinRuntimeHealth(health *RuntimeHealthEntry) bool
- func IsUsableAccountToken(token *store.AccountToken) bool
- func IsValidAPIEndpointURL(raw string) bool
- func IsValidHTTPURL(raw string) bool
- func IsValidProxyURL(raw string) bool
- func ListAccountsWithSites(db *sqlx.DB) ([]map[string]any, error)
- func ListAccountsWithSitesPaginated(db *sqlx.DB, limit, offset int, filter AccountListFilter) ([]map[string]any, int64, error)
- func ListSites(db *sqlx.DB) ([]map[string]any, error)
- func ListTokensWithRelations(db *sqlx.DB, accountID *int64) ([]map[string]any, error)
- func LoadSiteAPIEndpoints(db *sqlx.DB, siteIDs []int64) (map[int64][]store.SiteAPIEndpoint, error)
- func LoadSiteWithEndpoints(db *sqlx.DB, siteID int64) (map[string]any, error)
- func MarshalExtraConfig(config map[string]any) *string
- func MaskToken(token, platform string) string
- func MergeExtraConfig(existing *string, patch map[string]any) *string
- func MergeSub2ApiAuth(existing map[string]any, refreshToken any, tokenExpiresAt any) map[string]any
- func NativeChatRequestProfile(rawURL, platform string) string
- func NormalizeGlobalWeight(input *float64) *float64
- func NormalizeManagedRefreshToken(value any) (string, bool)
- func NormalizeManagedTokenExpiresAt(value any) (int64, bool)
- func NormalizeNullable(s *string) *string
- func NormalizeSiteAPIEndpointBaseUrl(raw string) string
- func NormalizeSortOrder(input *int) *int
- func NormalizeTokenForDisplay(token, platform string) string
- func NormalizeTokenGroups(groups []string) []string
- func ParseExtraConfig(raw *string) map[string]any
- func PopulateRouteChannelsByModelPattern(ctx context.Context, db *sqlx.DB, routeID int64, modelPattern string) (inserted int, err error)
- func ProxyAwareHTTPClient(proxyURL string, timeout time.Duration) *http.Client
- func RebuildRoutesBestEffort()
- func RedactAccountSecrets(account map[string]any)
- func RedactSiteCredentials(site map[string]any)
- func RefreshAccountPricing(ctx context.Context, db *sqlx.DB, accountID int64) error
- func RegisterSiteProxyCacheInvalidator(fn func())
- func ReloadRedirectRegistry(ctx context.Context, db *sqlx.DB)
- func RepairDefaultToken(db *sqlx.DB, accountID int64) (*store.AccountToken, error)
- func ResinEnabled(cfg *config.Config, site *store.Site) bool
- func ResinGlobalEnabled(cfg *config.Config) bool
- func ResolveAccountTokenValueStatus(tokenRow *store.AccountToken) string
- func ResolvePlatformUserID(extraConfig *string, username *string) int64
- func ResolvePlatformUserIDPtr(account *store.Account) *int
- func ResolveResinPlatform(cfg *config.Config, site *store.Site) string
- func RewriteWSURL(targetURL string, cfg *config.Config, platform, account string) string
- func SanitizeImportedSiteRows(table string, rows []map[string]any) ([]map[string]any, int)
- func SetAccountRuntimeHealth(db *sqlx.DB, accountID int64, entry RuntimeHealthEntry) error
- func SetDefaultToken(db *sqlx.DB, tokenID int64) (bool, error)
- func SetModelRefreshSideEffectsForTest(rebuild func(ctx context.Context, db *sqlx.DB) (RouteRebuildStats, error), ...) func()
- func SetRouteRebuildDB(db *sqlx.DB)
- func SitePublicMap(site store.Site) map[string]any
- func TempAccountFor(siteID int64, token string) string
- func TouchResinLease(accountID string)
- func UTLSEnabled(cfg *config.Config, site *store.Site) bool
- func UpdateAccountFields(db *sqlx.DB, accountID int64, updates map[string]any) error
- func UpdateAccountFieldsTx(tx *sqlx.Tx, accountID int64, updates map[string]any) error
- func UpdateSite(db *sqlx.DB, siteID int64, updates map[string]any) error
- func UpdateTodayIncomeSnapshot(extraConfig *string, todayIncome float64, now time.Time) *string
- func UpdateTokenFields(db *sqlx.DB, tokenID int64, updates map[string]any) error
- func UpsertSiteAPIEndpoints(tx *sqlx.Tx, siteID int64, endpoints []store.SiteAPIEndpoint) error
- func UpstreamPresetEndpointPaths(id, platform string) store.DirectEndpoints
- func ValidateProxyURL(raw string) error
- func ValidateSiteInitializationPreset(presetID, platform, rawURL string) error
- func VertexEndpointURL(baseURL, project, publisher string) (string, error)
- type AccountCapabilities
- type AccountCredentialMode
- type AccountListFilter
- type AccountModelRefreshResult
- type AccountWithSite
- type AutoReloginConfig
- type DetectResult
- type EstimateRewardInput
- type ImportAccountInput
- type ImportDuplicateStrategy
- type ImportSiteInput
- type ImportSiteItemResult
- type ImportSitesResult
- type LocalDayRange
- type ModelSyncSummary
- type PrimarySiteURLAnalysis
- type ProbeFilterConfig
- type ProxyRoutingStore
- func (s *ProxyRoutingStore) ClearAllRouteDecisionSnapshots(ctx context.Context) error
- func (s *ProxyRoutingStore) ClearRouteDecisionSnapshot(ctx context.Context, routeID int64) error
- func (s *ProxyRoutingStore) ClearRouteDecisionSnapshots(ctx context.Context, routeIDs []int64) error
- func (s *ProxyRoutingStore) FindAllEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
- func (s *ProxyRoutingStore) FindRouteIDsByOAuthRouteUnitID(ctx context.Context, unitID int64) ([]int64, error)
- func (s *ProxyRoutingStore) LoadChannelWithAccount(ctx context.Context, channelID int64) (..., error)
- func (s *ProxyRoutingStore) LoadChannelWithAccountAndRoute(ctx context.Context, channelID int64) (..., error)
- func (s *ProxyRoutingStore) LoadChannelsByAccountIDWithoutToken(ctx context.Context, accountID int64) ([]store.RouteChannel, error)
- func (s *ProxyRoutingStore) LoadChannelsByTokenID(ctx context.Context, tokenID int64) ([]store.RouteChannel, error)
- func (s *ProxyRoutingStore) LoadCredentialScopedChannelIDs(ctx context.Context, channel store.RouteChannel, accountID int64) ([]int64, error)
- func (s *ProxyRoutingStore) LoadEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
- func (s *ProxyRoutingStore) LoadOAuthRouteUnitMembers(ctx context.Context, unitIDs []int64) (map[int64][]routing.OAuthRouteUnitMemberCandidate, error)
- func (s *ProxyRoutingStore) LoadOAuthRouteUnitSummaries(ctx context.Context, unitIDs []int64) (map[int64]routing.OAuthRouteUnitSummary, error)
- func (s *ProxyRoutingStore) LoadRouteChannels(ctx context.Context, routeIDs []int64) ([]struct{ ... }, error)
- func (s *ProxyRoutingStore) LoadRouteGroupSources(ctx context.Context, groupRouteIDs []int64) (map[int64][]int64, error)
- func (s *ProxyRoutingStore) LoadRouteUnitMemberWithAccount(ctx context.Context, unitID, accountID int64) (..., error)
- func (s *ProxyRoutingStore) LoadRuntimeHealthChannelRows(ctx context.Context, channelIDs []int64) ([]struct{ ... }, error)
- func (s *ProxyRoutingStore) RecordDirectFailure(ctx context.Context, itemID int64, failure routing.SiteRuntimeFailureContext, ...) error
- func (s *ProxyRoutingStore) RecordDirectSuccess(ctx context.Context, itemID int64, latency, cost float64) error
- func (s *ProxyRoutingStore) UpdateChannelCooldownFields(ctx context.Context, channelIDs []int64, updates map[string]interface{}) error
- func (s *ProxyRoutingStore) UpdateChannelLastSelectedAt(ctx context.Context, channelID int64, lastSelectedAt string) error
- func (s *ProxyRoutingStore) UpdateChannelSuccessFields(ctx context.Context, channelID int64, updates map[string]interface{}) error
- func (s *ProxyRoutingStore) UpdateRouteDecisionSnapshot(ctx context.Context, routeID int64, snapshot string, refreshedAt string) error
- func (s *ProxyRoutingStore) UpdateRouteUnitMemberCooldownFields(ctx context.Context, memberID int64, updates map[string]interface{}) error
- func (s *ProxyRoutingStore) UpdateRouteUnitMemberLastSelectedAt(ctx context.Context, unitID, accountID int64, lastSelectedAt string) error
- func (s *ProxyRoutingStore) UpdateRouteUnitMemberSuccessFields(ctx context.Context, memberID int64, updates map[string]interface{}) error
- type RebuildOptions
- type RedirectFixCandidate
- type ResinLease
- type RouteRebuildStats
- type RuntimeHealthEntry
- type RuntimeHealthInput
- type RuntimeHealthSource
- type RuntimeHealthState
- type SiteInitializationPreset
- type TodayIncomeSnapshot
- type TokenDefaultSwitch
- type TokenSyncResult
- type UpstreamAPIToken
- type UpstreamPreset
- type UpstreamTokenListing
Constants ¶
const ( TokenValueStatusReady = "ready" TokenValueStatusMaskedPending = "masked_pending" )
const EffectiveProxyTokensOnActiveSitesSQL = `` /* 187-byte string literal not displayed */
EffectiveProxyTokensOnActiveSitesSQL is EffectiveProxyTokensSQL plus a site-status branch that zeroes rows of disabled sites. Use only for LEFT JOIN paths that keep all rows for counting but must not pollute token aggregates; requires the `s` alias. Under an INNER JOIN + active filter the branch is a no-op, so prefer the base expression there.
const EffectiveProxyTokensSQL = `` /* 153-byte string literal not displayed */
EffectiveProxyTokensSQL returns a SQL expression that prefers total_tokens and falls back to prompt_tokens + completion_tokens. Avoids under-counting partial upstream usage payloads and avoids double-counting when both are set. Requires the proxy_logs alias `pl`; site filtering (if any) is done by the caller's WHERE clause.
const MaxEventMessageBytes = 4096
MaxEventMessageBytes bounds events.message. A proxy request can carry an arbitrarily long model name, and the all-failed path writes it into an event; without a cap one request can inflate the database (and break backups) by megabytes.
const SiteSelectColumns = `` /* 408-byte string literal not displayed */
SiteSelectColumns lists known sites columns for SELECT (never SELECT *). Shared PG CI DBs may have leftover probe columns from schema experiments; SELECT * would fail struct scan with "missing destination name...".
const VertexProjectRule = "GCP project ID (6-30 lowercase letters, digits, hyphens) or project number"
VertexProjectRule is the operator-facing validation message.
Variables ¶
This section is empty.
Functions ¶
func AccountFor ¶ added in v0.13.0
AccountFor returns the stable Resin account identity for an existing account. The identity is acc-{Account.ID} using the immutable auto-increment PK. Returns "" when the account row has no ID yet (pre-account flows should use TempAccountFor instead).
func ApplyRedirectFixes ¶
func ApplyRedirectFixes(ctx context.Context, db *sqlx.DB, candidates []RedirectFixCandidate) (int, error)
ApplyRedirectFixes removes the disabled entries that ListRedirectFixCandidates reports (only after operator confirmation). Returns the number removed.
func ApplySiteStatusSideEffects ¶
ApplySiteStatusSideEffects handles status change side effects for sites.
func BuildMergedSub2ApiAuth ¶
func BuildMergedSub2ApiAuth(existingExtraConfig *string, refreshToken *string, tokenExpiresAt *int64, extraConfigPatch map[string]any) map[string]any
BuildMergedSub2ApiAuth builds the next sub2apiAuth object for a sub2api account. Sources (later wins for the same field): 1. existing extraConfig.sub2apiAuth 2. optional nested extraConfigPatch["sub2apiAuth"] 3. top-level refreshToken / tokenExpiresAt pointers
Returns nil when there are no valid fields to write (caller should leave extraConfig alone).
func BuildPlatformProxyConfig ¶
func BuildPlatformProxyConfig(cfg *config.Config, account *store.Account, site *store.Site) *platform.ProxyConfig
BuildPlatformProxyConfig resolves account and site proxy settings for platform calls.
Precedence (highest to lowest):
- key proxy (applied separately via proxy.ApplyKeyProxyOverride)
- account extraConfig.proxyUrl (explicit per-account proxy)
- site.ProxyURL (explicit per-site proxy)
- Resin sticky forward proxy (when RESIN_ENABLED and identity available)
- system proxy (account extraConfig.useSystemProxy or site.UseSystemProxy)
- direct (no proxy)
The Resin tier sits between explicit proxy URLs and the generic system-proxy opt-in so an operator who sets a per-account/per-site proxy still wins, but Resin takes priority over the shared SYSTEM_PROXY_URL. Resin requires a business identity: acc-{account.ID} when the account row exists. For pre-account flows (verify/login/create) with no account row yet, use BuildPlatformProxyConfigForToken which derives a deterministic temp identity.
func BuildPlatformProxyConfigForToken ¶ added in v0.13.0
func BuildPlatformProxyConfigForToken(cfg *config.Config, site *store.Site, rawToken string) *platform.ProxyConfig
BuildPlatformProxyConfigForToken is the pre-account variant of BuildPlatformProxyConfig for verify-token / login / create flows where no Account row exists yet. It derives a deterministic temp Resin identity from (siteID, rawToken) so all pre-account requests for the same token share an egress IP. Nothing carries that assignment over to the stable acc-{id} identity used once the Account row exists: the forward-proxy cache and the lease tracker are both keyed by identity, and the tracker is observability-only — resin.go is explicit that there is no TCP lease to release, so there is nothing to hand over.
Precedence matches BuildPlatformProxyConfig with the temp identity filling the resin slot: site.ProxyURL > resin(temp) > system > direct.
func BuildPlatformProxyConfigForTokenWithProxyURL ¶ added in v0.16.15
func BuildPlatformProxyConfigForTokenWithProxyURL(cfg *config.Config, site *store.Site, rawToken, proxyURL string) *platform.ProxyConfig
BuildPlatformProxyConfigForTokenWithProxyURL is the pre-account proxy builder for unsaved account-form values. A non-empty request override must win over the saved site proxy, Resin, and system proxy for the verification or create request; empty input keeps the normal site-level precedence.
func BuildStoredSub2ApiSubscriptionSummary ¶
BuildStoredSub2ApiSubscriptionSummary builds a storable subscription summary.
func BuildTimeFootnote ¶
BuildTimeFootnote builds the time footnote string for notifications.
func CanonicalFromActual ¶
CanonicalFromActual finds the canonical candidate for an actual model name. Rule priority: exact (case-folded) → date suffix → version suffix. Returns ok=false when no candidate matches. candidates are case-folded canonical names; canonicalName is the original (unfolded) form matched against.
func CanonicalizeSiteURL ¶
CanonicalizeSiteURL returns a canonical URL for persistence. Mirrors TS analyzePrimarySiteUrl().persistedUrl behavior.
func ClearResinLeasesForTest ¶ added in v0.13.0
func ClearResinLeasesForTest()
ClearResinLeasesForTest empties the lease tracker. Test-only — production relies on ActiveLeases' lazy pruning.
func CreateEvent ¶
func CreateEvent(db *sqlx.DB, eventType string, title string, message string, level string, relatedID int64, relatedType string) error
CreateEvent creates an event entry.
func CreateSite ¶
CreateSite creates a new site with apiEndpoints in a transaction.
func DecryptAccountPassword ¶
DecryptAccountPassword decrypts a ciphertext produced by EncryptAccountPassword. Returns empty string on any failure (mirrors TS: returns null/error silently).
func DecryptPassword ¶
DecryptPassword decrypts a password from extraConfig.
func DeleteAccount ¶
DeleteAccount deletes an account by ID.
func DeleteSite ¶
DeleteSite deletes a site by ID (cascade via DB foreign keys).
func DeleteTokenByID ¶
DeleteTokenByID deletes a token by ID with upstream-first strategy. The caller must handle the upstream deletion before calling this.
func DeriveVertexEndpoints ¶ added in v0.24.0
func DeriveVertexEndpoints(config store.DirectEndpoints, baseURL, project string) (store.DirectEndpoints, error)
DeriveVertexEndpoints substitutes project and region into the vertex endpoint templates of the preset config. Every URL field is visited; the result contains no placeholders.
func EncryptAccountPassword ¶
EncryptAccountPassword encrypts a password with AES-256-GCM. Returns "v1:base64url(iv):base64url(tag):base64url(ciphertext)". Mirrors TS encryptAccountPassword().
func EncryptPassword ¶
EncryptPassword encrypts a password for storage in extraConfig.autoRelogin.passwordCipher.
func EnsureDefaultTokenForAccount ¶
func EnsureDefaultTokenForAccount(db *sqlx.DB, accountID int64, tokenValue string, name, source, tokenGroup string, enabled bool) (int64, error)
EnsureDefaultTokenForAccount ensures a token exists and is default for a given account. Mirrors TS ensureDefaultTokenForAccount(), with preserve semantics: on an existing token match by value, operator-set name and enabled are kept (callers often pass name="default"; that must not clobber a real key name).
func EstimateRewardWithTodayIncomeFallback ¶
func EstimateRewardWithTodayIncomeFallback(input EstimateRewardInput) float64
EstimateRewardWithTodayIncomeFallback estimates reward using todayIncome fallback. Mirrors TS estimateRewardWithTodayIncomeFallback().
func FormatLocalDate ¶
FormatLocalDate formats a time in the local timezone as "2006-01-02". Mirrors TS formatLocalDate().
func FormatLocalDateTime ¶
FormatLocalDateTime formats a time in the local timezone as "2006-01-02 15:04:05". Mirrors TS formatLocalDateTime().
func FormatUtcSqlDateTime ¶
FormatUtcSqlDateTime formats a time as "YYYY-MM-DD HH:MM:SS" in UTC. Mirrors TS formatUtcSqlDateTime().
func ForwardProxyURL ¶ added in v0.13.0
ForwardProxyURL builds the HTTP forward-proxy URL with embedded proxy-auth userinfo. The username is "{Platform}.{Account}" and the password is the resin token. Go's http.Transport reads the proxy URL userinfo and emits the Proxy-Authorization: Basic header automatically — no manual header needed.
Returns ("", false) when Resin is misconfigured or platform/account empty.
func GenerateModelRedirects ¶
func GenerateModelRedirects(ctx context.Context, db *sqlx.DB, accountID int64, actualModels []string) (int, error)
GenerateModelRedirects sync-generates mappings for one account's actual model list. Best-effort: never overwrites manual rows, idempotent (upsert), updates last_seen_at for still-visible actual names. Returns the number of created mappings.
func GetAccountByID ¶
GetAccountByID fetches an account by its ID.
func GetDefaultTokenForAccount ¶
GetDefaultTokenForAccount returns the default token for an account.
func GetLocalTokenGroups ¶
GetLocalTokenGroups returns distinct token groups stored for the account.
func GetNextAccountSortOrder ¶
GetNextAccountSortOrder returns the next sortOrder value for new accounts.
func GetPlatformUserIdFromExtraConfig ¶
GetPlatformUserIdFromExtraConfig reads platformUserId from extraConfig.
func GetProxyURLFromExtraConfig ¶
GetProxyURLFromExtraConfig reads proxyUrl from extraConfig.
func GetResolvedTimeZone ¶
func GetResolvedTimeZone() string
GetResolvedTimeZone returns the current system timezone identifier. Mirrors TS getResolvedTimeZone().
func GetSub2ApiAuthFromExtraConfig ¶
GetSub2ApiAuthFromExtraConfig reads sub2apiAuth from extraConfig.
func GetTodayIncomeDelta ¶
GetTodayIncomeDelta returns the income delta for the current day. Mirrors TS getTodayIncomeDelta().
func GetTodayIncomeValue ¶
GetTodayIncomeValue returns the latest income value for the given day. Mirrors TS getTodayIncomeValue().
func GetTodayUnixSecondsRange ¶
GetTodayUnixSecondsRange returns the start and end of today as Unix timestamps. Mirrors TS getTodayUnixSecondsRange().
func GetTokenByID ¶
GetTokenByID fetches a token by its ID.
func GetTokenGroups ¶
func GetTokenGroups( ctx context.Context, db *sqlx.DB, accountID int64, adapter platform.PlatformAdapter, baseURL, accessToken string, platformUserID *int, proxy *platform.ProxyConfig, ) ([]string, error)
GetTokenGroups prefers platform.GetUserGroups for session accounts when an adapter and access token are available. Falls back to local DISTINCT token_group on adapter nil, missing access token, upstream error, or empty upstream result. Upstream errors are swallowed so local groups remain usable.
func GetUseSystemProxyFromExtraConfig ¶
GetUseSystemProxyFromExtraConfig reads useSystemProxy from extraConfig.
func GuessPlatformUserIdFromUsername ¶
GuessPlatformUserIdFromUsername attempts to parse the username as a numeric user ID.
func HasSessionToken ¶
HasSessionToken checks whether the account has a valid session token value.
func InsertAccount ¶
InsertAccount inserts a new account and returns the ID.
func InvalidateSiteCaches ¶
func InvalidateSiteCaches()
InvalidateSiteCaches invalidates both site proxy and token router caches.
func InvalidateSiteProxyCache ¶
func InvalidateSiteProxyCache()
InvalidateSiteProxyCache refreshes process-local caches that depend on site/proxy config. Always invalidates the token-router route cache; then runs registered hooks (admin accounts snapshot, future proxy config caches).
func InvalidateTokenRouterCache ¶
func InvalidateTokenRouterCache()
InvalidateTokenRouterCache signals that cached token-router state should be invalidated. Implemented in route_rebuild.go (delegates to routing.InvalidateCache).
func IsAPIKeyConnection ¶
IsAPIKeyConnection checks if an account is an API key connection.
func IsForbiddenPublicTargetURL ¶ added in v0.26.0
IsForbiddenPublicTargetURL applies the public-only outbound policy for targets supplied by an upstream response or another non-operator party. Unlike IsForbiddenSiteTargetURL it also rejects loopback, RFC1918, ULA and 0.0.0.0/8, and fails closed on unparseable or credential-bearing URLs.
func IsForbiddenSiteTargetURL ¶
IsForbiddenSiteTargetURL reports whether a site/endpoint URL must be rejected as a first-hop SSRF risk to cloud metadata / link-local targets. RFC1918 private and localhost remain allowed for lab/docker operators.
func IsManagedSub2ApiTokenDue ¶
IsManagedSub2ApiTokenDue checks if a managed Sub2Api token needs refresh. A token is "due" if it expires within the refresh lead window.
func IsMaskedPendingAccountToken ¶
func IsMaskedPendingAccountToken(token *store.AccountToken) bool
IsMaskedPendingAccountToken checks if a token is in masked-pending state.
func IsMaskedTokenValue ¶
IsMaskedTokenValue checks if a token value contains masking characters. Mirrors TS isMaskedTokenValue().
func IsSub2ApiPlatform ¶
IsSub2ApiPlatform checks if a platform is Sub2Api.
func IsUnsupportedCheckinRuntimeHealth ¶
func IsUnsupportedCheckinRuntimeHealth(health *RuntimeHealthEntry) bool
IsUnsupportedCheckinRuntimeHealth checks if the runtime health state represents an unsupported checkin degraded state that should be preserved during balance refresh. Mirrors TS isUnsupportedCheckinRuntimeHealth().
func IsUsableAccountToken ¶
func IsUsableAccountToken(token *store.AccountToken) bool
IsUsableAccountToken checks if a token is usable (ready + enabled).
func IsValidAPIEndpointURL ¶
IsValidAPIEndpointURL checks whether a normalized URL is a valid http(s) URL. Also rejects cloud metadata / link-local targets via IsForbiddenSiteTargetURL so any future caller is safe by default (parity with).
func IsValidHTTPURL ¶
IsValidHTTPURL checks whether a string is a valid http/https URL (not socks). Empty is valid (optional field). Also rejects cloud metadata / link-local targets via IsForbiddenSiteTargetURL so externalCheckin and similar callers cannot store first-hop SSRF URLs (extends).
func IsValidProxyURL ¶
IsValidProxyURL checks whether a string is a valid http(s)/socks proxy URL.
func ListAccountsWithSites ¶
ListAccountsWithSites returns all accounts joined with their sites. Each account is enriched with nested site, capabilities, credentialMode, and effective runtimeHealth (expired status never reports healthy).
func ListAccountsWithSitesPaginated ¶ added in v0.13.0
func ListAccountsWithSitesPaginated(db *sqlx.DB, limit, offset int, filter AccountListFilter) ([]map[string]any, int64, error)
ListAccountsWithSitesPaginated returns a single page of accounts joined with their sites, plus the total row count matching the same join (and the same optional filter, so `total` is the true filtered count). Enrichment is identical to ListAccountsWithSites so a paginated page is byte-compatible with a slice of the unpaginated snapshot. Used by GET /api/accounts?page=... to bound the admin list response when the fleet grows (defensive pagination, same envelope as /api/channels and /api/checkin/logs).
func ListSites ¶
ListSites returns all sites with apiEndpoints, totalBalance, and subscriptionSummary.
func ListTokensWithRelations ¶
ListTokensWithRelations returns tokens with account and site relations. Mirrors TS listTokensWithRelations().
func LoadSiteAPIEndpoints ¶
LoadSiteAPIEndpoints loads all api endpoints for a list of site IDs.
func LoadSiteWithEndpoints ¶
LoadSiteWithEndpoints loads a single site with its apiEndpoints attached.
func MarshalExtraConfig ¶
MarshalExtraConfig marshals a map to a JSON string.
func MergeExtraConfig ¶
MergeExtraConfig merges a patch into an existing extraConfig JSON string. A nil patch value (untyped nil) deletes the key; callers must not pass a typed nil pointer, which would marshal to JSON null instead of deleting.
func MergeSub2ApiAuth ¶
MergeSub2ApiAuth merges managed auth fields onto an existing sub2apiAuth map. Valid new values overwrite; invalid/missing values preserve existing keys. Unrelated keys on existing are always preserved. Returns nil when empty.
func NativeChatRequestProfile ¶ added in v0.24.0
NativeChatRequestProfile resolves the thinking contract of a recognized provider URL. Arbitrary compatible hosts do not inherit a brand's profile.
func NormalizeGlobalWeight ¶
func NormalizeManagedRefreshToken ¶
NormalizeManagedRefreshToken accepts a non-empty trimmed string refresh token. Returns ok=false for nil/empty/invalid values so callers preserve existing auth.
func NormalizeManagedTokenExpiresAt ¶
NormalizeManagedTokenExpiresAt accepts a positive Unix timestamp in milliseconds (number or numeric string). Legacy epoch-seconds values are accepted and normalized to milliseconds for TS/API compatibility.
func NormalizeNullable ¶
NormalizeNullable returns nil for empty string, the value otherwise.
func NormalizeSiteAPIEndpointBaseUrl ¶
NormalizeSiteAPIEndpointBaseUrl normalizes a site API endpoint URL. Mirrors TS normalizeSiteApiEndpointBaseUrl(): parse URL, strip search/hash, remove trailing slash.
func NormalizeSortOrder ¶
func NormalizeTokenForDisplay ¶
NormalizeTokenForDisplay normalizes a token for display. Mirrors TS normalizeTokenForDisplay().
func NormalizeTokenGroups ¶
NormalizeTokenGroups trims, de-duplicates, and ensures a non-empty result. When every input is blank, returns ["default"].
func ParseExtraConfig ¶
ParseExtraConfig parses an extraConfig field (JSON string) as a map.
func PopulateRouteChannelsByModelPattern ¶
func PopulateRouteChannelsByModelPattern(ctx context.Context, db *sqlx.DB, routeID int64, modelPattern string) (inserted int, err error)
PopulateRouteChannelsByModelPattern is the create-path helper: insert automatic channels for a newly created pattern route without wiping existing rows.
func ProxyAwareHTTPClient ¶
ProxyAwareHTTPClient creates an *http.Client that optionally routes through a proxy. If proxyURL is empty or fails to parse, the client dials directly and never consults HTTP_PROXY/HTTPS_PROXY environment variables.
The client always wires platform.RejectCrossOriginRedirect so callers (notably notify/telegram) cannot follow a public-origin 302 onto a different host. Phase bounds keep this helper's historical values (dial 10s, TLS 10s, response-header phase = timeout) on the shared httpclient baseline; the whole-request timeout is the caller's value.
func RebuildRoutesBestEffort ¶
func RebuildRoutesBestEffort()
RebuildRoutesBestEffort rebuilds pattern-route channels from current model availability and invalidates the token-router cache. Failures are logged and swallowed so account/site mutation paths stay best-effort.
func RedactAccountSecrets ¶ added in v0.17.0
RedactAccountSecrets removes plaintext credentials from an admin account response map, setting accessTokenMasked / apiTokenMasked when a value was present, and stripping every credential-shaped field from nested config.
This is the single credential-policy SSOT for account surfaces. Both the list/overview rows (buildAccountMap), search rows, and the write responses (PUT /api/accounts/{id}, POST /api/accounts/{id}/rebind-session) answer through it, so a no-op write can never harvest what the list surface deliberately withholds. Revealing a secret stays an explicit, separately routed act (GET /api/account-tokens/{id}/value, downstream-key export), and the credential-provisioning responses that hand back a secret the caller did not supply (password login, verify-token discovery) build their own maps.
extraConfig carries credentials in several shapes: oauth.refreshToken / idToken / sessionToken / accessToken, sub2apiAuth.refreshToken, and autoRelogin.passwordCipher. Instead of enumerating today's field names, the nested walker drops every key whose normalized name contains token, secret, cipher, password, or apikey. Display metadata (oauth provider/email/plan, tokenExpiresAt, account names, proxyUrl, ...) survives because numeric and boolean values are kept. Masked projections are kept by their suffix.
Values arrive either scanned from the DB (string / []byte / nil) or built by a handler from a typed struct row (*string), so secretValue() normalizes both instead of letting fmt.Sprint render a pointer address as the "secret".
func RedactSiteCredentials ¶ added in v0.26.0
RedactSiteCredentials applies the admin site credential policy to a site map: apiKey becomes a masked projection plus hasApiKey, and cfClearance (a live Cloudflare clearance cookie) is removed. Both GET /api/sites and search rows (scanned as maps) answer through this helper, so the two surfaces cannot drift.
func RefreshAccountPricing ¶ added in v0.26.0
RefreshAccountPricing is an explicit bounded management request. Reading the comparison page never triggers upstream requests.
func RegisterSiteProxyCacheInvalidator ¶
func RegisterSiteProxyCacheInvalidator(fn func())
RegisterSiteProxyCacheInvalidator appends a hook invoked by InvalidateSiteProxyCache. Safe for concurrent registration; hooks should be idempotent and non-blocking.
func ReloadRedirectRegistry ¶
ReloadRedirectRegistry reloads the in-process redirect registry from model_name_redirects so the routing hot path sees the latest canonical→actual mappings. Call at startup and after any redirect mutation (sync generation, manual edits, deletes). Best-effort: on query failure it logs and leaves the previous registry intact.
func RepairDefaultToken ¶
RepairDefaultToken finds and sets a new default token for an account. Mirrors TS repairDefaultToken().
func ResinEnabled ¶ added in v0.13.0
ResinEnabled reports whether Resin is active for the given site.
Precedence:
- site.ResinEnabled non-nil → explicit per-site override wins (true = force-enable even when global is off; false = force-disable even when global is on). This is the per-site override (#678).
- site.ResinEnabled nil → fall back to the global RESIN_ENABLED flag, which itself requires a non-empty RESIN_URL.
When site is nil only the global flag is consulted (used by wss runtime paths that don't have a site row in scope — the URL-rewrite / header gates there are advisory; per-site filtering already happened upstream in BuildPlatformProxyConfig).
func ResinGlobalEnabled ¶ added in v0.13.0
ResinGlobalEnabled reports whether the global RESIN_ENABLED flag is set and a non-empty RESIN_URL is configured. This is the configuration-only view (ignores per-site overrides) and is used by the /api/admin/resin/status endpoint to surface the operator-facing global toggle state.
func ResolveAccountTokenValueStatus ¶
func ResolveAccountTokenValueStatus(tokenRow *store.AccountToken) string
ResolveAccountTokenValueStatus resolves the valueStatus for a token.
func ResolvePlatformUserID ¶
ResolvePlatformUserID resolves the platform user ID from extraConfig or username.
func ResolvePlatformUserIDPtr ¶
ResolvePlatformUserIDPtr returns a *int platform user id when one can be resolved from account extraConfig or a numeric username.
func ResolveResinPlatform ¶ added in v0.13.0
ResolveResinPlatform resolves the Platform identity: explicit config value wins, otherwise fall back to the site's platform. Returns "" when neither is available.
func RewriteWSURL ¶ added in v0.13.0
RewriteWSURL rewrites a target wss/ws URL into Resin reverse-proxy form:
ws://{host}:{port}/{token}/{Platform}/{protocol}/{targetHost}{path}?query
where protocol is "https" for wss targets and "http" for ws targets (Resin requires the client→resin leg to always be ws). The Account identity is NOT embedded in the URL — it is sent via the X-Resin-Account header (handled by the caller). Returns "" when Resin is misconfigured, the platform/account is empty, or the target URL is not ws/wss.
func SanitizeImportedSiteRows ¶ added in v0.16.21
SanitizeImportedSiteRows drops imported rows whose outbound-target URL columns point at forbidden targets (cloud metadata / link-local). Empty or absent values pass (nullable columns; IsForbiddenSiteTargetURL is empty-tolerant). Returns the surviving rows and how many were dropped. Tables without guarded columns are returned unchanged.
func SetAccountRuntimeHealth ¶
func SetAccountRuntimeHealth(db *sqlx.DB, accountID int64, entry RuntimeHealthEntry) error
SetAccountRuntimeHealth writes runtime health state into the account's extraConfig. Mirrors TS setAccountRuntimeHealth().
func SetDefaultToken ¶
SetDefaultToken sets a token as the default for its account. Mirrors TS setDefaultToken().
func SetModelRefreshSideEffectsForTest ¶ added in v0.16.16
func SetModelRefreshSideEffectsForTest( rebuild func(ctx context.Context, db *sqlx.DB) (RouteRebuildStats, error), invalidate func(), ) func()
SetModelRefreshSideEffectsForTest swaps the rebuild/invalidate seams used by the refresh path and returns a restore function. Test-only.
func SetRouteRebuildDB ¶
SetRouteRebuildDB sets the SQL handle used by RebuildRoutesBestEffort when store.GetDB() is not initialized (tests). Pass nil to clear.
func SitePublicMap ¶ added in v0.26.0
SitePublicMap returns the admin-safe site projection without loading sub-resources. Account list responses also embed sites and must answer with the same credential policy as GET /api/sites instead of marshaling store.Site, whose JSON tags would expose apiKey and cfClearance.
func TempAccountFor ¶ added in v0.13.0
TempAccountFor returns a deterministic temp Resin identity for pre-account flows (verify/login/create) so all requests for the same token land on the same egress IP. The identity is tmp-{sha1(siteID:token) first 16 hex chars}. siteID may be 0; the identity remains deterministic per token.
The identity NEVER contains '.' or ':' (sha1 hex output is [0-9a-f]) so it is safe for Resin's proxy-auth splitting.
func TouchResinLease ¶ added in v0.13.0
func TouchResinLease(accountID string)
TouchResinLease records that accountID used Resin "now". Safe for concurrent calls; no-op when accountID is empty.
func UTLSEnabled ¶ added in v0.13.0
UTLSEnabled resolves whether uTLS TLS fingerprint masking is active for a site. Per-site UseUTLS overrides the global UTLS_ENABLED flag:
- site.UseUTLS != nil → explicit per-site decision (true/false)
- site.UseUTLS == nil → fall back to cfg.UTLSEnabled (global default)
Mirrors the ResinEnabled resolution pattern so operators can globally opt in via UTLS_ENABLED=true and selectively disable specific sites with use_utls=false.
func UpdateAccountFields ¶
UpdateAccountFields updates specific fields on an account. UpdateAccountFields writes a set of account columns in one UPDATE.
func UpdateAccountFieldsTx ¶ added in v0.16.2
UpdateAccountFieldsTx is the transaction variant of UpdateAccountFields. Use it within the same transaction that read-locked the account row so the read-merge-write of extra_config commits atomically (no lost updates).
func UpdateSite ¶
UpdateSite updates a site and its apiEndpoints in a transaction.
func UpdateTodayIncomeSnapshot ¶
UpdateTodayIncomeSnapshot updates the todayIncome snapshot in extraConfig. Mirrors TS updateTodayIncomeSnapshot().
func UpdateTokenFields ¶
UpdateTokenFields updates specific fields on a token.
func UpsertSiteAPIEndpoints ¶
UpsertSiteAPIEndpoints replaces all apiEndpoints for a site within a transaction.
func UpstreamPresetEndpointPaths ¶ added in v0.24.0
func UpstreamPresetEndpointPaths(id, platform string) store.DirectEndpoints
UpstreamPresetEndpointPaths returns every executable endpoint of a product. Paths are relative to the per-protocol bases on the resolved preset. The platform parameter remains for source compatibility with older callers.
func ValidateProxyURL ¶ added in v0.26.0
ValidateProxyURL validates an optional egress proxy URL. Empty means "no proxy" and is valid. A non-empty value needs a supported scheme, a host, and no whitespace or control characters: storing a value the transport cannot dial would silently disable egress, and control characters can split the URL across transport layers. Private/loopback targets are intentionally allowed here — internal proxies are a legitimate deployment; outbound destination guarding is enforced by the site dial guard instead.
func ValidateSiteInitializationPreset ¶
ValidateSiteInitializationPreset checks createSite initializationPresetId. Empty id is allowed (optional field). When set: 1. preset must exist 2. preset.platform must equal the resolved site platform 3. when the preset has host/path match rules, the URL must match those rules (or the defaultUrl persisted-url fallback when platform-filtered).
func VertexEndpointURL ¶ added in v0.24.0
VertexEndpointURL composes the publisher-models prefix for one Vertex channel base URL and project. ModelPath appends {model}:{action} to it.
Types ¶
type AccountCapabilities ¶
type AccountCapabilities struct {
CanCheckin bool `json:"canCheckin"`
CanRefreshBalance bool `json:"canRefreshBalance"`
ProxyOnly bool `json:"proxyOnly"`
}
AccountCapabilities describes what an account can do.
func BuildCapabilitiesForAccount ¶
func BuildCapabilitiesForAccount(account *store.Account) AccountCapabilities
BuildCapabilitiesForAccount returns the capabilities for an account.
func BuildCapabilitiesFromCredentialMode ¶
func BuildCapabilitiesFromCredentialMode(mode AccountCredentialMode, hasSessionToken bool) AccountCapabilities
BuildCapabilitiesFromCredentialMode returns capabilities from credential mode.
type AccountCredentialMode ¶
type AccountCredentialMode string
AccountCredentialMode is the credential mode for an account.
const ( CredentialModeAuto AccountCredentialMode = "auto" CredentialModeSession AccountCredentialMode = "session" CredentialModeAPIKey AccountCredentialMode = "apikey" )
func GetCredentialModeFromExtraConfig ¶
func GetCredentialModeFromExtraConfig(extraConfig *string) AccountCredentialMode
GetCredentialModeFromExtraConfig reads credentialMode from extraConfig JSON.
func NormalizeCredentialMode ¶
func NormalizeCredentialMode(input string) AccountCredentialMode
NormalizeCredentialMode normalizes a credential mode string.
func ResolveRequestedCredentialMode ¶
func ResolveRequestedCredentialMode(input *string) AccountCredentialMode
ResolveRequestedCredentialMode resolves the requested credential mode from input.
func ResolveStoredCredentialMode ¶
func ResolveStoredCredentialMode(account *store.Account) AccountCredentialMode
ResolveStoredCredentialMode resolves the effective credential mode from storage. 1. Read extraConfig.credentialMode; if explicit and != "auto", return it 2. Treat legacy mirrored accessToken/apiToken rows as "apikey" 3. If accessToken is non-empty, return "session" 4. Otherwise return "apikey"
type AccountListFilter ¶ added in v0.16.20
type AccountListFilter struct {
// Statuses is a whitelisted subset of the account status domain
// (active / disabled / expired). Empty means "no status filter".
Statuses []string
// SiteIDs narrows to the given sites. Empty means "all sites".
SiteIDs []int64
// Query is a case-insensitive substring match over username and site
// name/url/platform (mirrors the frontend's old client-side haystack).
// Empty means "no search filter".
Query string
}
AccountListFilter narrows the paginated accounts list server-side so the admin UI filters the whole fleet, not just the loaded page (issue #1108: client-side filters over a server-paginated table could never match rows on other pages).
type AccountModelRefreshResult ¶ added in v0.16.16
type AccountModelRefreshResult struct {
Success bool
ErrorCode string // "" on success; db_unavailable / not_found / disabled / inactive / unsupported_platform / missing_credential / timeout / unauthorized / upstream_error / empty_models / persist_failed
ErrorMessage string // refresh.errorMessage payload field
Message string // optional top-level "message" payload field
TopError string // top-level "error" payload field (db_unavailable / not_found paths)
Models []string // cleaned upstream model list (also on empty/persist failures)
CheckedAt string // RFC3339 availability write timestamp (success only)
TokenBackfilled bool
RedirectsCreated int
Rebuild RouteRebuildStats
RebuildErr error
RebuildRan bool // false when the caller deferred the rebuild (batch mode)
}
AccountModelRefreshResult carries the outcome of one account model refresh. The handler layer maps it onto the operator-facing JSON payload; the scheduler consumes the counters directly.
func RefreshAccountModels ¶ added in v0.16.16
func RefreshAccountModels(ctx context.Context, db *sqlx.DB, accountID int64, allowInactive, skipRebuild bool) AccountModelRefreshResult
RefreshAccountModels performs a real platform.GetModels refresh and persists results into model_availability.
allowInactive=true permits non-active accounts (e.g. expired) to refresh so recovery workflows can validate new credentials before reactivation. Disabled accounts are always rejected.
skipRebuild=true defers the route rebuild + routing-cache invalidation to the caller (periodic batch mode rebuilds exactly once after the whole pass); the single-account admin path passes false and rebuilds inline.
type AccountWithSite ¶
GetAccountWithSite joins account with site.
func GetAccountWithSiteByID ¶
func GetAccountWithSiteByID(db *sqlx.DB, id int64) (*AccountWithSite, error)
GetAccountWithSiteByID reads an account joined with its site (no row lock).
func GetAccountWithSiteByIDForUpdate ¶ added in v0.16.2
func GetAccountWithSiteByIDForUpdate(q accountQueryExecer, id int64) (*AccountWithSite, error)
GetAccountWithSiteByIDForUpdate reads the account joined with its site while locking the accounts row (PostgreSQL only: FOR UPDATE OF a; SQLite's single-connection pool already serializes transactions). Call it inside a transaction to make read-merge-write of mutable columns — notably extra_config — safe against concurrent lost updates.
type AutoReloginConfig ¶
AutoReloginConfig holds credentials for auto-relogin.
func GetAutoReloginConfig ¶
func GetAutoReloginConfig(extraConfig *string) *AutoReloginConfig
GetAutoReloginConfig reads autoRelogin from extraConfig. Returns nil if not configured.
type DetectResult ¶
type DetectResult struct {
URL string `json:"url"`
CanonicalURL string `json:"canonicalUrl"`
Platform string `json:"platform"`
SiteType string `json:"siteType"`
Confidence float64 `json:"confidence"`
InitializationPresetID *string `json:"initializationPresetId,omitempty"`
}
DetectResult is the result of platform detection.
Platform/SiteType both hold the detected platform (SiteType mirrors the TS "siteType" naming; Platform is retained for backward compatibility with the existing /api/sites/detect consumers). Confidence is a coarse signal of how the platform was resolved (preset match = 1.0, hostname heuristic = 0.8). CanonicalURL is the normalized URL suitable for persistence/dedup.
func DetectSite ¶
func DetectSite(rawURL string) *DetectResult
DetectSite attempts to detect the platform for a given URL. When a site initialization preset matches the URL, the result uses the preset adapter and includes initializationPresetId. Otherwise falls back to hostname heuristics for vendor/platform tags.
type EstimateRewardInput ¶
type EstimateRewardInput struct {
Day string
SuccessCount int
ParsedRewardCount int
RewardSum float64
ExtraConfig *string
}
EstimateRewardInput is the input for EstimateRewardWithTodayIncomeFallback.
type ImportAccountInput ¶ added in v0.11.0
type ImportAccountInput struct {
Username *string `json:"username,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
APIToken string `json:"apiToken,omitempty"`
}
ImportAccountInput is a lightweight account definition attached to an imported site. Imported accounts are stored as skipModelFetch API-key style credentials: the import wizard defers upstream model discovery to the normal background refresh instead of blocking the batch on per-account verification.
type ImportDuplicateStrategy ¶ added in v0.11.0
type ImportDuplicateStrategy string
ImportDuplicateStrategy controls how already-present sites are handled.
const ( ImportDuplicateSkip ImportDuplicateStrategy = "skip" ImportDuplicateMerge ImportDuplicateStrategy = "merge" )
type ImportSiteInput ¶ added in v0.11.0
type ImportSiteInput struct {
Name string `json:"name"`
URL string `json:"url"`
Platform string `json:"platform,omitempty"`
GlobalWeight *float64 `json:"globalWeight,omitempty"`
MaxConcurrency *int64 `json:"maxConcurrency,omitempty"`
DuplicateStrategy ImportDuplicateStrategy `json:"duplicateStrategy,omitempty"`
Accounts []ImportAccountInput `json:"accounts,omitempty"`
}
ImportSiteInput is one candidate site in a batch import.
type ImportSiteItemResult ¶ added in v0.11.0
type ImportSiteItemResult struct {
Name string `json:"name"`
URL string `json:"url"`
Status string `json:"status"` // imported | merged | skipped | failed
Reason string `json:"reason,omitempty"`
SiteID int64 `json:"siteId,omitempty"`
}
ImportSiteItemResult is the per-item outcome of a batch import.
type ImportSitesResult ¶ added in v0.11.0
type ImportSitesResult struct {
Imported int `json:"imported"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
Results []ImportSiteItemResult `json:"results"`
}
ImportSitesResult is the batch import summary. Imported counts sites that were newly created plus sites whose accounts were merged into an existing site; skipped counts idempotent duplicate no-ops; failed counts hard errors.
func ImportSites ¶ added in v0.11.0
func ImportSites(db *sqlx.DB, items []ImportSiteInput, strategy ImportDuplicateStrategy) (*ImportSitesResult, error)
ImportSites creates sites (and optional accounts) idempotently. A site is considered a duplicate when (platform, canonical url) already exists; with skip it is a no-op, with merge any provided accounts are attached to the existing site. Re-running the same payload therefore converges to imported=0, skipped=N.
type LocalDayRange ¶
LocalDayRange holds the day range boundaries.
func GetLocalDayRangeUTC ¶
func GetLocalDayRangeUTC(t time.Time) LocalDayRange
GetLocalDayRangeUTC returns the local day string and its UTC boundary timestamps. Mirrors TS getLocalDayRangeUtc().
type ModelSyncSummary ¶ added in v0.16.16
type ModelSyncSummary struct {
Total int
Success int
Failed int
Rebuild RouteRebuildStats
RebuildErr error
}
ModelSyncSummary reports one periodic model-sync pass. Every pass ends with exactly one rebuild, so there is no "did it run" flag to report.
func SyncAllAccountModels ¶ added in v0.16.16
func SyncAllAccountModels(ctx context.Context, db *sqlx.DB) ModelSyncSummary
SyncAllAccountModels refreshes upstream model lists for all candidate accounts sequentially (polite to upstreams, no concurrency races). Each account refresh skips its own route rebuild; after the pass exactly one route rebuild + one routing-cache invalidation runs for the whole batch. Per-account failures are logged and counted without aborting the pass.
The closing rebuild always runs, on a context that survives this one (#1174). It only reads and writes the local database — the upstream work is already over — so abandoning it because the pass hit a deadline or its caller went away left routes composed from an older view of availability, which is worse than finishing the cheap local step. When nothing changed it short-circuits without a single write, so "always" costs a read pass, not churn.
type PrimarySiteURLAnalysis ¶
type PrimarySiteURLAnalysis struct {
CanonicalURL string
PersistedURL string
MatchedPath string
Action string
}
PrimarySiteURLAnalysis mirrors web/shared/sitePrimaryUrl.js analyzePrimarySiteUrl.
func AnalyzePrimarySiteURL ¶
func AnalyzePrimarySiteURL(rawURL string) PrimarySiteURLAnalysis
AnalyzePrimarySiteURL ports analyzePrimarySiteUrl for preset fallback matching.
type ProbeFilterConfig ¶ added in v0.11.0
ProbeFilterConfig gates the route-rebuild probe filter (#625). IncludeModels/ExcludeModels are optional exact source-model names; empty means no-op. When Enabled, desired channels whose latest connectivity probe failed are dropped before any route_channels diff is written.
type ProxyRoutingStore ¶ added in v0.12.0
type ProxyRoutingStore struct {
// contains filtered or unexported fields
}
func NewProxyRoutingStore ¶ added in v0.12.0
func NewProxyRoutingStore(db *store.DB) *ProxyRoutingStore
func (*ProxyRoutingStore) ClearAllRouteDecisionSnapshots ¶ added in v0.12.0
func (s *ProxyRoutingStore) ClearAllRouteDecisionSnapshots(ctx context.Context) error
ClearAllRouteDecisionSnapshots clears every route decision snapshot.
func (*ProxyRoutingStore) ClearRouteDecisionSnapshot ¶ added in v0.12.0
func (s *ProxyRoutingStore) ClearRouteDecisionSnapshot(ctx context.Context, routeID int64) error
ClearRouteDecisionSnapshot clears one route decision snapshot.
func (*ProxyRoutingStore) ClearRouteDecisionSnapshots ¶ added in v0.12.0
func (s *ProxyRoutingStore) ClearRouteDecisionSnapshots(ctx context.Context, routeIDs []int64) error
ClearRouteDecisionSnapshots clears decision snapshots for the given route IDs.
func (*ProxyRoutingStore) FindAllEnabledRoutes ¶ added in v0.12.0
func (s *ProxyRoutingStore) FindAllEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
func (*ProxyRoutingStore) FindRouteIDsByOAuthRouteUnitID ¶ added in v0.12.0
func (*ProxyRoutingStore) LoadChannelWithAccount ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadChannelWithAccount(ctx context.Context, channelID int64) (*struct { Channel store.RouteChannel Account store.Account }, error)
func (*ProxyRoutingStore) LoadChannelWithAccountAndRoute ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadChannelWithAccountAndRoute(ctx context.Context, channelID int64) (*struct { Channel store.RouteChannel Account store.Account Route store.TokenRoute }, error)
func (*ProxyRoutingStore) LoadChannelsByAccountIDWithoutToken ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadChannelsByAccountIDWithoutToken(ctx context.Context, accountID int64) ([]store.RouteChannel, error)
func (*ProxyRoutingStore) LoadChannelsByTokenID ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadChannelsByTokenID(ctx context.Context, tokenID int64) ([]store.RouteChannel, error)
func (*ProxyRoutingStore) LoadCredentialScopedChannelIDs ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadCredentialScopedChannelIDs(ctx context.Context, channel store.RouteChannel, accountID int64) ([]int64, error)
func (*ProxyRoutingStore) LoadEnabledRoutes ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadEnabledRoutes(ctx context.Context) ([]store.TokenRoute, error)
func (*ProxyRoutingStore) LoadOAuthRouteUnitMembers ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadOAuthRouteUnitMembers(ctx context.Context, unitIDs []int64) (map[int64][]routing.OAuthRouteUnitMemberCandidate, error)
func (*ProxyRoutingStore) LoadOAuthRouteUnitSummaries ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadOAuthRouteUnitSummaries(ctx context.Context, unitIDs []int64) (map[int64]routing.OAuthRouteUnitSummary, error)
func (*ProxyRoutingStore) LoadRouteChannels ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadRouteChannels(ctx context.Context, routeIDs []int64) ([]struct { Channel store.RouteChannel Account store.Account Site store.Site Token *store.AccountToken }, error)
func (*ProxyRoutingStore) LoadRouteGroupSources ¶ added in v0.12.0
func (*ProxyRoutingStore) LoadRouteUnitMemberWithAccount ¶ added in v0.12.0
func (s *ProxyRoutingStore) LoadRouteUnitMemberWithAccount(ctx context.Context, unitID, accountID int64) (*struct { Member store.OAuthRouteUnitMember Account store.Account Unit store.OAuthRouteUnit }, error)
func (*ProxyRoutingStore) LoadRuntimeHealthChannelRows ¶ added in v0.12.0
func (*ProxyRoutingStore) RecordDirectFailure ¶ added in v0.23.0
func (s *ProxyRoutingStore) RecordDirectFailure(ctx context.Context, itemID int64, failure routing.SiteRuntimeFailureContext, configuredMaxSec int) error
func (*ProxyRoutingStore) RecordDirectSuccess ¶ added in v0.23.0
func (*ProxyRoutingStore) UpdateChannelCooldownFields ¶ added in v0.12.0
func (*ProxyRoutingStore) UpdateChannelLastSelectedAt ¶ added in v0.12.0
func (*ProxyRoutingStore) UpdateChannelSuccessFields ¶ added in v0.12.0
func (*ProxyRoutingStore) UpdateRouteDecisionSnapshot ¶ added in v0.12.0
func (s *ProxyRoutingStore) UpdateRouteDecisionSnapshot(ctx context.Context, routeID int64, snapshot string, refreshedAt string) error
UpdateRouteDecisionSnapshot persists a route decision explanation snapshot.
func (*ProxyRoutingStore) UpdateRouteUnitMemberCooldownFields ¶ added in v0.12.0
func (*ProxyRoutingStore) UpdateRouteUnitMemberLastSelectedAt ¶ added in v0.12.0
func (*ProxyRoutingStore) UpdateRouteUnitMemberSuccessFields ¶ added in v0.12.0
type RebuildOptions ¶ added in v0.11.0
type RebuildOptions struct {
CreateModelRoutes bool
ProbeFilter ProbeFilterConfig
}
RebuildOptions configures optional rebuild behavior. The zero value keeps the legacy non-probe path byte-for-byte identical.
type RedirectFixCandidate ¶
type RedirectFixCandidate struct {
SiteID int64 `db:"site_id" json:"siteId"`
SiteName string `db:"site_name" json:"siteName"`
AccountID int64 `db:"account_id" json:"accountId"`
ModelName string `db:"model_name" json:"modelName"`
Canonical string `db:"canonical" json:"canonical"`
Actual string `db:"actual" json:"actual"`
}
RedirectFixCandidate is one disabled-model entry that a redirect can fix.
func ListRedirectFixCandidates ¶
ListRedirectFixCandidates finds site_disabled_models entries whose model is a redirect canonical with an actually-available upstream model (available=1 in model_availability). These are safe to re-enable once confirmed.
type ResinLease ¶ added in v0.13.0
ResinLease is one entry in the active-lease snapshot returned by ActiveLeases and surfaced by GET /api/admin/resin/status.
func ActiveLeases ¶ added in v0.13.0
func ActiveLeases() []ResinLease
ActiveLeases returns the list of Resin account IDs whose last-used timestamp is fresher than resinLeaseStaleTTL, plus that timestamp in UTC RFC3339. Stale entries are pruned in-place so the snapshot stays bounded under long-running processes with high account churn.
type RouteRebuildStats ¶
type RouteRebuildStats struct {
RoutesCreated int `json:"routesCreated"`
UnsafeModelsSkipped int `json:"unsafeModelsSkipped"`
RoutesConsidered int `json:"routesConsidered"`
PatternRoutes int `json:"patternRoutes"`
GroupRoutes int `json:"groupRoutes"`
ChannelsInserted int `json:"channelsInserted"`
ChannelsRemoved int `json:"channelsRemoved"`
ChannelsKept int `json:"channelsKept"`
// Changed covers newly created routes and automatic channel changes.
Changed bool `json:"changed"`
}
RouteRebuildStats summarizes a synchronous rebuild pass. explicit_group routes do not materialize their own channels; they expand source routes at selection time via route_group_sources.
func RebuildTokenRoutesFromAvailability ¶
func RebuildTokenRoutesFromAvailability(ctx context.Context, db *sqlx.DB) (RouteRebuildStats, error)
RebuildTokenRoutesFromAvailability is the non-probe rebuild entrypoint. Model route creation follows the opt-in runtime setting (default off); the in-process cache is always invalidated after the pass.
func RebuildTokenRoutesFromAvailabilityWithOptions ¶ added in v0.11.0
func RebuildTokenRoutesFromAvailabilityWithOptions(ctx context.Context, db *sqlx.DB, opts RebuildOptions) (RouteRebuildStats, error)
RebuildTokenRoutesFromAvailabilityWithOptions repopulates automatic (non-manual) channels for every pattern/exact route from dual sources: 1. manual channels on exact-model routes whose model_pattern matches the target pattern 2. token_model_availability + model_availability rows whose model_name matches
explicit_group routes are counted but not rewritten: their membership is route_group_sources, and channel expansion happens at select time. Manual override channels on pattern routes are never deleted.
When opts.ProbeFilter.Enabled is true, desired channels are filtered by include/exclude model lists plus the latest connectivity probe result before any diff is written, and the cache is invalidated only when the model set actually changes. The zero-value RebuildOptions{} preserves legacy behavior.
Concurrent rebuilds serialize on a process-wide mutex.
type RuntimeHealthEntry ¶
type RuntimeHealthEntry struct {
State RuntimeHealthState `json:"state"`
Reason string `json:"reason"`
Source RuntimeHealthSource `json:"source"`
CheckedAt *string `json:"checkedAt,omitempty"`
}
RuntimeHealthEntry is a single runtime health record stored in extraConfig.
func BuildRuntimeHealthForAccount ¶
func BuildRuntimeHealthForAccount(input RuntimeHealthInput) RuntimeHealthEntry
BuildRuntimeHealthForAccount returns the effective runtime health for admin list/detail. Expired account status always reports unhealthy (auth), never healthy — expired status. Mirrors TS buildRuntimeHealthForAccount().
func ExtractRuntimeHealth ¶
func ExtractRuntimeHealth(extraConfig *string) *RuntimeHealthEntry
ExtractRuntimeHealth reads the runtime health from an account's extraConfig. Mirrors TS extractRuntimeHealth().
type RuntimeHealthInput ¶
type RuntimeHealthInput struct {
AccountStatus string
SiteStatus string
ExtraConfig *string
SessionCapable *bool
HasDiscoveredModels bool
OAuthProvider *string
}
RuntimeHealthInput is the input for effective runtime-health aggregation. Mirrors TS buildRuntimeHealthForAccount().
type RuntimeHealthSource ¶
type RuntimeHealthSource string
RuntimeHealthSource is the source of a runtime health update.
const ( HealthSourceCheckin RuntimeHealthSource = "checkin" HealthSourceBalance RuntimeHealthSource = "balance" HealthSourceAuth RuntimeHealthSource = "auth" HealthSourceSystem RuntimeHealthSource = "system" HealthSourceNone RuntimeHealthSource = "none" HealthSourceModel RuntimeHealthSource = "model-discovery" )
type RuntimeHealthState ¶
type RuntimeHealthState string
RuntimeHealthState is the health state of an account at runtime.
const ( HealthHealthy RuntimeHealthState = "healthy" HealthDegraded RuntimeHealthState = "degraded" HealthUnhealthy RuntimeHealthState = "unhealthy" HealthDisabled RuntimeHealthState = "disabled" HealthUnknown RuntimeHealthState = "unknown" )
type SiteInitializationPreset ¶
type SiteInitializationPreset struct {
ID string
Label string
ProviderLabel string
Description string
Platform string
DefaultURL string
InitialSegment string
RecommendedSkipModelFetch bool
RecommendedModels []string
DocsURL string
// MatchHost + MatchPaths define host/path auto-detect rules.
// Empty MatchHost means the preset is manual-only (matches always false).
MatchHost string
MatchPaths []string
}
SiteInitializationPreset owns connection defaults used by creation, detection and the admin template gallery. Platform values are registered adapters, not brands.
func DetectSiteInitializationPreset ¶
func DetectSiteInitializationPreset(rawURL, platform string) *SiteInitializationPreset
DetectSiteInitializationPreset mirrors the JS detectSiteInitializationPreset(url, platform). When platform is non-empty, only presets for that protocol family are considered.
func GetSiteInitializationPreset ¶
func GetSiteInitializationPreset(id string) *SiteInitializationPreset
GetSiteInitializationPreset returns a preset by id, or nil when unknown.
func ListSiteInitializationPresets ¶
func ListSiteInitializationPresets() []SiteInitializationPreset
ListSiteInitializationPresets returns a defensive copy of all known presets.
func (SiteInitializationPreset) HasURLMatchRules ¶
func (p SiteInitializationPreset) HasURLMatchRules() bool
HasURLMatchRules reports whether the preset defines host/path auto-detect rules.
func (SiteInitializationPreset) MatchesURL ¶
func (p SiteInitializationPreset) MatchesURL(rawURL string) bool
MatchesURL implements the JS preset.matches(url) host+paths check.
type TodayIncomeSnapshot ¶
type TodayIncomeSnapshot struct {
Day string `json:"day"`
Baseline float64 `json:"baseline"`
Latest float64 `json:"latest"`
UpdatedAt string `json:"updatedAt"`
}
TodayIncomeSnapshot tracks daily income baseline and latest.
type TokenDefaultSwitch ¶ added in v0.20.0
type TokenDefaultSwitch struct {
FromTokenID int64
FromTokenName string
ToTokenID int64
ToTokenName string
}
TokenDefaultSwitch records one convergence SyncTokensFromUpstream had to perform: the stored default relay credential is no longer listed upstream, so the default moved to a key the upstream still lists.
type TokenSyncResult ¶
type TokenSyncResult struct {
Created int
Updated int
MaskedPending int
PendingTokenIDs []int64
Total int
DefaultTokenID *int64
// DefaultSwitch is non-nil when the default relay credential moved because
// the key it pointed at is gone upstream.
DefaultSwitch *TokenDefaultSwitch
// DefaultSwitchSkipped names why an absent default was deliberately NOT
// re-elected, so a caller can tell "nothing to converge" from "could not
// prove the listing was complete". Empty when no skip decision was made.
DefaultSwitchSkipped string
}
TokenSyncResult summarizes SyncTokensFromUpstream outcomes.
func SyncTokensFromUpstream ¶
func SyncTokensFromUpstream(db *sqlx.DB, accountID int64, listing UpstreamTokenListing) (*TokenSyncResult, error)
SyncTokensFromUpstream upserts account tokens from upstream listings. When an existing ready token matches by key, local enabled (and non-empty operator-set name) are preserved; upstream enable flags do not clobber operator disable/enable choices (upstream / ).
type UpstreamAPIToken ¶
UpstreamAPIToken is a token payload returned by platform adapters during sync.
func FetchUpstreamAPITokens ¶
func FetchUpstreamAPITokens( ctx context.Context, adapter platform.PlatformAdapter, baseURL, accessToken string, platformUserID *int, proxy *platform.ProxyConfig, ) ([]UpstreamAPIToken, error)
FetchUpstreamAPITokens preserves the legacy slice-only API for callers that do not carry listing completeness.
func PlatformAPITokensToUpstream ¶
func PlatformAPITokensToUpstream(tokens []platform.ApiTokenInfo) []UpstreamAPIToken
PlatformAPITokensToUpstream converts platform.ApiTokenInfo values to the local UpstreamAPIToken shape used by SyncTokensFromUpstream.
type UpstreamPreset ¶ added in v0.24.0
type UpstreamPreset struct {
ID string `json:"id"`
// RequiresProject marks parameterized endpoint templates (Vertex): the
// resolve/connect inputs must carry projectId, and the region is parsed
// from the base URL host.
RequiresProject bool `json:"requiresProject,omitempty"`
Name string `json:"name"`
Label string `json:"label"`
Provider string `json:"provider"`
Platform string `json:"platform"`
Group string `json:"group"`
DefaultURL string `json:"defaultUrl"`
RequiresBaseURL bool `json:"requiresBaseUrl"`
CredentialMode string `json:"credentialMode"`
Protocols []string `json:"protocols"`
RecommendedModels []string `json:"recommendedModels"`
// contains filtered or unexported fields
}
UpstreamPreset is one product, including all configured protocols. Legacy protocol variants remain resolvable aliases, not separate gallery cards.
func GetUpstreamPreset ¶ added in v0.24.0
func GetUpstreamPreset(id string) *UpstreamPreset
func ListUpstreamPresets ¶ added in v0.24.0
func ListUpstreamPresets() []UpstreamPreset
func (UpstreamPreset) EndpointBaseURL ¶ added in v0.24.0
func (p UpstreamPreset) EndpointBaseURL(key string) string
func (UpstreamPreset) IsDefaultBaseURL ¶ added in v0.24.0
func (p UpstreamPreset) IsDefaultBaseURL(base string) bool
IsDefaultBaseURL recognizes legacy variant roots as product defaults, so an old Messages preset cannot accidentally become the new Chat endpoint root.
type UpstreamTokenListing ¶ added in v0.20.0
type UpstreamTokenListing struct {
Tokens []UpstreamAPIToken
Complete bool
// DefaultSwitchUnsafe is set for a legacy flat listing that answered without
// a total. Its tokens remain syncable, but absence cannot prove revocation.
DefaultSwitchUnsafe bool
}
UpstreamTokenListing carries the tokens plus the facts convergence needs: whether the adapter proved the listing complete, and whether a legacy fallback made even a short listing unsafe for default-switch decisions.
func FetchUpstreamAPITokenListing ¶ added in v0.20.0
func FetchUpstreamAPITokenListing( ctx context.Context, adapter platform.PlatformAdapter, baseURL, accessToken string, platformUserID *int, proxy *platform.ProxyConfig, ) (UpstreamTokenListing, error)
FetchUpstreamAPITokenListing loads tokens and carries whether the adapter proved the listing complete. Only adapters implementing the explicit complete-lister contract may bypass the convergence truncation guard.
Source Files
¶
- account_credential.go
- account_extra_config.go
- account_health.go
- account_model_refresh.go
- account_pricing.go
- account_service.go
- account_token_service.go
- direct_runtime.go
- doc.go
- domestic_chat_profile.go
- import_url_guard.go
- localtime.go
- model_redirects.go
- proxy_metrics_sql.go
- proxy_util.go
- resin.go
- route_creation.go
- route_rebuild.go
- routing_store.go
- site_detect.go
- site_endpoint_service.go
- site_import.go
- site_initialization_presets.go
- site_service.go
- today_reward.go
- upstream_preset_endpoints.go
- upstream_presets.go
- upstream_vertex.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package catalogsync owns the model-catalog data source registry: a DB-persisted, ordered list of catalog sources (llm-metadata / models.dev presets plus operator-added custom URLs) that are fetched in order and merged first-wins into the runtime catalog snapshot consumed by routing and the models marketplace.
|
Package catalogsync owns the model-catalog data source registry: a DB-persisted, ordered list of catalog sources (llm-metadata / models.dev presets plus operator-added custom URLs) that are fetched in order and merged first-wins into the runtime catalog snapshot consumed by routing and the models marketplace. |
|
Package events is the single source of truth for structured event emission.
|
Package events is the single source of truth for structured event emission. |
|
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens.
|
Package pricing provides pure, database-free functions for normalizing upstream pricing signals into a canonical product model and converting pricing multipliers (ratios) into USD per million tokens. |
|
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router.
|
Package pricingcatalog serves official catalog pricing from models.dev as a cold-start cost signal for the token router. |
|
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok).
|
Package promptfilter implements a lightweight, pattern-based prompt safety filter that blocks high-risk prompts before they reach shared OAuth upstream accounts (Codex, Claude, Gemini CLI, Grok). |
|
Package upstream owns transactional changes to the direct-upstream graph.
|
Package upstream owns transactional changes to the direct-upstream graph. |