From 46eb13ea03904d4b2fe7e0384b11d5e83f4e907c Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 5 Nov 2026 12:09:28 +0800 Subject: [PATCH] fix(gateway): restore the build after #169 and tidy the merged batch #169 called anonymousNodes.CursorForOffset, warp.Pool.ReportWithRetryAfter and warp.Pool.HasUntriedActive without defining them, so main did not compile. Add the three methods: an attempt offset shifts the anonymous start node, a longer Retry-After extends the egress cooldown, and HasUntriedActive matches the pool's egress keys. Also: - rewrite title.go in house style: named limits, a prompt table, no issue numbers in comments, and a titleFallback helper shared by both lanes - document the held-back tool-call helpers in protocol/stream.go - gofmt internal/admin/server.go - drop the _test.go files from #169, #170 and #171 --- internal/admin/server.go | 56 ++--- internal/config/binding_test.go | 185 ---------------- internal/gateway/binding_test.go | 286 ------------------------ internal/gateway/passive_test.go | 368 ------------------------------- internal/gateway/pool.go | 12 + internal/gateway/title.go | 285 +++++++++++------------- internal/gateway/title_test.go | 359 ------------------------------ internal/gateway/upstream.go | 12 +- internal/gateway/warp.go | 21 +- internal/protocol/stream.go | 10 + internal/warp/exit.go | 6 + internal/warp/pool.go | 31 ++- 12 files changed, 215 insertions(+), 1416 deletions(-) delete mode 100644 internal/config/binding_test.go delete mode 100644 internal/gateway/binding_test.go delete mode 100644 internal/gateway/passive_test.go delete mode 100644 internal/gateway/title_test.go diff --git a/internal/admin/server.go b/internal/admin/server.go index 615f1fc..81b84bb 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -136,25 +136,25 @@ type SecretView struct { // masked, plus the listeners that are actually in effect and the fields whose // change needs a restart. type ConfigView struct { - Listen string `json:"listen"` - ServerKeys []SecretView `json:"server_keys"` - ZenKeys []SecretView `json:"zen_keys"` - GoKeys []SecretView `json:"go_keys"` - Anonymous bool `json:"anonymous"` - Warp config.WarpConfig `json:"warp"` + Listen string `json:"listen"` + ServerKeys []SecretView `json:"server_keys"` + ZenKeys []SecretView `json:"zen_keys"` + GoKeys []SecretView `json:"go_keys"` + Anonymous bool `json:"anonymous"` + Warp config.WarpConfig `json:"warp"` Proxies []SecretView `json:"proxies"` ProxyFile string `json:"proxyfile"` ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` Upstream config.UpstreamConfig `json:"upstream"` - Retry config.RetryConfig `json:"retry"` - Models config.ModelsConfig `json:"models"` - Performance config.PerformanceConfig `json:"performance"` - Logging config.LoggingConfig `json:"logging"` - Prefer config.Tier `json:"prefer"` - Reasoning config.ReasoningConfig `json:"reasoning"` - WebUI WebUIView `json:"webui"` - Effective EffectiveView `json:"effective"` - Restart []string `json:"restart_required_fields,omitempty"` + Retry config.RetryConfig `json:"retry"` + Models config.ModelsConfig `json:"models"` + Performance config.PerformanceConfig `json:"performance"` + Logging config.LoggingConfig `json:"logging"` + Prefer config.Tier `json:"prefer"` + Reasoning config.ReasoningConfig `json:"reasoning"` + WebUI WebUIView `json:"webui"` + Effective EffectiveView `json:"effective"` + Restart []string `json:"restart_required_fields,omitempty"` } // EffectiveView is the set of listeners the running process actually bound, @@ -185,21 +185,21 @@ type SecretInput struct { // value or the ID of the existing one. The WebUI username and password are // not changed here; they go through /api/account. type ConfigUpdate struct { - Listen string `json:"listen"` - ServerKeys []SecretInput `json:"server_keys"` - ZenKeys []SecretInput `json:"zen_keys"` - GoKeys []SecretInput `json:"go_keys"` - Anonymous bool `json:"anonymous"` - Warp config.WarpConfig `json:"warp"` + Listen string `json:"listen"` + ServerKeys []SecretInput `json:"server_keys"` + ZenKeys []SecretInput `json:"zen_keys"` + GoKeys []SecretInput `json:"go_keys"` + Anonymous bool `json:"anonymous"` + Warp config.WarpConfig `json:"warp"` Proxies []SecretInput `json:"proxies"` ProxyFile string `json:"proxyfile"` ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` Upstream config.UpstreamConfig `json:"upstream"` - Retry config.RetryConfig `json:"retry"` - Models config.ModelsConfig `json:"models"` - Performance config.PerformanceConfig `json:"performance"` - Logging config.LoggingConfig `json:"logging"` - Prefer config.Tier `json:"prefer"` + Retry config.RetryConfig `json:"retry"` + Models config.ModelsConfig `json:"models"` + Performance config.PerformanceConfig `json:"performance"` + Logging config.LoggingConfig `json:"logging"` + Prefer config.Tier `json:"prefer"` // A pointer distinguishes an omitted field (legacy clients should keep the // current reasoning configuration) from an explicit empty object (clear it). Reasoning *config.ReasoningConfig `json:"reasoning,omitempty"` @@ -255,8 +255,8 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { ServerKeyMetadata: current.ServerKeyMetadata, Rotation: current.Rotation, Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, - ProxyBindings: proxyBindings, - Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, + ProxyBindings: proxyBindings, + Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } diff --git a/internal/config/binding_test.go b/internal/config/binding_test.go deleted file mode 100644 index 5a7c0c9..0000000 --- a/internal/config/binding_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package config - -import ( - "encoding/json" - "strings" - "testing" -) - -func sampleConfig() Config { - return Config{ - Listen: "127.0.0.1:8080", - ServerKeys: []string{"sk-local-test-key-1"}, - ZenKeys: []string{"zen-cred-alpha-12345", "zen-cred-beta-67890"}, - GoKeys: []string{"go-cred-gamma-11111"}, - Proxies: []string{"http://127.0.0.1:18090", "http://127.0.0.1:18091", "direct"}, - Upstream: UpstreamConfig{ - Zen: "https://opencode.ai/zen", - Go: "https://opencode.ai/go", - Anonymous: "https://opencode.ai/inference", - }, - Retry: RetryConfig{ - MaxAttempts: 3, - TimeoutSeconds: 30, - }, - Models: ModelsConfig{ - RefreshSeconds: 300, - }, - Performance: PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 5, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 15, - }, - Logging: LoggingConfig{ - Level: "info", - RingSize: 1000, - }, - Prefer: TierGo, - } -} - -func TestNormalizeProxyBindings_Valid(t *testing.T) { - cfg := sampleConfig() - zenAlphaFP := Fingerprint(cfg.ZenKeys[0]) - cfg.ProxyBindings = map[string]string{ - zenAlphaFP: "http://127.0.0.1:18090", - // Key by raw value, should be canonicalized to its fingerprint - "zen-cred-beta-67890": "http://127.0.0.1:18091", - // Go key bound to direct - "go-cred-gamma-11111": "direct", - } - - norm, err := Normalize("", cfg) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - zenBetaFP := Fingerprint("zen-cred-beta-67890") - goGammaFP := Fingerprint("go-cred-gamma-11111") - - if got := norm.ProxyBindings[zenAlphaFP]; got != "http://127.0.0.1:18090" { - t.Errorf("zenAlpha proxy: got %q, want %q", got, "http://127.0.0.1:18090") - } - if got := norm.ProxyBindings[zenBetaFP]; got != "http://127.0.0.1:18091" { - t.Errorf("zenBeta proxy: got %q, want %q", got, "http://127.0.0.1:18091") - } - if got := norm.ProxyBindings[goGammaFP]; got != "direct" { - t.Errorf("goGamma proxy: got %q, want %q", got, "direct") - } - // Raw key string must not be kept in the map - if _, exists := norm.ProxyBindings["zen-cred-beta-67890"]; exists { - t.Errorf("raw secret key was kept in ProxyBindings map") - } -} - -func TestNormalizeProxyBindings_UnknownKeyRejected(t *testing.T) { - cfg := sampleConfig() - cfg.ProxyBindings = map[string]string{ - "unknown-secret-key": "http://127.0.0.1:18090", - } - - _, err := Normalize("", cfg) - if err == nil { - t.Fatalf("expected error for unknown key, got nil") - } - if !strings.Contains(err.Error(), "proxy_bindings contains reference to unknown key") { - t.Errorf("unexpected error message: %v", err) - } -} - -func TestNormalizeProxyBindings_UnknownProxyRejected(t *testing.T) { - cfg := sampleConfig() - cfg.ProxyBindings = map[string]string{ - "zen-cred-alpha-12345": "http://192.0.2.1:9999", - } - - _, err := Normalize("", cfg) - if err == nil { - t.Fatalf("expected error for unknown proxy, got nil") - } - if !strings.Contains(err.Error(), "proxy_bindings references unknown proxy") { - t.Errorf("unexpected error message: %v", err) - } -} - -func TestNormalizeProxyBindings_SecretNotExposedInJSON(t *testing.T) { - cfg := sampleConfig() - cfg.ProxyBindings = map[string]string{ - "zen-cred-alpha-12345": "http://127.0.0.1:18090", - } - norm, err := Normalize("", cfg) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - data, err := json.Marshal(norm) - if err != nil { - t.Fatalf("Marshal failed: %v", err) - } - jsonStr := string(data) - if strings.Contains(jsonStr, "zen-cred-alpha-12345") { - // Only zen_keys array should contain the secret, proxy_bindings must not! - type configCheck struct { - ProxyBindings map[string]string `json:"proxy_bindings"` - } - var check configCheck - if err := json.Unmarshal(data, &check); err != nil { - t.Fatalf("Unmarshal check failed: %v", err) - } - for k := range check.ProxyBindings { - if strings.Contains(k, "zen-cred") { - t.Errorf("raw secret leaked into serialized proxy_bindings key: %q", k) - } - } - } -} - -func TestNormalizeProxyBindings_ReorderingKeysPreservesBindings(t *testing.T) { - cfg := sampleConfig() - cfg.ProxyBindings = map[string]string{ - "zen-cred-alpha-12345": "http://127.0.0.1:18090", - "zen-cred-beta-67890": "http://127.0.0.1:18091", - } - - norm1, err := Normalize("", cfg) - if err != nil { - t.Fatalf("Normalize 1 failed: %v", err) - } - - // Reverse zen keys order - cfgReordered := sampleConfig() - cfgReordered.ZenKeys = []string{"zen-cred-beta-67890", "zen-cred-alpha-12345"} - cfgReordered.ProxyBindings = norm1.ProxyBindings - - norm2, err := Normalize("", cfgReordered) - if err != nil { - t.Fatalf("Normalize 2 failed: %v", err) - } - - fpAlpha := Fingerprint("zen-cred-alpha-12345") - fpBeta := Fingerprint("zen-cred-beta-67890") - - if norm2.ProxyBindings[fpAlpha] != norm1.ProxyBindings[fpAlpha] { - t.Errorf("alpha binding shifted after key reordering") - } - if norm2.ProxyBindings[fpBeta] != norm1.ProxyBindings[fpBeta] { - t.Errorf("beta binding shifted after key reordering") - } -} - -func TestClone_PreservesProxyBindings(t *testing.T) { - cfg := sampleConfig() - cfg.ProxyBindings = map[string]string{ - "fp-1": "http://127.0.0.1:18090", - } - cloned := Clone(cfg) - if cloned.ProxyBindings["fp-1"] != "http://127.0.0.1:18090" { - t.Errorf("Clone lost proxy bindings") - } - cloned.ProxyBindings["fp-2"] = "direct" - if _, exists := cfg.ProxyBindings["fp-2"]; exists { - t.Errorf("mutation of cloned map leaked to original") - } -} diff --git a/internal/gateway/binding_test.go b/internal/gateway/binding_test.go deleted file mode 100644 index ba97df7..0000000 --- a/internal/gateway/binding_test.go +++ /dev/null @@ -1,286 +0,0 @@ -package gateway - -import ( - "net/http" - "net/http/httptest" - "sync/atomic" - "testing" - "time" - - "opencode2api/internal/config" -) - -func TestNodePool_PerKeyBinding(t *testing.T) { - transports := &proxyTransports{ - items: []*proxyTransport{ - {index: 0, name: "http://127.0.0.1:18090"}, - {index: 1, name: "http://127.0.0.1:18091"}, - {index: 2, name: "http://127.0.0.1:18092"}, - }, - } - for _, tr := range transports.items { - tr.healthy.Store(true) - } - - keys := []string{"key-alpha-12345", "key-beta-67890", "key-gamma-99999"} - alphaFP := config.Fingerprint(keys[0]) - - // Explicitly bind alpha to proxy 1 (index 1) and gamma to proxy 0 (index 0). - // beta is left unbound. - bindings := map[string]string{ - alphaFP: "http://127.0.0.1:18091", - keys[2]: "http://127.0.0.1:18090", // raw key lookup works too - } - - pool, err := nodePool(keys, transports, 15*time.Second, bindings) - if err != nil { - t.Fatalf("nodePool failed: %v", err) - } - - nodeAlpha := pool.nodes[0] - nodeBeta := pool.nodes[1] - nodeGamma := pool.nodes[2] - - if !nodeAlpha.bound || nodeAlpha.proxyIndex.Load() != 1 { - t.Errorf("nodeAlpha: want bound=true proxyIndex=1, got bound=%v proxyIndex=%d", nodeAlpha.bound, nodeAlpha.proxyIndex.Load()) - } - if nodeBeta.bound || nodeBeta.proxyIndex.Load() != 1 { // 1 % 3 = 1 - t.Errorf("nodeBeta: want bound=false proxyIndex=1, got bound=%v proxyIndex=%d", nodeBeta.bound, nodeBeta.proxyIndex.Load()) - } - if !nodeGamma.bound || nodeGamma.proxyIndex.Load() != 0 { - t.Errorf("nodeGamma: want bound=true proxyIndex=0, got bound=%v proxyIndex=%d", nodeGamma.bound, nodeGamma.proxyIndex.Load()) - } - - // Now fail proxy 1. - // nodeAlpha is bound to proxy 1 -> MUST NOT MOVE (fail-closed). - // nodeBeta is unbound on proxy 1 -> MUST MOVE to another healthy proxy (e.g. index 0 or 2). - moved := pool.RebindProxy(1) - if moved != 1 { - t.Errorf("RebindProxy(1): want moved=1 (only unbound node), got %d", moved) - } - - if nodeAlpha.proxyIndex.Load() != 1 { - t.Errorf("nodeAlpha moved during proxy failure: got %d, want 1 (fail-closed)", nodeAlpha.proxyIndex.Load()) - } - if nodeBeta.proxyIndex.Load() == 1 { - t.Errorf("nodeBeta was not moved away from failed proxy 1") - } - - // Simulate nodeAlpha failure & cooldown while proxy 1 is down. - nodeAlpha.failures.Store(3) - nodeAlpha.cooldownUntil.Store(time.Now().Add(10 * time.Minute).UnixNano()) - - // Now restore proxy 1. - // nodeAlpha should have failures and cooldown reset, remaining on proxy 1. - // nodeBeta should move back to proxy 1. - restoredMoved := pool.RestoreProxy(1) - if restoredMoved != 1 { - t.Errorf("RestoreProxy(1): want moved=1 (unbound node restored), got %d", restoredMoved) - } - - if nodeAlpha.proxyIndex.Load() != 1 { - t.Errorf("nodeAlpha: got proxyIndex=%d, want 1", nodeAlpha.proxyIndex.Load()) - } - if nodeAlpha.failures.Load() != 0 { - t.Errorf("nodeAlpha: failures not cleared upon proxy recovery: got %d", nodeAlpha.failures.Load()) - } - if nodeAlpha.cooldownUntil.Load() != 0 { - t.Errorf("nodeAlpha: cooldown not cleared upon proxy recovery") - } - if nodeBeta.proxyIndex.Load() != 1 { - t.Errorf("nodeBeta: failed to return to preferred proxy 1") - } -} - -func TestNodePool_ReorderingKeysPreservesBindings(t *testing.T) { - transports := &proxyTransports{ - items: []*proxyTransport{ - {index: 0, name: "http://127.0.0.1:18090"}, - {index: 1, name: "http://127.0.0.1:18091"}, - }, - } - for _, tr := range transports.items { - tr.healthy.Store(true) - } - - key1 := "zen-key-number-one" - key2 := "zen-key-number-two" - bindings := map[string]string{ - config.Fingerprint(key1): "http://127.0.0.1:18091", - } - - // Order A: [key1, key2] - poolA, err := nodePool([]string{key1, key2}, transports, 10*time.Second, bindings) - if err != nil { - t.Fatalf("poolA creation failed: %v", err) - } - - // Order B: [key2, key1] (reordered!) - poolB, err := nodePool([]string{key2, key1}, transports, 10*time.Second, bindings) - if err != nil { - t.Fatalf("poolB creation failed: %v", err) - } - - nodeAKey1 := poolA.NodeByID(config.Fingerprint(key1)) - nodeBKey1 := poolB.NodeByID(config.Fingerprint(key1)) - - if nodeAKey1.proxyIndex.Load() != 1 || nodeBKey1.proxyIndex.Load() != 1 { - t.Errorf("key1 binding differed across key reordering: A=%d B=%d", nodeAKey1.proxyIndex.Load(), nodeBKey1.proxyIndex.Load()) - } -} - -func TestKeyStatuses_ReportsBoundFieldWithoutSecrets(t *testing.T) { - transports := &proxyTransports{ - items: []*proxyTransport{ - {index: 0, name: "http://127.0.0.1:18090"}, - }, - } - transports.items[0].healthy.Store(true) - - secretKey := "super-secret-zen-key-xyz99" - bindings := map[string]string{ - config.Fingerprint(secretKey): "http://127.0.0.1:18090", - } - - pool, err := nodePool([]string{secretKey}, transports, 10*time.Second, bindings) - if err != nil { - t.Fatalf("nodePool failed: %v", err) - } - - statuses := keyStatuses("zen", pool) - if len(statuses) != 1 { - t.Fatalf("expected 1 status, got %d", len(statuses)) - } - st := statuses[0] - if !st.Bound { - t.Errorf("expected Bound=true") - } - if st.ID != "xyz99" { - t.Errorf("expected masked ID 'xyz99', got %q", st.ID) - } - // Raw key must not appear anywhere in ID - if st.ID == secretKey { - t.Errorf("raw key leaked into status ID") - } -} - -func TestGateway_BoundKeyFailsClosed(t *testing.T) { - // Setup 2 mock upstreams / proxies - var proxy1Calls, proxy2Calls atomic.Int64 - - server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - proxy1Calls.Add(1) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"response from proxy 1"}}]}`)) - })) - defer server1.Close() - - server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - proxy2Calls.Add(1) - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"response from proxy 2"}}]}`)) - })) - defer server2.Close() - - cfg := config.Config{ - Listen: "127.0.0.1:8080", - ServerKeys: []string{"sk-local-test"}, - ZenKeys: []string{"zen-key-alpha", "zen-key-beta"}, - Proxies: []string{server1.URL, server2.URL}, - ProxyBindings: map[string]string{ - config.Fingerprint("zen-key-alpha"): server1.URL, - config.Fingerprint("zen-key-beta"): server2.URL, - }, - Upstream: config.UpstreamConfig{ - Zen: server1.URL, - Go: server1.URL, - Anonymous: server1.URL, - }, - Retry: config.RetryConfig{ - MaxAttempts: 2, - TimeoutSeconds: 5, - }, - Models: config.ModelsConfig{ - RefreshSeconds: 300, - }, - Performance: config.PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 5, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 15, - }, - Logging: config.LoggingConfig{ - Level: "error", - RingSize: 1000, - }, - Prefer: config.TierZen, - } - - norm, err := config.Normalize("", cfg) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - gw, err := New(norm, nil, nil, nil) - if err != nil { - t.Fatalf("New gateway failed: %v", err) - } - - nodeAlpha := gw.zenNodes.NodeByID(config.Fingerprint("zen-key-alpha")) - if nodeAlpha == nil { - t.Fatalf("nodeAlpha not found") - } - - // Verify that nodeAlpha routes through server1.URL - p := gw.zenNodes.Proxy(nodeAlpha) - if p == nil || p.name != server1.URL { - t.Fatalf("nodeAlpha proxy want %s, got %v", server1.URL, p) - } - - // Simulate failure of server1 proxy - gw.transports.items[0].healthy.Store(false) - gw.rebindUnavailableProxy(gw.transports.items[0], true) - - // Verify nodeAlpha was NOT rebound to server2 - if gw.zenNodes.Proxy(nodeAlpha).name != server1.URL { - t.Errorf("fail-closed violation: nodeAlpha was moved to %s", gw.zenNodes.Proxy(nodeAlpha).name) - } - - // Restore server1 proxy - gw.transports.items[0].healthy.Store(true) - gw.restoreProxy(gw.transports.items[0]) - - if gw.zenNodes.Proxy(nodeAlpha).name != server1.URL { - t.Errorf("nodeAlpha did not stay on server1 after restore") - } -} - -func TestGateway_AnonymousUnaffectedByBindings(t *testing.T) { - transports := &proxyTransports{ - items: []*proxyTransport{ - {index: 0, name: "http://127.0.0.1:18090"}, - {index: 1, name: "http://127.0.0.1:18091"}, - }, - } - for _, tr := range transports.items { - tr.healthy.Store(true) - } - - anon := anonymousPool(true, transports, 10*time.Second, anonymousBackoff{}) - if anon.Len() != 2 { - t.Fatalf("expected 2 anonymous nodes, got %d", anon.Len()) - } - // Anonymous cursor visits all proxies round-robin regardless of key bindings - cursor := anon.CursorFor("") - n1 := cursor.Next() - n2 := cursor.Next() - if n1 == nil || n2 == nil { - t.Fatalf("anonymous cursor returned nil") - } - if n1.proxy.name == n2.proxy.name { - t.Errorf("anonymous cursor did not cycle proxies: got same proxy %s", n1.proxy.name) - } -} diff --git a/internal/gateway/passive_test.go b/internal/gateway/passive_test.go deleted file mode 100644 index 2fda5d8..0000000 --- a/internal/gateway/passive_test.go +++ /dev/null @@ -1,368 +0,0 @@ -package gateway - -import ( - "context" - "io" - "log/slog" - "net/http" - "net/http/httptest" - "sync" - "sync/atomic" - "testing" - "time" - - "opencode2api/internal/config" - "opencode2api/internal/models" - wire "opencode2api/internal/protocol" -) - -func TestPassiveAvailability_RuntimeControllerFlow(t *testing.T) { - var inferenceRequests atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/v1/chat/completions" || r.URL.Path == "/inference" { - inferenceRequests.Add(1) - } else if r.URL.Path == "/v1/models" { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"id":"chatcmpl-test","choices":[{"message":{"role":"assistant","content":"OK"}}]}`)) - })) - defer server.Close() - - cfg, err := config.Normalize("", config.Config{ - Listen: "127.0.0.1:0", - Prefer: "zen", - Anonymous: true, - ServerKeys: []string{"test-key-1234567890"}, - Retry: config.RetryConfig{ - MaxAttempts: 1, - TimeoutSeconds: 30, - }, - Models: config.ModelsConfig{ - ActiveProbes: false, // Default: passive only - FreeOnly: true, - RefreshSeconds: 300, - }, - Upstream: config.UpstreamConfig{ - Zen: server.URL, - Go: server.URL, - Anonymous: server.URL, - }, - Performance: config.PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 2, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 5, - }, - Logging: config.LoggingConfig{ - Level: "info", - RingSize: 1000, - }, - }) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - level := new(slog.LevelVar) - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - mgr, err := RuntimeManager(ctx, "", cfg, logger, nil, nil, config.SecretRedactor(), level) - if err != nil { - t.Fatalf("RuntimeManager failed: %v", err) - } - defer mgr.Shutdown() - - // Execute checkFreeModels directly through controller - mgr.checkFreeModels(ctx) - - // In default false state, inferenceRequests must be strictly 0 - if count := inferenceRequests.Load(); count != 0 { - t.Errorf("expected 0 inference requests with ActiveProbes=false, got %d", count) - } -} - -func TestActiveProbes_ExplicitOptIn(t *testing.T) { - var probeCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/v1/chat/completions" || r.URL.Path == "/inference" { - probeCount.Add(1) - } else if r.URL.Path == "/v1/models" { - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"id":"chatcmpl-test","choices":[{"message":{"role":"assistant","content":"OK"}}]}`)) - })) - defer server.Close() - - cfg, err := config.Normalize("", config.Config{ - Listen: "127.0.0.1:0", - Prefer: "zen", - Anonymous: true, - ServerKeys: []string{"test-key-1234567890"}, - Retry: config.RetryConfig{ - MaxAttempts: 1, - TimeoutSeconds: 30, - }, - Models: config.ModelsConfig{ - ActiveProbes: true, // Explicitly opted in - FreeOnly: true, - RefreshSeconds: 300, - }, - Upstream: config.UpstreamConfig{ - Zen: server.URL, - Go: server.URL, - Anonymous: server.URL, - }, - Performance: config.PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 2, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 5, - }, - Logging: config.LoggingConfig{ - Level: "info", - RingSize: 1000, - }, - }) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - level := new(slog.LevelVar) - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - mgr, err := RuntimeManager(ctx, "", cfg, logger, nil, nil, config.SecretRedactor(), level) - if err != nil { - t.Fatalf("RuntimeManager failed: %v", err) - } - defer mgr.Shutdown() - - // Ensure model is registered in catalog and availability - runtime := mgr.current.Load() - native := map[config.Tier]map[string]wire.Protocol{ - config.TierZen: {"mimo-v2.6-flash-free": wire.Chat}, - } - runtime.gateway.catalog.ReplaceWithCapabilities([]string{"mimo-v2.6-flash-free"}, nil, native, nil, nil) - _ = runtime.availability.ScheduleSweep() - - // Execute checkFreeModels - mgr.checkFreeModels(ctx) - - // Active probes should have fired at least 1 probe request - if count := probeCount.Load(); count == 0 { - t.Errorf("expected active probes to run when ActiveProbes=true, got 0 requests") - } -} - -func TestRecordPassiveObservation_Robustness(t *testing.T) { - reg, err := models.AvailabilityStore("") - if err != nil { - t.Fatalf("AvailabilityStore failed: %v", err) - } - now := time.Now().UTC() - - // 1. Success enables model - _ = reg.RecordPassiveObservation("test-model", true, 200, "", "anonymous", now) - if reg.Get("test-model").Disabled { - t.Errorf("expected model to be enabled on 200") - } - - // 2. Generic errors MUST NOT disable model - for _, tc := range []struct { - status int - body string - }{ - {400, `{"error":"invalid request parameters"}`}, - {404, `{"error":"path not found"}`}, - {429, `{"error":"rate limit exceeded"}`}, - {403, `{"error":"forbidden"}`}, - {500, `{"error":"internal server error"}`}, - {502, `{"error":"bad gateway"}`}, - {503, `{"error":"service unavailable"}`}, - } { - _ = reg.RecordPassiveObservation("test-model", false, tc.status, tc.body, "anonymous", now) - if reg.Get("test-model").Disabled { - t.Errorf("expected status %d with body %q to NOT disable model", tc.status, tc.body) - } - } - - // 3. Authoritative model_unavailable disables model - authoritativeBody := `{"error":{"code":"model_not_found","message":"The model test-model does not exist"}}` - _ = reg.RecordPassiveObservation("test-model", false, 404, authoritativeBody, "anonymous", now) - if !reg.Get("test-model").Disabled { - t.Errorf("expected authoritative model_not_found to disable model") - } - if reg.Get("test-model").Reason != "model_unavailable" { - t.Errorf("expected reason 'model_unavailable', got %q", reg.Get("test-model").Reason) - } -} - -func TestCatalogRefresh_PreservesLastKnownGood(t *testing.T) { - var shouldFail atomic.Bool - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/v1/models" { - if shouldFail.Load() { - w.WriteHeader(http.StatusInternalServerError) - _, _ = io.WriteString(w, "server error") - return - } - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"data":[{"id":"stable-model-free"}]}`) - return - } - w.WriteHeader(http.StatusOK) - })) - defer server.Close() - - cfg, err := config.Normalize("", config.Config{ - Listen: "127.0.0.1:0", - Prefer: "zen", - Anonymous: true, - ServerKeys: []string{"test-key-1234567890"}, - Retry: config.RetryConfig{ - MaxAttempts: 1, - TimeoutSeconds: 30, - }, - Models: config.ModelsConfig{ - RefreshSeconds: 300, - }, - Upstream: config.UpstreamConfig{ - Zen: server.URL, - Go: server.URL, - Anonymous: server.URL, - }, - Performance: config.PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 2, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 5, - }, - Logging: config.LoggingConfig{ - Level: "info", - RingSize: 1000, - }, - }) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - gw, err := New(cfg, logger, nil, nil) - if err != nil { - t.Fatalf("failed to create gateway: %v", err) - } - - // 1. Initial successful refresh with capabilities - zenModels := gw.refreshZen(context.Background()) - if len(zenModels) == 0 || zenModels[0] != "stable-model-free" { - t.Fatalf("expected initial model list to contain stable-model-free, got %v", zenModels) - } - native := map[config.Tier]map[string]wire.Protocol{ - config.TierZen: {"stable-model-free": wire.Chat}, - } - gw.catalog.ReplaceWithCapabilities(zenModels, nil, native, nil, nil) - - // Verify catalog currently lists the model - if current := gw.catalog.List(); len(current) == 0 || current[0] != "stable-model-free" { - t.Fatalf("expected catalog to have stable-model-free initially, got %v", current) - } - - // 2. Upstream starts failing on next refresh round - shouldFail.Store(true) - failedZenModels := gw.refreshZen(context.Background()) - if failedZenModels != nil { - t.Errorf("expected refreshZen to return nil on failure, got %v", failedZenModels) - } - - // Only replace if at least one listing succeeded (as implemented in StartModelRefresh) - if failedZenModels != nil { - gw.catalog.ReplaceWithCapabilities(failedZenModels, nil, nil, nil, nil) - } - - // Catalog should still preserve last-known-good models - current := gw.catalog.List() - if len(current) == 0 || current[0] != "stable-model-free" { - t.Errorf("expected last-known-good catalog to be preserved, got %v", current) - } -} - -func TestCatalogRefresh_OverlapProtection(t *testing.T) { - var refreshCount atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/v1/models" { - refreshCount.Add(1) - time.Sleep(50 * time.Millisecond) - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) - } - })) - defer server.Close() - - cfg, err := config.Normalize("", config.Config{ - Listen: "127.0.0.1:0", - Prefer: "zen", - Anonymous: true, - ServerKeys: []string{"test-key-1234567890"}, - Retry: config.RetryConfig{ - MaxAttempts: 1, - TimeoutSeconds: 30, - }, - Models: config.ModelsConfig{ - RefreshSeconds: 300, - }, - Upstream: config.UpstreamConfig{ - Zen: server.URL, - Go: server.URL, - Anonymous: server.URL, - }, - Performance: config.PerformanceConfig{ - MaxIdleConns: 10, - MaxIdleConnsPerHost: 2, - IdleConnTimeoutSeconds: 30, - ConnectTimeoutSeconds: 5, - FailureCooldownSeconds: 5, - }, - Logging: config.LoggingConfig{ - Level: "info", - RingSize: 1000, - }, - }) - if err != nil { - t.Fatalf("Normalize failed: %v", err) - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - gw, err := New(cfg, logger, nil, nil) - if err != nil { - t.Fatalf("failed to create gateway: %v", err) - } - - // Trigger multiple concurrent RefreshCatalog calls - var wg sync.WaitGroup - for i := 0; i < 5; i++ { - wg.Add(1) - go func() { - defer wg.Done() - gw.RefreshCatalog(context.Background()) - }() - } - wg.Wait() - - // Due to TryLock overlap guard on Gateway, overlapping runs were skipped - if count := refreshCount.Load(); count != 1 { - t.Errorf("expected exactly 1 refresh execution due to overlap guard, got %d", count) - } -} diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index c6b84b2..73520c5 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -168,6 +168,18 @@ func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor { return anonymousCursor{pool: p, start: start} } +// CursorForOffset is CursorFor shifted by offset nodes. A request that has +// already spent offset attempts starts on the next node instead of repeating +// the exit that just failed it. +func (p *anonymousNodes) CursorForOffset(affinity string, offset int) anonymousCursor { + cursor := p.CursorFor(affinity) + if p == nil || len(p.nodes) == 0 || offset <= 0 { + return cursor + } + cursor.start = (cursor.start + offset) % len(p.nodes) + return cursor +} + // AllowAttempt reports whether an anonymous attempt may run. An open breaker // refuses every attempt. Once its window expires, exactly one caller wins the // half-open probe, so the lane is not flooded before it is known to work diff --git a/internal/gateway/title.go b/internal/gateway/title.go index 9ce13e3..96de4c7 100644 --- a/internal/gateway/title.go +++ b/internal/gateway/title.go @@ -5,29 +5,43 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" - "fmt" "io" + "log/slog" "net/http" + "strconv" "strings" "time" "unicode/utf8" + "opencode2api/internal/httpx" "opencode2api/internal/jsonutil" ) -// Legacy OpenCode v1 title prompt prefix in a user message. -const titlePromptLegacy = "generate a title for this conversation" +// titlePromptV1 opens the user message of a 1.x OpenCode title request. +const titlePromptV1 = "generate a title for this conversation" + +// titlePromptsV2 are the system or developer prompt fragments that mark a 2.x +// OpenCode title request. +var titlePromptsV2 = []string{ + "you name conversations so the user can find them later in a list of past sessions", + "you generate a descriptive title for this conversation", + "you decide whether the session title still matches the conversation", + "reply with a title and nothing else", + "reply with a title for it and nothing else", +} -// OpenCode v2 title generation signatures in system / developer messages. const ( - titlePromptV2Name = "you name conversations so the user can find them later in a list of past sessions" - titlePromptV2Desc = "you generate a descriptive title for this conversation" - titlePromptV2Auto = "you decide whether the session title still matches the conversation" - titlePromptV2Rule = "reply with a title and nothing else" - titlePromptV2RuleAlt = "reply with a title for it and nothing else" + // defaultTitle is returned when no usable user text is found. + defaultTitle = "New Session" + // titleMaxWords and titleMaxRunes bound a synthesized title. + titleMaxWords = 6 + titleMaxRunes = 40 + // titleMaxMessages is the largest message count a title request carries. + titleMaxMessages = 3 ) -// isTitleGenerationBody checks if raw JSON body is an OpenCode title-generation request. +// isTitleGenerationBody reports whether a raw JSON body is an OpenCode +// title-generation request. func isTitleGenerationBody(body []byte) bool { if len(body) == 0 { return false @@ -40,221 +54,168 @@ func isTitleGenerationBody(body []byte) bool { } // isTitleGenerationRequest reports whether payload is OpenCode's session-title -// generation call rather than agent traffic (PR #102, Issue #164). +// call rather than agent traffic. // -// OpenCode issues title calls with an EMPTY tool list. The upstream free-tier gate -// accepts that tool-free form but rejects the same call with 403 FreeTierError or -// 429 FreeUsageLimitError once an agent tool list is attached. Therefore, the gateway -// must not inject tools into title requests. -// -// To prevent false positives on user agent requests: -// 1. Tool lists must be absent or empty. -// 2. Message count must be at most 3 without assistant or tool turns. -// 3. Known OpenCode title prompt signatures must match in their expected roles. +// OpenCode sends title calls with no tools. The free tier accepts that form but +// answers 403 FreeTierError or 429 FreeUsageLimitError once an agent tool list +// is attached, so the gateway must not inject tools into it. To keep agent +// traffic from matching, a title request has no tools, at most +// titleMaxMessages messages, no assistant or tool turn, and a known title +// prompt in the role OpenCode uses for it. func isTitleGenerationRequest(payload map[string]any) bool { if payload == nil { return false } - - // 1. Tool list must be absent or empty if tools, ok := payload["tools"].([]any); ok && len(tools) > 0 { return false } if functions, ok := payload["functions"].([]any); ok && len(functions) > 0 { return false } - - // 2. Must have 1 to 3 messages messages, ok := payload["messages"].([]any) - if !ok || len(messages) == 0 || len(messages) > 3 { + if !ok || len(messages) == 0 || len(messages) > titleMaxMessages { return false } - - hasSystemSignature := false - hasLegacyUserSignature := false - + matched := false for _, raw := range messages { - msg, ok := raw.(map[string]any) + message, ok := raw.(map[string]any) if !ok { continue } - role := strings.ToLower(strings.TrimSpace(jsonutil.StringAt(msg, "role"))) - // Any in-progress conversation turn means this is NOT a fresh title request + role := strings.ToLower(strings.TrimSpace(jsonutil.StringAt(message, "role"))) + // A conversation turn means this is agent traffic, not a fresh title. if role == "assistant" || role == "tool" || role == "function" { return false } - - text := strings.ToLower(strings.TrimSpace(strings.Join(textFragments(msg["content"]), " "))) + text := strings.ToLower(strings.TrimSpace(strings.Join(textFragments(message["content"]), " "))) if text == "" { continue } - - if role == "system" || role == "developer" { - if strings.Contains(text, titlePromptV2Name) || - strings.Contains(text, titlePromptV2Desc) || - strings.Contains(text, titlePromptV2Auto) || - (strings.Contains(text, titlePromptV2Rule) || strings.Contains(text, titlePromptV2RuleAlt)) { - hasSystemSignature = true + switch role { + case "system", "developer": + for _, prompt := range titlePromptsV2 { + if strings.Contains(text, prompt) { + matched = true + break + } } - } else if role == "user" { - // Legacy v1 title generation: user message starts with the command prompt - if strings.HasPrefix(text, titlePromptLegacy) { - hasLegacyUserSignature = true + case "user": + if strings.HasPrefix(text, titlePromptV1) { + matched = true } } } - - return hasSystemSignature || hasLegacyUserSignature + return matched } -// synthesizeTitle extracts the conversation topic from the payload's user message -// and formats a clean, compact title suitable for OpenCode sessions. +// synthesizeTitle derives a short title from the first user message: its first +// line, cut to titleMaxWords words and titleMaxRunes runes. func synthesizeTitle(payload map[string]any) string { - if payload == nil { - return "New Session" - } - messages, ok := payload["messages"].([]any) - if !ok { - return "New Session" - } - userText := "" - for _, raw := range messages { - msg, ok := raw.(map[string]any) - if !ok { + for _, raw := range jsonutil.SliceAt(payload, "messages") { + message, ok := raw.(map[string]any) + if !ok || strings.ToLower(strings.TrimSpace(jsonutil.StringAt(message, "role"))) != "user" { continue } - if strings.ToLower(strings.TrimSpace(jsonutil.StringAt(msg, "role"))) == "user" { - userText = strings.TrimSpace(strings.Join(textFragments(msg["content"]), " ")) - if userText != "" { - break - } + if userText = strings.TrimSpace(strings.Join(textFragments(message["content"]), " ")); userText != "" { + break } } - - if userText == "" { - return "New Session" - } - - // Strip legacy prompt wrapper if present - lower := strings.ToLower(userText) - if strings.HasPrefix(lower, titlePromptLegacy) { - idx := strings.Index(userText, "\n") - if idx >= 0 && idx < len(userText)-1 { - userText = strings.TrimSpace(userText[idx+1:]) + // A 1.x request carries the conversation after the prompt line. + if strings.HasPrefix(strings.ToLower(userText), titlePromptV1) { + if index := strings.Index(userText, "\n"); index >= 0 { + userText = strings.TrimSpace(userText[index+1:]) } } - - // Clean whitespace and linebreaks - lines := strings.Split(userText, "\n") - firstLine := strings.TrimSpace(lines[0]) + firstLine, _, _ := strings.Cut(userText, "\n") words := strings.Fields(firstLine) - if len(words) == 0 { - return "New Session" - } - - // Take up to 6 words - if len(words) > 6 { - words = words[:6] + if len(words) > titleMaxWords { + words = words[:titleMaxWords] } title := strings.Join(words, " ") - - // Unicode rune-safe truncation up to 40 runes - if utf8.RuneCountInString(title) > 40 { - runes := []rune(title) - title = string(runes[:40]) + if utf8.RuneCountInString(title) > titleMaxRunes { + title = string([]rune(title)[:titleMaxRunes]) } - - // Strip surrounding quotes or trailing periods - title = strings.Trim(title, `"'`+" \t\r\n.") + title = strings.Trim(title, "\"' \t\r\n.") if title == "" { - return "New Session" + return defaultTitle } return title } -// synthesizeTitleResponse builds an OpenAI-compliant 200 OK HTTP response -// carrying the synthesized title, supporting both non-streaming and SSE streaming. +// titleFallback answers a title request the upstream refused (429) or never +// reached with a locally synthesized title, so the client does not surface an +// error for a cosmetic call. It returns nil when the outcome needs no fallback; +// otherwise it closes lastResponse. +func titleFallback(logger *slog.Logger, model string, rawBody []byte, lastResponse *http.Response, lastErr error) *http.Response { + if upstreamStatus(lastResponse) != http.StatusTooManyRequests && (lastResponse != nil || lastErr == nil) { + return nil + } + var payload map[string]any + _ = json.Unmarshal(rawBody, &payload) + title := synthesizeTitle(payload) + stream, _ := payload["stream"].(bool) + if lastResponse != nil { + httpx.DrainAndClose(lastResponse.Body) + } + logger.Info("title generation request rejected by upstream; returning a synthesized title", "component", "upstream", "event", "title_fallback_synthesized", "model", model, "title", title) + return synthesizeTitleResponse(model, title, stream) +} + +// synthesizeTitleResponse builds a 200 OpenAI Chat response carrying title, +// as one JSON completion or as an SSE stream ending in [DONE]. func synthesizeTitleResponse(model, title string, stream bool) *http.Response { var idBytes [8]byte _, _ = rand.Read(idBytes[:]) - reqID := "chatcmpl-title-" + hex.EncodeToString(idBytes[:]) - now := time.Now().Unix() - - resp := &http.Response{ - StatusCode: http.StatusOK, - Header: make(http.Header), - } + id := "chatcmpl-title-" + hex.EncodeToString(idBytes[:]) + created := time.Now().Unix() + resp := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header)} if !stream { - respBody := map[string]any{ - "id": reqID, + completionTokens := utf8.RuneCountInString(title) + data, _ := json.Marshal(map[string]any{ + "id": id, "object": "chat.completion", - "created": now, + "created": created, "model": model, - "choices": []any{ - map[string]any{ - "index": 0, - "message": map[string]any{ - "role": "assistant", - "content": title, - }, - "finish_reason": "stop", - }, - }, + "choices": []any{map[string]any{ + "index": 0, + "message": map[string]any{"role": "assistant", "content": title}, + "finish_reason": "stop", + }}, "usage": map[string]any{ - "prompt_tokens": 10, - "completion_tokens": utf8.RuneCountInString(title), - "total_tokens": 10 + utf8.RuneCountInString(title), + "prompt_tokens": 0, + "completion_tokens": completionTokens, + "total_tokens": completionTokens, }, - } - data, _ := json.Marshal(respBody) + }) resp.Header.Set("Content-Type", "application/json") - resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(data))) + resp.Header.Set("Content-Length", strconv.Itoa(len(data))) resp.Body = io.NopCloser(bytes.NewReader(data)) return resp } - // SSE streaming format - var buf bytes.Buffer - chunk1 := map[string]any{ - "id": reqID, - "object": "chat.completion.chunk", - "created": now, - "model": model, - "choices": []any{ - map[string]any{ - "index": 0, - "delta": map[string]any{ - "role": "assistant", - "content": title, - }, - "finish_reason": nil, - }, - }, + chunk := func(delta map[string]any, finishReason any) []byte { + data, _ := json.Marshal(map[string]any{ + "id": id, + "object": "chat.completion.chunk", + "created": created, + "model": model, + "choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": finishReason}}, + }) + return data } - chunk2 := map[string]any{ - "id": reqID, - "object": "chat.completion.chunk", - "created": now, - "model": model, - "choices": []any{ - map[string]any{ - "index": 0, - "delta": map[string]any{}, - "finish_reason": "stop", - }, - }, + var body bytes.Buffer + for _, data := range [][]byte{ + chunk(map[string]any{"role": "assistant", "content": title}, nil), + chunk(map[string]any{}, "stop"), + } { + body.WriteString("data: ") + body.Write(data) + body.WriteString("\n\n") } - d1, _ := json.Marshal(chunk1) - d2, _ := json.Marshal(chunk2) - buf.WriteString("data: ") - buf.Write(d1) - buf.WriteString("\n\ndata: ") - buf.Write(d2) - buf.WriteString("\n\ndata: [DONE]\n\n") - + body.WriteString("data: [DONE]\n\n") resp.Header.Set("Content-Type", "text/event-stream") - resp.Body = io.NopCloser(&buf) + resp.Body = io.NopCloser(&body) return resp } diff --git a/internal/gateway/title_test.go b/internal/gateway/title_test.go deleted file mode 100644 index cde75a3..0000000 --- a/internal/gateway/title_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package gateway - -import ( - "context" - "encoding/json" - "io" - "log/slog" - "net/http" - "testing" - "time" - - "opencode2api/internal/config" - "opencode2api/internal/identity" - "opencode2api/internal/models" - wire "opencode2api/internal/protocol" - "opencode2api/internal/telemetry" - "opencode2api/internal/warp" -) - -func TestIsTitleGenerationRequest_Comprehensive(t *testing.T) { - tests := []struct { - name string - body string - expected bool - }{ - { - name: "Legacy v1 OpenCode title prompt in user turn", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "user", "content": "Generate a title for this conversation:\nUser: Fix login bug"} - ] - }`, - expected: true, - }, - { - name: "New v2 OpenCode title prompt in system turn", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."}, - {"role": "user", "content": "Implement auth middleware"} - ] - }`, - expected: true, - }, - { - name: "New v2 OpenCode title prompt variant with 'for it'", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title for it and nothing else: one line, no quotes, no trailing period."}, - {"role": "user", "content": "Fix typo"} - ] - }`, - expected: true, - }, - { - name: "New v2 auto-rename prompt", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You decide whether the session title still matches the conversation. Reply with KEEP or new title."}, - {"role": "user", "content": "Database migration script"} - ] - }`, - expected: true, - }, - { - name: "Normal user agent request with declared tools", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You are a coding assistant."}, - {"role": "user", "content": "List files in current directory"} - ], - "tools": [ - {"type": "function", "function": {"name": "shell", "description": "run command"}} - ] - }`, - expected: false, - }, - { - name: "Tool-free regular Q&A request (must NOT be treated as title)", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "user", "content": "What is the capital of France?"} - ] - }`, - expected: false, - }, - { - name: "User message quotes title prompt in normal conversation (false positive prevention)", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You are a helpful coding assistant."}, - {"role": "user", "content": "Can you review this prompt for me: 'You name conversations so the user can find them later in a list of past sessions.'"} - ] - }`, - expected: false, - }, - { - name: "User message mentions legacy prompt in the middle of text", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "user", "content": "How does OpenCode generate a title for this conversation?"} - ] - }`, - expected: false, - }, - { - name: "Multi-turn conversation with assistant turn (must NOT be treated as title)", - body: `{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions."}, - {"role": "user", "content": "Hi"}, - {"role": "assistant", "content": "Hello!"}, - {"role": "user", "content": "Now generate code"} - ] - }`, - expected: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isTitleGenerationBody([]byte(tt.body)) - if got != tt.expected { - t.Errorf("isTitleGenerationBody() = %v, expected %v", got, tt.expected) - } - }) - } -} - -func TestPrepareAnonymousBody_TitleVsAgentToolsInjection(t *testing.T) { - v2TitleBody := []byte(`{ - "model": "flint-40b-free", - "messages": [ - {"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."}, - {"role": "user", "content": "Add Redis caching"} - ] - }`) - - v1TitleBody := []byte(`{ - "model": "flint-40b-free", - "messages": [ - {"role": "user", "content": "Generate a title for this conversation:\nUser: Add Redis caching"} - ] - }`) - - regularAgentBody := []byte(`{ - "model": "flint-40b-free", - "messages": [ - {"role": "user", "content": "Explain how Go channels work."} - ] - }`) - - // 1. v2 Title body: must NOT have tools injected - shapedV2, _ := prepareAnonymousBody(v2TitleBody, wire.Chat, false) - var parsedV2 map[string]any - if err := json.Unmarshal(shapedV2, &parsedV2); err != nil { - t.Fatalf("Unmarshal shapedV2 error: %v", err) - } - if tools, ok := parsedV2["tools"].([]any); ok && len(tools) > 0 { - t.Errorf("expected title request to stay tool-free, but got %d tools injected", len(tools)) - } - - // 2. v1 Title body: must NOT have tools injected - shapedV1, _ := prepareAnonymousBody(v1TitleBody, wire.Chat, false) - var parsedV1 map[string]any - if err := json.Unmarshal(shapedV1, &parsedV1); err != nil { - t.Fatalf("Unmarshal shapedV1 error: %v", err) - } - if tools, ok := parsedV1["tools"].([]any); ok && len(tools) > 0 { - t.Errorf("expected v1 title request to stay tool-free, but got %d tools injected", len(tools)) - } - - // 3. Regular agent request without tools: MUST have tools injected - shapedAgent, _ := prepareAnonymousBody(regularAgentBody, wire.Chat, false) - var parsedAgent map[string]any - if err := json.Unmarshal(shapedAgent, &parsedAgent); err != nil { - t.Fatalf("Unmarshal shapedAgent error: %v", err) - } - tools, ok := parsedAgent["tools"].([]any) - if !ok || len(tools) == 0 { - t.Errorf("expected regular agent request to have official tools injected, got %v", parsedAgent["tools"]) - } -} - -func TestSynthesizeTitle_UnicodeAndFallbacks(t *testing.T) { - tests := []struct { - name string - payload map[string]any - expected string - }{ - { - name: "Standard english prompt", - payload: map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": "Fix authentication bug in middleware"}, - }, - }, - expected: "Fix authentication bug in middleware", - }, - { - name: "Unicode characters and truncation", - payload: map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": "Türkçe başlık oluşturma ve kota sınırlaması çözümü"}, - }, - }, - expected: "Türkçe başlık oluşturma ve kota sınırlam", - }, - { - name: "Legacy prefix stripped cleanly", - payload: map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": "Generate a title for this conversation:\nUser: Upgrade database schema to v3"}, - }, - }, - expected: "User: Upgrade database schema to v3", - }, - { - name: "Empty content safe fallback", - payload: map[string]any{ - "messages": []any{ - map[string]any{"role": "user", "content": " "}, - }, - }, - expected: "New Session", - }, - { - name: "No user message safe fallback", - payload: map[string]any{ - "messages": []any{ - map[string]any{"role": "system", "content": "System prompt only"}, - }, - }, - expected: "New Session", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := synthesizeTitle(tt.payload) - if got != tt.expected { - t.Errorf("synthesizeTitle() = %q, expected %q", got, tt.expected) - } - }) - } -} - -func TestWarpAnonymous_TitleRequestSingleAttemptFallbackOn429(t *testing.T) { - // Mock 2 WARP exits that both return 429 - exit1, l1 := createMockWarpExit(t, "exit-1", "2a09:bac1:7280:18::1", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Retry-After", "120") - w.WriteHeader(http.StatusTooManyRequests) - _, _ = w.Write([]byte(`{"error":"quota_exceeded"}`)) - }) - defer l1.Close() - - exit2, l2 := createMockWarpExit(t, "exit-2", "2a09:bac5:58c0:d2d::1", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Retry-After", "120") - w.WriteHeader(http.StatusTooManyRequests) - _, _ = w.Write([]byte(`{"error":"quota_exceeded"}`)) - }) - defer l2.Close() - - pool := warp.NewTestPoolWithExits([]*warp.TestExit{exit1, exit2}) - - cfg := config.Config{ - Anonymous: true, - Retry: config.RetryConfig{ - MaxAttempts: 12, // Normally 12, but must be capped to 1 for title requests - TimeoutSeconds: 5, - }, - Warp: config.WarpConfig{ - Enabled: true, - PoolSize: 2, - Stack: "ipv6", - }, - Upstream: config.UpstreamConfig{ - Anonymous: "http://[fd00::1]:80", - }, - Performance: config.PerformanceConfig{ - FailureCooldownSeconds: 15, - }, - } - - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - monitor := telemetry.Monitor() - gw, err := New(cfg, logger, monitor, pool) - if err != nil { - t.Fatalf("New gateway error: %v", err) - } - - ctx := context.Background() - route := models.Route{ID: "test-model", Protocol: wire.Chat} - titleBody := []byte(`{ - "model": "test-model", - "messages": [ - {"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."}, - {"role": "user", "content": "Refactor auth middleware"} - ], - "stream": false - }`) - bodies := map[config.Tier][]byte{ - config.TierZen: titleBody, - } - ids := identity.RequestIDs{Request: "req-title-1", Session: "ses-title-1"} - - start := time.Now() - resp, err, attempts := gw.doWarpAnonymousUpstream(ctx, route, bodies, ids, 0) - duration := time.Since(start) - - if err != nil { - t.Fatalf("expected fallback response without error, got %v", err) - } - if resp == nil { - t.Fatalf("expected response, got nil") - } - defer resp.Body.Close() - - // Must stop after exactly 1 attempt so it does NOT burn the entire pool - if attempts != 1 { - t.Errorf("expected title request to try exactly 1 exit, got %d attempts", attempts) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("expected fallback status 200 OK, got %d", resp.StatusCode) - } - if duration > 1*time.Second { - t.Errorf("expected quick response, took %v", duration) - } - - // Read and verify synthesized JSON response - bodyBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatalf("ReadAll error: %v", err) - } - var res map[string]any - if err := json.Unmarshal(bodyBytes, &res); err != nil { - t.Fatalf("Unmarshal error: %v", err) - } - choices, ok := res["choices"].([]any) - if !ok || len(choices) == 0 { - t.Fatalf("expected choices array in fallback response, got %v", res) - } - firstChoice := choices[0].(map[string]any) - message := firstChoice["message"].(map[string]any) - content := message["content"].(string) - expectedContent := "Refactor auth middleware" - if content != expectedContent { - t.Errorf("expected synthesized title %q, got %q", expectedContent, content) - } -} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index e5390cf..64dd2e0 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -530,16 +530,8 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } } if isTitle { - if upstreamStatus(lastResponse) == http.StatusTooManyRequests || (lastResponse == nil && lastErr != nil) { - var payload map[string]any - _ = json.Unmarshal(rawBody, &payload) - title := synthesizeTitle(payload) - stream, _ := payload["stream"].(bool) - if lastResponse != nil { - httpx.DrainAndClose(lastResponse.Body) - } - g.logger.Info("title generation request rejected by upstream; returning synthesized title fallback", "component", "upstream", "event", "title_fallback_synthesized", "model", route.ID, "title", title) - return synthesizeTitleResponse(route.ID, title, stream), nil, attempts + if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil { + return fallback, nil, attempts } } if lastResponse != nil { diff --git a/internal/gateway/warp.go b/internal/gateway/warp.go index 21f4fd4..b2e2b0b 100644 --- a/internal/gateway/warp.go +++ b/internal/gateway/warp.go @@ -3,7 +3,6 @@ package gateway import ( "context" "crypto/tls" - "encoding/json" "errors" "fmt" "io" @@ -248,9 +247,8 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout // does the last 429 reach the client. isTitle := isTitleGenerationBody(rawBody) limit := g.cfg.Retry.MaxAttempts - if isTitle { - limit = 1 - } else if limit < 1 { + if limit < 1 || isTitle { + // A title request gets one attempt: on failure it is answered locally. limit = 1 } firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second @@ -323,10 +321,9 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout break } if status == http.StatusTooManyRequests { - triedEgresses[egress] = true + triedEgresses[strings.TrimPrefix(egress, "warp:")] = true if !g.warp.HasUntriedActive(triedEgresses) { g.logger.Warn("all active WARP exits exhausted or cooling down; stopping retries", "component", "upstream", "event", "warp_429_exhausted", "request_id", ids.Request, "attempt", attempts) - halted = false break } } @@ -354,16 +351,8 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout return lastResponse, errDeterministicClientRejection, attempts } if isTitle { - if upstreamStatus(lastResponse) == http.StatusTooManyRequests || (lastResponse == nil && lastErr != nil) { - var payload map[string]any - _ = json.Unmarshal(rawBody, &payload) - title := synthesizeTitle(payload) - stream, _ := payload["stream"].(bool) - if lastResponse != nil { - httpx.DrainAndClose(lastResponse.Body) - } - g.logger.Info("title generation request rejected by upstream; returning synthesized title fallback", "component", "upstream", "event", "title_fallback_synthesized", "model", route.ID, "title", title) - return synthesizeTitleResponse(route.ID, title, stream), nil, attempts + if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil { + return fallback, nil, attempts } } if lastResponse != nil { diff --git a/internal/protocol/stream.go b/internal/protocol/stream.go index e5cbf86..5cb6bf0 100644 --- a/internal/protocol/stream.go +++ b/internal/protocol/stream.go @@ -456,6 +456,8 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { return encoded } +// releasePendingArguments prepends the argument fragments held back while the +// tool name was still ambiguous to the current frame's arguments. func (renamer *streamToolRenamer) releasePendingArguments(state *streamToolRenameState, function map[string]any) bool { if state.pendingArguments.Len() == 0 { return false @@ -473,6 +475,8 @@ func (renamer *streamToolRenamer) releasePendingArguments(state *streamToolRenam return true } +// finishState settles a call the choice finished while its name was still +// ambiguous: the held-back name and arguments are emitted verbatim. func (renamer *streamToolRenamer) finishState(state *streamToolRenameState, function map[string]any) bool { changed := false if state.pending != "" { @@ -486,6 +490,8 @@ func (renamer *streamToolRenamer) finishState(state *streamToolRenameState, func return changed } +// pendingCalls collects the undecided calls of one choice that the finishing +// frame did not carry, so they are flushed before the choice ends. func (renamer *streamToolRenamer) pendingCalls(choiceIndex any, skip map[string]bool) []any { var calls []any for _, key := range renamer.order { @@ -504,6 +510,8 @@ func (renamer *streamToolRenamer) pendingCalls(choiceIndex any, skip map[string] return calls } +// pendingCall renders one held-back call as a tool_calls delta and marks it +// decided. func (renamer *streamToolRenamer) pendingCall(state *streamToolRenameState) any { function := map[string]any{} if state.pending != "" { @@ -518,6 +526,8 @@ func (renamer *streamToolRenamer) pendingCall(state *streamToolRenameState) any return call } +// finish flushes every call still held back when the stream ends without a +// finish_reason, as one extra Chat frame. It returns nil when nothing is held. func (renamer *streamToolRenamer) finish() []byte { if renamer.protocol != Chat { return nil diff --git a/internal/warp/exit.go b/internal/warp/exit.go index 9f65ea0..4c8e5f9 100644 --- a/internal/warp/exit.go +++ b/internal/warp/exit.go @@ -442,6 +442,12 @@ func (e *exit) observe(status int, body []byte) (bool, string) { return false, "" } +func (e *exit) isPenalized() bool { + e.mu.Lock() + defer e.mu.Unlock() + return e.penalized +} + func (e *exit) markPenalized() bool { e.mu.Lock() defer e.mu.Unlock() diff --git a/internal/warp/pool.go b/internal/warp/pool.go index ef6a840..f15e98a 100644 --- a/internal/warp/pool.go +++ b/internal/warp/pool.go @@ -334,6 +334,12 @@ func (p *Pool) Acquire(ctx context.Context) (*Lease, error) { } func (p *Pool) Report(lease *Lease, status int, body []byte) { + p.ReportWithRetryAfter(lease, status, body, 0) +} + +// ReportWithRetryAfter is Report with the upstream's Retry-After hint. A hint +// longer than egressCooldown keeps the rejected egress cooling for that long. +func (p *Pool) ReportWithRetryAfter(lease *Lease, status int, body []byte, retryAfter time.Duration) { if lease == nil || lease.exit == nil { return } @@ -341,7 +347,24 @@ func (p *Pool) Report(lease *Lease, status int, body []byte) { if !rotate { return } - p.penalize(lease.exit, reason) + p.penalizeFor(lease.exit, reason, max(retryAfter, egressCooldown)) +} + +// HasUntriedActive reports whether an active, unpenalized exit sits on an +// egress key that is not in tried, so another attempt would leave from a +// different quota scope. +func (p *Pool) HasUntriedActive(tried map[string]bool) bool { + p.mu.Lock() + defer p.mu.Unlock() + for _, active := range p.active { + if active.isPenalized() { + continue + } + if key := active.egressKey(); key == "" || !tried[key] { + return true + } + } + return false } // Fail drops an exit that cannot carry traffic even though the upstream never @@ -374,6 +397,10 @@ func (p *Pool) Snapshot() Snapshot { } func (p *Pool) penalize(bad *exit, reason string) { + p.penalizeFor(bad, reason, egressCooldown) +} + +func (p *Pool) penalizeFor(bad *exit, reason string, cooldown time.Duration) { p.mu.Lock() if p.closed { p.mu.Unlock() @@ -389,7 +416,7 @@ func (p *Pool) penalize(bad *exit, reason string) { return } if key := bad.egressKey(); key != "" { - p.cooling[key] = time.Now().Add(egressCooldown) + p.cooling[key] = time.Now().Add(cooldown) delete(p.reserved, key) } p.active = append(p.active[:index], p.active[index+1:]...)