diff --git a/.github/workflows/pr-test-build.yml b/.github/workflows/pr-test-build.yml index 02cfacefe61..a45f47aa135 100644 --- a/.github/workflows/pr-test-build.yml +++ b/.github/workflows/pr-test-build.yml @@ -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 diff --git a/docs/management-api-v8.md b/docs/management-api-v8.md index 3dbc15daf73..a4a4f940f1d 100644 --- a/docs/management-api-v8.md +++ b/docs/management-api-v8.md @@ -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/` | GET | Get model definitions. | | `/observability/logs` | GET, DELETE | Read or clear application logs. | | `/observability/logs/errors` | GET | List error-log files. | @@ -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":""}` 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--Utilization`, and optional RFC3339 +`Anthropic-Usage--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. diff --git a/internal/api/handlers/management/auth_files.go b/internal/api/handlers/management/auth_files.go index 93af86bada3..3c4afddd2f5 100644 --- a/internal/api/handlers/management/auth_files.go +++ b/internal/api/handlers/management/auth_files.go @@ -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) { @@ -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 @@ -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 } diff --git a/internal/api/handlers/management/quota_reconcile.go b/internal/api/handlers/management/quota_reconcile.go new file mode 100644 index 00000000000..54dee1d01a6 --- /dev/null +++ b/internal/api/handlers/management/quota_reconcile.go @@ -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) +} diff --git a/internal/api/server_management_v8.go b/internal/api/server_management_v8.go index 2b4dee04084..3844d142156 100644 --- a/internal/api/server_management_v8.go +++ b/internal/api/server_management_v8.go @@ -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) diff --git a/internal/api/server_quota_reconcile_test.go b/internal/api/server_quota_reconcile_test.go new file mode 100644 index 00000000000..4be40fc43f7 --- /dev/null +++ b/internal/api/server_quota_reconcile_test.go @@ -0,0 +1,334 @@ +package api + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/api/handlers/management" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + internallogging "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type reconcileIntegrationTransport struct { + t *testing.T + body string + calls int +} + +func (p *reconcileIntegrationTransport) RoundTripperFor(*coreauth.Auth) http.RoundTripper { return p } +func (p *reconcileIntegrationTransport) RoundTrip(r *http.Request) (*http.Response, error) { + p.calls++ + if r.Method != "GET" || r.URL.String() != "https://api.anthropic.com/api/oauth/usage" || r.Body != nil { + p.t.Fatalf("unexpected upstream operation: %s %s", r.Method, r.URL) + } + if r.Header.Get("Authorization") != "Bearer synthetic-oauth-token" || r.Header.Get("X-Caller-Header") != "" { + p.t.Fatal("provider request did not use only saved authorization") + } + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(p.body))}, nil +} + +type reconcileIntegrationExecutor struct{ ordinary, streamed []string } + +func (*reconcileIntegrationExecutor) Identifier() string { return "claude" } +func (e *reconcileIntegrationExecutor) Execute(_ context.Context, a *coreauth.Auth, _ executor.Request, _ executor.Options) (executor.Response, error) { + e.ordinary = append(e.ordinary, a.ID) + return executor.Response{Payload: []byte(`{"ok":true}`)}, nil +} +func (e *reconcileIntegrationExecutor) ExecuteStream(_ context.Context, a *coreauth.Auth, _ executor.Request, _ executor.Options) (*executor.StreamResult, error) { + e.streamed = append(e.streamed, a.ID) + chunks := make(chan executor.StreamChunk, 1) + chunks <- executor.StreamChunk{Payload: []byte("data: ok\n\n")} + close(chunks) + return &executor.StreamResult{Chunks: chunks}, nil +} +func (*reconcileIntegrationExecutor) Refresh(_ context.Context, a *coreauth.Auth) (*coreauth.Auth, error) { + return a, nil +} +func (*reconcileIntegrationExecutor) CountTokens(context.Context, *coreauth.Auth, executor.Request, executor.Options) (executor.Response, error) { + return executor.Response{}, errors.New("not used") +} +func (*reconcileIntegrationExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not used") +} + +type reconcileIntegrationStore struct { + coreauth.CooldownStateStore + fail bool +} + +func (s *reconcileIntegrationStore) Save(ctx context.Context, records []coreauth.CooldownStateRecord) error { + if s.fail { + return errors.New("synthetic disk failure") + } + return s.CooldownStateStore.Save(ctx, records) +} + +func TestManagementQuotaReconcileRoutingAndRestart(t *testing.T) { + for _, tc := range []struct { + name string + partial bool + window, usage string + }{ + {"durable success", false, "5h", `{"five_hour":{"utilization":0},"seven_day":{"utilization":42}}`}, + {"failed persistence then retry", true, "5h", `{"five_hour":{"utilization":0},"seven_day":{"utilization":42}}`}, + {"weekly restored short unknown", false, "7d", `{"five_hour":null,"seven_day":{"utilization":42}}`}, + } { + t.Run(tc.name, func(t *testing.T) { + partial := tc.partial + t.Setenv("MANAGEMENT_PASSWORD", "quota-management-test-key") + ctx := context.Background() + cfg := &config.Config{AuthDir: t.TempDir()} + m := coreauth.NewManager(nil, &coreauth.HeadroomSelector{}, nil) + m.SetConfig(cfg) + store := &reconcileIntegrationStore{CooldownStateStore: coreauth.NewFileCooldownStateStoreWithAuthDir(cfg.AuthDir, cfg.AuthDir)} + if !m.SwapCooldownStateStore(ctx, store, false) { + t.Fatal("store setup failed") + } + id := "quota-route-" + strings.ReplaceAll(t.Name(), "/", "-") + newAuth := func() *coreauth.Auth { + return &coreauth.Auth{ID: id, FileName: id + ".json", Provider: "claude", Status: coreauth.StatusActive, Attributes: map[string]string{coreauth.AttributeRuntimeOnly: "true"}, Metadata: map[string]any{"access_token": "synthetic-oauth-token"}} + } + a, errRegister := m.Register(ctx, newAuth()) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := registry.GetGlobalRegistry() + reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: "claude-sonnet-route"}, {ID: "claude-opus-route"}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + after := time.Hour + m.MarkResult(ctx, coreauth.Result{AuthID: id, Provider: "claude", Model: "claude-opus-route", RetryAfter: &after, Error: &coreauth.Error{HTTPStatus: 503, Message: "independent model failure"}}) + rejectedCtx := internallogging.WithResponseHeadersHolder(ctx) + internallogging.SetResponseHeaders(rejectedCtx, http.Header{"Anthropic-Ratelimit-Unified-" + tc.window + "-Status": []string{"rejected"}}) + after = 24 * time.Hour + m.MarkResult(rejectedCtx, coreauth.Result{AuthID: id, Provider: "claude", Model: "claude-sonnet-route", CredentialScope: true, RetryAfter: &after, Error: &coreauth.Error{HTTPStatus: 429, Message: "quota rejected"}}) + provider := &reconcileIntegrationTransport{t: t, body: tc.usage} + m.SetRoundTripperProvider(provider) + exec := &reconcileIntegrationExecutor{} + m.RegisterExecutor(exec) + dispatch := func(stream bool, model string) error { + if !stream { + _, errExecute := m.Execute(ctx, []string{"claude"}, executor.Request{Model: model}, executor.Options{}) + return errExecute + } + result, errExecute := m.ExecuteStream(ctx, []string{"claude"}, executor.Request{Model: model}, executor.Options{Stream: true}) + if result != nil { + for chunk := range result.Chunks { + if chunk.Err != nil { + return chunk.Err + } + } + } + return errExecute + } + for _, stream := range []bool{false, true} { + if errExecute := dispatch(stream, "claude-sonnet-route"); errExecute == nil { + t.Fatal("locally exhausted credential dispatched before reconcile") + } + } + if len(exec.ordinary)+len(exec.streamed) != 0 || provider.calls != 0 { + t.Fatal("blocked request reached executor/provider") + } + h := management.NewHandlerWithoutConfigFilePath(cfg, m) + s := &Server{cfg: cfg, engine: gin.New(), mgmt: h} + s.managementRoutesEnabled.Store(true) + s.registerManagementRoutes() + request := func(method, path, body, key string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.RemoteAddr = "127.0.0.1:1234" + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + r.Header.Set("X-Caller-Header", "untrusted") + w := httptest.NewRecorder() + s.engine.ServeHTTP(w, r) + return w + } + body := `{"auth_index":"` + a.Index + `"}` + for _, key := range []string{"", "wrong-key"} { + w := request("POST", "/v8/management/routing/quota/reconcile", body, key) + if w.Code != 401 || provider.calls != 0 { + t.Fatalf("unauthenticated request reached provider: status=%d calls=%d", w.Code, provider.calls) + } + } + store.fail = partial + w := request("POST", "/v8/management/routing/quota/reconcile", body, "quota-management-test-key") + wantStatus := 200 + if partial { + wantStatus = 503 + } + if w.Code != wantStatus { + t.Fatalf("status=%d body=%s", w.Code, w.Body) + } + response := ojson.ParseBytes(w.Body.Bytes()) + if response.Get("observed_at").String() == "" || response.Get("auth_index").String() != a.Index || strings.Contains(w.Body.String(), "synthetic-oauth-token") { + t.Fatalf("unexpected result: %s", w.Body) + } + for _, stream := range []bool{false, true} { + if errExecute := dispatch(stream, "claude-sonnet-route"); errExecute != nil { + t.Fatalf("fresh authoritative usage still blocked dispatch stream=%v (ordinary executor calls=%d streamed=%d): %v", stream, len(exec.ordinary), len(exec.streamed), errExecute) + } + } + if response.Get("outcome").String() != "reconciled" { + t.Fatalf("unexpected reconcile outcome: %s", w.Body) + } + current, _ := m.GetByID(id) + if current.Quota.Exceeded { + t.Fatal("proven credential quota not cleared") + } + if state := current.ModelStates["claude-opus-route"]; state == nil || state.LastError == nil || state.LastError.HTTPStatus != 503 { + t.Fatalf("independent model state lost: %+v", state) + } + if partial { + oldRecords, errLoad := store.Load(ctx) + if errLoad != nil { + t.Fatal(errLoad) + } + oldStillBlocked := false + for _, record := range oldRecords { + if record.Quota.Reason == "credential_quota" { + oldStillBlocked = true + } + } + if !oldStillBlocked || response.Get("runtime_applied").Bool() != true || response.Get("persistence").String() != "failed" { + t.Fatal("failed persistence was hidden") + } + negativeReload := coreauth.NewManager(nil, nil, nil) + negativeReload.SetConfig(cfg) + if _, errReload := negativeReload.Register(ctx, newAuth()); errReload != nil { + t.Fatal(errReload) + } + if !negativeReload.SwapCooldownStateStore(ctx, store, false) { + t.Fatal("negative reload setup") + } + if errRestore := negativeReload.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatal(errRestore) + } + negativeAuth, _ := negativeReload.GetByID(id) + if !negativeAuth.Quota.Exceeded { + t.Fatal("negative restart did not preserve failed durable write") + } + store.fail = false + w = request("POST", "/v8/management/routing/quota/reconcile", body, "quota-management-test-key") + if w.Code != 200 { + t.Fatalf("persistence retry failed: %d %s", w.Code, w.Body) + } + } + listed := request("GET", "/v8/management/credentials", "", "quota-management-test-key") + list := ojson.ParseBytes(listed.Body.Bytes()) + if listed.Code != 200 || list.Get("snapshot_at").String() == "" { + t.Fatalf("missing snapshot freshness: %s", listed.Body) + } + found := false + list.Get("files").ForEach(func(_, entry ojson.Result) bool { + if entry.Get("auth_index").String() == a.Index { + found = true + if entry.Get("quota.observed_at").String() == "" || entry.Get("quota.signals.Anthropic-Usage-Source").String() != "oauth_usage" || entry.Get("quota.signals.Anthropic-Ratelimit-Unified-5h-Status").String() != "" { + t.Fatalf("stale list observation: %s", entry.Raw) + } + } + return true + }) + if !found { + t.Fatal("restored credential missing from list") + } + for _, stream := range []bool{false, true} { + if errExecute := dispatch(stream, "claude-opus-route"); errExecute == nil { + t.Fatal("independent model failure became selectable") + } + } + if len(exec.ordinary) != 1 || len(exec.streamed) != 1 || exec.ordinary[0] != id || exec.streamed[0] != id { + t.Fatalf("dispatch attribution ordinary=%v stream=%v", exec.ordinary, exec.streamed) + } + reloaded := coreauth.NewManager(nil, &coreauth.HeadroomSelector{}, nil) + reloaded.SetConfig(cfg) + if _, errReload := reloaded.Register(ctx, newAuth()); errReload != nil { + t.Fatal(errReload) + } + if !reloaded.SwapCooldownStateStore(ctx, store, false) { + t.Fatal("reload store setup") + } + if errRestore := reloaded.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatal(errRestore) + } + reloaded.RegisterExecutor(exec) + if _, errExecute := reloaded.Execute(ctx, []string{"claude"}, executor.Request{Model: "claude-sonnet-route"}, executor.Options{}); errExecute != nil { + t.Fatalf("restart restored obsolete cooldown: %v", errExecute) + } + if _, errExecute := reloaded.Execute(ctx, []string{"claude"}, executor.Request{Model: "claude-opus-route"}, executor.Options{}); errExecute == nil { + t.Fatal("restart erased independent model failure") + } + }) + } +} + +func TestManagementQuotaReconcileRejectsCallerAuthority(t *testing.T) { + t.Setenv("MANAGEMENT_PASSWORD", "quota-management-test-key") + m := coreauth.NewManager(nil, nil, nil) + a, errRegister := m.Register(context.Background(), &coreauth.Auth{ID: "quota-authority", Provider: "claude", Metadata: map[string]any{"access_token": "synthetic-oauth-token"}}) + if errRegister != nil { + t.Fatal(errRegister) + } + p := &reconcileIntegrationTransport{t: t, body: `{"five_hour":{"utilization":0}}`} + m.SetRoundTripperProvider(p) + cfg := &config.Config{} + s := &Server{cfg: cfg, engine: gin.New(), mgmt: management.NewHandlerWithoutConfigFilePath(cfg, m)} + s.managementRoutesEnabled.Store(true) + s.registerManagementRoutes() + for _, tc := range []struct { + body string + status int + }{ + {`{"auth_index":"` + a.Index + `","url":"https://example.invalid"}`, 400}, + {`{"auth_index":"` + a.Index + `","host":"example.invalid"}`, 400}, + {`{"auth_index":"` + a.Index + `","proxy":"http://example.invalid"}`, 400}, + {`{"auth_index":"` + a.Index + `","quota":{"utilization":0}}`, 400}, + {`{"auth_index":"` + a.Index + `","auth_index":"` + a.Index + `"}`, 400}, + {`{"auth_id":"quota-authority"}`, 400}, {`{"auth_index":"quota-authority"}`, 404}, + {`{"auth_index":123}`, 400}, {`null`, 400}, {`{"auth_index":"` + strings.Repeat("x", 4096) + `"}`, 400}, + } { + r := httptest.NewRequest("POST", "/v8/management/routing/quota/reconcile", strings.NewReader(tc.body)) + r.RemoteAddr = "127.0.0.1:1234" + r.Header.Set("Authorization", "Bearer quota-management-test-key") + w := httptest.NewRecorder() + s.engine.ServeHTTP(w, r) + if w.Code != tc.status || p.calls != 0 { + t.Fatalf("body=%s status=%d provider calls=%d", tc.body, w.Code, p.calls) + } + } + for _, kind := range []string{"disabled", "api key", "other provider"} { + t.Run(kind, func(t *testing.T) { + updated, _ := m.GetByID(a.ID) + updated.Disabled = kind == "disabled" + updated.Provider = "claude" + updated.Attributes = map[string]string{} + if kind == "api key" { + updated.Attributes[coreauth.AttributeAuthKind] = coreauth.AuthKindAPIKey + } + if kind == "other provider" { + updated.Provider = "codex" + } + if _, errUpdate := m.Update(context.Background(), updated); errUpdate != nil { + t.Fatal(errUpdate) + } + r := httptest.NewRequest("POST", "/v8/management/routing/quota/reconcile", strings.NewReader(`{"auth_index":"`+a.Index+`"}`)) + r.RemoteAddr = "127.0.0.1:1234" + r.Header.Set("Authorization", "Bearer quota-management-test-key") + w := httptest.NewRecorder() + s.engine.ServeHTTP(w, r) + if w.Code != 400 || p.calls != 0 { + t.Fatalf("%s status=%d body=%s calls=%d", kind, w.Code, w.Body, p.calls) + } + }) + } +} diff --git a/sdk/cliproxy/auth/auto_refresh_loop.go b/sdk/cliproxy/auth/auto_refresh_loop.go index b7f87bf02d0..8be067595d6 100644 --- a/sdk/cliproxy/auth/auto_refresh_loop.go +++ b/sdk/cliproxy/auth/auto_refresh_loop.go @@ -36,6 +36,7 @@ type authRefreshJob struct { pendingUntil time.Time loop *authAutoRefreshLoop running bool // guarded by manager.mu + quotaReconcile bool } func newAuthAutoRefreshLoop(manager *Manager, interval time.Duration, concurrency int) *authAutoRefreshLoop { @@ -100,14 +101,23 @@ func (l *authAutoRefreshLoop) worker(ctx context.Context) { if job == nil { continue } - if l.manager.beginRefreshJob(ctx, job) { - _, _ = l.manager.refreshAuthForRequestAtEpoch(ctx, job.id, "", job.registrationEpoch) - } - l.manager.finishRefreshJob(job, time.Time{}, false) + l.runRefreshJob(ctx, job) } } } +func (l *authAutoRefreshLoop) runRefreshJob(ctx context.Context, job *authRefreshJob) { + defer l.manager.finishRefreshJob(job, time.Time{}, false) + if !l.manager.beginRefreshJob(ctx, job) { + return + } + if job.quotaReconcile { + _, _ = l.manager.reconcileClaudeQuota(ctx, job.id, job.registrationEpoch) + } else { + _, _ = l.manager.refreshAuthForRequestAtEpoch(ctx, job.id, "", job.registrationEpoch) + } +} + func (l *authAutoRefreshLoop) releaseQueuedJobs() { l.manager.mu.RLock() var jobs []*authRefreshJob @@ -278,6 +288,8 @@ func (l *authAutoRefreshLoop) handleDueAuth(ctx context.Context, now time.Time, next, shouldSchedule := manager.nextRefreshCheckAt(now, auth, l.interval) shouldRefresh := manager.shouldRefresh(auth, now) exec, _ := manager.executorLocked(executorKeyFromAuth(auth)) + quotaAt, quotaScheduled := manager.claudeQuotaRevalidateAt(auth, now) + quotaDue := quotaScheduled && !quotaAt.After(now) registrationEpoch := auth.RegistrationEpoch manager.mu.RUnlock() @@ -291,7 +303,7 @@ func (l *authAutoRefreshLoop) handleDueAuth(ctx context.Context, now time.Time, return } - if exec == nil { + if exec == nil && !quotaDue { l.upsert(authID, now.Add(l.interval)) return } @@ -398,7 +410,16 @@ func (m *Manager) nextRefreshCheckAt(now time.Time, auth *Auth, interval time.Du if m.codexAutoRefreshUnavailable(auth, now) { return time.Time{}, false } - return nextRefreshCheckAt(now, auth, interval) + if auth != nil { + if job := m.refreshJobs[auth.ID]; job != nil && job.quotaReconcile { + return job.pendingUntil, true + } + } + next, scheduled := nextRefreshCheckAt(now, auth, interval) + if quotaAt, quotaScheduled := m.claudeQuotaRevalidateAt(auth, now); quotaScheduled && (!scheduled || quotaAt.Before(next)) { + return quotaAt, true + } + return next, scheduled } func nextRefreshCheckAt(now time.Time, auth *Auth, interval time.Duration) (time.Time, bool) { diff --git a/sdk/cliproxy/auth/claude_quota_reconcile.go b/sdk/cliproxy/auth/claude_quota_reconcile.go new file mode 100644 index 00000000000..c3e46f902cc --- /dev/null +++ b/sdk/cliproxy/auth/claude_quota_reconcile.go @@ -0,0 +1,494 @@ +package auth + +import ( + "context" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil" + log "github.com/sirupsen/logrus" +) + +const claudeUsageURL = "https://api.anthropic.com/api/oauth/usage" + +// This control-plane read is bounded to keep quota polling from starving OAuth +// refresh workers. Inference transports and their timeout policy are unchanged. +const claudeQuotaReadTimeout = 30 * time.Second +const claudeQuotaRevalidateInterval = 15 * time.Minute + +var ( + ErrQuotaAuthNotFound = errors.New("auth not found") + ErrClaudeQuotaUnsupported = errors.New("quota reconciliation requires an enabled Claude OAuth credential") + ErrQuotaObservationStale = errors.New("credential changed during quota observation") + ErrQuotaUsageUnavailable = errors.New("provider quota usage unavailable") + ErrQuotaPersistence = errors.New("routing updated; persistence retry required") +) + +// QuotaReconcileState separates the last provider read from a status snapshot. +// It is runtime-only: cooldown stores own durable routing restrictions. +type QuotaReconcileState struct { + CheckedAt time.Time `json:"checked_at,omitempty"` + NextCheckAt time.Time `json:"next_check_at,omitempty"` + Status string `json:"status,omitempty"` + PersistencePending bool `json:"persistence_pending"` +} + +type QuotaReconcileResult struct { + AuthIndex string `json:"auth_index"` + Outcome string `json:"outcome"` + ObservedAt time.Time `json:"observed_at"` + Models []string `json:"models"` + RemainingQuotaBlocks int `json:"remaining_quota_blocks"` +} + +type claudeUsageWindow struct { + used float64 + reset time.Time +} +type claudeQuotaUsage map[string]claudeUsageWindow + +// ReconcileClaudeQuota performs a non-spending, fixed-origin usage read. Neither +// token renewal nor a successful read is treated as an inference success. +func (m *Manager) ReconcileClaudeQuota(ctx context.Context, id string) (*QuotaReconcileResult, error) { + return m.reconcileClaudeQuota(ctx, id, 0) +} + +// ReconcileClaudeQuotaByIndex binds the management target to its registration +// before any provider read, including replacement between lookup and dispatch. +func (m *Manager) ReconcileClaudeQuotaByIndex(ctx context.Context, index string) (*QuotaReconcileResult, error) { + m.mu.RLock() + var id string + var epoch uint64 + for _, a := range m.auths { + if a.Index == index { + id, epoch = a.ID, a.RegistrationEpoch + break + } + } + m.mu.RUnlock() + if id == "" { + return nil, ErrQuotaAuthNotFound + } + return m.reconcileClaudeQuota(ctx, id, epoch) +} + +func claudeQuotaEligible(a *Auth) bool { + return a != nil && strings.EqualFold(a.Provider, "claude") && a.AuthKind() == AuthKindOAuth && + !a.Disabled && a.Status != StatusDisabled && !hasUnauthorizedAuthFailure(a) && + !a.RequiresSignIn && a.RejectedAccessToken == "" && authAccessToken(a) != "" +} + +func (m *Manager) reconcileClaudeQuota(ctx context.Context, id string, epoch uint64) (*QuotaReconcileResult, error) { + if ctx == nil { + ctx = context.Background() + } + ctx, cancel := context.WithTimeout(ctx, claudeQuotaReadTimeout) + defer cancel() + base, ok := m.GetByID(id) + if !ok { + return nil, ErrQuotaObservationStale + } + if m.HomeEnabled() || !claudeQuotaEligible(base) { + return nil, ErrClaudeQuotaUnsupported + } + if epoch != 0 && base.RegistrationEpoch != epoch { + return nil, ErrQuotaObservationStale + } + file, digest, errFile := m.claudeQuotaFileFence(base) + if errFile != nil { + return nil, ErrQuotaObservationStale + } + usage, errRead := m.readClaudeQuotaUsage(ctx, base) + now := time.Now() + // Serialize commit with failures, disablement, removal and replacement. The + // provider read holds no manager or credential mutation lock. + release, errLock := m.lockAuthMutationContext(ctx, id) + if errLock != nil { + return nil, errLock + } + defer release() + if file != "" { + data, errDisk := os.ReadFile(file) + if errDisk != nil || canonicalAuthFileDigest(data) != digest { + return nil, ErrQuotaObservationStale + } + } + m.mu.Lock() + current := m.auths[id] + if current == nil || current.Generation != base.Generation || current.RegistrationEpoch != base.RegistrationEpoch || + current.CredentialVersion != base.CredentialVersion || CredentialsChanged(current, base) || !claudeQuotaEligible(current) { + m.mu.Unlock() + return nil, ErrQuotaObservationStale + } + current.QuotaReconcile.CheckedAt = now + current.QuotaReconcile.NextCheckAt = now.Add(claudeQuotaRevalidateInterval) + if errRead != nil { + current.QuotaReconcile.Status = "provider_error" + current.Generation++ + m.mu.Unlock() + release() + m.queueRefreshReschedule(id) + return nil, errRead + } + models, changed := reconcileClaudeQuotaState(current, usage, now) + remaining := claudeQuotaBlockCount(current, now) + outcome := "unchanged" + if changed { + outcome = "reconciled" + } else if remaining > 0 { + outcome = "blocked" + } + current.QuotaReconcile.Status = outcome + current.QuotaReconcile.PersistencePending = true + current.Generation++ + current.UpdatedAt = now + snapshot := current.Clone() + m.mu.Unlock() + + // Publish the same generation to both routing owners. Their generation + // fences reject this snapshot if a concurrent result has already advanced it. + registered, regEpoch := registry.GetGlobalRegistry().GetModelsAndEpochForClient(id) + projections := make([]registry.ClientModelProjection, 0, len(registered)) + for _, model := range registered { + if model != nil { + projections = append(projections, m.clientModelProjectionForAuth(snapshot, model.ID, now)) + } + } + registry.GetGlobalRegistry().ApplyClientModelProjections(id, regEpoch, snapshot.Generation, projections) + if m.scheduler != nil { + m.scheduler.upsertAuth(snapshot) + } + release() + m.queueRefreshReschedule(id) + result := &QuotaReconcileResult{AuthIndex: snapshot.Index, Outcome: outcome, ObservedAt: now, Models: models, RemainingQuotaBlocks: remaining} + // Always retry the durable snapshot, even when this call changed no routing + // fields. Otherwise an earlier failed deletion would survive a restart. + m.configCooldownMu.Lock() + m.mu.RLock() + store := m.cooldownStore + m.mu.RUnlock() + persisted := m.persistCooldownStatesToLocked(ctx, store) + m.configCooldownMu.Unlock() + m.mu.Lock() + if latest := m.auths[id]; latest != nil && latest.RegistrationEpoch == snapshot.RegistrationEpoch && latest.CredentialVersion == snapshot.CredentialVersion && latest.Generation == snapshot.Generation { + latest.QuotaReconcile.PersistencePending = !persisted + if !persisted { + latest.QuotaReconcile.Status = "persistence_failed" + } + } + m.mu.Unlock() + if !persisted { + return result, ErrQuotaPersistence + } + return result, nil +} + +func (m *Manager) claudeQuotaFileFence(a *Auth) (string, string, error) { + if a.AuthSourceKind() != AuthSourceFile { + return "", "", nil + } + path := authAttribute(a, AttributePath) + if path == "" { + path = a.FileName + } + if path == "" { + return "", "", ErrQuotaObservationStale + } + if !filepath.IsAbs(path) { + cfg, _ := m.runtimeConfig.Load().(*config.Config) + if cfg != nil && cfg.AuthDir != "" { + path = filepath.Join(cfg.AuthDir, path) + } + } + data, errRead := os.ReadFile(path) + if errRead != nil { + return "", "", errRead + } + // A file replacement not yet adopted by the watcher must not let the old + // runtime token authorize clearing the new credential's cooldown. + if ojson.GetBytes(data, "access_token").String() != authAccessToken(a) || ojson.GetBytes(data, "disabled").Bool() { + return "", "", ErrQuotaObservationStale + } + return path, canonicalAuthFileDigest(data), nil +} + +func (m *Manager) readClaudeQuotaUsage(ctx context.Context, a *Auth) (claudeQuotaUsage, error) { + req, errReq := http.NewRequestWithContext(ctx, http.MethodGet, claudeUsageURL, nil) + if errReq != nil { + return nil, ErrQuotaUsageUnavailable + } + req.Header.Set("Authorization", "Bearer "+authAccessToken(a)) + req.Header.Set("Anthropic-Beta", "oauth-2025-04-20") + req.Header.Set("Accept", "application/json") + proxyURL := strings.TrimSpace(a.ProxyURL) + if proxyURL == "" { + cfg, _ := m.runtimeConfig.Load().(*config.Config) + if cfg != nil { + proxyURL = strings.TrimSpace(cfg.ProxyURL) + } + } + var transport http.RoundTripper + ownedTransport := false + if proxyURL != "" { + var errProxy error + transport, _, errProxy = proxyutil.BuildHTTPTransport(proxyURL) + ownedTransport = true + if errProxy != nil { + return nil, ErrQuotaUsageUnavailable + } + } else { + transport = m.roundTripperFor(a) + } + if transport == nil { + direct := http.DefaultTransport.(*http.Transport).Clone() + direct.Proxy = nil + transport = direct + ownedTransport = true + } + if ownedTransport { + if idle, ok := transport.(interface{ CloseIdleConnections() }); ok { + defer idle.CloseIdleConnections() + } + } + client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, errDo := client.Do(req) + if errDo != nil { + return nil, ErrQuotaUsageUnavailable + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Warn("quota usage response close failed") + } + }() + if resp.StatusCode != http.StatusOK { + return nil, ErrQuotaUsageUnavailable + } + const maxUsageBody = 1024 * 1024 + body, errBody := io.ReadAll(io.LimitReader(resp.Body, maxUsageBody+1)) + if errBody != nil || len(body) > maxUsageBody { + return nil, ErrQuotaUsageUnavailable + } + return parseClaudeQuotaUsage(body) +} + +func parseClaudeQuotaUsage(body []byte) (claudeQuotaUsage, error) { + root := ojson.ParseBytes(body) + if !ojson.ValidBytes(body) || !root.IsObject() { + return nil, ErrQuotaUsageUnavailable + } + usage := make(claudeQuotaUsage) + valid := true + seen := make(map[string]bool) + root.ForEach(func(key, value ojson.Result) bool { + name := key.String() + if seen[name] { + valid = false + return false + } + seen[name] = true + if !claudeUsageWindowKnown(name) || value.Type == ojson.Null { + return true + } + fields := make(map[string]bool) + value.ForEach(func(k, _ ojson.Result) bool { + field := k.String() + if fields[field] { + valid = false + } + fields[field] = true + return true + }) + if !valid { + return false + } + util := value.Get("utilization") + if !value.IsObject() || util.Type != ojson.Number || util.Float() < 0 || util.Float() > 100 { + valid = false + return false + } + window := claudeUsageWindow{used: util.Float()} + reset := value.Get("resets_at") + if reset.Type != ojson.Null { + var errTime error + window.reset, errTime = time.Parse(time.RFC3339Nano, reset.String()) + if reset.Type != ojson.String || errTime != nil { + valid = false + return false + } + } + usage[name] = window + return true + }) + if !valid || len(usage) == 0 { + return nil, ErrQuotaUsageUnavailable + } + return usage, nil +} + +func claudeUsageWindowKnown(name string) bool { + switch name { + case "five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "seven_day_oauth_apps": + return true + } + return false +} + +func claudeUsageName(window string) string { + switch window { + case "5h": + return "five_hour" + case "7d": + return "seven_day" + } + if suffix, ok := strings.CutPrefix(window, "7d_"); ok { + return "seven_day_" + suffix + } + return window +} + +func claudeQuotaProvenRestored(q QuotaState, usage claudeQuotaUsage, model string, now time.Time) bool { + // A restored old window cannot override newly observed exhaustion. A broad + // credential restriction remains conservative across model-specific windows. + for name, window := range usage { + applicable := model == "" || name != "seven_day_opus" && name != "seven_day_sonnet" || strings.Contains(strings.ToLower(model), strings.TrimPrefix(name, "seven_day_")) + if applicable && window.used >= 100 { + return false + } + } + signals := q.cooldownSignals + if len(signals) == 0 && !q.cooldownEvaluated { + signals = q.Signals + } + claims := make(map[string]bool) + for key, value := range signals { + if window, ok := claudeUnifiedWindowName(key); ok && strings.EqualFold(value, "rejected") { + claims[claudeUsageName(window)] = true + } + } + if claim := strings.TrimSpace(signals["Anthropic-Ratelimit-Unified-Representative-Claim"]); claim != "" { + claims[claim] = true + } + // No known attribution is not evidence of restored capacity. In particular, + // a null short window cannot be inferred from a healthy weekly percentage. + if len(claims) == 0 { + return false + } + for claim := range claims { + window, ok := usage[claim] + if !ok || !claudeUsageWindowKnown(claim) || window.used >= 100 || !window.reset.IsZero() && !window.reset.After(now) { + return false + } + } + return true +} + +func claudeUsageSignals(usage claudeQuotaUsage) map[string]string { + signals := map[string]string{"Anthropic-Usage-Source": "oauth_usage"} + for name, window := range usage { + prefix := "Anthropic-Usage-" + name + "-" + signals[prefix+"Utilization"] = strconv.FormatFloat(window.used, 'f', -1, 64) + if !window.reset.IsZero() { + signals[prefix+"Resets-At"] = window.reset.Format(time.RFC3339Nano) + } + } + return signals +} + +func reconcileClaudeQuotaState(a *Auth, usage claudeQuotaUsage, now time.Time) ([]string, bool) { + models := make([]string, 0) + credentialCleared := a.Quota.Exceeded && a.Quota.Reason == "credential_quota" && + !effectiveCredQuotaForceUntil(a).After(now) && claudeQuotaProvenRestored(a.Quota, usage, "", now) + if credentialCleared { + applyCooldownFields(&a.Quota, QuotaState{}) + a.credQuotaForceUntil = time.Time{} + models = append(models, modelsForRegisteredAuth(a.ID)...) + // Drop only the outer quota layer. Independent auth retry/force layers + // are reapplied by updateAggregatedAvailability below. + a.NextRetryAfter = time.Time{} + a.Unavailable = false + if statusCodeFromResult(a.LastError) == http.StatusTooManyRequests { + a.LastError = nil + a.StatusMessage = "" + } + } + for model, state := range a.ModelStates { + if state == nil { + continue + } + if state.Status == StatusDisabled { + continue + } + wrapped := state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" + if wrapped && credentialCleared { + if shadow := state.credentialQuotaShadow; shadow != nil { + *state = *shadow.cloneShallow() + } else { + resetModelState(state, now) + } + state.credentialQuotaPropagated = false + state.credentialQuotaShadow = nil + models = append(models, model) + } else if !wrapped && state.Status != StatusDisabled && state.Quota.Exceeded && state.Quota.Reason == "quota" && + !effectiveModelForceUntil(state).After(now) && statusCodeFromResult(state.LastError) == http.StatusTooManyRequests && + claudeQuotaProvenRestored(state.Quota, usage, model, now) { + resetModelState(state, now) + models = append(models, model) + } + // Observations are snapshots of this read, never a merge with a prior + // rejected/100% signal. This does not erase independent cooldown proof. + state.Quota.ObservedAt = now + state.Quota.Signals = claudeUsageSignals(usage) + } + a.Quota.ObservedAt = now + a.Quota.Signals = claudeUsageSignals(usage) + if credentialCleared || len(models) > 0 { + if a.Quota.Reason == "quota" && len(a.ModelStates) > 0 { + applyCooldownFields(&a.Quota, QuotaState{}) + } + updateAggregatedAvailability(a, now) + if !a.Unavailable && !hasModelError(a, now) && a.LastError == nil { + a.Status = StatusActive + a.StatusMessage = "" + } + } + models = dedupeStrings(models) + sort.Strings(models) + return models, credentialCleared || len(models) > 0 +} + +func claudeQuotaBlockCount(a *Auth, now time.Time) int { + count := 0 + if a.Quota.Exceeded && a.Quota.Reason == "credential_quota" { + count++ + } + for _, state := range a.ModelStates { + if state != nil && state.Quota.Exceeded && isModelStateActiveCooldown(state, now) { + count++ + } + } + return count +} + +func (m *Manager) claudeQuotaRevalidateAt(a *Auth, now time.Time) (time.Time, bool) { + if m.HomeEnabled() || !claudeQuotaEligible(a) || !a.HasValidAccessToken(now) || (!a.QuotaReconcile.PersistencePending && claudeQuotaBlockCount(a, now) == 0) { + return time.Time{}, false + } + if !a.QuotaReconcile.NextCheckAt.IsZero() { + return a.QuotaReconcile.NextCheckAt, true + } + since := a.Quota.ObservedAt + if since.IsZero() { + return now, true + } + return since.Add(claudeQuotaRevalidateInterval), true +} diff --git a/sdk/cliproxy/auth/claude_quota_reconcile_test.go b/sdk/cliproxy/auth/claude_quota_reconcile_test.go new file mode 100644 index 00000000000..36c70b5b0ec --- /dev/null +++ b/sdk/cliproxy/auth/claude_quota_reconcile_test.go @@ -0,0 +1,450 @@ +package auth + +import ( + "context" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + internallogging "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type quotaUsageTransport func(*http.Request) (*http.Response, error) + +func (f quotaUsageTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +func (f quotaUsageTransport) RoundTripperFor(*Auth) http.RoundTripper { return f } + +func quotaUsageResponse(body string) *http.Response { + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}} +} + +const restoredQuotaUsage = `{"five_hour":{"utilization":0},"seven_day":{"utilization":42}}` + +func quotaReconcileFixture(t *testing.T) (*Manager, *Auth) { + t.Helper() + m := NewManager(nil, &HeadroomSelector{}, nil) + a, errRegister := m.Register(context.Background(), &Auth{ + ID: t.Name(), Provider: "claude", Status: StatusActive, + Metadata: map[string]any{"access_token": "synthetic-oauth-token"}, + Attributes: map[string]string{AttributeRuntimeOnly: "true"}, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + reg := registry.GetGlobalRegistry() + reg.RegisterClient(a.ID, "claude", []*registry.ModelInfo{{ID: "claude-sonnet-test"}, {ID: "claude-opus-test"}}) + t.Cleanup(func() { reg.UnregisterClient(a.ID) }) + quotaReconcileReject(m, a.ID, "claude-sonnet-test", "5h") + m.SetRoundTripperProvider(quotaUsageTransport(func(r *http.Request) (*http.Response, error) { + if r.Method != http.MethodGet || r.URL.String() != claudeUsageURL || r.Body != nil { + t.Fatalf("unexpected provider request: %s %s", r.Method, r.URL) + } + if r.Header.Get("Authorization") != "Bearer synthetic-oauth-token" || r.Header.Get("Anthropic-Beta") != "oauth-2025-04-20" { + t.Fatal("missing saved OAuth authorization") + } + if deadline, ok := r.Context().Deadline(); !ok || time.Until(deadline) > claudeQuotaReadTimeout { + t.Fatal("quota operation is not bounded") + } + return quotaUsageResponse(restoredQuotaUsage), nil + })) + return m, a +} + +func quotaReconcileReject(m *Manager, id, model, window string) { + ctx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(ctx, http.Header{ + "Anthropic-Ratelimit-Unified-" + window + "-Status": []string{"rejected"}, + }) + after := 24 * time.Hour + m.MarkResult(ctx, Result{AuthID: id, Provider: "claude", Model: model, CredentialScope: true, RetryAfter: &after, Error: &Error{HTTPStatus: 429, Message: "quota rejected"}}) +} + +func TestClaudeQuotaReconcileRestoresOnlyProvenQuota(t *testing.T) { + for _, tc := range []struct { + name, body string + clear bool + }{ + {"restored", restoredQuotaUsage, true}, + {"still exhausted", `{"five_hour":{"utilization":100},"seven_day":{"utilization":42}}`, false}, + {"different exhausted window", `{"five_hour":{"utilization":0},"seven_day":{"utilization":100}}`, false}, + {"model window exhausted", `{"five_hour":{"utilization":0},"seven_day_sonnet":{"utilization":100}}`, false}, + {"null short window", `{"five_hour":null,"seven_day":{"utilization":42}}`, false}, + {"unknown short window", `{"seven_day":{"utilization":42}}`, false}, + {"past reset", `{"five_hour":{"utilization":0,"resets_at":"2020-01-01T00:00:00Z"}}`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + m, a := quotaReconcileFixture(t) + m.SetRoundTripperProvider(quotaUsageTransport(func(*http.Request) (*http.Response, error) { return quotaUsageResponse(tc.body), nil })) + result, errReconcile := m.ReconcileClaudeQuotaByIndex(context.Background(), a.Index) + if errReconcile != nil { + t.Fatal(errReconcile) + } + got, _ := m.GetByID(a.ID) + if got.Quota.Exceeded == tc.clear { + t.Fatalf("clear=%v quota=%+v", tc.clear, got.Quota) + } + if result.ObservedAt.IsZero() || got.Quota.ObservedAt != result.ObservedAt || got.Quota.Signals["Anthropic-Usage-Source"] != "oauth_usage" { + t.Fatal("fresh observation missing") + } + if got.Quota.Signals["Anthropic-Ratelimit-Unified-5h-Status"] != "" { + t.Fatal("old rejected observation republished") + } + if !tc.clear && result.Outcome != "blocked" { + t.Fatalf("outcome=%s", result.Outcome) + } + }) + } +} + +func TestClaudeQuotaReconcilePreservesIndependentRestrictions(t *testing.T) { + m, a := quotaReconcileFixture(t) + now := time.Now() + m.mu.Lock() + current := m.auths[a.ID] + shadow := &ModelState{Status: StatusError, Unavailable: true, NextRetryAfter: now.Add(time.Hour), LastError: &Error{HTTPStatus: 503, Message: "independent failure"}} + current.ModelStates["claude-opus-test"] = &ModelState{Quota: cooldownFieldsOf(current.Quota), Status: StatusError, Unavailable: true, NextRetryAfter: current.NextRetryAfter} + current.ModelStates["claude-opus-test"].credentialQuotaShadow = shadow + current.ModelStates["claude-opus-test"].credentialQuotaPropagated = true + current.forceCooldownUntil = now.Add(2 * time.Hour) + m.mu.Unlock() + if _, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID); errReconcile != nil { + t.Fatal(errReconcile) + } + got, _ := m.GetByID(a.ID) + state := got.ModelStates["claude-opus-test"] + if got.Quota.Exceeded || !got.Unavailable || !got.forceCooldownUntil.Equal(now.Add(2*time.Hour)) { + t.Fatalf("independent credential force altered: %+v", got) + } + if state.LastError == nil || state.LastError.HTTPStatus != 503 || !state.NextRetryAfter.Equal(shadow.NextRetryAfter) { + t.Fatalf("independent model shadow lost: %+v", state) + } + for _, active := range []bool{true, false} { + t.Run(map[bool]string{true: "active force", false: "expired force"}[active], func(t *testing.T) { + m, a := quotaReconcileFixture(t) + m.mu.Lock() + if active { + m.auths[a.ID].credQuotaForceUntil = time.Now().Add(time.Hour) + } else { + m.auths[a.ID].credQuotaForceUntil = time.Now().Add(-time.Hour) + } + m.mu.Unlock() + _, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID) + if errReconcile != nil { + t.Fatal(errReconcile) + } + got, _ := m.GetByID(a.ID) + if got.Quota.Exceeded != active { + t.Fatalf("force active=%v quota=%+v", active, got.Quota) + } + }) + } +} + +func TestClaudeQuotaReconcileRejectsAmbiguousUsage(t *testing.T) { + for _, body := range []string{ + `{}`, `[]`, `{"five_hour":null}`, `{"five_hour":{"utilization":-1}}`, `{"five_hour":{"utilization":101}}`, + `{"five_hour":{"utilization":"0"}}`, `{"five_hour":{"utilization":0,"resets_at":"invalid"}}`, + `{"five_hour":{"utilization":0},"five_hour":{"utilization":100}}`, + `{"five_hour":{"utilization":0,"utilization":100}}`, `{"five_hour":{"utilization":0,"resets_at":null,"resets_at":"2027-01-01T00:00:00Z"}}`, + } { + if _, errParse := parseClaudeQuotaUsage([]byte(body)); !errors.Is(errParse, ErrQuotaUsageUnavailable) { + t.Fatalf("accepted ambiguous usage: %s", body) + } + } +} + +func TestClaudeQuotaReconcileFencesConcurrentChanges(t *testing.T) { + for _, kind := range []string{"new rejection", "disable", "token replacement", "remove", "registration replacement", "file replacement", "file deletion", "out of order"} { + t.Run(kind, func(t *testing.T) { + m, a := quotaReconcileFixture(t) + var path string + if strings.HasPrefix(kind, "file ") { + path = filepath.Join(t.TempDir(), "credential.json") + if errWrite := os.WriteFile(path, []byte(`{"access_token":"synthetic-oauth-token"}`), 0600); errWrite != nil { + t.Fatal(errWrite) + } + m.mu.Lock() + delete(m.auths[a.ID].Attributes, AttributeRuntimeOnly) + m.auths[a.ID].Attributes[AttributePath] = path + m.mu.Unlock() + } + m.SetRoundTripperProvider(quotaUsageTransport(func(*http.Request) (*http.Response, error) { + switch kind { + case "new rejection": + quotaReconcileReject(m, a.ID, "claude-opus-test", "7d") + case "disable", "token replacement": + updated, _ := m.GetByID(a.ID) + if kind == "disable" { + updated.Disabled = true + } else { + updated.Metadata["access_token"] = "replacement-token" + } + if _, errUpdate := m.Update(context.Background(), updated); errUpdate != nil { + t.Fatal(errUpdate) + } + case "remove": + m.Remove(context.Background(), a.ID) + case "registration replacement": + m.Remove(context.Background(), a.ID) + if _, errRegister := m.Register(context.Background(), &Auth{ID: a.ID, Provider: "claude", Metadata: map[string]any{"access_token": "replacement-token"}}); errRegister != nil { + t.Fatal(errRegister) + } + case "file replacement": + if errWrite := os.WriteFile(path, []byte(`{"access_token":"replacement-token"}`), 0600); errWrite != nil { + t.Fatal(errWrite) + } + case "file deletion": + if errRemove := os.Remove(path); errRemove != nil { + t.Fatal(errRemove) + } + case "out of order": + m.SetRoundTripperProvider(quotaUsageTransport(func(*http.Request) (*http.Response, error) { + return quotaUsageResponse(`{"five_hour":{"utilization":100}}`), nil + })) + if _, errNew := m.ReconcileClaudeQuota(context.Background(), a.ID); errNew != nil { + t.Fatal(errNew) + } + } + return quotaUsageResponse(restoredQuotaUsage), nil + })) + if result, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID); result != nil || !errors.Is(errReconcile, ErrQuotaObservationStale) { + t.Fatalf("result=%+v err=%v", result, errReconcile) + } + if kind == "disable" { + got, _ := m.GetByID(a.ID) + if !got.Disabled { + t.Fatal("stale read re-enabled credential") + } + } + if kind != "remove" && kind != "registration replacement" && kind != "disable" { + got, _ := m.GetByID(a.ID) + if !got.Quota.Exceeded { + t.Fatal("stale observation cleared newer cooldown") + } + } + if kind == "file deletion" { + if _, errStat := os.Stat(path); !errors.Is(errStat, os.ErrNotExist) { + t.Fatal("deleted OAuth file recreated") + } + } + }) + } +} + +func TestClaudeQuotaReconcileProviderErrorsStayBlocked(t *testing.T) { + for _, kind := range []string{"redirect", "failure", "oversize", "transport"} { + t.Run(kind, func(t *testing.T) { + m, a := quotaReconcileFixture(t) + var calls int + m.SetRoundTripperProvider(quotaUsageTransport(func(r *http.Request) (*http.Response, error) { + calls++ + if r.URL.String() != claudeUsageURL { + t.Fatal("redirect followed") + } + response := quotaUsageResponse(restoredQuotaUsage) + switch kind { + case "redirect": + response.StatusCode = 302 + response.Header.Set("Location", "https://example.invalid/steal") + case "failure": + response.StatusCode = 401 + case "oversize": + response.Body = io.NopCloser(strings.NewReader(strings.Repeat("x", 1024*1024+1))) + case "transport": + return nil, errors.New("synthetic-oauth-token") + } + return response, nil + })) + _, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID) + if !errors.Is(errReconcile, ErrQuotaUsageUnavailable) || strings.Contains(errReconcile.Error(), "synthetic-oauth-token") || calls != 1 { + t.Fatalf("calls=%d error=%v", calls, errReconcile) + } + got, _ := m.GetByID(a.ID) + if !got.Quota.Exceeded || got.QuotaReconcile.Status != "provider_error" { + t.Fatal("failed read changed routing or freshness") + } + }) + } +} + +func TestClaudeQuotaAutomaticRecoveryCadenceAndCancellation(t *testing.T) { + for _, kind := range []string{"success", "missing file", "provider error", "cancellation"} { + t.Run(kind, func(t *testing.T) { + m, a := quotaReconcileFixture(t) + now := time.Now() + m.mu.Lock() + m.auths[a.ID].Quota.ObservedAt = now.Add(-time.Hour) + m.auths[a.ID].NextRefreshAfter = now.Add(2 * time.Hour) + m.mu.Unlock() + var calls atomic.Int32 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + m.SetRoundTripperProvider(quotaUsageTransport(func(r *http.Request) (*http.Response, error) { + calls.Add(1) + if _, ok := r.Context().Deadline(); !ok { + t.Fatal("quota read missing deadline") + } + if kind == "provider error" { + return nil, errors.New("unavailable") + } + if kind == "cancellation" { + cancel() + <-r.Context().Done() + return nil, r.Context().Err() + } + return quotaUsageResponse(restoredQuotaUsage), nil + })) + if kind == "missing file" { + m.mu.Lock() + delete(m.auths[a.ID].Attributes, AttributeRuntimeOnly) + m.auths[a.ID].Attributes[AttributePath] = filepath.Join(t.TempDir(), "missing.json") + m.mu.Unlock() + } + loop := newAuthAutoRefreshLoop(m, time.Second, 1) + loop.handleDueAuth(ctx, now, a.ID) + var job *authRefreshJob + select { + case job = <-loop.jobs: + default: + t.Fatal("due quota not queued without provider executor") + } + if !job.quotaReconcile { + t.Fatal("queued token refresh instead of quota read") + } + loop.runRefreshJob(ctx, job) + m.mu.RLock() + remainingJob := m.refreshJobs[a.ID] + next, scheduled := m.nextRefreshCheckAt(now, m.auths[a.ID], time.Second) + marker := m.auths[a.ID].NextRefreshAfter + m.mu.RUnlock() + if remainingJob != nil || scheduled && !next.After(now) { + t.Fatalf("job not released or immediate retry: next=%v", next) + } + if !marker.Equal(now.Add(2 * time.Hour)) { + t.Fatal("quota job overwrote OAuth refresh schedule") + } + loop.handleDueAuth(context.Background(), now, a.ID) + select { + case <-loop.jobs: + t.Fatal("immediate quota retry storm") + default: + } + want := int32(1) + if kind == "missing file" { + want = 0 + } + if calls.Load() != want { + t.Fatalf("provider calls=%d want=%d", calls.Load(), want) + } + got, _ := m.GetByID(a.ID) + if kind == "success" && got.Quota.Exceeded { + t.Fatal("automatic non-spending read did not restore routing") + } + }) + } +} + +func TestClaudeQuotaAutomaticRecoveryExcludesHomeAndDisabled(t *testing.T) { + m, a := quotaReconcileFixture(t) + m.SetConfig(&config.Config{Home: config.HomeConfig{Enabled: true}}) + got, _ := m.GetByID(a.ID) + if _, scheduled := m.claudeQuotaRevalidateAt(got, time.Now()); scheduled { + t.Fatal("Home quota job scheduled") + } + m.SetConfig(&config.Config{}) + got.Disabled = true + if _, scheduled := m.claudeQuotaRevalidateAt(got, time.Now()); scheduled { + t.Fatal("disabled quota job scheduled") + } +} + +func TestClaudeQuotaObservationReplacesSelectorMemory(t *testing.T) { + for _, name := range []string{"headroom", "reset aware"} { + t.Run(name, func(t *testing.T) { + now := time.Now() + var selector Selector + if name == "headroom" { + selector = fixedHeadroomSelector(now) + } else { + selector = &ResetAwareSelector{nowFunc: func() time.Time { return now }} + } + a := headroomAuth("restored", now, 1, 4, 1, 20) + b := headroomAuth("other", now, .7, 4, .8, 100) + if got, errPick := selector.Pick(context.Background(), "claude", "", executor.Options{}, []*Auth{a, b}); errPick != nil || got.ID != b.ID { + t.Fatalf("old observation not used: %v %v", got, errPick) + } + a.Quota.Signals = claudeUsageSignals(claudeQuotaUsage{"five_hour": {used: 0, reset: now.Add(time.Hour)}, "seven_day": {used: 1, reset: now.Add(2 * time.Hour)}}) + if got, errPick := selector.Pick(context.Background(), "claude", "", executor.Options{}, []*Auth{a, b}); errPick != nil || got.ID != a.ID { + t.Fatalf("fresh usage retained old 100%% cache: %v %v", got, errPick) + } + }) + } +} + +func TestClaudeQuotaReconcileRegistryRegistrationFence(t *testing.T) { + m, a := quotaReconcileFixture(t) + reg := registry.GetGlobalRegistry() + m.SetRoundTripperProvider(quotaUsageTransport(func(*http.Request) (*http.Response, error) { + // A model-list refresh can happen independently of manager mutation. + // Publication must use the current registry epoch while the credential + // gate prevents a replacement auth registration from joining it. + reg.UnregisterClient(a.ID) + reg.RegisterClient(a.ID, "claude", []*registry.ModelInfo{{ID: "claude-sonnet-test"}}) + _, epoch := reg.GetModelsAndEpochForClient(a.ID) + if !reg.ApplyClientModelProjections(a.ID, epoch, 1, []registry.ClientModelProjection{{ModelID: "claude-sonnet-test", QuotaExceeded: true}}) { + t.Fatal("replacement projection failed") + } + return quotaUsageResponse(restoredQuotaUsage), nil + })) + if _, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID); errReconcile != nil { + t.Fatal(errReconcile) + } + if reg.IsModelQuotaExceededForClient(a.ID, "claude-sonnet-test") { + t.Fatal("restored availability was not projected to current model-list registration") + } +} + +func TestClaudeQuotaReconcilePreservesDisabledModelsAndUnknownClaims(t *testing.T) { + m, a := quotaReconcileFixture(t) + m.mu.Lock() + m.auths[a.ID].ModelStates["disabled"] = &ModelState{Status: StatusDisabled, Unavailable: true, Quota: cooldownFieldsOf(m.auths[a.ID].Quota)} + m.mu.Unlock() + if _, errReconcile := m.ReconcileClaudeQuota(context.Background(), a.ID); errReconcile != nil { + t.Fatal(errReconcile) + } + got, _ := m.GetByID(a.ID) + if got.ModelStates["disabled"].Status != StatusDisabled { + t.Fatal("quota reconcile enabled disabled model") + } + unknown := QuotaState{Exceeded: true, Reason: "credential_quota", cooldownEvaluated: true, cooldownSignals: map[string]string{"Anthropic-Ratelimit-Unified-Representative-Claim": "unrecognized"}} + if claudeQuotaProvenRestored(unknown, claudeQuotaUsage{"five_hour": {used: 0}}, "", time.Now()) { + t.Fatal("unknown claim accepted as restored") + } +} + +func TestClaudeQuotaReconcileModelLocalRestrictions(t *testing.T) { + now := time.Now() + q := QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: now.Add(time.Hour), cooldownEvaluated: true, cooldownSignals: map[string]string{"Anthropic-Ratelimit-Unified-5h-Status": "rejected"}} + a := &Auth{Status: StatusError, ModelStates: map[string]*ModelState{}} + for _, model := range []string{"claude-sonnet-test", "claude-opus-test", "forced"} { + a.ModelStates[model] = &ModelState{Status: StatusError, Unavailable: true, NextRetryAfter: now.Add(time.Hour), Quota: q, LastError: &Error{HTTPStatus: 429}} + } + a.ModelStates["forced"].forceCooldownSeeded = true + a.ModelStates["forced"].forceCooldownUntil = now.Add(time.Hour) + models, changed := reconcileClaudeQuotaState(a, claudeQuotaUsage{"five_hour": {used: 0}, "seven_day_sonnet": {used: 100}}, now) + if !changed || len(models) != 1 || models[0] != "claude-opus-test" { + t.Fatalf("model-local application=%v changed=%v", models, changed) + } + if a.ModelStates["claude-opus-test"].Quota.Exceeded || !a.ModelStates["claude-sonnet-test"].Quota.Exceeded || !a.ModelStates["forced"].Quota.Exceeded { + t.Fatal("model-specific or forced restriction was broadened") + } +} diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index b2186f064c3..bcf342b4ea6 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -2191,7 +2191,8 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { // A newly exhausted Devin credential must join the refresh schedule so // quota revalidation can detect early restoration (issue #6690). if authSnapshot != nil { - if _, due := devinQuotaRevalidateAt(authSnapshot, now); due { + _, claudeQuotaDue := m.claudeQuotaRevalidateAt(authSnapshot, now) + if _, due := devinQuotaRevalidateAt(authSnapshot, now); due || claudeQuotaDue { m.queueRefreshReschedule(result.AuthID) } else if scheduleUnauthorizedRefresh { m.queueRefreshReschedule(result.AuthID) diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index 4eba974b697..1d2d470a1fd 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -397,6 +397,7 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo auth.CredentialVersion = max(auth.CredentialVersion, existingVersion) + 1 } else { auth.CredentialVersion = existingVersion + auth.QuotaReconcile = existing.QuotaReconcile } cooldownStateChanged := false now := time.Now() diff --git a/sdk/cliproxy/auth/conductor_refresh.go b/sdk/cliproxy/auth/conductor_refresh.go index 343957ec39f..b5eb35780ba 100644 --- a/sdk/cliproxy/auth/conductor_refresh.go +++ b/sdk/cliproxy/auth/conductor_refresh.go @@ -139,6 +139,9 @@ func (m *Manager) shouldRefresh(a *Auth, now time.Time) bool { if hasUnauthorizedAuthFailure(a) || hasDisabledInvalidGrantFailure(a) { return false } + if next, due := m.claudeQuotaRevalidateAt(a, now); due && !next.After(now) { + return true + } if !a.NextRefreshAfter.IsZero() && now.Before(a.NextRefreshAfter) { return false } @@ -366,7 +369,9 @@ func (m *Manager) markRefreshPending(loop *authAutoRefreshLoop, id string, regis m.mu.Unlock() return nil } - if m.refreshJobs[id] != nil || (!auth.NextRefreshAfter.IsZero() && now.Before(auth.NextRefreshAfter)) { + quotaAt, quotaScheduled := m.claudeQuotaRevalidateAt(auth, now) + quotaDue := quotaScheduled && !quotaAt.After(now) + if m.refreshJobs[id] != nil || (!quotaDue && !auth.NextRefreshAfter.IsZero() && now.Before(auth.NextRefreshAfter)) { m.mu.Unlock() return nil } @@ -375,12 +380,17 @@ func (m *Manager) markRefreshPending(loop *authAutoRefreshLoop, id string, regis registrationEpoch: registrationEpoch, pendingUntil: now.Add(refreshPendingBackoff), loop: loop, + quotaReconcile: quotaDue, } if m.refreshJobs == nil { m.refreshJobs = make(map[string]*authRefreshJob) } m.refreshJobs[id] = job - auth.NextRefreshAfter = job.pendingUntil + if quotaDue { + auth.QuotaReconcile.NextCheckAt = now.Add(claudeQuotaRevalidateInterval) + } else { + auth.NextRefreshAfter = job.pendingUntil + } auth.Generation++ auth.UpdatedAt = now m.mu.Unlock() @@ -407,7 +417,7 @@ func (m *Manager) finishRefreshJob(job *authRefreshJob, retryAt time.Time, queue return } delete(m.refreshJobs, job.id) - if auth := m.auths[job.id]; auth != nil && auth.RegistrationEpoch == job.registrationEpoch && auth.NextRefreshAfter.Equal(job.pendingUntil) { + if auth := m.auths[job.id]; !job.quotaReconcile && auth != nil && auth.RegistrationEpoch == job.registrationEpoch && auth.NextRefreshAfter.Equal(job.pendingUntil) { // Clear only this job's pending marker, preserving newer refresh outcomes. auth.NextRefreshAfter = retryAt auth.Generation++ diff --git a/sdk/cliproxy/auth/headroom_selector.go b/sdk/cliproxy/auth/headroom_selector.go index 591c6aadefd..f59c67ccfa5 100644 --- a/sdk/cliproxy/auth/headroom_selector.go +++ b/sdk/cliproxy/auth/headroom_selector.go @@ -61,6 +61,11 @@ func (m *claudeUsageMemory) readWindows(auths []*Auth, now time.Time) [][len(cla signals[strings.ToLower(key)] = strings.TrimSpace(value) } known := m.seen[auth.ID] + if signals["anthropic-usage-source"] == "oauth_usage" { + // A fresh usage read replaces the whole snapshot, including null + // windows. Do not retain a rejected pre-reconciliation cache entry. + known = [len(claudeWindows)]windowUsage{} + } for w, window := range claudeWindows { if reading, ok := readClaudeWindow(signals, window.name); ok { known[w] = reading @@ -199,6 +204,15 @@ func (s *HeadroomSelector) usage(auths []*Auth, now time.Time) ([]float64, []int // readClaudeWindow parses one unified window from lower-cased signals. A // rejected window reads as fully used. func readClaudeWindow(signals map[string]string, window string) (windowUsage, bool) { + if signals["anthropic-usage-source"] == "oauth_usage" { + prefix := "anthropic-usage-" + claudeUsageName(window) + "-" + used, errUsed := strconv.ParseFloat(signals[prefix+"utilization"], 64) + reset, errReset := time.Parse(time.RFC3339Nano, signals[prefix+"resets-at"]) + if errUsed != nil || errReset != nil || used < 0 || used > 100 { + return windowUsage{}, false + } + return windowUsage{used: used / 100, reset: reset}, true + } prefix := "anthropic-ratelimit-unified-" + window + "-" reset, errReset := strconv.ParseInt(signals[prefix+"reset"], 10, 64) if errReset != nil { diff --git a/sdk/cliproxy/auth/types.go b/sdk/cliproxy/auth/types.go index 959264e14b4..d7c541c8b43 100644 --- a/sdk/cliproxy/auth/types.go +++ b/sdk/cliproxy/auth/types.go @@ -93,6 +93,8 @@ type Auth struct { Metadata map[string]any `json:"metadata,omitempty"` // Quota captures recent quota information for load balancers. Quota QuotaState `json:"quota"` + // QuotaReconcile records bounded non-spending quota recovery attempts. + QuotaReconcile QuotaReconcileState `json:"-"` // LastError stores the last failure encountered while executing or refreshing. LastError *Error `json:"last_error,omitempty"` // CreatedAt is the creation timestamp in UTC.