Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,8 @@ routing:
# Plan capacity weights relative to each provider's base paid plan (1.0), used by
# soonest-reset-first. Built-in: claude pro/team 1, max 5, max_5x 5, max_20x 20 (any max_<N>x
# tier weighs N); codex plus/team/business/enterprise/edu 1, prolite 5, pro 20, promax 50;
# xai supergrok 1, supergrok_heavy 10. The Codex ratios are approximate and change over time.
# xai supergrok 1, supergrok_heavy 10; qoder pro 1, pro+ 3, ultra 10. The Codex ratios are
# approximate and change over time.
# Entries here replace the built-in value for that plan; names are case-insensitive and
# "Max 20x" equals "max_20x".
# Each weight must be > 0 and <= 1000.
Expand Down Expand Up @@ -1390,7 +1391,9 @@ observability:
quota-history:
enabled: false
# Provider IDs to poll. Empty enables all supported providers and quota plugins.
# Built-in IDs: claude, codex, xai, antigravity, kimi, kimi-ai, meta, devin, mistral.
# Built-in IDs: claude, codex, xai, antigravity, kimi, kimi-ai, meta, devin, mistral, qoder.
# A Qoder account is an auth file holding a personal access token:
# {"type": "qoder", "personal_access_token": "<token>", "email": "<label>"}
providers: []
# Poll interval per account (Go duration or "<n>d"). Default 10m, minimum 5m.
interval: 10m
Expand Down
8 changes: 8 additions & 0 deletions internal/api/handlers/management/api_tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,14 @@ func (h *Handler) resolveTokenForAuth(ctx context.Context, auth *coreauth.Auth,
return token, errToken
}

if strings.EqualFold(strings.TrimSpace(auth.Provider), "qoder") {
// A Qoder credential holds the personal access token Qoder CLI reads
// from QODER_PERSONAL_ACCESS_TOKEN.
if v, ok := auth.Metadata["personal_access_token"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v), nil
}
}

return tokenValueForAuth(auth), nil
}

Expand Down
5 changes: 5 additions & 0 deletions internal/api/handlers/management/quota_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ func (h *Handler) quotaHistoryRequest(ctx context.Context, auth *coreauth.Auth,
return 0, nil, errors.New("failed to build request")
}
}
if strings.EqualFold(auth.Provider, "qoder") && doc.Get("personal_token").String() == "$TOKEN$" {
if errSet := doc.Set("personal_token", token); errSet != nil {
return 0, nil, errors.New("failed to build request")
}
}
data = doc.Bytes()
}
req, errReq := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(data))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@ func TestQuotaHistoryPostTransport(t *testing.T) {
for _, tc := range []struct{ provider, token, authorization, body string }{
{"devin", "fixture-\"-\\-token", "", `{"metadata":{"apiKey":"$TOKEN$"}}`},
{"meta", "", "Bearer dca:fixture", `{}`},
{"qoder", "fixture-\"-\\-pat", "", `{"personal_token":"$TOKEN$"}`},
} {
t.Run(tc.provider, func(t *testing.T) {
auth := &coreauth.Auth{ID: tc.provider, Provider: tc.provider, Metadata: map[string]any{"session_token": tc.token}}
if tc.provider == "qoder" {
// The personal access token wins over any other token field.
auth.Metadata = map[string]any{"personal_access_token": tc.token, "access_token": "fixture-other"}
}
headers := map[string]string{"Content-Type": "application/json"}
if tc.authorization != "" {
headers["Authorization"] = tc.authorization
Expand All @@ -77,6 +82,9 @@ func TestQuotaHistoryPostTransport(t *testing.T) {
if tc.provider == "devin" && ojson.Get(got.body, "metadata.apiKey").String() != tc.token {
t.Fatalf("invalid JSON token substitution %q", got.body)
}
if tc.provider == "qoder" && ojson.Get(got.body, "personal_token").String() != tc.token {
t.Fatalf("invalid JSON token substitution %q", got.body)
}
if strings.Contains(got.body, "$TOKEN$") {
t.Fatal("unresolved token placeholder")
}
Expand Down
1 change: 1 addition & 0 deletions internal/quotahistory/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ var providerPollers = map[string]providerPoller{
"meta": (*Recorder).fetchMeta,
"devin": (*Recorder).fetchDevin,
"mistral": (*Recorder).fetchMistral,
"qoder": (*Recorder).fetchQoder,
}

func (r *Recorder) fetchMistral(ctx context.Context, auth *coreauth.Auth) (map[string]Window, string, error) {
Expand Down
216 changes: 216 additions & 0 deletions internal/quotahistory/qoder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package quotahistory

import (
"context"
"errors"
"strings"
"time"

"github.com/MoeForge/moego/ojson"
coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth"
)

// Qoder accounts are read with a personal access token, the same way Qoder CLI
// reads them when QODER_PERSONAL_ACCESS_TOKEN is set: the token is exchanged
// for a short-lived session token, which then reads the credit usage. Neither
// request spends credits. Qoder is not routed through the hub; its readings are
// recorded for the panel only.
const (
QoderTokenExchangeURL = "https://api.qoder.sh/api/v1/jobToken/exchange"
// QoderUsageURL is what Qoder CLI's /usage shows; it names the credit refresh time.
QoderUsageURL = "https://api.qoder.sh/sash/api/v2/me/usage"
// QoderQuotaURL reports the same credits without the refresh time.
QoderQuotaURL = "https://api.qoder.sh/api/v2/quota/usage"
QoderPlanURL = "https://api.qoder.sh/api/v2/user/plan"

// qoderSessionLifetime is used when the exchange does not say when the
// session token expires; qoderSessionMargin renews one before it does.
qoderSessionLifetime = time.Hour
qoderSessionMargin = 10 * time.Minute
)

type qoderSession struct {
token string
expires time.Time
}

func qoderHeaders() map[string]string {
// Region 2 is the global (non-China) Qoder service, as Qoder CLI sends it.
return map[string]string{"Accept": "application/json", "Content-Type": "application/json", "X-Qoder-Region": "2"}
}

func (r *Recorder) fetchQoder(ctx context.Context, auth *coreauth.Auth) (map[string]Window, string, error) {
body, err := r.qoderGet(ctx, auth, QoderUsageURL)
if err != nil {
return nil, "", err
}
windows, userType, errParse := parseQoderUsage(body)
if errParse != nil {
// The quota endpoint carries the credits when the usage view has none,
// such as an organization's usage shown as a web page.
if body, err = r.qoderGet(ctx, auth, QoderQuotaURL); err != nil {
return nil, "", err
}
if windows, userType, errParse = parseQoderUsage(body); errParse != nil {
return nil, "", errParse
}
}
plan := r.cachedPlan(auth, func() string {
body, errPlan := r.qoderGet(ctx, auth, QoderPlanURL)
if errPlan != nil {
return ""
}
return parseQoderPlan(body)
})
if plan == "" {
plan = qoderPlanFromUserType(userType)
}
return windows, plan, nil
}

// qoderGet sends one GET with the account's session token. A cached session
// that is refused is replaced once, since Qoder may end it before it expires.
func (r *Recorder) qoderGet(ctx context.Context, auth *coreauth.Auth, url string) ([]byte, error) {
token, cached, err := r.qoderSession(ctx, auth)
if err != nil {
return nil, err
}
headers := qoderHeaders()
headers["Authorization"] = "Bearer " + token
body, err := r.get(ctx, auth, url, headers)
if err == nil || !cached || (err.Error() != "HTTP 401" && err.Error() != "HTTP 403") {
return body, err
}
r.forgetQoderSession(auth.ID)
if token, _, err = r.qoderSession(ctx, auth); err != nil {
return nil, err
}
headers["Authorization"] = "Bearer " + token
return r.get(ctx, auth, url, headers)
}

// qoderSession returns a live session token for the account, exchanging its
// personal access token ("$TOKEN$", filled in by the transport) when none is
// cached. cached reports whether the token came from the cache.
func (r *Recorder) qoderSession(ctx context.Context, auth *coreauth.Auth) (token string, cached bool, err error) {
r.plansMu.Lock()
session, ok := r.qoderSessions[auth.ID]
r.plansMu.Unlock()
if ok && r.now().Before(session.expires) {
return session.token, true, nil
}
body, err := r.request(ctx, auth, "POST", QoderTokenExchangeURL, qoderHeaders(), []byte(`{"personal_token":"$TOKEN$"}`))
if err != nil {
return "", false, err
}
session, ok = parseQoderSession(body, r.now())
if !ok {
return "", false, errors.New("qoder token exchange returned no token")
}
r.plansMu.Lock()
r.qoderSessions[auth.ID] = session
r.plansMu.Unlock()
return session.token, false, nil
}

func (r *Recorder) forgetQoderSession(authID string) {
r.plansMu.Lock()
delete(r.qoderSessions, authID)
r.plansMu.Unlock()
}

// parseQoderSession reads the token exchange answer. The session is kept until
// shortly before it expires.
func parseQoderSession(body []byte, now time.Time) (qoderSession, bool) {
root, err := usageRoot(body)
if err != nil {
return qoderSession{}, false
}
token := firstString(root.Get("token"), root.Get("access_token"), root.Get("device_token"))
if token == "" {
return qoderSession{}, false
}
expires := now.Add(qoderSessionLifetime)
if at := resetMs(firstExisting(root.Get("expires_at"), root.Get("expiresAt"))); at != nil {
expires = time.UnixMilli(*at)
}
if expires.Sub(now) > 2*qoderSessionMargin {
expires = expires.Add(-qoderSessionMargin)
}
return qoderSession{token: token, expires: expires}, true
}

// parseQoderUsage maps a Qoder credit usage answer to windows: "monthly" for
// the plan's credits, which refresh at the plan cycle, and "add_on" for bought
// credits, which do not renew. It accepts the usage view
// ({"displayMode":"qoder","qoderUsage":{...}}) and the bare quota object.
// Credit fractions are computed from used and total; the reported percentages
// are rounded.
func parseQoderUsage(body []byte) (map[string]Window, string, error) {
root, err := usageRoot(body)
if err != nil {
return nil, "", err
}
usage := root
if nested := firstExisting(root.Get("qoderUsage"), root.Get("qoder_usage")); nested.Exists() {
usage = nested
} else if mode := firstString(root.Get("displayMode")); mode != "" && mode != "qoder" {
// An organization's usage is shown on a web page, without credit figures.
return nil, "", errEmptyPayload
}
if !usage.IsObject() {
return nil, "", errEmptyPayload
}
windows := make(map[string]Window)
if window, ok := qoderCredits(firstExisting(usage.Get("userQuota"), usage.Get("user_quota"))); ok {
window.Label = "Plan credits"
window.ResetsAt = resetMs(firstExisting(usage.Get("refreshAt"), usage.Get("refresh_at"), usage.Get("expiresAt"), usage.Get("expires_at")))
if window.ResetsAt != nil {
// The plan cycle is a calendar month ending at the refresh time.
reset := time.UnixMilli(*window.ResetsAt).UTC()
window.PeriodHours = reset.Sub(reset.AddDate(0, -1, 0)).Hours()
}
windows["monthly"] = window
}
if window, ok := qoderCredits(firstExisting(usage.Get("addOnQuota"), usage.Get("add_on_quota"))); ok {
window.Label = "Add-on credits"
windows["add_on"] = window
}
if len(windows) == 0 {
return nil, "", errEmptyPayload
}
return windows, firstString(usage.Get("userType"), usage.Get("user_type")), nil
}

// qoderCredits reads one credit allowance ({"total","used","remaining"}).
// An allowance of no credits is not a window.
func qoderCredits(raw ojson.Result) (Window, bool) {
total, hasTotal := number(raw.Get("total"))
if !raw.IsObject() || !hasTotal || total <= 0 {
return Window{}, false
}
used, hasUsed := number(raw.Get("used"))
if !hasUsed {
remaining, hasRemaining := number(raw.Get("remaining"))
if !hasRemaining {
return Window{}, false
}
used = total - remaining
}
return Window{UsedPercent: clampedPercent(used / total * 100)}, true
}

// parseQoderPlan names the plan tier ("Pro", "Ultra").
func parseQoderPlan(body []byte) string {
root, err := usageRoot(body)
if err != nil {
return ""
}
return firstString(root.Get("plan_tier_name"), root.Get("planTierName"))
}

// qoderPlanFromUserType turns a user type ("personal_ultra") into a plan name
// ("ultra") when the plan endpoint has not named one.
func qoderPlanFromUserType(userType string) string {
return strings.TrimPrefix(strings.ToLower(strings.TrimSpace(userType)), "personal_")
}
Loading