Skip to content
Closed
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
10 changes: 10 additions & 0 deletions sdk/cliproxy/auth/antigravity_credits.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ func AntigravityCreditsRequested(ctx context.Context) bool {
return v
}

// AntigravityCreditsHintRefreshInterval defines how long a cached AI credits hint
// remains fresh before it should be re-validated.
const AntigravityCreditsHintRefreshInterval = 10 * time.Minute

// AntigravityCreditsHint stores the latest known AI credits state for one auth.
type AntigravityCreditsHint struct {
Known bool
Expand All @@ -36,6 +40,12 @@ type AntigravityCreditsHint struct {
UpdatedAt time.Time
}

// IsAntigravityCreditsHintFresh reports whether a known credits hint is still
// within AntigravityCreditsHintRefreshInterval of now.
func IsAntigravityCreditsHintFresh(hint AntigravityCreditsHint, now time.Time) bool {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Treat future credit-hint timestamps as stale

If a hint is written by a node whose clock is ahead, now.Sub(hint.UpdatedAt) is negative and therefore always below the refresh interval. A known-unavailable hint can consequently exclude an Antigravity credential without revalidation until the local clock passes the future timestamp plus ten minutes, yielding a false no-fallback result when it is the only candidate.

return hint.Known && !hint.UpdatedAt.IsZero() && now.Sub(hint.UpdatedAt) < AntigravityCreditsHintRefreshInterval
}

var antigravityCreditsHintByAuth sync.Map

// SetAntigravityCreditsHint updates the latest known AI credits state for an auth.
Expand Down
30 changes: 29 additions & 1 deletion sdk/cliproxy/auth/api_key_model_capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,19 @@ func compileAPIKeyModelCapabilitiesForAuth(cfg *internalconfig.Config, auth *Aut
}
case "vertex":
if entry := resolveVertexAPIKeyConfig(cfg, auth); entry != nil {
compileConfiguredModelCapabilities(out, entry.Models, "gemini")
for _, configured := range entry.Models {
support := configured.Thinking
openAPI := isVertexOpenAPIConfigModel(configured.Name)
if configured.OpenAPI != nil {
openAPI = *configured.OpenAPI
} else if entry.OpenAPI != nil {
openAPI = *entry.OpenAPI
}
if support == nil && openAPI && modelconfig.ResolveModelInfo(configured.Name, "gemini", nil).Thinking == nil {
support = &registry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}
}
addConfiguredModelCapability(out, configured.Name, configured.Alias, "gemini", support, false)
}
}
case "meta":
if entry := resolveMetaAPIKeyConfig(cfg, auth); entry != nil {
Expand Down Expand Up @@ -485,3 +497,19 @@ func addConfiguredModelCapability(out map[string][]apiKeyModelCapabilityRoute, n
}
return modelInfo
}

// isVertexOpenAPIConfigModel recognizes partner models without depending on executors.
func isVertexOpenAPIConfigModel(model string) bool {
base := strings.TrimSpace(thinking.ParseSuffix(model).ModelName)
if strings.HasPrefix(strings.ToLower(base), "publishers/") {
publisher, tail, ok := strings.Cut(base[len("publishers/"):], "/")
if !ok || !strings.HasPrefix(strings.ToLower(tail), "models/") {
return false
}
base = strings.TrimSpace(publisher) + "/" + strings.TrimSpace(tail[len("models/"):])
}
publisher, name, ok := strings.Cut(base, "/")
publisher, name = strings.TrimSpace(publisher), strings.TrimSpace(name)
return ok && publisher != "" && name != "" && !strings.Contains(name, "/") &&
!strings.EqualFold(publisher, "google") && !strings.EqualFold(publisher, "models") && !strings.EqualFold(publisher, "publishers")
}
46 changes: 46 additions & 0 deletions sdk/cliproxy/auth/auth_change_watch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package auth

// WatchAuthChanges observes structural changes to one runtime credential,
// including token preparation/refresh, replacement, removal and store reload.
// Notifications are coalesced: consumers must inspect the latest manager state.
// The caller must unsubscribe when its work ends. Request result accounting does
// not notify watchers, so ordinary Generation increments do not invalidate work.
func (m *Manager) WatchAuthChanges(authID string) (<-chan struct{}, func()) {
changes := make(chan struct{}, 1)
if m == nil || authID == "" {
close(changes)
return changes, func() {}
}
m.mu.Lock()
if m.authChangeWatchers == nil {
m.authChangeWatchers = make(map[string]map[chan struct{}]struct{})
}
if m.authChangeWatchers[authID] == nil {
m.authChangeWatchers[authID] = make(map[chan struct{}]struct{})
}
m.authChangeWatchers[authID][changes] = struct{}{}
m.mu.Unlock()
return changes, func() {
m.mu.Lock()
defer m.mu.Unlock()
watchers := m.authChangeWatchers[authID]
if _, exists := watchers[changes]; !exists {
return
}
delete(watchers, changes)
if len(watchers) == 0 {
delete(m.authChangeWatchers, authID)
}
close(changes)
}
}

// Caller holds m.mu. No user callback or blocking work runs under the manager lock.
func (m *Manager) notifyAuthChangeLocked(authID string) {
for changes := range m.authChangeWatchers[authID] {
select {
case changes <- struct{}{}:
default:
}
}
}
32 changes: 30 additions & 2 deletions sdk/cliproxy/auth/auto_refresh_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,14 +400,42 @@ func nextRefreshCheckAt(now time.Time, auth *Auth, interval time.Duration) (time
return time.Time{}, false
}

if auth.AuthKind() == AuthKindAPIKey {
return time.Time{}, false
// Quota-exhausted Devin credentials revalidate upstream status so early
// restoration can be detected (issue #6690); their tokens never expire,
// so the generic expiry/lead schedule below would drop them entirely.
// A custom RefreshEvaluator keeps precedence (matching shouldRefresh),
// otherwise an evaluator veto would reschedule an immediately-due entry.
if _, hasEvaluator := auth.Runtime.(RefreshEvaluator); hasEvaluator {
// Fall through to the evaluator branch below.
} else if next, due := devinQuotaRevalidateAt(auth, now); due {
if !auth.NextRefreshAfter.IsZero() && auth.NextRefreshAfter.After(next) {
next = auth.NextRefreshAfter
}
if !next.After(now) {
return now, true
}
return next, true
}

if !auth.NextRefreshAfter.IsZero() && now.Before(auth.NextRefreshAfter) {
return auth.NextRefreshAfter, true
}

if siwcDueAt, hasSIWC, _ := CodexSIWCNeedsRefresh(auth, now); hasSIWC {
minDue := siwcDueAt
if outerDueAt, hasOuter, _ := CodexOuterNeedsRefresh(auth, now); hasOuter && outerDueAt.Before(minDue) {
minDue = outerDueAt
}
if !minDue.After(now) {
return now, true
}
return minDue, true
}

if auth.AuthKind() == AuthKindAPIKey {
return time.Time{}, false
}

if evaluator, ok := auth.Runtime.(RefreshEvaluator); ok && evaluator != nil {
if interval <= 0 {
interval = refreshCheckInterval
Expand Down
9 changes: 9 additions & 0 deletions sdk/cliproxy/auth/classification.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ func (a *Auth) AuthKind() string {
if a == nil {
return ""
}
if IsCodexUseSIWC(a) {
return AuthKindOAuth
}
if kind := normalizeAuthKind(authAttribute(a, AttributeAuthKind)); kind != "" {
return kind
}
Expand Down Expand Up @@ -119,6 +122,12 @@ func authHasOAuthMetadata(auth *Auth) bool {
if token, ok := auth.Metadata["token"].(map[string]any); ok && len(token) > 0 {
return true
}
if siwc, ok := auth.Metadata["siwc"].(map[string]any); ok && len(siwc) > 0 {
return true
}
if sa, ok := auth.Metadata["service_account"].(map[string]any); ok && len(sa) > 0 {
return true
}
return false
}

Expand Down
135 changes: 135 additions & 0 deletions sdk/cliproxy/auth/codex_persist.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package auth

import (
"context"
"encoding/json"
"fmt"
"os"
"strings"

"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex"
)

// IsCodexAuthRecord reports whether auth represents a Codex credential record.
func IsCodexAuthRecord(auth *Auth) bool {
if auth == nil {
return false
}
if strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") {
return true
}
if auth.Metadata != nil {
if t, ok := auth.Metadata["type"].(string); ok && strings.EqualFold(strings.TrimSpace(t), "codex") {
return true
}
}
if _, ok := auth.Storage.(*codex.CodexTokenStorage); ok {
return true
}
return false
}

// PersistCodexAuthFile persists a Codex auth record to path using inter-process file locking,
// read-before-write merging, and scoped refresh patches when present.
// It returns handled=false when auth is not a Codex credential record.
func PersistCodexAuthFile(ctx context.Context, path string, auth *Auth) (bool, error) {
if !IsCodexAuthRecord(auth) {
return false, nil
}

type metadataSetter interface {
SetMetadata(map[string]any)
}

switch {
case auth.CodexRefreshPatch != nil:
errRefresh := codex.WithFileLock(path, func() error {
existing, errRead := os.ReadFile(path)
if errRead != nil {
if os.IsNotExist(errRead) {
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
auth.Metadata["disabled"] = auth.Disabled
NormalizeCredentialMetadata(auth.Metadata)
return codex.WriteJSONFileAtomic(path, auth.Metadata)
}
return fmt.Errorf("auth filestore: read refresh source failed: %w", errRead)
}
var diskMap map[string]any
if errUnmarshal := json.Unmarshal(existing, &diskMap); errUnmarshal != nil || diskMap == nil {
return fmt.Errorf("auth filestore: invalid refresh source JSON")
}
merged := auth.CodexRefreshPatch.Apply(diskMap)
NormalizeCredentialMetadata(merged)
if errWrite := codex.WriteJSONFileAtomic(path, merged); errWrite != nil {
return errWrite
}
auth.Metadata = merged
return nil
})
if errRefresh != nil {
return true, errRefresh
}
auth.CodexRefreshPatch = nil
auth.Storage = nil
if disabled, ok := auth.Metadata["disabled"].(bool); ok {
auth.Disabled = disabled
}
return true, nil

case auth.Storage != nil:
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
auth.Metadata["disabled"] = auth.Disabled
if storage, ok := auth.Storage.(*codex.CodexTokenStorage); ok && storage != nil {
clonedStorage := *storage
clonedStorage.ReplaceCredentials = HasAuthCreationIntent(ctx)
auth.Storage = &clonedStorage
}
if setter, ok := auth.Storage.(metadataSetter); ok {
setter.SetMetadata(auth.Metadata)
}
if errSave := auth.Storage.SaveTokenToFile(path); errSave != nil {
return true, errSave
}
if persistedBytes, errReadPersisted := os.ReadFile(path); errReadPersisted == nil && len(persistedBytes) > 0 {
var diskMap map[string]any
if errUnmarshal := json.Unmarshal(persistedBytes, &diskMap); errUnmarshal == nil && len(diskMap) > 0 {
auth.Metadata = codex.MergeCodexCredentialsFromDisk(diskMap, auth.Metadata)
NormalizeCredentialMetadata(auth.Metadata)
}
}
return true, nil

case auth.Metadata != nil:
auth.Metadata["disabled"] = auth.Disabled
errLock := codex.WithFileLock(path, func() error {
existing, errRead := os.ReadFile(path)
if errRead == nil && len(existing) > 0 {
var diskMap map[string]any
if errUnmarshal := json.Unmarshal(existing, &diskMap); errUnmarshal == nil && len(diskMap) > 0 {
if !HasAuthCreationIntent(ctx) {
auth.Metadata = codex.MergeCodexCredentialsFromDisk(diskMap, auth.Metadata)
}
auth.Metadata["disabled"] = auth.Disabled
NormalizeCredentialMetadata(auth.Metadata)
if raw, errMarshal := json.Marshal(auth.Metadata); errMarshal == nil && string(existing) == string(raw) {
return nil
}
}
} else if errRead != nil && !os.IsNotExist(errRead) {
return fmt.Errorf("auth filestore: read existing failed: %w", errRead)
}
return codex.WriteJSONFileAtomic(path, auth.Metadata)
})
if errLock != nil {
return true, errLock
}
return true, nil

default:
return false, nil
}
}
Loading
Loading