History

feat(executor): refine session and conversation header handling for Codex

- Updated session handling to replace `Session_id` and `Conversation_id` headers with new logic ensuring consistent use of `Cache.ID` and prompt keys. - Restored `Session_id` as a priority extraction source for `ExtractSessionID`. - Added tests to validate case-sensitive and case-insensitive headers, canonical account header usage, and session key preservation. - Removed legacy support for deprecated `Conversation_id` header to clean up API.

Luis Pater committed 5 months agov7.1.37

Commit 05b97241 parent fb4f39d9 files · +129 −61Browse files

Unified · Split

9 files
  1. config.example.yaml +1 −1
  2. internal/config/config.go +1 −1
  3. internal/runtime/executor/codex_executor.go +20 −9
  4. internal/runtime/executor/codex_executor_cache_test.go +18 −4
  5. internal/runtime/executor/codex_websockets_executor.go +15 −14
  6. internal/runtime/executor/codex_websockets_executor_test.go +34 −11
  7. sdk/api/handlers/openai/openai_responses_websocket_toolcall_repair.go +6 −0
  8. sdk/cliproxy/auth/selector.go +27 −15
  9. sdk/cliproxy/auth/selector_test.go +7 −6
config.example.yaml+1−1
@@ -119,7 +119,7 @@ routing: · 118 unmodified lines
119 strategy: "round-robin" # round-robin (default), fill-first119 strategy: "round-robin" # round-robin (default), fill-first
120 # Enable universal session-sticky routing for all clients.120 # Enable universal session-sticky routing for all clients.
121 # Session IDs are extracted from: metadata.user_id (Claude Code session format),121 # Session IDs are extracted from: metadata.user_id (Claude Code session format),
122 # X-Session-ID, X-Amp-Thread-Id (Amp CLI),122 # X-Session-ID, Session_id (Codex), X-Amp-Thread-Id (Amp CLI),
123 # X-Client-Request-Id (PI), conversation_id, or first few messages hash.123 # X-Client-Request-Id (PI), conversation_id, or first few messages hash.
124 # Automatic failover is always enabled when bound auth becomes unavailable.124 # Automatic failover is always enabled when bound auth becomes unavailable.
125 session-affinity: false # default: false125 session-affinity: false # default: false
internal/config/config.go+1−1
@@ -237,7 +237,7 @@ type RoutingConfig struct { · 236 unmodified lines
237 237
238 // SessionAffinity enables universal session-sticky routing for all clients.238 // SessionAffinity enables universal session-sticky routing for all clients.
239 // Session IDs are extracted from multiple sources:239 // Session IDs are extracted from multiple sources:
240 // metadata.user_id (Claude Code session format), X-Session-ID,240 // metadata.user_id (Claude Code session format), X-Session-ID, Session_id (Codex),
241 // X-Amp-Thread-Id (Amp CLI thread), X-Client-Request-Id (PI), metadata.user_id,241 // X-Amp-Thread-Id (Amp CLI thread), X-Client-Request-Id (PI), metadata.user_id,
242 // conversation_id, or message hash.242 // conversation_id, or message hash.
243 // Automatic failover is always enabled when bound auth becomes unavailable.243 // Automatic failover is always enabled when bound auth becomes unavailable.
internal/runtime/executor/codex_executor.go+20−9
@@ -931,6 +931,9 @@ func (e *CodexExecutor) cacheHelper(ctx context.Context, from sdktranslator.Form · 930 unmodified lines
931 if err != nil {931 if err != nil {
932 return nil, nil, codexIdentityConfuseState{}, err932 return nil, nil, codexIdentityConfuseState{}, err
933 }933 }
934 if cache.ID != "" {
935 httpReq.Header.Set("Session_id", cache.ID)
936 }
934 return httpReq, rawJSON, identityState, nil937 return httpReq, rawJSON, identityState, nil
935}938}
936 939
@@ -964,7 +967,6 @@ func applyCodexIdentityConfuseHeaders(headers http.Header, state *codexIdentityC · 27 unmodified lines
964 if headers == nil {967 if headers == nil {
965 return968 return
966 }969 }
967 defer deleteDeprecatedCodexConversationHeader(headers)
968 if state == nil || !state.enabled {970 if state == nil || !state.enabled {
969 return971 return
970 }972 }
@@ -977,6 +979,12 @@ func applyCodexIdentityConfuseHeaders(headers http.Header, state *codexIdentityC · 6 unmodified lines
977 }979 }
978 980
979 setHeaderCasePreserved(headers, "Session-Id", state.promptCacheKey)981 setHeaderCasePreserved(headers, "Session-Id", state.promptCacheKey)
982 if headerValueCaseInsensitive(headers, "session_id") != "" {
983 setHeaderCasePreserved(headers, "session_id", state.promptCacheKey)
984 }
985 if headerValueCaseInsensitive(headers, "Conversation_id") != "" {
986 setHeaderCasePreserved(headers, "Conversation_id", state.promptCacheKey)
987 }
980 headers.Set("X-Client-Request-Id", state.promptCacheKey)988 headers.Set("X-Client-Request-Id", state.promptCacheKey)
981 headers.Set("Thread-Id", state.promptCacheKey)989 headers.Set("Thread-Id", state.promptCacheKey)
982 headers.Set("X-Codex-Window-Id", state.promptCacheKey+":0")990 headers.Set("X-Codex-Window-Id", state.promptCacheKey+":0")
@@ -1072,6 +1080,10 @@ func applyCodexHeaders(r *http.Request, auth *cliproxyauth.Auth, token string, s · 89 unmodified lines
1072 cfgUserAgent, _ := codexHeaderDefaults(cfg, auth)1080 cfgUserAgent, _ := codexHeaderDefaults(cfg, auth)
1073 ensureHeaderWithConfigPrecedence(r.Header, ginHeaders, "User-Agent", cfgUserAgent, codexUserAgent)1081 ensureHeaderWithConfigPrecedence(r.Header, ginHeaders, "User-Agent", cfgUserAgent, codexUserAgent)
1074 1082
1083 if strings.Contains(r.Header.Get("User-Agent"), "Mac OS") {
1084 misc.EnsureHeader(r.Header, ginHeaders, "Session_id", uuid.NewString())
1085 }
1086
1075 if stream {1087 if stream {
1076 r.Header.Set("Accept", "text/event-stream")1088 r.Header.Set("Accept", "text/event-stream")
1077 } else {1089 } else {
@@ -1090,19 +1102,18 @@ func applyCodexHeaders(r *http.Request, auth *cliproxyauth.Auth, token string, s · 12 unmodified lines
1090 } else if !isAPIKey {1102 } else if !isAPIKey {
1091 r.Header.Set("Originator", codexOriginator)1103 r.Header.Set("Originator", codexOriginator)
1092 }1104 }
1093 // if !isAPIKey {1105 if !isAPIKey {
1094 // if auth != nil && auth.Metadata != nil {1106 if auth != nil && auth.Metadata != nil {
1095 // if accountID, ok := auth.Metadata["account_id"].(string); ok {1107 if accountID, ok := auth.Metadata["account_id"].(string); ok {
1096 // r.Header.Set("Chatgpt-Account-Id", accountID)1108 r.Header.Set("Chatgpt-Account-Id", accountID)
1097 // }1109 }
1098 // }1110 }
1099 // }1111 }
1100 var attrs map[string]string1112 var attrs map[string]string
1101 if auth != nil {1113 if auth != nil {
1102 attrs = auth.Attributes1114 attrs = auth.Attributes
1103 }1115 }
1104 util.ApplyCustomHeadersFromAttrs(r, attrs)1116 util.ApplyCustomHeadersFromAttrs(r, attrs)
1105 deleteDeprecatedCodexConversationHeader(r.Header)
1106}1117}
1107 1118
1108func newCodexStatusErr(statusCode int, body []byte) statusErr {1119func newCodexStatusErr(statusCode int, body []byte) statusErr {
internal/runtime/executor/codex_executor_cache_test.go+18−4
@@ -47,8 +47,8 @@ func TestCodexExecutorCacheHelper_OpenAIChatCompletions_StablePromptCacheKeyFrom · 46 unmodified lines
47 if gotConversation := httpReq.Header.Get("Conversation_id"); gotConversation != "" {47 if gotConversation := httpReq.Header.Get("Conversation_id"); gotConversation != "" {
48 t.Fatalf("Conversation_id = %q, want empty", gotConversation)48 t.Fatalf("Conversation_id = %q, want empty", gotConversation)
49 }49 }
50 if gotSession := httpReq.Header.Get("Session_id"); gotSession != "" {50 if gotSession := httpReq.Header.Get("Session_id"); gotSession != expectedKey {
51 t.Fatalf("Session_id = %q, want empty", gotSession)51 t.Fatalf("Session_id = %q, want %q", gotSession, expectedKey)
52 }52 }
53 53
54 httpReq2, _, _, err := executor.cacheHelper(ctx, sdktranslator.FromString("openai"), url, nil, req, req.Payload, rawJSON)54 httpReq2, _, _, err := executor.cacheHelper(ctx, sdktranslator.FromString("openai"), url, nil, req, req.Payload, rawJSON)
@@ -119,8 +119,8 @@ func TestCodexExecutorCacheHelper_IdentityConfuseRemapsBodyAndHeaders(t *testing · 64 unmodified lines
119 t.Fatalf("%s = %q, want %q", headerName, gotHeader, expectedPromptCacheKey)119 t.Fatalf("%s = %q, want %q", headerName, gotHeader, expectedPromptCacheKey)
120 }120 }
121 }121 }
122 if gotSession := httpReq.Header.Get("Session_id"); gotSession != "" {122 if gotSession := httpReq.Header.Get("Session_id"); gotSession != expectedPromptCacheKey {
123 t.Fatalf("Session_id = %q, want empty", gotSession)123 t.Fatalf("Session_id = %q, want %q", gotSession, expectedPromptCacheKey)
124 }124 }
125 if gotWindow := httpReq.Header.Get("X-Codex-Window-Id"); gotWindow != expectedPromptCacheKey+":0" {125 if gotWindow := httpReq.Header.Get("X-Codex-Window-Id"); gotWindow != expectedPromptCacheKey+":0" {
126 t.Fatalf("X-Codex-Window-Id = %q, want %q", gotWindow, expectedPromptCacheKey+":0")126 t.Fatalf("X-Codex-Window-Id = %q, want %q", gotWindow, expectedPromptCacheKey+":0")
@@ -137,6 +137,20 @@ func TestCodexExecutorCacheHelper_IdentityConfuseRemapsBodyAndHeaders(t *testing · 10 unmodified lines
137 }137 }
138}138}
139 139
140func TestApplyCodexHeadersUsesAccountHeaderForOAuth(t *testing.T) {
141 httpReq := httptest.NewRequest("POST", "https://example.com/responses", nil)
142 auth := &cliproxyauth.Auth{
143 Provider: "codex",
144 Metadata: map[string]any{"account_id": "acct-1"},
145 }
146
147 applyCodexHeaders(httpReq, auth, "oauth-token", true, nil)
148
149 if got := httpReq.Header.Get("Chatgpt-Account-Id"); got != "acct-1" {
150 t.Fatalf("Chatgpt-Account-Id = %q, want acct-1", got)
151 }
152}
153
140func TestCodexIdentityConfuseKeepsClientBodySeparateFromUpstreamBody(t *testing.T) {154func TestCodexIdentityConfuseKeepsClientBodySeparateFromUpstreamBody(t *testing.T) {
141 cfg := &config.Config{155 cfg := &config.Config{
142 Routing: config.RoutingConfig{Strategy: "fill-first"},156 Routing: config.RoutingConfig{Strategy: "fill-first"},
internal/runtime/executor/codex_websockets_executor.go+15−14
@@ -857,6 +857,8 @@ func applyCodexPromptCacheHeaders(from sdktranslator.Format, req cliproxyexecuto · 856 unmodified lines
857 857
858 if cache.ID != "" {858 if cache.ID != "" {
859 rawJSON, _ = sjson.SetBytes(rawJSON, "prompt_cache_key", cache.ID)859 rawJSON, _ = sjson.SetBytes(rawJSON, "prompt_cache_key", cache.ID)
860 setHeaderCasePreserved(headers, "session_id", cache.ID)
861 headers.Set("Conversation_id", cache.ID)
860 }862 }
861 863
862 return rawJSON, headers864 return rawJSON, headers
@@ -897,27 +899,30 @@ func applyCodexWebsocketHeaders(ctx context.Context, headers http.Header, auth * · 34 unmodified lines
897 betaHeader = codexResponsesWebsocketBetaHeaderValue899 betaHeader = codexResponsesWebsocketBetaHeaderValue
898 }900 }
899 headers.Set("OpenAI-Beta", betaHeader)901 headers.Set("OpenAI-Beta", betaHeader)
902 if strings.Contains(headers.Get("User-Agent"), "Mac OS") {
903 ensureHeaderCasePreserved(headers, ginHeaders, "session_id", "", uuid.NewString())
904 }
905 ensureHeaderCasePreserved(headers, ginHeaders, "session_id", "", "")
900 if originator := strings.TrimSpace(ginHeaders.Get("Originator")); originator != "" {906 if originator := strings.TrimSpace(ginHeaders.Get("Originator")); originator != "" {
901 headers.Set("Originator", originator)907 headers.Set("Originator", originator)
902 } else if !isAPIKey {908 } else if !isAPIKey {
903 headers.Set("Originator", codexOriginator)909 headers.Set("Originator", codexOriginator)
904 }910 }
905 // if !isAPIKey {911 if !isAPIKey {
906 // if auth != nil && auth.Metadata != nil {912 if auth != nil && auth.Metadata != nil {
907 // if accountID, ok := auth.Metadata["account_id"].(string); ok {913 if accountID, ok := auth.Metadata["account_id"].(string); ok {
908 // if trimmed := strings.TrimSpace(accountID); trimmed != "" {914 if trimmed := strings.TrimSpace(accountID); trimmed != "" {
909 // setHeaderCasePreserved(headers, "ChatGPT-Account-ID", trimmed)915 setHeaderCasePreserved(headers, "ChatGPT-Account-ID", trimmed)
910 // }916 }
911 // }917 }
912 // }918 }
913 // }919 }
914 920
915 var attrs map[string]string921 var attrs map[string]string
916 if auth != nil {922 if auth != nil {
917 attrs = auth.Attributes923 attrs = auth.Attributes
918 }924 }
919 util.ApplyCustomHeadersFromAttrs(&http.Request{Header: headers}, attrs)925 util.ApplyCustomHeadersFromAttrs(&http.Request{Header: headers}, attrs)
920 deleteDeprecatedCodexConversationHeader(headers)
921 926
922 return headers927 return headers
923}928}
@@ -993,10 +998,6 @@ func deleteHeaderCaseInsensitive(headers http.Header, key string) { · 69 unmodified lines
993 }998 }
994}999}
995 1000
996func deleteDeprecatedCodexConversationHeader(headers http.Header) {
997 deleteHeaderCaseInsensitive(headers, "Conversation_id")
998}
999
1000func codexHeaderDefaults(cfg *config.Config, auth *cliproxyauth.Auth) (string, string) {1001func codexHeaderDefaults(cfg *config.Config, auth *cliproxyauth.Auth) (string, string) {
1001 if cfg == nil || auth == nil {1002 if cfg == nil || auth == nil {
1002 return "", ""1003 return "", ""
internal/runtime/executor/codex_websockets_executor_test.go+34−11
@@ -217,8 +217,11 @@ func TestApplyCodexWebsocketHeadersPassesThroughClientIdentityHeaders(t *testing · 216 unmodified lines
217 if got := headers.Get("X-Client-Request-Id"); got != "019d2233-e240-7162-992d-38df0a2a0e0d" {217 if got := headers.Get("X-Client-Request-Id"); got != "019d2233-e240-7162-992d-38df0a2a0e0d" {
218 t.Fatalf("X-Client-Request-Id = %s, want %s", got, "019d2233-e240-7162-992d-38df0a2a0e0d")218 t.Fatalf("X-Client-Request-Id = %s, want %s", got, "019d2233-e240-7162-992d-38df0a2a0e0d")
219 }219 }
220 if got := headerValueCaseInsensitive(headers, "session_id"); got != "" {220 if got := headerValueCaseInsensitive(headers, "session_id"); got != "legacy-session" {
221 t.Fatalf("session_id = %q, want empty", got)221 t.Fatalf("session_id = %s, want legacy-session", got)
222 }
223 if _, ok := headers["session_id"]; !ok {
224 t.Fatalf("expected lowercase session_id header key, got %#v", headers)
222 }225 }
223}226}
224 227
@@ -341,16 +344,36 @@ func TestApplyCodexWebsocketHeadersPreservesExplicitAPIKeyUserAgent(t *testing.T · 116 unmodified lines
341 }344 }
342}345}
343 346
344func TestApplyCodexPromptCacheHeadersDoesNotSetDeprecatedConversationHeader(t *testing.T) {347func TestApplyCodexWebsocketHeadersUsesCanonicalAccountHeader(t *testing.T) {
348 auth := &cliproxyauth.Auth{Provider: "codex", Metadata: map[string]any{"account_id": "acct-1"}}
349
350 headers := applyCodexWebsocketHeaders(context.Background(), http.Header{}, auth, "", nil)
351
352 if got := headerValueCaseInsensitive(headers, "ChatGPT-Account-ID"); got != "acct-1" {
353 t.Fatalf("ChatGPT-Account-ID = %s, want acct-1", got)
354 }
355 values, ok := headers["ChatGPT-Account-ID"]
356 if !ok {
357 t.Fatalf("expected exact ChatGPT-Account-ID key, got %#v", headers)
358 }
359 if len(values) != 1 || values[0] != "acct-1" {
360 t.Fatalf("ChatGPT-Account-ID values = %#v, want [acct-1]", values)
361 }
362}
363
364func TestApplyCodexPromptCacheHeadersSetsLowercaseSessionAndLegacyConversation(t *testing.T) {
345 req := cliproxyexecutor.Request{Model: "gpt-5-codex", Payload: []byte(`{"prompt_cache_key":"cache-1"}`)}365 req := cliproxyexecutor.Request{Model: "gpt-5-codex", Payload: []byte(`{"prompt_cache_key":"cache-1"}`)}
346 366
347 _, headers := applyCodexPromptCacheHeaders("openai-response", req, []byte(`{"model":"gpt-5-codex"}`))367 _, headers := applyCodexPromptCacheHeaders("openai-response", req, []byte(`{"model":"gpt-5-codex"}`))
348 368
349 if got := headerValueCaseInsensitive(headers, "session_id"); got != "" {369 if got := headerValueCaseInsensitive(headers, "session_id"); got != "cache-1" {
350 t.Fatalf("session_id = %q, want empty", got)370 t.Fatalf("session_id = %s, want cache-1", got)
371 }
372 if _, ok := headers["session_id"]; !ok {
373 t.Fatalf("expected lowercase session_id key, got %#v", headers)
351 }374 }
352 if got := headers.Get("Conversation_id"); got != "" {375 if got := headers.Get("Conversation_id"); got != "cache-1" {
353 t.Fatalf("Conversation_id = %q, want empty", got)376 t.Fatalf("Conversation_id = %s, want cache-1", got)
354 }377 }
355}378}
356 379
@@ -379,8 +402,8 @@ func TestApplyCodexWebsocketHeadersIdentityConfuseRemapsPromptCacheKey(t *testin · 22 unmodified lines
379 if gotKey := gjson.GetBytes(body, "prompt_cache_key").String(); gotKey != expectedPromptCacheKey {402 if gotKey := gjson.GetBytes(body, "prompt_cache_key").String(); gotKey != expectedPromptCacheKey {
380 t.Fatalf("prompt_cache_key = %q, want %q", gotKey, expectedPromptCacheKey)403 t.Fatalf("prompt_cache_key = %q, want %q", gotKey, expectedPromptCacheKey)
381 }404 }
382 if gotSession := headerValueCaseInsensitive(headers, "session_id"); gotSession != "" {405 if gotSession := headerValueCaseInsensitive(headers, "session_id"); gotSession != expectedPromptCacheKey {
383 t.Fatalf("session_id = %q, want empty", gotSession)406 t.Fatalf("session_id = %q, want %q", gotSession, expectedPromptCacheKey)
384 }407 }
385 if gotRequestID := headers.Get("X-Client-Request-Id"); gotRequestID != expectedPromptCacheKey {408 if gotRequestID := headers.Get("X-Client-Request-Id"); gotRequestID != expectedPromptCacheKey {
386 t.Fatalf("X-Client-Request-Id = %q, want %q", gotRequestID, expectedPromptCacheKey)409 t.Fatalf("X-Client-Request-Id = %q, want %q", gotRequestID, expectedPromptCacheKey)
@@ -388,8 +411,8 @@ func TestApplyCodexWebsocketHeadersIdentityConfuseRemapsPromptCacheKey(t *testin · 1 unmodified line
388 if gotThreadID := headers.Get("Thread-Id"); gotThreadID != expectedPromptCacheKey {411 if gotThreadID := headers.Get("Thread-Id"); gotThreadID != expectedPromptCacheKey {
389 t.Fatalf("Thread-Id = %q, want %q", gotThreadID, expectedPromptCacheKey)412 t.Fatalf("Thread-Id = %q, want %q", gotThreadID, expectedPromptCacheKey)
390 }413 }
391 if gotConversation := headers.Get("Conversation_id"); gotConversation != "" {414 if gotConversation := headers.Get("Conversation_id"); gotConversation != expectedPromptCacheKey {
392 t.Fatalf("Conversation_id = %q, want empty", gotConversation)415 t.Fatalf("Conversation_id = %q, want %q", gotConversation, expectedPromptCacheKey)
393 }416 }
394 if gotWindowID := headers.Get("X-Codex-Window-Id"); gotWindowID != expectedPromptCacheKey+":0" {417 if gotWindowID := headers.Get("X-Codex-Window-Id"); gotWindowID != expectedPromptCacheKey+":0" {
395 t.Fatalf("X-Codex-Window-Id = %q, want %q", gotWindowID, expectedPromptCacheKey+":0")418 t.Fatalf("X-Codex-Window-Id = %q, want %q", gotWindowID, expectedPromptCacheKey+":0")
sdk/api/handlers/openai/openai_responses_websocket_toolcall_repair.go+6−0
@@ -147,6 +147,12 @@ func websocketDownstreamSessionKey(req *http.Request) string { · 146 unmodified lines
147 return sessionID147 return sessionID
148 }148 }
149 }149 }
150 if sessionID := strings.TrimSpace(req.Header.Get("Session-Id")); sessionID != "" {
151 return sessionID
152 }
153 if sessionID := strings.TrimSpace(req.Header.Get("Session_id")); sessionID != "" {
154 return sessionID
155 }
150 return ""156 return ""
151}157}
152 158
sdk/cliproxy/auth/selector.go+27−15
@@ -471,11 +471,12 @@ func NewSessionAffinitySelectorWithConfig(cfg SessionAffinityConfig) *SessionAff · 470 unmodified lines
471// Priority for session ID extraction:471// Priority for session ID extraction:
472// 1. metadata.user_id (Claude Code format with _session_{uuid}) - highest priority472// 1. metadata.user_id (Claude Code format with _session_{uuid}) - highest priority
473// 2. X-Session-ID header473// 2. X-Session-ID header
474// 3. X-Amp-Thread-Id header (Amp CLI thread ID)474// 3. Session_id header (Codex)
475// 4. X-Client-Request-Id header (PI)475// 4. X-Amp-Thread-Id header (Amp CLI thread ID)
476// 5. metadata.user_id (non-Claude Code format)476// 5. X-Client-Request-Id header (PI)
477// 6. conversation_id field in request body477// 6. metadata.user_id (non-Claude Code format)
478// 7. Stable hash from first few messages content (fallback)478// 7. conversation_id field in request body
479// 8. Stable hash from first few messages content (fallback)
479//480//
480// Note: The cache key includes provider, session ID, and model to handle cases where481// Note: The cache key includes provider, session ID, and model to handle cases where
481// a session uses multiple models (e.g., gemini-2.5-pro and gemini-3-flash-preview)482// a session uses multiple models (e.g., gemini-2.5-pro and gemini-3-flash-preview)
@@ -572,11 +573,12 @@ func (s *SessionAffinitySelector) InvalidateAuth(authID string) { · 90 unmodified lines
572// Priority order:573// Priority order:
573// 1. metadata.user_id (Claude Code format with _session_{uuid}) - highest priority for Claude Code clients574// 1. metadata.user_id (Claude Code format with _session_{uuid}) - highest priority for Claude Code clients
574// 2. X-Session-ID header575// 2. X-Session-ID header
575// 3. X-Amp-Thread-Id header (Amp CLI thread ID)576// 3. Session_id header (Codex)
576// 4. X-Client-Request-Id header (PI)577// 4. X-Amp-Thread-Id header (Amp CLI thread ID)
577// 5. metadata.user_id (non-Claude Code format)578// 5. X-Client-Request-Id header (PI)
578// 6. conversation_id field in request body579// 6. metadata.user_id (non-Claude Code format)
579// 7. Stable hash from first few messages content (fallback)580// 7. conversation_id field in request body
581// 8. Stable hash from first few messages content (fallback)
580func ExtractSessionID(headers http.Header, payload []byte, metadata map[string]any) string {582func ExtractSessionID(headers http.Header, payload []byte, metadata map[string]any) string {
581 primary, _ := extractSessionIDs(headers, payload, metadata)583 primary, _ := extractSessionIDs(headers, payload, metadata)
582 return primary584 return primary
@@ -612,14 +614,24 @@ func extractSessionIDs(headers http.Header, payload []byte, metadata map[string] · 29 unmodified lines
612 }614 }
613 }615 }
614 616
615 // 3. X-Amp-Thread-Id header (Amp CLI thread ID)617 // 3. Session_id header (Codex)
618 if headers != nil {
619 if sid := headers.Get("Session-Id"); sid != "" {
620 return "codex:" + sid, ""
621 }
622 if sid := headers.Get("Session_id"); sid != "" {
623 return "codex:" + sid, ""
624 }
625 }
626
627 // 4. X-Amp-Thread-Id header (Amp CLI thread ID)
616 if headers != nil {628 if headers != nil {
617 if tid := headers.Get("X-Amp-Thread-Id"); tid != "" {629 if tid := headers.Get("X-Amp-Thread-Id"); tid != "" {
618 return "amp:" + tid, ""630 return "amp:" + tid, ""
619 }631 }
620 }632 }
621 633
622 // 4. X-Client-Request-Id header (PI)634 // 5. X-Client-Request-Id header (PI)
623 if headers != nil {635 if headers != nil {
624 if rid := headers.Get("X-Client-Request-Id"); rid != "" {636 if rid := headers.Get("X-Client-Request-Id"); rid != "" {
625 return "clientreq:" + rid, ""637 return "clientreq:" + rid, ""
@@ -630,18 +642,18 @@ func extractSessionIDs(headers http.Header, payload []byte, metadata map[string] · 4 unmodified lines
630 return "", ""642 return "", ""
631 }643 }
632 644
633 // 5. metadata.user_id (non-Claude Code format)645 // 6. metadata.user_id (non-Claude Code format)
634 userID := gjson.GetBytes(payload, "metadata.user_id").String()646 userID := gjson.GetBytes(payload, "metadata.user_id").String()
635 if userID != "" {647 if userID != "" {
636 return "user:" + userID, ""648 return "user:" + userID, ""
637 }649 }
638 650
639 // 6. conversation_id field651 // 7. conversation_id field
640 if convID := gjson.GetBytes(payload, "conversation_id").String(); convID != "" {652 if convID := gjson.GetBytes(payload, "conversation_id").String(); convID != "" {
641 return "conv:" + convID, ""653 return "conv:" + convID, ""
642 }654 }
643 655
644 // 7. Hash-based fallback from message content656 // 8. Hash-based fallback from message content
645 return extractMessageHashIDs(payload)657 return extractMessageHashIDs(payload)
646}658}
647 659
sdk/cliproxy/auth/selector_test.go+7−6
@@ -776,15 +776,16 @@ func TestExtractSessionID_Headers(t *testing.T) { · 775 unmodified lines
776 }776 }
777}777}
778 778
779func TestExtractSessionID_IgnoresCodexSessionIDHeader(t *testing.T) {779func TestExtractSessionID_CodexSessionIDHeader(t *testing.T) {
780 t.Parallel()780 t.Parallel()
781 781
782 headers := make(http.Header)782 headers := make(http.Header)
783 headers.Set("Session_id", "codex-session-123")783 headers.Set("Session_id", "codex-session-123")
784 784
785 got := ExtractSessionID(headers, nil, nil)785 got := ExtractSessionID(headers, nil, nil)
786 if got != "" {786 want := "codex:codex-session-123"
787 t.Errorf("ExtractSessionID() with deprecated Session_id = %q, want empty", got)787 if got != want {
788 t.Errorf("ExtractSessionID() with Session_id = %q, want %q", got, want)
788 }789 }
789}790}
790 791
@@ -801,7 +802,7 @@ func TestExtractSessionID_ClientRequestIDHeader(t *testing.T) { · 10 unmodified lines
801 }802 }
802}803}
803 804
804func TestExtractSessionID_ClientRequestIDIgnoresDeprecatedCodexSessionID(t *testing.T) {805func TestExtractSessionID_CodexSessionIDPriorityOverClientRequestID(t *testing.T) {
805 t.Parallel()806 t.Parallel()
806 807
807 headers := make(http.Header)808 headers := make(http.Header)
@@ -809,9 +810,9 @@ func TestExtractSessionID_ClientRequestIDIgnoresDeprecatedCodexSessionID(t *test · 1 unmodified line
809 headers.Set("Session_id", "codex-session-456")810 headers.Set("Session_id", "codex-session-456")
810 811
811 got := ExtractSessionID(headers, nil, nil)812 got := ExtractSessionID(headers, nil, nil)
812 want := "clientreq:pi-session-123"813 want := "codex:codex-session-456"
813 if got != want {814 if got != want {
814 t.Errorf("ExtractSessionID() = %q, want %q (deprecated Session_id should be ignored)", got, want)815 t.Errorf("ExtractSessionID() = %q, want %q (Session_id should take priority over X-Client-Request-Id)", got, want)
815 }816 }
816}817}
817 818

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t