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
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,30 @@ Antigravity's published catalog includes `claude-opus-4-6-thinking` and `claude-

Strip every entry whose `id` starts with `claude-`, whose `type` is `claude`, or whose `owned_by` is `anthropic` from the `antigravity` array. Applied both to the in-tree `models.json` (so `go test ./...` and local dev see the patched shape) and to `.github/scripts/refresh-model-catalogs.sh` (so upstream catalog refreshes during tagged builds re-apply the strip automatically). After the patch the antigravity OAuth is Gemini-only and Claude requests fall through to the Anthropic OAuth pool.

### Patch 5 — retry a failed model-catalog fetch every 30 s

`internal/registry/model_updater.go` (`runModelCatalogUpdater`), also used by the Codex and Devin catalog updaters. Backport of the open upstream PR [#6236](https://github.com/router-for-me/CLIProxyAPI/pull/6236).

Upstream fetches the catalog once at startup and then every 3 h. When the proxy starts before DNS works, the fetch fails and models newer than the embedded catalog answer `400 unknown provider for model` for 3 h. After a failed attempt, retry in 30 s; after any successful fetch, go back to 3 h. Drop this patch when upstream merges #6236 or an equivalent.

### Patch 6 — register models of loaded auth files before the listener opens

`sdk/cliproxy/service_lifecycle.go` (`syncPluginModelRuntime` before `server.Start`). Backport of the open upstream PR [#6464](https://github.com/router-for-me/CLIProxyAPI/pull/6464); upstream closed the issue, [#6702](https://github.com/router-for-me/CLIProxyAPI/issues/6702), as not planned.

Without it, requests in the first second after a restart get `400 unknown provider` for OAuth-file models, because those models are registered only after the file watcher's first load.

### Patch 7 — wait up to 10 s for the first catalog fetch before listening

`internal/registry/model_updater.go` (`WaitForStartupModelRefresh`) and `sdk/cliproxy/service_lifecycle.go`. Not upstream; [#6257](https://github.com/router-for-me/CLIProxyAPI/pull/6257) (open) solves the same race with a 503 gate.

Patch 6 registers models from the catalog in memory at that moment. Right after a restart that is the embedded catalog, so models added upstream since the build still fail until the background fetch lands. The start waits for the first fetch (success or failure) and gives up after 10 s.

## Tests

```bash
go test ./internal/translator/openai/claude/... # Patches 1 + 2
go test ./internal/registry/... # Patch 4 (catalog integrity)
go test ./internal/registry/... # Patches 4, 5, 7
go test ./sdk/cliproxy/ -run TestServiceRun_RegistersLoadedAuthModelsBeforeListening # Patch 6
```

## Rebase
Expand Down
34 changes: 33 additions & 1 deletion internal/registry/codex_client_models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,9 @@ func TestRefreshCodexClientModelsKeepsLastValidSnapshot(t *testing.T) {

before, revision := GetCodexClientModelsSnapshot()
codexClientModelsURLs = urls
tryRefreshCodexClientModels(context.Background(), "test refresh")
if tryRefreshCodexClientModels(context.Background(), "test refresh") {
t.Fatal("failed refresh reported success")
}
after, afterRevision := GetCodexClientModelsSnapshot()
if string(after) != string(before) {
t.Fatal("failed remote refresh replaced last valid catalog")
Expand Down Expand Up @@ -198,6 +200,36 @@ func testCodexClientModel(slug string, priority int) map[string]any {
}
}

func TestRefreshCodexClientModelsSuccessAndUnchanged(t *testing.T) {
original, _ := GetCodexClientModelsSnapshot()
previousURLs := codexClientModelsURLs
t.Cleanup(func() {
codexClientModelsURLs = previousURLs
if _, err := loadCodexClientModelsFromBytes(original, "test cleanup"); err != nil {
t.Fatalf("restore original catalog: %v", err)
}
})
catalog := testCodexClientCatalog(t, testCodexClientModel("gpt-5.5", 1), testCodexClientModel("test-new-model", 2))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(catalog)
}))
defer server.Close()
codexClientModelsURLs = []string{server.URL}
if !tryRefreshCodexClientModels(context.Background(), "test refresh") {
t.Fatal("valid refresh reported failure")
}
after, revision := GetCodexClientModelsSnapshot()
if string(after) != string(catalog) {
t.Fatal("successful refresh did not publish the fetched catalog")
}
if !tryRefreshCodexClientModels(context.Background(), "test unchanged refresh") {
t.Fatal("unchanged catalog should count as a successful refresh")
}
if got := GetCodexClientModelsRevision(); got != revision {
t.Fatalf("unchanged catalog revision = %d, want %d", got, revision)
}
}

func testCodexClientCatalog(t *testing.T, models ...map[string]any) []byte {
t.Helper()
data, err := json.Marshal(map[string]any{"models": models})
Expand Down
24 changes: 6 additions & 18 deletions internal/registry/codex_client_models_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"io"
"net/http"
"sync"
"time"

log "github.com/sirupsen/logrus"
)
Expand All @@ -29,38 +28,27 @@ func StartCodexClientModelsUpdater(ctx context.Context) {
}

func runCodexClientModelsUpdater(ctx context.Context) {
tryRefreshCodexClientModels(ctx, "startup Codex client model refresh")

ticker := time.NewTicker(modelsRefreshInterval)
defer ticker.Stop()
log.Infof("periodic Codex client model refresh started (interval=%s)", modelsRefreshInterval)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
tryRefreshCodexClientModels(ctx, "periodic Codex client model refresh")
}
}
runModelCatalogUpdater(ctx, "Codex client model refresh", tryRefreshCodexClientModels)
}

func tryRefreshCodexClientModels(ctx context.Context, label string) {
func tryRefreshCodexClientModels(ctx context.Context, label string) bool {
data, sourceURL := fetchCodexClientModelsFromRemote(ctx)
if data == nil {
log.Warnf("%s: fetch failed from all URLs, keeping current data", label)
return
return false
}

changed, err := loadCodexClientModelsFromBytes(data, sourceURL)
if err != nil {
log.Warnf("%s: fetched catalog rejected, keeping current data: %v", label, err)
return
return false
}
if !changed {
log.Infof("%s completed from %s, no changes detected", label, sourceURL)
return
return true
}
log.Infof("%s completed from %s, catalog updated", label, sourceURL)
return true
}

func fetchCodexClientModelsFromRemote(ctx context.Context) ([]byte, string) {
Expand Down
11 changes: 9 additions & 2 deletions internal/registry/devin_models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ func TestDevinModelsRemoteFetchFallback(t *testing.T) {
}

// Attempt refresh from failing remote
tryRefreshDevinModels(context.Background(), "test failing refresh")
if tryRefreshDevinModels(context.Background(), "test failing refresh") {
t.Fatal("failed refresh reported success")
}

afterCount := len(GetDevinModels())
if afterCount != initialCount {
Expand All @@ -185,7 +187,12 @@ func TestDevinModelsRemoteFetchFallback(t *testing.T) {
defer tsValid.Close()

devinModelsURLs = []string{tsValid.URL + "/devin_models.json"}
tryRefreshDevinModels(context.Background(), "test succeeding refresh")
if !tryRefreshDevinModels(context.Background(), "test succeeding refresh") {
t.Fatal("valid refresh reported failure")
}
if !tryRefreshDevinModels(context.Background(), "test unchanged refresh") {
t.Fatal("unchanged catalog should count as a successful refresh")
}

updatedModels := GetDevinModels()
if len(updatedModels) != 1 || updatedModels[0].ID != "devin/custom-test-model" {
Expand Down
24 changes: 6 additions & 18 deletions internal/registry/devin_models_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"io"
"net/http"
"sync"
"time"

log "github.com/sirupsen/logrus"
)
Expand All @@ -29,38 +28,27 @@ func StartDevinModelsUpdater(ctx context.Context) {
}

func runDevinModelsUpdater(ctx context.Context) {
tryRefreshDevinModels(ctx, "startup Devin model refresh")

ticker := time.NewTicker(modelsRefreshInterval)
defer ticker.Stop()
log.Infof("periodic Devin model refresh started (interval=%s)", modelsRefreshInterval)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
tryRefreshDevinModels(ctx, "periodic Devin model refresh")
}
}
runModelCatalogUpdater(ctx, "Devin model refresh", tryRefreshDevinModels)
}

func tryRefreshDevinModels(ctx context.Context, label string) {
func tryRefreshDevinModels(ctx context.Context, label string) bool {
data, sourceURL := fetchDevinModelsFromRemote(ctx)
if data == nil {
log.Warnf("%s: fetch failed from all URLs, keeping current data (embedded or cached fallback)", label)
return
return false
}

changed, err := loadDevinModelsFromBytes(data, sourceURL)
if err != nil {
log.Warnf("%s: fetched catalog rejected, keeping current data: %v", label, err)
return
return false
}
if !changed {
log.Infof("%s completed from %s, no changes detected", label, sourceURL)
return
return true
}
log.Infof("%s completed from %s, catalog updated", label, sourceURL)
return true
}

func fetchDevinModelsFromRemote(ctx context.Context) ([]byte, string) {
Expand Down
89 changes: 64 additions & 25 deletions internal/registry/model_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
const (
modelsFetchTimeout = 30 * time.Second
modelsRefreshInterval = 3 * time.Hour
modelsRetryInterval = 30 * time.Second
)

var modelsURLs = []string{
Expand All @@ -37,6 +38,42 @@ var modelsCatalogStore = &modelStore{}

var updaterOnce sync.Once

// The first catalog fetch runs in the background. Service.Run waits for it
// (bounded) so models newer than the embedded catalog are registered before
// the listener opens instead of answering 400 unknown provider.
var (
startupRefreshStarted = make(chan struct{})
startupRefreshFinished = make(chan struct{})
startupRefreshDoneOnce sync.Once
)

func markStartupModelRefreshFinished() {
startupRefreshDoneOnce.Do(func() { close(startupRefreshFinished) })
}

// WaitForStartupModelRefresh blocks until the first model catalog fetch has
// finished (successfully or not), the timeout passes, or ctx ends. It returns
// at once when the updater was never started (local-model or Home mode).
// It reports whether the first fetch finished.
func WaitForStartupModelRefresh(ctx context.Context, timeout time.Duration) bool {
select {
case <-startupRefreshStarted:
default:
return false
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-startupRefreshFinished:
return true
case <-timer.C:
log.Warnf("startup model refresh still running after %s; opening the listener with the current catalog", timeout)
return false
case <-ctx.Done():
return false
}
}

// ModelRefreshCallback is invoked when startup or periodic model refresh detects changes.
// changedProviders contains the provider names whose model definitions changed.
type ModelRefreshCallback func(changedProviders []string)
Expand Down Expand Up @@ -77,49 +114,50 @@ func init() {
// Safe to call multiple times; only one updater will run.
func StartModelsUpdater(ctx context.Context) {
updaterOnce.Do(func() {
close(startupRefreshStarted)
go runModelsUpdater(ctx)
})
}

func runModelsUpdater(ctx context.Context) {
tryStartupRefresh(ctx)
periodicRefresh(ctx)
runModelCatalogUpdater(ctx, "model refresh", func(ctx context.Context, label string) bool {
defer markStartupModelRefreshFinished()
return tryRefreshModels(ctx, label)
})
}

func periodicRefresh(ctx context.Context) {
ticker := time.NewTicker(modelsRefreshInterval)
defer ticker.Stop()
log.Infof("periodic model refresh started (interval=%s)", modelsRefreshInterval)
for {
// runModelCatalogUpdater keeps failed refreshes from leaving the fallback catalog
// in use for the full refresh interval, including when networking is not ready at
// startup. A successful fetch, even without changes, restores the normal cadence.
func runModelCatalogUpdater(ctx context.Context, name string, refresh func(context.Context, string) bool) {
label := "startup " + name
for ctx.Err() == nil {
delay := modelsRefreshInterval
if !refresh(ctx, label) {
delay = modelsRetryInterval
}
if ctx.Err() != nil {
return
}
log.WithField("next_refresh_after", delay).Debugf("%s scheduled", name)
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return
case <-ticker.C:
tryPeriodicRefresh(ctx)
case <-timer.C:
}
label = "periodic " + name
}
}

// tryPeriodicRefresh fetches models from remote, compares with the current
// catalog, and notifies the registered callback if any provider changed.
func tryPeriodicRefresh(ctx context.Context) {
tryRefreshModels(ctx, "periodic model refresh")
}

// tryStartupRefresh fetches models from remote in the background during
// process startup. It uses the same change detection as periodic refresh so
// existing auth registrations can be updated after the callback is registered.
func tryStartupRefresh(ctx context.Context) {
tryRefreshModels(ctx, "startup model refresh")
}

func tryRefreshModels(ctx context.Context, label string) {
func tryRefreshModels(ctx context.Context, label string) bool {
oldData := getModels()

parsed, url := fetchModelsFromRemote(ctx)
if parsed == nil {
log.Warnf("%s: fetch failed from all URLs, keeping current data", label)
return
return false
}

if len(parsed.Meta) == 0 && oldData != nil && len(oldData.Meta) > 0 {
Expand All @@ -136,11 +174,12 @@ func tryRefreshModels(ctx context.Context, label string) {

if len(changed) == 0 {
log.Infof("%s completed from %s, no changes detected", label, url)
return
return true
}

log.Infof("%s completed from %s, changes detected for providers: %v", label, url, changed)
notifyModelRefresh(changed)
return true
}

// fetchModelsFromRemote tries all remote URLs and returns the parsed model catalog
Expand Down
Loading
Loading