platform

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: AGPL-3.0 Imports: 25 Imported by: 1 module, 0 packages

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

README

Upstream Platform Adapters (上游适配器架构)

本目录承载 Metapi 接入的各类 AI 中转站、官方聚合面板与直接模型上游的统一适配器实现。


一、 核心适配契约 (PlatformAdapter)

每个适配器实现 platform/adapter.go 中定义的 PlatformAdapter 接口,支持四大维度的能力:

  • 自动探测 (URL 识别)
  • 账号与会话管理 (Login / VerifyToken)
  • 资产与日常运营 (Checkin 自动签到 / GetBalance 余额刷新)
  • 模型自动发现与令牌管理 (GetModels / GetAPITokens)

二、 继承与复用体系 (Struct Embedding)

为降低社区开发新站点的重复代码量,所有适配器通过组合复用基类:

  • BaseAdapter: 通用 HTTP、超时、代理与失败分类
  • StandardAdapter: OpenAI / Claude / Gemini 原生端点兼容
  • OneApiAdapter: OneAPI 及其衍生面板规范 (OneHub / DoneHub)
  • NewApiAdapter: NewAPI 规范 (支持平台 UserID 与加密登录回退, AnyRouter)
  • Sub2ApiAdapter: 订阅转换型站点

三、 社区贡献快速上手 (How to Add a New Site)

若社区发现了新的聚合站点或需要定制签到逻辑:

  1. 在 platform/ 下创建 provider.go 及对应的 provider_test.go。
  2. 继承基类 (如 NewApiAdapter 或 BaseAdapter),重写差异方法 (如定制的 Checkin 路径)。
  3. 在 platform/registry.go 中注册该适配器。
  4. 运行 go test ./platform/... 验证。

Documentation

Overview

BaseAdapter (base.go) ├── StandardAdapter (standard.go) │ ├── OpenAiAdapter (openai.go) │ ├── ClaudeAdapter (claude.go) │ ├── GeminiAdapter (gemini.go) │ │ └── GeminiCliAdapter (gemini_cli.go) │ └── CliProxyApiAdapter (cliproxyapi.go) ├── CodexAdapter (codex.go) ├── AntigravityAdapter (antigravity.go) ├── OneApiAdapter (oneapi.go) │ └── OneHubAdapter (onehub.go) │ └── DoneHubAdapter (donehub.go) ├── VeloeraAdapter (veloera.go) ├── Sub2ApiAdapter (sub2api.go) └── NewApiAdapter (newapi.go)

└── AnyRouterAdapter (anyrouter.go)

Package platform implements adapters for the registered upstream AI API platforms.

Index

Constants

View Source
const ClaudeDefaultAnthropicVersion = "2023-06-01"

ClaudeDefaultAnthropicVersion is the anthropic-version header value used when a caller does not supply one. Single source of truth for every path that speaks the Anthropic-native protocol (platform adapters, OAuth flows, and the /v1 proxy data plane).

View Source
const DefaultBrowserUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"

DefaultBrowserUserAgent is the single fixed browser identity used for outbound requests to upstream sites. Adapter API calls (login/checkin/ balance/model pull) previously went out as Go's default "Go-http-client/1.1", which is a bright bot beacon for UA-denial WAF rules on NewAPI/OneAPI forks.

Keep the Chrome version bumped quarterly so the declared identity stays current with the real Chrome release cadence.

View Source
const (
	// CheckinUnsupportedMessage is what an adapter returns when the platform has
	// no check-in at all. Adapters and the vocabulary below reference the same
	// constant so a message this codebase authored cannot fall out of the
	// classifier that reads it — that drift is what left six platforms reporting
	// unknown_error.
	DefaultCheckinUnsupportedMessage = "checkin endpoint not supported"
)

Check-in answers are classified here, next to the rest of the upstream message semantics (error_classification.go), because four callers ask the same question about the same sentence: the New API adapter's cookie retry ladder, the check-in runner (status, runtime health, event level), the structured failure classifier (checkin_logs.failure_reason) and the runtime-health reader. Three of the four used to keep their own list and the lists disagreed:

  • 11 of the 16 "already checked in" wordings the runner accepted were written to checkin_logs as code=unknown_error;
  • an upstream whose check-in is switched off (New API answers 签到功能未启用) matched none of the three lists, so a healthy account was reported unhealthy with an error-level event (#1267);
  • six registered platforms (openai, claude, gemini, gemini-cli, antigravity, sensetime) answer with StandardAdapter's own default wording, which no list contained either — the same unknown_error, on every check-in cycle, for a third of the platform registry.

The wordings below are enumerated from what supported upstreams and our own adapters actually return (New API's model/checkin.go and its three locale catalogs; StandardAdapter/BaseAdapter defaults; the TS heritage list). Nothing here is a guessed phrasing: a speculative string would soften a real failure into "unsupported" or "already done", which is the one thing a classifier must not do.

View Source
const UpstreamTokenListPageLimit = 100

UpstreamTokenListPageLimit is the per-endpoint page size every adapter uses when it lists a site's upstream API tokens (new-api/one-api pass it as `size=`, sub2api as `page_size=`). It is exported because a caller that reasons about "this key is not in the upstream list" has to know whether the list could have been truncated: sub2api lists two endpoints, so its combined answer can reach twice this size, and an absent key only proves revocation when the listing was complete.

Variables

View Source
var (

	// ErrNewAPITokenListingCompletenessUnproven means the legacy listing
	// answered but did not expose a total that can prove the snapshot complete.
	// Callers may still use the tokens for synchronization, but must not use
	// their absence to converge the default relay credential.
	ErrNewAPITokenListingCompletenessUnproven = errors.New("new-api token listing completeness unproven")
)
View Source
var PlatformAliases = map[string]string{
	"anyrouter":      "anyrouter",
	"vo-api":         "new-api",
	"super-api":      "new-api",
	"rix-api":        "new-api",
	"neo-api":        "new-api",
	"newapi":         "new-api",
	"new api":        "new-api",
	"new-api":        "new-api",
	"oneapi":         "one-api",
	"one api":        "one-api",
	"one-api":        "one-api",
	"onehub":         "one-hub",
	"one-hub":        "one-hub",
	"donehub":        "done-hub",
	"done-hub":       "done-hub",
	"veloera":        "veloera",
	"sub2api":        "sub2api",
	"openai":         "openai",
	"codex":          "codex",
	"chatgpt-codex":  "codex",
	"chatgpt codex":  "codex",
	"anthropic":      "claude",
	"claude":         "claude",
	"gemini":         "gemini",
	"gemini-cli":     "gemini-cli",
	"antigravity":    "antigravity",
	"anti-gravity":   "antigravity",
	"grok":           "grok",
	"xai":            "grok",
	"x.ai":           "grok",
	"github-copilot": "github-copilot",
	"github copilot": "github-copilot",
	"copilot":        "github-copilot",
	"google":         "gemini",
	"cliproxyapi":    "cliproxyapi",
	"cpa":            "cliproxyapi",
	"cli-proxy-api":  "cliproxyapi",
	"sensetime":      "sensetime",
}

PLATFORM_ALIASES maps user-facing platform names to canonical identifiers.

Functions

func ApplyCustomHeaders

func ApplyCustomHeaders(req *http.Request, custom map[string]string)

ApplyCustomHeaders sets non-denied custom headers onto req using the default request-wins policy (does not overwrite existing request headers). Prefer ApplyCustomHeadersWithOptions when the site flag is known. Nil req or empty map is a no-op.

func ApplyCustomHeadersWithOptions

func ApplyCustomHeadersWithOptions(req *http.Request, custom map[string]string, opts ApplyCustomHeadersOptions)

ApplyCustomHeadersWithOptions sets non-denied custom headers onto req. OverrideRequest=true → site-wins (Header.Set). OverrideRequest=false → request-wins (skip when req already has a non-empty value for that header).

func ApplySiteIdentity added in v0.13.0

func ApplySiteIdentity(req *http.Request, proxyConfig *ProxyConfig)

ApplySiteIdentity injects a per-site Cloudflare clearance cookie and browser UA override into the request. The Cookie header is deny-listed in custom_headers for security, so cf_clearance flows through this dedicated typed field instead. Existing cookies are preserved via AddCookie.

func DoWithProxy

func DoWithProxy(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig) (*http.Response, error)

DoWithProxy is a convenience function that works without a SiteProxy instance.

func DoWithProxyStreamBudget added in v0.20.0

func DoWithProxyStreamBudget(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig, firstByteTimeoutMs int64) (*http.Response, error)

DoWithProxyStreamBudget uses one header timer, not the buffered transport's header or whole-request timeout. firstByteTimeoutMs is milliseconds; values <= 0 use httpclient.DefaultRequestCeiling. After headers, the caller and relay idle guard own the body lifetime. Callers must close resp.Body.

func ExplainUpstreamFailure added in v0.19.0

func ExplainUpstreamFailure(httpStatus int, message string) string

ExplainUpstreamFailure renders one compact, credential-safe sentence naming why an upstream call failed, for operator-facing surfaces such as a 502 body or an account health reason. It never echoes the raw upstream text: that text can carry a URL, a token fragment or a request id, and it already reaches the server log in full.

The class comes from ClassifyUpstreamError, but ClassUnknown is not read as "nothing to say". That classifier is deliberately conservative because only ClassExpired may write accounts.status='expired'; an operator still needs to hear that a 401 from the upstream auth endpoint is a credential problem even when the wording was too weak to auto-mark the account. So an unclassified failure falls back to what its status alone proves (#1210: a bare "balance refresh failed" hid `HTTP 401: Token has expired`, which the server had already logged).

It returns "" only when nothing safe can be named, and the caller then keeps its own stable message prefix instead of inventing a cause.

func IsAlreadyCheckedInMessage added in v0.20.0

func IsAlreadyCheckedInMessage(message string) bool

IsAlreadyCheckedInMessage reports whether the answer means today's check-in already happened.

func IsAuthRelatedUpstreamError

func IsAuthRelatedUpstreamError(httpStatus int, message string) bool

IsAuthRelatedUpstreamError is true for expired or other auth classes.

func IsCheckinEndpointAbsent added in v0.20.0

func IsCheckinEndpointAbsent(message string) bool

IsCheckinEndpointAbsent reports whether the answer says the check-in route itself is missing. This is the narrow question the New API cookie retry ladder asks: an absent route can be a disguised session failure, so it is worth one more probe, whereas "the site does not offer check-in" is already a complete answer and probing further only costs an upstream call.

func IsCloudflareChallengeMessage added in v0.20.0

func IsCloudflareChallengeMessage(message string) bool

IsCloudflareChallengeMessage reports whether the upstream is serving a Cloudflare challenge instead of the answer. One owner: service/alert and the check-in failure classifier both used to keep a byte-identical copy, and an ablation (putting the copy back) kept the whole suite green — neither had an owner. It normalizes its own input so a caller cannot lose matches by passing the message un-lowercased.

func IsDeniedCustomHeader

func IsDeniedCustomHeader(name string) bool

IsDeniedCustomHeader reports whether a site custom_headers entry must not be forwarded upstream. Blocks identity, framing, content-coding, hop-by-hop, cookies, Proxy-*, and Metapi control preference headers.

Security: custom Authorization must never override the Bearer set from the selected account token; Host/Connection/etc. must not be attacker-controlled.

func IsManualVerificationRequiredMessage added in v0.20.0

func IsManualVerificationRequiredMessage(message string) bool

IsManualVerificationRequiredMessage reports whether the upstream needs a human to solve a Turnstile challenge once before automated check-in can proceed.

func IsTokenExpiredError

func IsTokenExpiredError(httpStatus int, message string) bool

IsTokenExpiredError reports whether the signal is a confirmed expired/invalid stored credential. This matches mark policy (ClassExpired only). Auto-relogin callers that need broader 401/unauthorized heuristics must use local shouldAttemptAutoRelogin* patterns, not this gate. Mirrors historical TS isTokenExpiredError() with non-auth + generic-401 guards.

func IsUnsupportedCheckinMessage added in v0.20.0

func IsUnsupportedCheckinMessage(message string) bool

IsUnsupportedCheckinMessage reports whether a check-in answer means "this site does not offer check-in" rather than "check-in failed".

func NormalizePlatformAlias

func NormalizePlatformAlias(platform string) string

NormalizePlatformAlias maps a raw platform string to its canonical form.

func RejectCrossOriginRedirect

func RejectCrossOriginRedirect(req *http.Request, via []*http.Request) error

RejectCrossOriginRedirect is the shared CheckRedirect policy for outbound HTTP clients that talk to operator-configured upstream sites.

It refuses:

  • more than 5 redirects
  • https → non-https scheme downgrades
  • any host change (blocks 302 to metadata / loopback / private SSRF targets)

Same-origin redirects remain allowed so normal upstream path hops still work. Used by platform.DoWithProxy, proxy.RuntimeExecutor, and residual bare clients (health probe / admin harness / defaultUpstreamClient).

func ShouldMarkAccountExpired

func ShouldMarkAccountExpired(httpStatus int, message string) bool

ShouldMarkAccountExpired is the guard used before writing accounts.status='expired'. Only ClassExpired (confirmed credential invalid/expiry wording) may mark. Generic 401/unauthorized, network, 429, and 5xx must return false.

Types

type AccountPricing added in v0.26.0

type AccountPricing struct {
	Models       []ModelPrice        `json:"models"`
	GroupRatios  map[string]*float64 `json:"groupRatios"`
	UsableGroups map[string]string   `json:"usableGroups"`
}

func ParseNewAPIPricing added in v0.26.0

func ParseNewAPIPricing(data []byte) (*AccountPricing, error)

ParseNewAPIPricing accepts the public /api/pricing response, not the metadata catalog's ratio-config response. Missing group context must remain unknown.

type AntigravityAdapter

type AntigravityAdapter struct {
	*StandardAdapter
}

AntigravityAdapter handles Google Antigravity platforms (OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods.

func (*AntigravityAdapter) Detect

func (a *AntigravityAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the antigravity host only. The bare "antigravity" substring previously matched any URL whose path contained /antigravity (e.g. Sub2API model endpoints), swallowing them before sub2api was reached.

func (*AntigravityAdapter) GetModels

func (a *AntigravityAdapter) GetModels(ctx context.Context, baseURL string, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches from /v1internal:fetchAvailableModels with Antigravity-specific headers.

type AnyRouterAdapter

type AnyRouterAdapter struct {
	*NewApiAdapter
}

AnyRouterAdapter reuses NewAPI-compatible session operations, but token management is intentionally disabled because AnyRouter's API-key workflow is not the NewAPI /api/token/ contract.

func (*AnyRouterAdapter) CreateAPIToken

func (a *AnyRouterAdapter) CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

func (*AnyRouterAdapter) DeleteAPIToken

func (a *AnyRouterAdapter) DeleteAPIToken(ctx context.Context, url, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

func (*AnyRouterAdapter) Detect

func (a *AnyRouterAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect matches URL keyword "anyrouter" (case-insensitive).

func (*AnyRouterAdapter) GetAPIToken

func (a *AnyRouterAdapter) GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

func (*AnyRouterAdapter) GetAPITokens

func (a *AnyRouterAdapter) GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

type ApiTokenInfo

type ApiTokenInfo struct {
	Name       string `json:"name"`
	Key        string `json:"key"`
	Enabled    bool   `json:"enabled"`
	TokenGroup string `json:"tokenGroup,omitempty"`
}

ApiTokenInfo describes a single API key/token.

type ApplyCustomHeadersOptions

type ApplyCustomHeadersOptions struct {
	OverrideRequest bool
}

ApplyCustomHeadersOptions controls collision policy for site custom headers. When OverrideRequest is false (default, request-wins), a site header is applied only if the request does not already carry that header. When true (site-wins), site headers always Set over existing request values — matching the upstream customHeadersOverrideRequestHeaders=true behavior.

type BalanceInfo

type BalanceInfo struct {
	Balance               float64              `json:"balance"`
	Used                  float64              `json:"used"`
	Quota                 float64              `json:"quota"`
	TodayIncome           *float64             `json:"todayIncome,omitempty"`
	TodayQuotaConsumption *float64             `json:"todayQuotaConsumption,omitempty"`
	SubscriptionSummary   *SubscriptionSummary `json:"subscriptionSummary,omitempty"`
}

BalanceInfo holds balance and usage information in USD.

type BaseAdapter

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

BaseAdapter provides default implementations for PlatformAdapter methods. Concrete adapters embed this and override specific methods as needed.

func NewBaseAdapter

func NewBaseAdapter(name string) *BaseAdapter

NewBaseAdapter creates a BaseAdapter with the given platform name.

func (*BaseAdapter) Checkin

func (b *BaseAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin returns unsupported by default.

func (*BaseAdapter) CreateAPIToken

func (b *BaseAdapter) CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken returns false by default.

func (*BaseAdapter) DeleteAPIToken

func (b *BaseAdapter) DeleteAPIToken(ctx context.Context, url, accessToken string, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken returns nil (no-op) by default.

func (*BaseAdapter) Detect

func (b *BaseAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect must be implemented by concrete adapters.

func (*BaseAdapter) GetAPIToken

func (b *BaseAdapter) GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken returns nil by default.

func (*BaseAdapter) GetAPITokens

func (b *BaseAdapter) GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens returns a single-item list if GetAPIToken finds one.

func (*BaseAdapter) GetBalance

func (b *BaseAdapter) GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance returns zero balance by default.

func (*BaseAdapter) GetModels

func (b *BaseAdapter) GetModels(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels returns empty list by default.

func (*BaseAdapter) GetSiteAnnouncements

func (b *BaseAdapter) GetSiteAnnouncements(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements returns empty list by default.

func (*BaseAdapter) GetUserGroups

func (b *BaseAdapter) GetUserGroups(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups returns ["default"] by default.

func (*BaseAdapter) GetUserInfo

func (b *BaseAdapter) GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo provides a default implementation: GET /api/user/self with Bearer auth.

func (*BaseAdapter) Login

func (b *BaseAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login provides a default login implementation: POST /api/user/login.

func (*BaseAdapter) PlatformName

func (b *BaseAdapter) PlatformName() string

PlatformName returns the platform identifier.

func (*BaseAdapter) VerifyToken

func (b *BaseAdapter) VerifyToken(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken provides default token verification (session + apikey paths).

type CheckinResult

type CheckinResult struct {
	Success bool
	Message string
	Reward  string // optional
}

CheckinResult is the outcome of a daily checkin.

type ClaudeAdapter

type ClaudeAdapter struct {
	*StandardAdapter
}

ClaudeAdapter handles api.anthropic.com platforms (native + OpenAI-compat gateways).

func (*ClaudeAdapter) Detect

func (c *ClaudeAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the exact api.anthropic.com host, or anthropic.com with a /v1 path prefix (avoids anthropic.com/v1-docs style false positives).

func (*ClaudeAdapter) GetModels

func (c *ClaudeAdapter) GetModels(ctx context.Context, baseURL string, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels tries native Anthropic endpoint first, then falls back to OpenAI-compat by stripping the /anthropic suffix from the base URL.

type CliProxyApiAdapter

type CliProxyApiAdapter struct {
	*StandardAdapter
}

CliProxyApiAdapter handles CLIProxy API (port 8317 + x-cpa-* headers).

func (*CliProxyApiAdapter) Detect

func (c *CliProxyApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect uses 3 conditions: port 8317, "cliproxy" keyword, or HTTP probe with x-cpa-* headers.

func (*CliProxyApiAdapter) GetModels

func (c *CliProxyApiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches models from the standard /v1/models endpoint.

func (*CliProxyApiAdapter) VerifyToken added in v0.14.0

func (c *CliProxyApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken verifies a pasted CLIProxyAPI credential.

CliProxyApiAdapter deliberately overrides VerifyToken instead of inheriting BaseAdapter.VerifyToken: the base implementation statically dispatches to one-api style GET /api/user/self (absent on CLIProxyAPI) and reports every credential as "unknown". CLIProxyAPI credentials are keys: a provider API key whose models are served through /v1/models, or the management key (validated against the /v0/management API).

type CodexAdapter

type CodexAdapter struct {
	*StandardAdapter
}

CodexAdapter handles chatgpt.com/backend-api/codex (OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods.

func (*CodexAdapter) Detect

func (c *CodexAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect matches URL keyword: chatgpt.com/backend-api/codex.

type CreateAPITokenOptions

type CreateAPITokenOptions struct {
	Name               string
	Group              string
	UnlimitedQuota     bool    // default true
	RemainQuota        float64 // default 0
	ExpiredTime        int64   // Unix timestamp, -1 = never expire
	AllowIPs           string
	ModelLimitsEnabled bool
	ModelLimits        string
}

CreateAPITokenOptions holds parameters for creating a new API key.

type DoneHubAdapter

type DoneHubAdapter struct {
	*OneHubAdapter
}

DoneHubAdapter extends OneHubAdapter with checkin unsupported, remaining-quota balance, and /api/notice.

func (*DoneHubAdapter) Checkin

func (d *DoneHubAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: always unsupported for DoneHub.

func (*DoneHubAdapter) Detect

func (d *DoneHubAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect: URL keyword match "donehub" or "done-hub" (title-first platform).

func (*DoneHubAdapter) GetBalance

func (d *DoneHubAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=remaining, total=quota+used, divisor=500000.

func (*DoneHubAdapter) GetSiteAnnouncements

func (d *DoneHubAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements: GET /api/notice.

type GeminiAdapter

type GeminiAdapter struct {
	*StandardAdapter
}

GeminiAdapter handles Google Gemini API platforms with 3-path model discovery.

func (*GeminiAdapter) Detect

func (g *GeminiAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches URL keywords: generativelanguage.googleapis.com, googleapis.com/v1beta/openai, gemini.google.com.

func (*GeminiAdapter) GetModels

func (g *GeminiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels uses 3-path discovery: OpenAI-compat (if on /openai/ path) -> native Gemini -> OpenAI-compat fallback.

All three paths used to end in `[]string{}, nil`, so an unreachable site, a rejected key and a site that exposes none of the three shapes were the same answer, and the caller can only classify a failure it is told about.

type GeminiCliAdapter

type GeminiCliAdapter struct {
	*GeminiAdapter
}

GeminiCliAdapter extends GeminiAdapter with its own detect for cloudcode-pa.googleapis.com.

func (*GeminiCliAdapter) Detect

func (g *GeminiCliAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect overrides GeminiAdapter's detect: matches cloudcode-pa.googleapis.com only.

type GitHubCopilotAdapter added in v0.25.0

type GitHubCopilotAdapter struct {
	*StandardAdapter
}

GitHubCopilotAdapter handles api.githubcopilot.com. Credentials are managed by the Device OAuth provider in service/oauth/copilot.go.

func (*GitHubCopilotAdapter) Detect added in v0.25.0

func (a *GitHubCopilotAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the Copilot chat host and GitHub API URLs whose path already identifies a Copilot endpoint.

func (*GitHubCopilotAdapter) GetModels added in v0.25.0

func (a *GitHubCopilotAdapter) GetModels(ctx context.Context, baseURL string, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels returns the curated seed list; it never claims live availability.

type GrokAdapter added in v0.13.0

type GrokAdapter struct {
	*StandardAdapter
}

GrokAdapter handles xAI Grok platforms (api.x.ai, OAuth-driven). StandardAdapter provides the "not supported"/empty defaults for auth, checkin and balance methods — Grok credentials are managed via the Device OAuth flow registered in service/oauth/grok.go.

func (*GrokAdapter) Detect added in v0.13.0

func (g *GrokAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the xAI API host. xAI serves its public API from api.x.ai; the bare x.ai host is also accepted so users may register either form.

func (*GrokAdapter) GetModels added in v0.13.0

func (g *GrokAdapter) GetModels(ctx context.Context, baseURL string, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels returns the hardcoded Grok seed model list. xAI's public API does expose /v1/models, but the seed list keeps detection/verification working without a live upstream call (mirrors the Codex "empty by default" contract while still surfacing a useful model catalog for auto-complete).

type LoginResult

type LoginResult struct {
	Success     bool
	AccessToken string
	Username    string
	Message     string
}

LoginResult is the outcome of a login attempt.

func LoginReusingCredential added in v0.22.0

func LoginReusingCredential(adp PlatformAdapter, ctx context.Context, url, username, password string, platformUserID *int, proxy *ProxyConfig, existing string) (*LoginResult, error)

LoginReusingCredential lets adapters with durable dashboard credentials validate an already-stored credential before requesting another one. Other platforms retain their usual login behavior.

type ModelPrice added in v0.26.0

type ModelPrice struct {
	Model             string   `json:"model"`
	QuotaType         int      `json:"quotaType"`
	ModelRatio        *float64 `json:"modelRatio"`
	CompletionRatio   *float64 `json:"completionRatio"`
	CacheRatio        *float64 `json:"cacheRatio"`
	CacheWriteRatio   *float64 `json:"cacheWriteRatio"`
	PricePerRequest   *float64 `json:"pricePerRequest"`
	Groups            []string `json:"groups"`
	BillingMode       string   `json:"billingMode"`
	BillingExpression string   `json:"billingExpression"`
}

ModelPrice is the advertised pricing contract, before the effective group multiplier. Optional amounts distinguish a free rate from a rate the upstream omitted.

type NewApiAdapter

type NewApiAdapter struct {
	*BaseAdapter
}

NewApiAdapter handles NewAPI platforms with full cookie fallback, shield challenge, user-ID probing, and 7-header injection. Serves as the base for AnyRouterAdapter.

func (*NewApiAdapter) Checkin

func (n *NewApiAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

func (*NewApiAdapter) CreateAPIToken

func (n *NewApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

func (*NewApiAdapter) DeleteAPIToken

func (n *NewApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

func (*NewApiAdapter) Detect

func (n *NewApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks success===true and that data.system_name's value names a NewAPI fork. one-api v0.6.10 also ships system_name (default "One API"), so mere presence of the key misdetects one-api as new-api; the value-based check keeps the two apart. Known NewAPI fork aliases (vo-api/super-api/rix-api/neo-api) short-circuit via URL keyword so shield/WAF-fronted deployments whose /api/status probe is blocked still get detected. Operators who rename SYSTEM_NAME to something unrelated degrade to manual platform selection — acceptable for an auto-detect heuristic.

func (*NewApiAdapter) GetAPIToken

func (n *NewApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

func (*NewApiAdapter) GetAPITokens

func (n *NewApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

func (*NewApiAdapter) GetAPITokensComplete added in v0.20.0

func (n *NewApiAdapter) GetAPITokensComplete(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, bool, error)

GetAPITokensComplete is the explicit completeness contract consumed by the token-sync convergence path. A legacy flat response without a total is returned with ErrNewAPITokenListingCompletenessUnproven so callers can sync the tokens but must not converge the default from their absence.

func (*NewApiAdapter) GetBalance

func (n *NewApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

func (*NewApiAdapter) GetModels

func (n *NewApiAdapter) GetModels(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

func (*NewApiAdapter) GetPricing added in v0.26.0

func (n *NewApiAdapter) GetPricing(ctx context.Context, baseURL, token string, userID *int, proxy *ProxyConfig) (*AccountPricing, error)

GetPricing uses the account's management identity. New API has already applied user-group overrides to group_ratio; consumers apply each value exactly once.

func (*NewApiAdapter) GetSiteAnnouncements

func (n *NewApiAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

func (*NewApiAdapter) GetUserGroups

func (n *NewApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

func (*NewApiAdapter) GetUserInfo

func (n *NewApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

func (*NewApiAdapter) Login

func (n *NewApiAdapter) Login(ctx context.Context, baseURL, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

func (*NewApiAdapter) LoginWithExistingCredential added in v0.22.0

func (n *NewApiAdapter) LoginWithExistingCredential(ctx context.Context, baseURL, username, password string, platformUserId *int, proxy *ProxyConfig, existing string) (*LoginResult, error)

LoginWithExistingCredential accepts the stored PAT only as a reuse candidate. The fresh browser login must succeed first; the upstream token listing then proves ownership, validity and sufficient grant before the PAT is reused.

func (*NewApiAdapter) VerifyToken

func (n *NewApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

type OneApiAdapter

type OneApiAdapter struct {
	*BaseAdapter
}

OneApiAdapter handles OneAPI platforms (detect: /api/status by version + system_name value discriminator against new-api). Serves as the base for OneHubAdapter and DoneHubAdapter.

func (*OneApiAdapter) Checkin

func (o *OneApiAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: POST /api/user/checkin. Bearer auth first; session-cookie credentials (one-api v0.6.10 login) fall back to a Cookie header.

func (*OneApiAdapter) CreateAPIToken

func (o *OneApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken: POST /api/token/ (Bearer auth).

A failed fetch is an error, not "not created". The caller answers 502 for both, but only the error path logs the reason and puts it in the response, so `false, nil` here reported "we asked and the upstream said no" for a call that never reached anyone. An answered `success:false` stays (false, nil): that is the upstream's own verdict.

func (*OneApiAdapter) DeleteAPIToken

func (o *OneApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken: list -> find key -> DELETE /api/token/{id} (with trailing-slash fallback).

nil means "that key is gone upstream, or was never there". A failed listing and a failed delete are both errors: the caller deletes the local row only when this returns nil, so reporting success for a call that never landed left a live upstream credential with no local row tracking it. NewApiAdapter.DeleteAPIToken in this package already drew that line.

func (*OneApiAdapter) Detect

func (o *OneApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks success===true, data.version is present, and system_name (when present) names one-api. one-api v0.5.x has no system_name (legacy shape); v0.6.10+ ships system_name (default "One API"). The value check keeps new-api (default "New API") and one-api apart. Requiring version keeps unrelated /api/status endpoints from being labeled one-api. Operators who rename SYSTEM_NAME to something unrelated degrade to manual platform selection — acceptable for an auto-detect heuristic.

func (*OneApiAdapter) GetAPIToken

func (o *OneApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken returns the first enabled token.

func (*OneApiAdapter) GetAPITokens

func (o *OneApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens: GET /api/token/?p=0&size=100 (Bearer auth).

func (*OneApiAdapter) GetBalance

func (o *OneApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=total, balance=quota-used, divisor=500000. Bearer auth first; session-cookie credentials fall back to a Cookie header.

A failed fetch is an error, mirroring NewApiAdapter.GetBalance below in this package: service/balance stores whatever struct comes back as the account's balance and drives runtime health, the token-expired alert and the auto-relogin retry from err != nil. Returning a zero BalanceInfo with a nil error therefore wrote balance=0 over the real one and skipped all three. #1244 fixed the same shape in veloera and done-hub; one-api and the one-hub adapter that embeds it were the last two holding it.

func (*OneApiAdapter) GetModels

func (o *OneApiAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: GET /v1/models (Bearer auth).

func (*OneApiAdapter) GetUserGroups

func (o *OneApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: GET /api/user_group_map, fallback /api/user/self/groups.

func (*OneApiAdapter) GetUserInfo added in v0.14.0

func (o *OneApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo: GET /api/user/self with Bearer auth first; session-cookie credentials fall back to a Cookie header (one-api v0.6.10 login).

func (*OneApiAdapter) Login added in v0.14.0

func (o *OneApiAdapter) Login(ctx context.Context, baseURL, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login POSTs /api/user/login and accepts either a legacy data.access_token or a captured session cookie. one-api v0.6.10 returns success:true with an EMPTY data.access_token and authenticates via a Set-Cookie session cookie, so the cookie header becomes the stored credential. Mirrors NewApiAdapter.Login (same fetchLoginResponse + hasUsableSessionCookie flow).

func (*OneApiAdapter) VerifyToken added in v0.14.0

func (o *OneApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken mirrors BaseAdapter.VerifyToken but dispatches to the cookie-aware overrides above. BaseAdapter.VerifyToken calls its own Bearer-only GetUserInfo/GetBalance (Go static dispatch on the embedded receiver), which would reject session-cookie credentials stored by the v0.6.10 login; this override routes through o.GetUserInfo/o.GetBalance instead.

type OneHubAdapter

type OneHubAdapter struct {
	*OneApiAdapter
}

OneHubAdapter extends OneApiAdapter with title-first detect and /api/available_model fallback.

func (*OneHubAdapter) Detect

func (o *OneHubAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect: URL keyword match "onehub" or "one-hub" (case-insensitive, title-first platform).

func (*OneHubAdapter) GetModels

func (o *OneHubAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: try /v1/models (OneApi), fall back to /api/available_model.

The embedded one-api ladder already reports its failures; this wrapper used to drop that error and then swallow its own fallback's failure too, so one-hub answered "no models" for a site nobody reached.

func (*OneHubAdapter) GetUserGroups

func (o *OneHubAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: /api/user_group_map with data-object keys, fallback to OneApi's implementation.

type OpenAiAdapter

type OpenAiAdapter struct {
	*StandardAdapter
}

OpenAiAdapter handles api.openai.com platforms.

func (*OpenAiAdapter) Detect

func (o *OpenAiAdapter) Detect(ctx context.Context, urlStr string) (bool, error)

Detect matches the exact api.openai.com host (avoids suffix confusion such as api.openai.com.evil.example).

func (*OpenAiAdapter) GetModels

func (o *OpenAiAdapter) GetModels(ctx context.Context, baseURL string, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels fetches models from the standard /v1/models OpenAI endpoint.

type PlatformAdapter

type PlatformAdapter interface {
	PlatformName() string

	// Detect returns true if the given URL can be handled by this adapter.
	Detect(ctx context.Context, url string) (bool, error)

	// Session management.
	// platformUserId is for NewApi-fork platforms' cookie-based auth fallback.
	Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)
	GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)
	VerifyToken(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

	// Daily operations.
	Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)
	GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

	// Model discovery: returns model ID strings.
	GetModels(ctx context.Context, url, token string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

	// Token management (NewAPI-style platforms).
	GetAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)
	GetAPITokens(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)
	CreateAPIToken(ctx context.Context, url, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)
	DeleteAPIToken(ctx context.Context, url, accessToken string, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

	// Announcements and groups.
	GetSiteAnnouncements(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)
	GetUserGroups(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)
}

PlatformAdapter is the interface every platform adapter must implement.

func GetAdapter

func GetAdapter(platform string) PlatformAdapter

GetAdapter returns the registered adapter for a given canonical platform name.

func ListAdapters

func ListAdapters() []PlatformAdapter

ListAdapters returns all registered adapters (for diagnostics).

type PricingProvider added in v0.26.0

type PricingProvider interface {
	GetPricing(context.Context, string, string, *int, *ProxyConfig) (*AccountPricing, error)
}

type ProxyConfig

type ProxyConfig struct {
	ProxyURL      string
	CustomHeaders map[string]string
	// CustomHeadersOverrideRequest: when true, site custom headers overwrite
	// same-name request headers (site-wins opt-in). Default
	// false = request-wins (only fill missing headers).
	CustomHeadersOverrideRequest bool
	UseSystemProxy               bool
	InsecureSkipTLS              bool
	// ClearanceCookie is a per-site Cloudflare cf_clearance value injected as
	// a Cookie header on outbound requests to bypass CF challenges.
	ClearanceCookie string
	// BrowserUA overrides the global browser User-Agent for a specific site
	// (used to match the UA of a harvested cf_clearance cookie).
	BrowserUA string
	// ResinAccount records the Resin business-identity used for this request
	// (set by BuildPlatformProxyConfig when the resin forward proxy is active).
	// Downstream code (e.g. native wss reverse-proxy) can read this to set the
	// X-Resin-Account header on paths that bypass the HTTP forward proxy.
	ResinAccount string
	// UseUTLS switches the transport to a uTLS-backed DialTLSContext that
	// mimics Chrome's ClientHello (HelloChrome_Auto), masking the JA3/JA4
	// fingerprint that Cloudflare and similar WAFs use to block automated
	// traffic. When false (default) the standard crypto/tls transport is
	// used. Resolved from site-level use_utls or the global UTLS_ENABLED flag
	// by service.BuildPlatformProxyConfig; the platform layer only reads
	// the resolved bool.
	UseUTLS bool
}

ProxyConfig carries optional proxy settings for a single request.

type SiteAnnouncement

type SiteAnnouncement struct {
	SourceKey         string          `json:"sourceKey"`
	Title             string          `json:"title"`
	Content           string          `json:"content"`
	Level             string          `json:"level"` // "info", "warning", "error"
	SourceURL         string          `json:"sourceUrl,omitempty"`
	StartsAt          string          `json:"startsAt,omitempty"`
	EndsAt            string          `json:"endsAt,omitempty"`
	UpstreamCreatedAt string          `json:"upstreamCreatedAt,omitempty"`
	UpstreamUpdatedAt string          `json:"upstreamUpdatedAt,omitempty"`
	RawPayload        json.RawMessage `json:"rawPayload,omitempty"`
}

SiteAnnouncement is a notice or announcement from the upstream platform.

type SiteProxy

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

SiteProxy is the outbound HTTP client with SOCKS/HTTP proxy support.

func NewSiteProxy

func NewSiteProxy(systemProxyURL string) *SiteProxy

NewSiteProxy creates a new SiteProxy.

func (*SiteProxy) Do

func (sp *SiteProxy) Do(ctx context.Context, req *http.Request, proxyConfig *ProxyConfig) (*http.Response, error)

Do executes an HTTP request through the site proxy layer.

type SiteProxyConfig

type SiteProxyConfig struct {
	ProxyURL       string
	UseSystemProxy bool
	CustomHeaders  map[string]string
}

SiteProxyConfig holds proxy configuration for a site.

type StandardAdapter

type StandardAdapter struct {
	*BaseAdapter
	LoginUnsupportedMessage   string
	CheckinUnsupportedMessage string
}

StandardAdapter is the base for standard API providers (OpenAI, Claude, Gemini, CliProxyApi). It provides sane "not supported" defaults for login/checkin/getBalance/getUserInfo.

func NewStandardAdapter

func NewStandardAdapter(name string) *StandardAdapter

NewStandardAdapter creates a StandardAdapter.

func (*StandardAdapter) Checkin

func (s *StandardAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin returns unsupported.

func (*StandardAdapter) GetBalance

func (s *StandardAdapter) GetBalance(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance returns zero balance.

func (*StandardAdapter) GetUserInfo

func (s *StandardAdapter) GetUserInfo(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo returns nil.

func (*StandardAdapter) Login

func (s *StandardAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login returns unsupported.

type Sub2ApiAdapter

type Sub2ApiAdapter struct {
	*BaseAdapter
}

Sub2ApiAdapter handles Sub2API platforms (JWT auth, {code, message, data} envelope). Directly extends BaseAdapter. Does NOT support login or checkin.

func (*Sub2ApiAdapter) Checkin

func (s *Sub2ApiAdapter) Checkin(ctx context.Context, url, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: not supported.

func (*Sub2ApiAdapter) CreateAPIToken

func (s *Sub2ApiAdapter) CreateAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, options *CreateAPITokenOptions, proxy *ProxyConfig) (bool, error)

CreateAPIToken: POST /api/v1/keys + POST /api/v1/api-keys.

func (*Sub2ApiAdapter) DeleteAPIToken

func (s *Sub2ApiAdapter) DeleteAPIToken(ctx context.Context, baseURL, accessToken, tokenKey string, platformUserId *int, proxy *ProxyConfig) error

DeleteAPIToken: list -> find key -> DELETE /api/v1/keys/{id} + /api/v1/api-keys/{id}.

func (*Sub2ApiAdapter) Detect

func (s *Sub2ApiAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect uses a multi-path approach: URL keyword, /api/v1/auth/me probe, /v1/models probe, root title.

func (*Sub2ApiAdapter) GetAPIToken

func (s *Sub2ApiAdapter) GetAPIToken(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*string, error)

GetAPIToken: returns first enabled token.

func (*Sub2ApiAdapter) GetAPITokens

func (s *Sub2ApiAdapter) GetAPITokens(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]ApiTokenInfo, error)

GetAPITokens: GET /api/v1/keys?page=1&page_size=100 + /api/v1/api-keys?page=1&page_size=100.

func (*Sub2ApiAdapter) GetBalance

func (s *Sub2ApiAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: USD balance from /api/v1/auth/me, converted to quota, plus subscription summary.

func (*Sub2ApiAdapter) GetModels

func (s *Sub2ApiAdapter) GetModels(ctx context.Context, baseURL, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: standard OpenAI-compat endpoints, with API key discovery fallback.

func (*Sub2ApiAdapter) GetSiteAnnouncements

func (s *Sub2ApiAdapter) GetSiteAnnouncements(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]SiteAnnouncement, error)

GetSiteAnnouncements: GET /api/v1/announcements?page=1&page_size=100.

func (*Sub2ApiAdapter) GetUserGroups

func (s *Sub2ApiAdapter) GetUserGroups(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetUserGroups: 5 endpoint fallback + key-based inference. GetUserGroups asks the upstream which groups exist.

["default"] is this family's last resort, not an answer: newapi and oneapi both reach it only after every rung answered and none of them refused. This adapter used to reach it unconditionally, so an unreachable site, an expired credential or an upstream refusal all reported a group the upstream never advertised. That is worse here than elsewhere, because the caller prefers any non-blank upstream answer over the fallback it already has — so the fabricated "default" beat GetLocalTokenGroups' truthful DISTINCT token_group, and the operator saw one invented group instead of the real ones.

The refusal message this now surfaces was already written and already unreachable for sub2api accounts: resolveGroupFetchErrorMessage renders an expired session as "账号会话可能已过期,请重新登录后再拉取分组".

func (*Sub2ApiAdapter) GetUserInfo

func (s *Sub2ApiAdapter) GetUserInfo(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*UserInfo, error)

GetUserInfo: GET /api/v1/auth/me.

func (*Sub2ApiAdapter) Login

func (s *Sub2ApiAdapter) Login(ctx context.Context, url, username, password string, platformUserId *int, proxy *ProxyConfig) (*LoginResult, error)

Login: JWT-only, always unsupported.

func (*Sub2ApiAdapter) VerifyToken added in v0.14.0

func (s *Sub2ApiAdapter) VerifyToken(ctx context.Context, baseURL, token string, platformUserId *int, proxy *ProxyConfig) (*TokenVerifyResult, error)

VerifyToken verifies a pasted Sub2API credential.

Sub2ApiAdapter deliberately overrides VerifyToken instead of inheriting BaseAdapter.VerifyToken: the base implementation dispatches statically to BaseAdapter.GetUserInfo (one-api style GET /api/user/self, which does not exist on Sub2API) and BaseAdapter.GetModels (always empty), so an inherited implementation would report every Sub2API credential as "unknown".

The session path validates the JWT against /api/v1/auth/me and resolves user info, balance and the first API key; a pasted API key (sk-...) falls back to /v1/models verification with the key-discovery fallback.

type SubscriptionPlanSummary

type SubscriptionPlanSummary struct {
	ID              *int     `json:"id,omitempty"`
	GroupID         *int     `json:"groupId,omitempty"`
	GroupName       string   `json:"groupName,omitempty"`
	Status          string   `json:"status,omitempty"`
	ExpiresAt       string   `json:"expiresAt,omitempty"`
	DailyUsedUsd    *float64 `json:"dailyUsedUsd,omitempty"`
	DailyLimitUsd   *float64 `json:"dailyLimitUsd,omitempty"`
	WeeklyUsedUsd   *float64 `json:"weeklyUsedUsd,omitempty"`
	WeeklyLimitUsd  *float64 `json:"weeklyLimitUsd,omitempty"`
	MonthlyUsedUsd  *float64 `json:"monthlyUsedUsd,omitempty"`
	MonthlyLimitUsd *float64 `json:"monthlyLimitUsd,omitempty"`
}

SubscriptionPlanSummary describes a single subscription plan.

type SubscriptionSummary

type SubscriptionSummary struct {
	ActiveCount   int
	TotalUsedUsd  float64
	Subscriptions []SubscriptionPlanSummary
}

SubscriptionSummary aggregates subscription data.

type TokenVerifyResult

type TokenVerifyResult struct {
	TokenType string // "session", "apikey", "unknown"
	UserInfo  *UserInfo
	Balance   *BalanceInfo
	APIToken  string // first discovered API key (optional)
	Models    []string
}

TokenVerifyResult reports the result of token verification.

type UpstreamErrorClass

type UpstreamErrorClass string

UpstreamErrorClass is the high-level class for upstream failure signals. Used for account-status decisions, retry UX, and residual-risk documentation.

const (
	// ClassExpired means the upstream credential/session looks expired or invalid.
	// Only this class may mark accounts.status = 'expired'.
	ClassExpired UpstreamErrorClass = "expired"
	// ClassAuth means an auth/session problem that is not clearly token expiry.
	ClassAuth UpstreamErrorClass = "auth"
	// ClassBilling means payment / quota / credit failures.
	ClassBilling UpstreamErrorClass = "billing"
	// ClassModel means model capability / unsupported-model failures.
	ClassModel UpstreamErrorClass = "model"
	// ClassValidation means request validation / argument errors.
	ClassValidation UpstreamErrorClass = "validation"
	// ClassTransient means rate-limit / timeout / 5xx / network-like failures.
	ClassTransient UpstreamErrorClass = "transient"
	// ClassUnknown is the residual bucket.
	ClassUnknown UpstreamErrorClass = "unknown"
)

func ClassifyUpstreamError

func ClassifyUpstreamError(httpStatus int, message string) UpstreamErrorClass

ClassifyUpstreamError maps an upstream HTTP status + message to a class. Classification is intentionally conservative for ClassExpired: non-auth 401/403 bodies (billing, model, validation, rate-limit) must not mark keys expired.

type UserInfo

type UserInfo struct {
	Username    string `json:"username"`
	DisplayName string `json:"displayName,omitempty"`
	Email       string `json:"email,omitempty"`
	Role        *int   `json:"role,omitempty"`
}

UserInfo holds the authenticated user's profile.

type VeloeraAdapter

type VeloeraAdapter struct {
	*BaseAdapter
}

VeloeraAdapter handles Veloera platforms (1M divisor + Veloera-User header). Directly extends BaseAdapter, NOT NewApiAdapter.

func (*VeloeraAdapter) Checkin

func (v *VeloeraAdapter) Checkin(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*CheckinResult, error)

Checkin: POST /api/user/checkin (veloeraHeaders, requires platformUserId).

func (*VeloeraAdapter) Detect

func (v *VeloeraAdapter) Detect(ctx context.Context, url string) (bool, error)

Detect probes GET /api/status and checks for "veloera" in system_name or version.

func (*VeloeraAdapter) GetBalance

func (v *VeloeraAdapter) GetBalance(ctx context.Context, baseURL, accessToken string, platformUserId *int, proxy *ProxyConfig) (*BalanceInfo, error)

GetBalance: quota=total, balance=quota-used, divisor=1,000,000 (NOT 500,000!).

func (*VeloeraAdapter) GetModels

func (v *VeloeraAdapter) GetModels(ctx context.Context, baseURL string, apiToken string, platformUserId *int, proxy *ProxyConfig) ([]string, error)

GetModels: GET /v1/models (Bearer auth only, no Veloera headers).

Jump to

Keyboard shortcuts

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