Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
e02fee7
fix(auth): persist explicit session affinity across restarts and reloads
rune-gh Nov 17, 2026
be2aea1
fix(quota): restore safe persisted routing readings before polling
rune-gh Nov 17, 2026
3e890a3
fix(codex): observe HTTP SSE quota events before filtering
rune-gh Nov 17, 2026
a0b8f71
fix(auth): preserve affinity across tier and transport changes
rune-gh Nov 17, 2026
38d3bee
fix(auth): serialize affinity publication with credential retirement
rune-gh Nov 17, 2026
a2175f8
fix(auth): preserve observed credential epochs during failover
rune-gh Nov 17, 2026
6314e0f
fix(claude): stop replay after accepted responses are interrupted
rune-gh Nov 29, 2026
327e0d3
fix(logging): synchronize deferred request capture finalization
rune-gh Nov 29, 2026
fba00ea
fix(claude): preserve Fast response decoding error status
rune-gh Nov 29, 2026
5589fc9
fix(mistral): give Mistral models their real reasoning levels
rune-gh Nov 29, 2026
dfbb8b9
feat(auth): let auth files opt proxied transports into connection poo…
rune-gh Dec 1, 2026
4cec7dd
fix(auth): answer 404 when every account rejects the model
rune-gh Nov 29, 2026
751fe62
fix(quota): lift quota cooldowns when a usage poll shows allowance again
rune-gh Dec 2, 2026
a46eb66
fix(quota): judge renewal from every reported window and skip non-quo…
rune-gh Dec 2, 2026
8f43d14
fix(quota): keep cooldowns a renewal poll cannot vouch for
rune-gh Dec 2, 2026
f1545a4
fix(quota): judge only live quota and account-only 429s against the p…
rune-gh Dec 2, 2026
3ec412a
fix(quota): let traffic on other models not delay a model quota recovery
rune-gh Dec 2, 2026
0cbe386
Merge verified audit and test fixes onto the deployed Windows hub
rune-gh Dec 2, 2026
2411ed3
fix(opencode): restrict catalog and routing to selected providers
rune-gh Dec 2, 2026
e7f14e1
Merge remote-tracking branch 'origin/main' into t3/qoder-quota-panel
rune-gh Dec 3, 2026
c2273f4
fix(auth): back off non-refreshing auths with past next check
rune-gh Dec 3, 2026
16dba45
fix(codex): sync temp file before close and rename in WriteJSONFileAt…
rune-gh Dec 3, 2026
3ebc365
fix(auth): treat Claude expired refresh token response as terminal
rune-gh Dec 3, 2026
2712538
fix(claude): defer OAuth token refresh during macOS maintenance wakes
rune-gh Dec 3, 2026
5bc1226
fix(codex,auth): classify zero-byte refresh failures as pre-send and …
rune-gh Dec 3, 2026
4b140ad
fix(codex): preserve pre-send classification for definite file claim …
rune-gh Dec 3, 2026
f2b2fd2
fix(auth,cliproxy): wait for in-flight auto-refresh saves during shut…
rune-gh Dec 3, 2026
4cfb402
fix(auth): write auth files atomically via temp file, sync, and rename
rune-gh Dec 3, 2026
1e84ea1
fix(antigravity): update Hub fallback and changelist map to 2.37.0 wi…
rune-gh Dec 3, 2026
15ac14c
fix(auth): clear stream rewriter before emitting flushed tail in wrap…
rune-gh Dec 3, 2026
0b791f6
fix(auth): close canceled streams during upstream stalls
rune-gh Dec 3, 2026
b1599d0
fix(antigravity): bound post-refresh credits warm to prevent goroutin…
rune-gh Dec 3, 2026
d2b0bfb
fix(proxyutil): honor context cancellation on SOCKS5 HTTP transports
rune-gh Dec 3, 2026
291e900
fix(xai): evict ephemeral and 24h idle websocket ID states
rune-gh Dec 3, 2026
34399cf
fix(codex): handle nil auth in websocket streams
rune-gh Dec 3, 2026
d09266a
fix(auth): fix pendingBuf corruption and split-line handling in Strea…
rune-gh Dec 3, 2026
503f774
fix(cache): prevent TOCTOU eviction of live signature cache buckets
rune-gh Dec 3, 2026
2fdb2f9
fix(codex): renew websocket read deadline on active heartbeats and ne…
rune-gh Dec 3, 2026
63e2505
fix(executor): report canceled and truncated streams as failures in x…
rune-gh Dec 3, 2026
3265e0c
fix(claude): strip thinking suffix from advisor tool model
rune-gh Dec 3, 2026
4f2ff08
fix(claude): strip foreign advisor blocks after credential rebind
rune-gh Dec 3, 2026
d694484
fix(claude): stabilize advisor system prompt placement
rune-gh Dec 3, 2026
5e9e283
fix(openai): recognize codex client headers for responses terminal ev…
rune-gh Dec 3, 2026
b70e217
fix(antigravity): align OAuth token refresh transport and User-Agent
rune-gh Dec 3, 2026
c857fe1
fix(auth): enforce consistent cancellation and Retry-After cooldown h…
rune-gh Dec 3, 2026
3dd9e76
fix(clienterror,openai): classify bio_policy and safety policy blocks…
rune-gh Dec 3, 2026
bb3d542
fix(codex): preserve string errors and recognize untyped failures
rune-gh Dec 3, 2026
bcabc69
fix(openai,codex): build stream errors via ojson.Doc and preserve SSE…
rune-gh Dec 3, 2026
0834e20
fix(codex,openai): preserve nested WS error headers and honor explici…
rune-gh Dec 3, 2026
7d49104
fix(codex): preserve Retry-After headers on inferred WebSocket statuses
rune-gh Dec 3, 2026
206e209
fix(codex): preserve nested Retry-After headers on overload errors
rune-gh Dec 3, 2026
6955e36
fix(codex): fail over in-stream billing quota errors during bootstrap…
rune-gh Dec 3, 2026
3949374
fix(auth): recognize codex-acp user agents in Codex SIWC bypass
rune-gh Dec 3, 2026
318efc5
fix(gemini): prevent goroutine leak on client disconnect in interacti…
rune-gh Dec 3, 2026
4fa2579
fix(auth): preserve disabled unavailability and skip inference verifi…
rune-gh Dec 3, 2026
cc10296
fix(auth): preserve disabled and terminal 401 states during model rec…
rune-gh Dec 3, 2026
63c6eb0
fix(auth): preserve terminal tos violation state
rune-gh Dec 3, 2026
0ce0138
fix(cliproxy): validate absent auth file snapshots under mutation lock
rune-gh Dec 3, 2026
912550d
Revert "fix(auth): enforce consistent cancellation and Retry-After co…
rune-gh Dec 3, 2026
7c0e06d
Revert "fix(auth): close canceled streams during upstream stalls"
rune-gh Dec 3, 2026
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
6 changes: 4 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,10 @@ upstream:
# Why: the upstream smuggles `server_is_overloaded` rejections *inside* an HTTP 200 stream,
# right after those handshake events, instead of returning 503 on the wire. Buffering them
# keeps the downstream response headers uncommitted long enough to transparently retry on
# another credential. Only overload/rate-limit rejections trigger failover; every other terminal
# failure is still delivered in-stream exactly as before. One pre-existing behaviour is worth
# another credential. Only overload/rate-limit rejections and structured billing quota exhaustion
# (`insufficient_quota` / `credit_balance_exhausted`) trigger failover while the bootstrap window
# is still uncommitted; every other terminal failure, and any error after output/tool events commit
# the stream, is still delivered in-stream with no replay. One pre-existing behaviour is worth
# knowing, because this option makes the window it lives in much longer: if the stream ends while
# the bootstrap is still holding, the attempt ends instead of the error reaching the client, and
# whether another credential is then tried depends on how it ended. A clean end with no terminal
Expand Down
4 changes: 4 additions & 0 deletions internal/api/handlers/management/auth_files_fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,10 @@ func syncAuthFileMetadataFields(auth *coreauth.Auth, touchedRoots map[string]str
auth.ProxyURL = strings.TrimSpace(proxyURL)
}
}
if _, ok := touchedRoots[coreauth.ProxyConnectionPoolMetadataKey]; ok {
auth.ProxyConnectionPool = nil
coreauth.ApplyProxyConnectionPoolMetadata(auth, auth.Metadata)
}
if _, ok := touchedRoots["headers"]; ok {
syncAuthFileHeaderAttributes(auth)
}
Expand Down
49 changes: 49 additions & 0 deletions internal/api/handlers/management/auth_files_patch_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1512,3 +1512,52 @@ func mustGetAuthByID(t *testing.T, manager *coreauth.Manager, id string) *coreau
}
return got
}

func TestPatchAuthFileFields_ProxyConnectionPool(t *testing.T) {
t.Setenv("MANAGEMENT_PASSWORD", "")

store := &memoryAuthStore{}
manager := coreauth.NewManager(store, nil, nil)
record := &coreauth.Auth{
ID: "xai.json",
FileName: "xai.json",
Provider: "xai",
Attributes: map[string]string{"path": "/tmp/xai.json"},
Metadata: map[string]any{"type": "xai"},
}
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
t.Fatalf("failed to register auth record: %v", errRegister)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)

patch := func(body string) *coreauth.Auth {
t.Helper()
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
ctx.Request = req
h.PatchAuthFileFields(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
}
updated, ok := manager.GetByID("xai.json")
if !ok || updated == nil {
t.Fatal("expected auth record to exist after patch")
}
return updated
}

updated := patch(`{"name":"xai.json","proxy_url":"socks5://user:pass@127.0.0.1:1080","proxy_connection_pool":{"max-idle-conns-per-host":4}}`)
if updated.ProxyConnectionPool == nil || updated.ProxyConnectionPool.MaxIdleConnsPerHost == nil || *updated.ProxyConnectionPool.MaxIdleConnsPerHost != 4 {
t.Fatalf("ProxyConnectionPool = %+v, want max-idle-conns-per-host 4", updated.ProxyConnectionPool)
}

updated = patch(`{"name":"xai.json","proxy_connection_pool":null}`)
if updated.ProxyConnectionPool != nil {
t.Fatalf("ProxyConnectionPool = %+v, want nil after removing the field", updated.ProxyConnectionPool)
}
if updated.ProxyURL != "socks5://user:pass@127.0.0.1:1080" {
t.Fatalf("ProxyURL = %q, want it untouched", updated.ProxyURL)
}
}
55 changes: 36 additions & 19 deletions internal/api/middleware/request_logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -80,7 +81,7 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc {
deferredCapture := attachDeferredRequestBodyCapture(c.Request, logger, requestInfo, false, false)
if captureBody {
c.Set(authenticatedRequestBodyCapturerContextKey, func() {
if deferredCapture != nil && deferredCapture.bytesRead == 0 {
if deferredCapture != nil && !deferredCapture.hasRead() {
c.Request.Body = deferredCapture.body
requestInfo.deferredBodyCapture = nil
deferredCapture.Cleanup()
Expand Down Expand Up @@ -151,6 +152,7 @@ func CaptureAuthenticatedRequestBody(c *gin.Context) {
}

type deferredRequestBodyCapture struct {
mu sync.Mutex
body io.ReadCloser
factory fileBodySourceFactory
memBuf bytes.Buffer
Expand Down Expand Up @@ -188,15 +190,21 @@ func (c *deferredRequestBodyCapture) Read(payload []byte) (int, error) {
if c == nil || c.body == nil {
return 0, io.EOF
}
// Close must be able to unblock the underlying read.
n, errRead := c.body.Read(payload)
c.mu.Lock()
defer c.mu.Unlock()
if c.finished {
return n, errRead
}
if errRead == io.EOF {
c.sawEOF = true
}
if n == 0 {
return n, errRead
}
c.bytesRead += int64(n)
if c.skipCapture || c.captureErr != nil || c.finished {
if c.skipCapture || c.captureErr != nil {
return n, errRead
}

Expand Down Expand Up @@ -273,17 +281,16 @@ func (c *deferredRequestBodyCapture) Close() error {
if c == nil {
return nil
}
_ = c.Finish()
c.mu.Lock()
_ = c.finishLocked()
c.mu.Unlock()
if c.body == nil {
return nil
}
return c.body.Close()
}

func (c *deferredRequestBodyCapture) Finish() error {
if c == nil {
return nil
}
func (c *deferredRequestBodyCapture) finishLocked() error {
if c.finished {
return c.captureErr
}
Expand All @@ -301,39 +308,47 @@ func (c *deferredRequestBodyCapture) Bytes() ([]byte, string, error) {
if c == nil || c.skipCapture {
return nil, "", nil
}
if errFinish := c.Finish(); errFinish != nil {
c.mu.Lock()
defer c.mu.Unlock()
if errFinish := c.finishLocked(); errFinish != nil {
return nil, "", errFinish
}
if c.source != nil {
body, errBytes := c.source.Bytes()
if errBytes != nil {
return nil, "", errBytes
}
return body, c.statusMarker(), nil
return body, c.statusMarkerLocked(), nil
}
var body []byte
if c.memBuf.Len() > 0 {
body = bytes.Clone(c.memBuf.Bytes())
}
return body, c.statusMarker(), nil
return body, c.statusMarkerLocked(), nil
}

func (c *deferredRequestBodyCapture) isComplete() bool {
if c == nil {
return true
}
c.mu.Lock()
defer c.mu.Unlock()
return c.isCompleteLocked()
}

func (c *deferredRequestBodyCapture) hasRead() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.bytesRead > 0
}

func (c *deferredRequestBodyCapture) isCompleteLocked() bool {
return c.sawEOF || (c.contentLength >= 0 && c.bytesRead >= c.contentLength)
}

func (c *deferredRequestBodyCapture) statusMarker() string {
if c == nil {
return ""
}
func (c *deferredRequestBodyCapture) statusMarkerLocked() string {
var markers []string
if c.truncated {
markers = append(markers, fmt.Sprintf("[REQUEST BODY TRUNCATED: captured first %d bytes]", c.bytesCaptured))
}
if !c.isComplete() {
if !c.isCompleteLocked() {
if c.contentLength >= 0 {
markers = append(markers, fmt.Sprintf("[REQUEST BODY CAPTURE INCOMPLETE: consumed %d of %d bytes]", c.bytesRead, c.contentLength))
} else {
Expand All @@ -347,7 +362,9 @@ func (c *deferredRequestBodyCapture) Cleanup() {
if c == nil {
return
}
if errFinish := c.Finish(); errFinish != nil {
c.mu.Lock()
defer c.mu.Unlock()
if errFinish := c.finishLocked(); errFinish != nil {
log.WithError(errFinish).Warn("failed to finish deferred request body capture")
}
c.memBuf.Reset()
Expand Down
37 changes: 37 additions & 0 deletions internal/api/middleware/request_logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1621,3 +1621,40 @@ func TestRequestLoggingMiddlewareIsolatesDeferredResponseAcrossStreamCancelAndGi
}
})
}

type blockedCaptureBody struct {
started chan struct{}
closed chan struct{}
}

func (b *blockedCaptureBody) Read(p []byte) (int, error) {
close(b.started)
<-b.closed
return copy(p, "late bytes"), io.EOF
}

func (b *blockedCaptureBody) Close() error {
close(b.closed)
return nil
}

func TestDeferredRequestBodyCaptureCloseDuringBlockedRead(t *testing.T) {
body := &blockedCaptureBody{started: make(chan struct{}), closed: make(chan struct{})}
capture := &deferredRequestBodyCapture{body: body, contentLength: -1}
done := make(chan string, 1)
go func() {
payload := make([]byte, 32)
n, _ := capture.Read(payload)
done <- string(payload[:n])
}()
<-body.started
if errClose := capture.Close(); errClose != nil {
t.Fatal(errClose)
}
if got := <-done; got != "late bytes" {
t.Fatalf("reader got %q", got)
}
if payload, _, errRead := capture.Bytes(); errRead != nil || len(payload) != 0 || capture.hasRead() || capture.isComplete() {
t.Fatalf("late read changed the finalized capture: %q, %v", payload, errRead)
}
}
2 changes: 1 addition & 1 deletion internal/api/middleware/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ func (w *ResponseWriterWrapper) currentCapturedRequestBody() []byte {
if len(w.requestInfo.Body) > 0 {
return w.requestInfo.Body
}
if w.requestInfo.deferredBodyCapture == nil || w.requestInfo.deferredBodyCapture.bytesRead == 0 {
if w.requestInfo.deferredBodyCapture == nil || !w.requestInfo.deferredBodyCapture.hasRead() {
return nil
}
body, _, errRead := w.requestInfo.deferredBodyCapture.Bytes()
Expand Down
9 changes: 9 additions & 0 deletions internal/auth/claude/anthropic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,9 @@ func (o *ClaudeAuth) RefreshTokens(ctx context.Context, refreshToken string) (*C
result, err, _ := claudeRefreshGroup.Do(refreshToken, func() (interface{}, error) {
refreshCtx, cancelRefresh := context.WithTimeout(context.WithoutCancel(ctx), claudeRefreshTimeout)
defer cancelRefresh()
if errReadiness := claudeRefreshReadiness(refreshCtx); errReadiness != nil {
return nil, errReadiness
}
refreshCtx = context.WithValue(refreshCtx, claudeRefreshHandshakeTimeoutContextKey{}, claudeRefreshHandshakeTimeout)
return o.refreshTokensSingleFlight(refreshCtx, refreshToken)
})
Expand Down Expand Up @@ -642,6 +645,9 @@ func (o *ClaudeAuth) CreateTokenStorage(bundle *ClaudeAuthBundle) *ClaudeTokenSt
// - *ClaudeTokenData: The refreshed token data
// - error: An error if all retry attempts fail
func (o *ClaudeAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) (*ClaudeTokenData, error) {
if maxRetries <= 0 {
maxRetries = 1
}
var lastErr error

for attempt := 0; attempt < maxRetries; attempt++ {
Expand All @@ -658,6 +664,9 @@ func (o *ClaudeAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken st
if err == nil {
return tokenData, nil
}
if errors.Is(err, context.Canceled) || errors.Is(err, ErrClaudeRefreshDeferred) {
return nil, err
}

lastErr = err
log.Warnf("Token refresh attempt %d failed: %v", attempt+1, err)
Expand Down
18 changes: 18 additions & 0 deletions internal/auth/claude/power_darwin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//go:build darwin

package claude

import (
"context"

baseauth "github.com/rune-oai/t3code-proxy/internal/auth"
)

// ReadClaudeSystemState reads the macOS power capabilities used by Claude OAuth renewal.
var ReadClaudeSystemState = func(ctx context.Context) ([]byte, error) {
return baseauth.ReadMacOSSystemState(ctx)
}

func claudeRefreshReadiness(ctx context.Context) error {
return baseauth.CheckMacOSRefreshReadiness(ctx, "Claude", ReadClaudeSystemState)
}
Loading