Skip to content
Draft
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
4 changes: 4 additions & 0 deletions .github/workflows/pr-test-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ jobs:
with:
go-version-file: go.mod
cache: true
- name: Test Claude quota reconciliation
env:
CGO_ENABLED: "0"
run: go test -tags purego -count=1 -run '(ClaudeQuota|ManagementQuotaReconcile)' ./sdk/cliproxy/auth ./internal/api
- name: Refresh models catalog
run: bash .github/scripts/refresh-model-catalogs.sh
- name: Build
Expand Down
50 changes: 50 additions & 0 deletions docs/management-api-v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ retain the corresponding business operation's fields.
| `/server/latest-version` | GET | Get latest release information. |
| `/requests/api-call` | POST | Make an authenticated upstream call. |
| `/routing/cooldown/reset` | POST | Clear credential cooldown. |
| `/routing/quota/reconcile` | POST | Re-read Claude OAuth usage and selectively reconcile proven restored quota. |
| `/routing/model-definitions/<channel>` | GET | Get model definitions. |
| `/observability/logs` | GET, DELETE | Read or clear application logs. |
| `/observability/logs/errors` | GET | List error-log files. |
Expand Down Expand Up @@ -308,3 +309,52 @@ accepts legacy, new, or mixed layouts, normalizing v8 documents on save.

Plugin OAuth uses the shared v8 login endpoint. Other plugin-defined HTTP
extensions retain their declared `/v0/management` routes.

### Claude OAuth quota reconciliation

`POST /v8/management/routing/quota/reconcile` accepts exactly
`{"auth_index":"<runtime-index>"}` under the usual management authentication.
It makes one non-spending `GET https://api.anthropic.com/api/oauth/usage` using
the stored OAuth token. It never redeems a grant, renews a token, or runs inference.
Caller-supplied URLs, headers, proxy settings, and usage values are rejected.
Redirects are refused. This control-plane read has a 30-second deadline so a
stalled provider cannot hold the shared OAuth refresh workers indefinitely;
inference timeout behavior is unchanged.

A valid fresh observation clears only quota restrictions attributed to windows
that are now known below 100%. Missing/null claimed windows, stale reset timestamps, unrecognized claims,
and any applicable exhausted window retain the restriction. An unrelated null
window remains unknown: for example, fresh weekly headroom can clear a stored
weekly-only block even if the short window is null, but it cannot clear a stored
short-window block.
Independent model errors, disabled credentials/models, and active forced
cooldowns remain. Token, registration, file, or routing changes during the read
make its result stale and prevent application.

Success returns `status:"ok"`, `auth_index`, `outcome` (`reconciled`, `unchanged`,
or `blocked`), `observed_at`, `models`, `remaining_quota_blocks`, and
`persistence:"ok"`. A reconciled credential can still have independent blocked
models. A failed cooldown-store write returns HTTP 503 with `status:"partial"`,
`runtime_applied:true`, and `persistence:"failed"`; retrying this same endpoint
repairs persistence without spending or redeeming again. A stale read returns
409 with `runtime_applied:false`. Unsupported credentials return 400, missing
indexes 404, and unavailable/malformed usage 502.

The existing refresh loop also checks locally quota-blocked enabled Claude OAuth
credentials every 15 minutes, including a retry floor after stale/error attempts.
It uses the same guarded operation and leaves token-renewal scheduling intact.
A pending persistence failure remains eligible for retry after routing recovers.
Home-managed, disabled, invalid-token, and signed-out credentials are excluded.

Credential lists expose `snapshot_at` for list generation time. Per-credential
`quota.observed_at` is the time of the last actual provider observation; listing
or failed reconciliation never refreshes it. `quota.signals` replaces the whole
passive snapshot and carries `Anthropic-Usage-Source: oauth_usage`, percentage
values (0–100) under `Anthropic-Usage-<window>-Utilization`, and optional RFC3339
`Anthropic-Usage-<window>-Resets-At`. Windows are `five_hour`, `seven_day`,
`seven_day_opus`, `seven_day_sonnet`, and `seven_day_oauth_apps`; null/missing
windows are omitted and remain unknown. Previous rejected response headers are
not merged into this snapshot. `quota_reconciliation` separately exposes the last
attempt, next retry, status, and persistence-pending flag. These observations are
runtime-only; the existing cooldown-store format is unchanged and remains
readable by the previous release.
7 changes: 5 additions & 2 deletions internal/api/handlers/management/auth_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ func (h *Handler) ListAuthFiles(c *gin.Context) {
nameJ, _ := files[j]["name"].(string)
return strings.ToLower(nameI) < strings.ToLower(nameJ)
})
c.JSON(200, gin.H{"observed_at": observedAt, "files": files})
c.JSON(200, gin.H{"observed_at": observedAt, "snapshot_at": observedAt, "files": files})
}

func parseAuthFilesPagination(c *gin.Context) (authFilesPagination, error) {
Expand Down Expand Up @@ -219,7 +219,7 @@ func (p authFilesPagination) bounds(total int) (int, int) {
}

func authFilesListResponse(observedAt time.Time, files []gin.H, pagination authFilesPagination, total, end int) gin.H {
response := gin.H{"observed_at": observedAt, "files": files}
response := gin.H{"observed_at": observedAt, "snapshot_at": observedAt, "files": files}
if pagination.enabled {
response["total"] = total
response["page"] = pagination.page
Expand Down Expand Up @@ -688,6 +688,9 @@ func (h *Handler) buildAuthFileEntryLocked(auth *coreauth.Auth, quota authFileQu
entry["failed"] = auth.Failed
entry["recent_requests"] = auth.RecentRequestsSnapshot(time.Now())
entry["quota"] = quotaObservationPayloadForProvider(auth.Provider, auth.Quota)
if strings.EqualFold(auth.Provider, "claude") {
entry["quota_reconciliation"] = auth.QuotaReconcile
}
if modelQuotas := modelQuotaObservationPayload(auth.Provider, auth.ModelStates); len(modelQuotas) > 0 {
entry["model_quotas"] = modelQuotas
}
Expand Down
67 changes: 67 additions & 0 deletions internal/api/handlers/management/quota_reconcile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package management

import (
"errors"
"io"
"net/http"
"strings"

"github.com/MoeForge/moego/ojson"
"github.com/gin-gonic/gin"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
)

// ReconcileQuota accepts only a runtime auth index. Provider observations and
// transport destinations are always obtained by the auth manager itself.
func (h *Handler) ReconcileQuota(c *gin.Context) {
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
return
}
body, errRead := io.ReadAll(io.LimitReader(c.Request.Body, 4097))
root := ojson.ParseBytes(body)
index := root.Get("auth_index")
fields := 0
validFields := true
root.ForEach(func(key, value ojson.Result) bool {
fields++
validFields = validFields && key.String() == "auth_index"
return true
})
if errRead != nil || len(body) > 4096 || !ojson.ValidBytes(body) || !root.IsObject() || !validFields || fields != 1 || index.Type != ojson.String || strings.TrimSpace(index.String()) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "body must contain only auth_index"})
return
}
result, errReconcile := h.authManager.ReconcileClaudeQuotaByIndex(c.Request.Context(), index.String())
if result == nil {
status := http.StatusBadGateway
state := "error"
message := "provider quota usage unavailable"
if errors.Is(errReconcile, coreauth.ErrClaudeQuotaUnsupported) {
status = http.StatusBadRequest
message = errReconcile.Error()
}
if errors.Is(errReconcile, coreauth.ErrQuotaObservationStale) {
status = http.StatusConflict
state = "stale"
message = errReconcile.Error()
}
if errors.Is(errReconcile, coreauth.ErrQuotaAuthNotFound) {
status = http.StatusNotFound
message = errReconcile.Error()
}
c.JSON(status, gin.H{"status": state, "error": message, "runtime_applied": false})
return
}
payload := gin.H{"status": "ok", "auth_index": result.AuthIndex, "outcome": result.Outcome,
"observed_at": result.ObservedAt, "models": result.Models, "remaining_quota_blocks": result.RemainingQuotaBlocks, "persistence": "ok"}
if errors.Is(errReconcile, coreauth.ErrQuotaPersistence) {
payload["status"] = "partial"
payload["error"] = errReconcile.Error()
payload["runtime_applied"] = true
payload["persistence"] = "failed"
c.JSON(http.StatusServiceUnavailable, payload)
return
}
c.JSON(http.StatusOK, payload)
}
1 change: 1 addition & 0 deletions internal/api/server_management_v8.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func (s *Server) registerManagementV8Routes() {
v8.GET("/server/latest-version", s.mgmt.GetLatestVersion)
v8.POST("/requests/api-call", s.mgmt.APICall)
v8.POST("/routing/cooldown/reset", s.mgmt.ResetQuota)
v8.POST("/routing/quota/reconcile", s.mgmt.ReconcileQuota)
v8.GET("/routing/model-definitions/:channel", s.mgmt.GetStaticModelDefinitions)
v8.POST("/routing/model-definitions/refresh", s.mgmt.RefreshModelDefinitions)
v8.POST("/models/refresh", s.mgmt.RefreshModelDefinitions)
Expand Down
Loading
Loading