From b7be5ed7d00d9821d28a619c58c2eb3d60abaeb6 Mon Sep 17 00:00:00 2001 From: hanlap0503 Date: Fri, 16 Oct 2026 06:35:01 +0000 Subject: [PATCH 1/3] fix: route rotation aliases through anonymous lane Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- internal/gateway/health.go | 6 +-- internal/gateway/rotation.go | 74 ++++++++++++++++++++---------------- 2 files changed, 42 insertions(+), 38 deletions(-) diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 8586c77..7a2dd1b 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -6,7 +6,6 @@ import ( "time" "opencode2api/internal/buildinfo" - "opencode2api/internal/config" "opencode2api/internal/httpx" modelcatalog "opencode2api/internal/models" wire "opencode2api/internal/protocol" @@ -208,12 +207,9 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { data = append(data, entry) } for _, group := range g.rotation.Snapshot().Groups { - if g.goNodes.Len() == 0 { - continue - } available := false for _, model := range group.Order { - if route, err := g.catalog.RouteForTier(model, config.TierGo, false, true); err == nil && route.Protocol != wire.SystemOne { + if route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous); err == nil && route.Protocol != wire.SystemOne { available = true break } diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index c3845cb..3fc5590 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -23,7 +23,7 @@ import ( func (g *Gateway) syncRotation() { available := map[string]bool{} for _, model := range g.catalog.List() { - if route, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil && route.Protocol != wire.SystemOne { + if route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous); err == nil && route.Protocol != wire.SystemOne { available[model] = true } } @@ -81,7 +81,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa break } visited[token.Model] = true - route, err := g.catalog.RouteForTier(token.Model, config.TierGo, false, g.goNodes.Len() > 0) + route, err := g.catalog.Route(token.Model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) if err != nil { continue } @@ -90,7 +90,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa total++ if meta != nil { meta.Model = token.Model - meta.Tier = "go" + meta.Tier = string(route.Tier) meta.Protocol = route.Protocol meta.Attempts = total meta.Usage = wire.Usage{} @@ -181,36 +181,44 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, result.reason = "request_conversion_error" return result } - body, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo) - cursor := g.goNodes.CursorFor(ids.Session) - var node *upstreamNode - // Each group attempt is exactly one HTTP call. Key selection may change, - // but there is no nested retry, stale-reasoning replay, or model-wide key ban. - for n := 0; n < attempt; n++ { - node = cursor.Next() + var resp *http.Response + var shaped bool + if route.Anonymous { + resp, err, _ = g.doAnonymousUpstream(ctx, route, bodies, ids, attempt-1) + } else { + body, keyShaped := g.shapeKeyBody(bodies[route.Tier], route, route.Tier) + shaped = keyShaped + pool, upstreamURL := g.zenNodes, g.cfg.Upstream.Zen + if route.Tier == config.TierGo { + pool, upstreamURL = g.goNodes, g.cfg.Upstream.Go + } + cursor := pool.CursorFor(ids.Session) + var node *upstreamNode + for n := 0; n < attempt; n++ { + node = cursor.Next() + } + if node == nil { + result.err = fmt.Errorf("no %s key", route.Tier) + return result + } + proxy := pool.Proxy(node) + if proxy == nil { + result.err = errors.New("no proxy") + return result + } + req, requestErr := newUpstreamRequest(ctx, upstreamURL, route.Protocol, body, ids, node.key) + if requestErr != nil { + result.err = requestErr + return result + } + req.GetBody = nil + client := *proxy.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + setRequestCredential(parent, route.Tier, config.KeyDisplayID(node.key), "key", false, proxy) + started := time.Now() + resp, err = client.Do(req) + g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started)) } - if node == nil { - result.err = errors.New("no Go key") - return result - } - proxy := g.goNodes.Proxy(node) - if proxy == nil { - result.err = errors.New("no proxy") - return result - } - req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) - if err != nil { - result.err = err - return result - } - // A reused connection must not cause net/http to implicitly replay POSTs. - req.GetBody = nil - client := *proxy.client - client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy) - started := time.Now() - resp, err := client.Do(req) - g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started)) if resp != nil { defer resp.Body.Close() } @@ -294,7 +302,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, result.reason = "first_output_timeout" return result } - if shaped { + if route.Anonymous || shaped { b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID) } var document map[string]any From f99600e7b94991ef519b3aad33478a1729d4b43e Mon Sep 17 00:00:00 2001 From: hanlap0503 Date: Fri, 16 Oct 2026 06:41:19 +0000 Subject: [PATCH 2/3] fix: simplify rotation manager configuration and add test for model exclusion --- internal/rotation/state.go | 40 +++++---------------------- internal/rotation/state_test.go | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 33 deletions(-) create mode 100644 internal/rotation/state_test.go diff --git a/internal/rotation/state.go b/internal/rotation/state.go index 9f42417..938993b 100644 --- a/internal/rotation/state.go +++ b/internal/rotation/state.go @@ -9,7 +9,6 @@ import ( "os" "path/filepath" "slices" - "sort" "sync" "time" ) @@ -52,7 +51,6 @@ type Manager struct { mu sync.Mutex path string state Snapshot - cfg config.RotationConfig } func New(path string, cfg config.RotationConfig) (*Manager, error) { @@ -86,19 +84,7 @@ func (m *Manager) Configure(cfg config.RotationConfig) { m.state.Groups = append(m.state.Groups, &Group{ID: id}) } g := m.state.Groups[i] - previous := m.cfg.SOTA - if i == 1 { - previous = m.cfg.Sweet - } - order := slices.Clone(g.Order) - if len(order) == 0 || !slices.Equal(previous.Order, c.Order) { - order = slices.Clone(c.Order) - for _, v := range g.Order { - if !slices.Contains(order, v) { - order = append(order, v) - } - } - } + order := slices.Clone(c.Order) if !slices.Equal(order, g.Order) || g.Alias != c.Alias { g.Generation++ } @@ -107,12 +93,14 @@ func (m *Manager) Configure(cfg config.RotationConfig) { if g.Paused == nil { g.Paused = map[string]time.Time{} } - if !slices.Contains(g.Order, g.Current) && len(g.Order) > 0 { - g.Current = g.Order[0] + if !slices.Contains(g.Order, g.Current) { + g.Current = "" + if len(g.Order) > 0 { + g.Current = g.Order[0] + } g.Generation++ } } - m.cfg = cfg m.state.FirstOutputSeconds = cfg.FirstOutputSeconds m.saveLocked() } @@ -123,24 +111,10 @@ func (m *Manager) Sync(available map[string]bool) { for _, g := range m.state.Groups { g.Available = map[string]bool{} for model := range available { - if config.IsSOTA(model) == (g.ID == "sota") { + if config.IsSOTA(model) == (g.ID == "sota") && slices.Contains(g.Order, model) { g.Available[model] = true } } - added := []string{} - for model := range g.Available { - if !slices.Contains(g.Order, model) { - added = append(added, model) - } - } - sort.Strings(added) - if len(g.Order) == 0 && slices.Contains(added, "glm-5.3-flash") { - added = append([]string{"glm-5.3-flash"}, slices.Delete(added, slices.Index(added, "glm-5.3-flash"), slices.Index(added, "glm-5.3-flash")+1)...) - } - if len(added) > 0 { - g.Order = append(g.Order, added...) - changed = true - } if g.Current == "" && len(g.Order) > 0 { g.Current = g.Order[0] g.Generation++ diff --git a/internal/rotation/state_test.go b/internal/rotation/state_test.go new file mode 100644 index 0000000..39b2b1a --- /dev/null +++ b/internal/rotation/state_test.go @@ -0,0 +1,49 @@ +package rotation + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "testing" + + "opencode2api/internal/config" +) + +func TestConfiguredOrderExcludesDiscoveredAndPersistedModels(t *testing.T) { + path := filepath.Join(t.TempDir(), "rotation.json") + initial := Snapshot{Groups: []*Group{ + {ID: "sota", Alias: "sota", Order: config.SOTAModels, Current: config.SOTAModels[0]}, + {ID: "sweet", Alias: "sweet", Order: []string{"configured-free", "persisted-free"}, Current: "persisted-free"}, + }} + data, err := json.Marshal(initial) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + + cfg := config.RotationConfig{ + Sweet: config.RotationGroup{Alias: "sweet", Order: []string{"configured-free"}}, + } + manager, err := New(path, cfg) + if err != nil { + t.Fatal(err) + } + manager.Sync(map[string]bool{ + "configured-free": true, + "discovered-free": true, + }) + + sweet := manager.Snapshot().Groups[1] + if !reflect.DeepEqual(sweet.Order, []string{"configured-free"}) { + t.Fatalf("Sweet order = %v, want only configured models", sweet.Order) + } + if sweet.Current != "configured-free" { + t.Fatalf("Sweet current = %q, want configured-free", sweet.Current) + } + if !reflect.DeepEqual(sweet.Available, map[string]bool{"configured-free": true}) { + t.Fatalf("Sweet available = %v, want only configured models", sweet.Available) + } +} From 2626f49fbb761fe7c6868abb45f4542a17dbebbd Mon Sep 17 00:00:00 2001 From: hanlap0503 Date: Fri, 16 Oct 2026 06:41:31 +0000 Subject: [PATCH 3/3] fix: update check-models script to save working models and handle empty responses --- README.vi.md | 2 ++ scripts/check-models.sh | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.vi.md b/README.vi.md index ab623c5..9de4caa 100644 --- a/README.vi.md +++ b/README.vi.md @@ -171,6 +171,8 @@ curl http://localhost:8080/v1/systemone \ System One ghép một state tự do với các câu hỏi có kiểu và trả về câu trả lời có kiểu, nên payload này không dùng chung hình dạng với cầu nối chat/responses và được chuyển tiếp nguyên văn, không bao giờ dịch. Chỉ những mô hình có giao thức gốc là System One mới được phục vụ tại đây; một payload quyết định gửi tới endpoint message (`/v1/chat/completions`, `/v1/responses`) cũng được chuyển tiếp nguyên văn thay vì chuyển đổi. Câu trả lời streaming từ upstream được chuyển tiếp nguyên trạng, không khôi phục luồng. +Để kiểm tra các mô hình và lưu ID của những mô hình gọi thành công vào `working-models.txt`, chạy `bash scripts/check-models.sh`. Script dùng `config.json` để lấy `server_keys` và sẽ hỏi xác nhận trước khi gửi request; thêm `--yes` để bỏ qua xác nhận. + ### Ranh giới tương thích Request dùng giao thức gốc của upstream sẽ giữ nguyên các trường riêng của nhà cung cấp. Request đi qua nhiều giao thức sẽ đi qua một biểu diễn chung; không phải tuỳ chọn nào cũng có phần tương đương. Ví dụ, ràng buộc output JSON của Chat và `seed` không được chuyển tiếp sang Anthropic Messages. Nội dung hoặc loại tool không được hỗ trợ có thể bị từ chối. diff --git a/scripts/check-models.sh b/scripts/check-models.sh index a122c94..d86c746 100755 --- a/scripts/check-models.sh +++ b/scripts/check-models.sh @@ -33,7 +33,8 @@ fi BASE_URL=${BASE_URL%/} models_file=$(mktemp) response_file=$(mktemp) -trap 'rm -f "$models_file" "$response_file"' EXIT +working_models_tmp=$(mktemp ./.working-models.txt.tmp.XXXXXX) +trap 'rm -f "$models_file" "$response_file" "$working_models_tmp"' EXIT if ! curl -sS --fail-with-body "$BASE_URL/v1/models" \ -H "Authorization: Bearer $API_KEY" -o "$models_file"; then @@ -50,7 +51,12 @@ fi model_count=$(jq '.data | length' "$models_file") if [[ "$model_count" -eq 0 ]]; then + if ! mv -f "$working_models_tmp" working-models.txt; then + printf 'Could not write working-models.txt\n' >&2 + exit 1 + fi printf 'No models were returned by %s/v1/models\n' "$BASE_URL" + printf 'An empty model list was saved to working-models.txt\n' exit 0 fi @@ -109,6 +115,7 @@ while IFS=$'\t' read -r model protocol; do if [[ "$curl_ok" == true && "$status" =~ ^2[0-9][0-9]$ ]] \ && jq -e 'type == "object" and (has("error") | not)' "$response_file" >/dev/null 2>&1; then printf 'PASS %s (%s, HTTP %s)\n' "$model" "$protocol" "$status" + printf '%s\n' "$model" >> "$working_models_tmp" passed=$((passed + 1)) else message=$(jq -r '.error.message // .message // empty' "$response_file" 2>/dev/null | head -c 200) @@ -121,8 +128,14 @@ while IFS=$'\t' read -r model protocol; do fi done < <(jq -r '.data[] | [.id, (.native_protocol // "chat")] | @tsv' "$models_file") +if ! mv -f "$working_models_tmp" working-models.txt; then + printf 'Could not write working-models.txt\n' >&2 + exit 1 +fi + printf '\nSummary: %s passed, %s failed, %s skipped (total %s)\n' \ "$passed" "$failed" "$skipped" "$model_count" +printf 'Working model list saved to working-models.txt\n' if [[ "$failed" -gt 0 || "$skipped" -gt 0 ]]; then exit 1 fi \ No newline at end of file