Skip to content

feat(channel): support Codex upstream model discovery - #6184

Merged
Calcium-Ion merged 3 commits into
QuantumNous:mainfrom
seefs001:feature/codex-model-fetch
Jul 18, 2026
Merged

Calcium-Ion merged 3 commits into
QuantumNous:mainfrom
seefs001:feature/codex-model-fetch

Conversation

@seefs001

@seefs001 seefs001 commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

codex支持获取上游模型(从Github获取最新客户端版本号,获取后端可用模型)
新建渠道时的获取上游模型方法整合到编辑时的获取方法,避免行为不一致。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

Summary by CodeRabbit

  • New Features

    • Added automatic model discovery for Codex channels, including credential refresh and latest client-version handling.
    • Expanded model fetching support to an additional channel type.
    • Added compact model variants where applicable.
  • Bug Fixes

    • Standardized model-fetching behavior and request handling across channel types.
    • Improved model list cleanup by removing duplicates and unsupported entries.
    • Unified error responses when model retrieval fails.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The change routes model retrieval through shared controller logic, adds Codex-specific upstream discovery with version caching and credential refresh, updates Codex model variants, and enables channel type 57 for model fetching.

Changes

Codex upstream model discovery

Layer / File(s) Summary
Codex model variant definitions
relay/channel/codex/constants.go, setting/ratio_setting/compact_suffix.go
Codex model lists now use shared compact-variant generation and exclude the compact codex-auto-review variant.
Codex upstream API and version cache
service/codex_models.go
Adds cached stable client-version lookup and authenticated Codex model retrieval with validation, status handling, filtering, and deduplication.
Codex channel discovery service
service/codex_channel_models.go
Validates Codex channels, fetches models, refreshes credentials after unauthorized responses, and returns compact model variants.
Shared controller model-fetch integration
controller/channel.go, controller/channel_upstream_update.go, controller/channel_upstream_update_test.go, web/default/src/features/channels/constants.ts
Normalizes fetch requests through shared channel logic, dispatches Codex channels to the new service, tests shared upstream behavior, and adds channel type 57 to the fetchable allowlist.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant FetchModels
  participant fetchChannelUpstreamModelIDs
  participant FetchCodexChannelModels
  participant CodexBackend
  Client->>FetchModels: request model list
  FetchModels->>fetchChannelUpstreamModelIDs: pass normalized channel
  fetchChannelUpstreamModelIDs->>FetchCodexChannelModels: dispatch Codex retrieval
  FetchCodexChannelModels->>CodexBackend: request available models
  CodexBackend-->>FetchCodexChannelModels: return model slugs
  FetchCodexChannelModels-->>FetchModels: return normalized IDs
  FetchModels-->>Client: JSON model list
Loading

Possibly related PRs

Suggested reviewers: calcium-ion

Poem

I’m a rabbit with models in tow,
Through Codex’s bright backend I go.
Keys refresh, variants bloom,
Cached versions clear the room—
Shared fetch paths make the list grow!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning [#6181, #6071] Codex discovery and shared upstream fetching were added, but #6181's multi-account JSON support is still blocked by the single-key-only Codex path. Allow FetchCodexChannelModels to handle multi-key Codex account pools while keeping the new backend-api/codex/models fetch path.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: Codex upstream model discovery.
Out of Scope Changes check ✅ Passed The changes stay focused on Codex discovery and upstream fetch consolidation, and the frontend constant update supports the new channel type.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@controller/channel_upstream_update_test.go`:
- Around line 17-31: Update the httptest handler in
TestFetchModelsUsesSharedChannelFetchBehavior to use assert.Equal for the
request path and x-api-key and Authorization header checks instead of raw
t.Errorf, preserving these checks as non-fatal assertions.

In `@controller/channel.go`:
- Around line 1183-1188: FetchModels in controller/channel.go must preserve
ChannelInfo.IsMultiKey when constructing the request-scoped model.Channel; copy
the existing channel info into that instance before calling
fetchChannelUpstreamModelIDs. This enables the Codex guard in
service/codex_channel_models.go lines 19-21; no direct change is required there.

In `@service/codex_channel_models.go`:
- Around line 27-39: The single 20-second context in the Codex model-fetch flow
is shared by the version lookup and subsequent model/credential calls. Update
the context handling around GetLatestCodexClientVersion and
fetchCodexChannelModels to give the version lookup its own timeout or otherwise
preserve sufficient timeout budget for the model fetch, credential refresh, and
retry sequence; keep cancellation and existing error propagation intact.
- Around line 81-89: Update the model variant construction to reuse the shared
deduping WithCompactModelVariants helper, adding the slices import if required
by that helper’s established usage. Remove the hand-rolled suffix loop around
modelVariants while preserving the exclusion of codex-auto-review and preventing
duplicates when models already contain compact-suffixed names.

In `@service/codex_models.go`:
- Around line 134-141: Update the request headers configured after
http.NewRequestWithContext in the models request: add the originator header with
value codex_cli_rs and change the User-Agent prefix from codex-cli/ to
codex_cli_rs/. Preserve the existing Authorization, account ID, and Accept
headers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e005e665-68d7-484b-8727-4b0c37eb2a11

📥 Commits

Reviewing files that changed from the base of the PR and between 7c28993 and c2f2580.

📒 Files selected for processing (8)
  • controller/channel.go
  • controller/channel_upstream_update.go
  • controller/channel_upstream_update_test.go
  • relay/channel/codex/constants.go
  • service/codex_channel_models.go
  • service/codex_models.go
  • setting/ratio_setting/compact_suffix.go
  • web/default/src/features/channels/constants.ts

Comment on lines +17 to +31
func TestFetchModelsUsesSharedChannelFetchBehavior(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
if r.Header.Get("x-api-key") != "first-key" {
t.Errorf("unexpected x-api-key header: %s", r.Header.Get("x-api-key"))
}
if r.Header.Get("Authorization") != "" {
t.Errorf("unexpected Authorization header: %s", r.Header.Get("Authorization"))
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":" claude-sonnet "},{"id":"claude-sonnet"}]}`))
}))
t.Cleanup(server.Close)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Use assert instead of raw t.Errorf for non-fatal header/path checks.

As per coding guidelines, "New or substantially rewritten Go backend tests must use require for setup and fatal assertions and assert for non-fatal value checks." The path/header checks inside the httptest handler use t.Errorf directly instead of assert.Equal.

✅ Proposed fix
+	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 )

 func TestFetchModelsUsesSharedChannelFetchBehavior(t *testing.T) {
 	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		if r.URL.Path != "/v1/models" {
-			t.Errorf("unexpected path: %s", r.URL.Path)
-		}
-		if r.Header.Get("x-api-key") != "first-key" {
-			t.Errorf("unexpected x-api-key header: %s", r.Header.Get("x-api-key"))
-		}
-		if r.Header.Get("Authorization") != "" {
-			t.Errorf("unexpected Authorization header: %s", r.Header.Get("Authorization"))
-		}
+		assert.Equal(t, "/v1/models", r.URL.Path)
+		assert.Equal(t, "first-key", r.Header.Get("x-api-key"))
+		assert.Empty(t, r.Header.Get("Authorization"))
 		w.Header().Set("Content-Type", "application/json")
 		_, _ = w.Write([]byte(`{"data":[{"id":" claude-sonnet "},{"id":"claude-sonnet"}]}`))
 	}))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestFetchModelsUsesSharedChannelFetchBehavior(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
if r.Header.Get("x-api-key") != "first-key" {
t.Errorf("unexpected x-api-key header: %s", r.Header.Get("x-api-key"))
}
if r.Header.Get("Authorization") != "" {
t.Errorf("unexpected Authorization header: %s", r.Header.Get("Authorization"))
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":" claude-sonnet "},{"id":"claude-sonnet"}]}`))
}))
t.Cleanup(server.Close)
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFetchModelsUsesSharedChannelFetchBehavior(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/v1/models", r.URL.Path)
assert.Equal(t, "first-key", r.Header.Get("x-api-key"))
assert.Empty(t, r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":" claude-sonnet "},{"id":"claude-sonnet"}]}`))
}))
t.Cleanup(server.Close)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/channel_upstream_update_test.go` around lines 17 - 31, Update the
httptest handler in TestFetchModelsUsesSharedChannelFetchBehavior to use
assert.Equal for the request path and x-api-key and Authorization header checks
instead of raw t.Errorf, preserving these checks as non-fatal assertions.

Source: Coding guidelines

Comment thread controller/channel.go
Comment on lines +1183 to +1188
channel := &model.Channel{
Type: req.Type,
Key: key,
BaseURL: &baseURL,
}

request.Header.Set("Authorization", "Bearer "+key)

response, err := client.Do(request)
models, err := fetchChannelUpstreamModelIDs(channel)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant files and surrounding context.
git ls-files controller/channel.go service/codex_channel_models.go
printf '\n--- controller/channel.go (around 1183) ---\n'
sed -n '1160,1215p' controller/channel.go
printf '\n--- service/codex_channel_models.go ---\n'
cat -n service/codex_channel_models.go

printf '\n--- search for ChannelInfo population / FetchModels callers ---\n'
rg -n "FetchModels|ChannelInfo|IsMultiKey|fetchChannelUpstreamModelIDs|parseCodexOAuthKey|FetchCodexChannelModels" controller service model -S

Repository: QuantumNous/new-api

Length of output: 17996


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant symbols in controller/channel.go before reading any larger slices.
ast-grep outline controller/channel.go --view expanded

Repository: QuantumNous/new-api

Length of output: 5045


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the upstream model fetch flow and request shapes for edit/create.
rg -n "type .*Request|FetchModels" controller service model -S

Repository: QuantumNous/new-api

Length of output: 4483


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1140,1205p' controller/channel.go
echo '---'
sed -n '1,120p' service/codex_channel_models.go

Repository: QuantumNous/new-api

Length of output: 4148


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the shared upstream fetch dispatcher and key parsing behavior.
sed -n '258,340p' controller/channel_upstream_update.go
echo '---'
sed -n '1,140p' service/codex_credential_refresh.go
echo '---'
sed -n '1,140p' service/codex_credential_refresh_task.go

Repository: QuantumNous/new-api

Length of output: 9134


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check how existing channels are represented when fetched from storage / cache, and whether FetchModels ever receives them.
sed -n '1,120p' model/channel.go
echo '---'
sed -n '220,320p' model/channel_cache.go
echo '---'
sed -n '920,980p' controller/channel.go

Repository: QuantumNous/new-api

Length of output: 9448


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '258,340p' controller/channel_upstream_update.go

Repository: QuantumNous/new-api

Length of output: 2672


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "func parseCodexOAuthKey|type CodexOAuthKey|MultiKey" service/codex_credential_refresh.go service/codex_credential_refresh_task.go service -S
sed -n '1,120p' service/codex_credential_refresh.go

Repository: QuantumNous/new-api

Length of output: 3875


Propagate ChannelInfo.IsMultiKey into FetchModels

FetchModels builds a fresh model.Channel with only Type, Key, and BaseURL, so ChannelInfo.IsMultiKey is always false here. That makes the Codex guard in service/codex_channel_models.go#L19-L21 unreachable and routes multi-key requests into parseCodexOAuthKey instead of the intended error. Copy the existing channel info into this request-scoped channel before fetching models.

📍 Affects 2 files
  • controller/channel.go#L1183-L1188 (this comment)
  • service/codex_channel_models.go#L19-L21
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/channel.go` around lines 1183 - 1188, FetchModels in
controller/channel.go must preserve ChannelInfo.IsMultiKey when constructing the
request-scoped model.Channel; copy the existing channel info into that instance
before calling fetchChannelUpstreamModelIDs. This enables the Codex guard in
service/codex_channel_models.go lines 19-21; no direct change is required there.

Comment on lines +27 to +39
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

clientVersion, err := GetLatestCodexClientVersion(ctx, client)
if err != nil {
return nil, fmt.Errorf("failed to get Codex client version: %w", err)
}

baseURL := channel.GetBaseURL()
if baseURL == "" {
baseURL = constant.ChannelBaseURLs[constant.ChannelTypeCodex]
}
return fetchCodexChannelModels(ctx, channel, baseURL, client, clientVersion)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Single 20s timeout shared across up to 4 sequential upstream calls.

The same ctx (20s budget) covers GetLatestCodexClientVersion here and, in the caller chain, FetchCodexModels, a possible RefreshCodexChannelCredential, and a retry FetchCodexModels. A slow GitHub lookup (cache miss) leaves little budget for the actual Codex API round trips, increasing spurious timeout failures on an otherwise healthy upstream.

Consider a longer overall budget or per-call timeouts (e.g. separate contexts for the version lookup vs. the model fetch/refresh/retry sequence).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/codex_channel_models.go` around lines 27 - 39, The single 20-second
context in the Codex model-fetch flow is shared by the version lookup and
subsequent model/credential calls. Update the context handling around
GetLatestCodexClientVersion and fetchCodexChannelModels to give the version
lookup its own timeout or otherwise preserve sufficient timeout budget for the
model fetch, credential refresh, and retry sequence; keep cancellation and
existing error propagation intact.

Comment on lines +81 to +89
modelVariants := make([]string, 0, len(models)*2)
modelVariants = append(modelVariants, models...)
for _, modelName := range models {
if modelName == "codex-auto-review" {
continue
}
modelVariants = append(modelVariants, ratio_setting.WithCompactModelSuffix(modelName))
}
return modelVariants, nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Duplicate model entries possible: reuse WithCompactModelVariants instead of hand-rolled suffixing.

Unlike relay/channel/codex/constants.go, this loop appends WithCompactModelSuffix(modelName) for every model without checking whether that suffixed name is already present in models (upstream may naturally return both a base and its compact-suffixed slug). That produces duplicate entries in the returned list.

🐛 Proposed fix: reuse the shared, deduping helper
-	modelVariants := make([]string, 0, len(models)*2)
-	modelVariants = append(modelVariants, models...)
-	for _, modelName := range models {
-		if modelName == "codex-auto-review" {
-			continue
-		}
-		modelVariants = append(modelVariants, ratio_setting.WithCompactModelSuffix(modelName))
-	}
-	return modelVariants, nil
+	modelVariants := slices.DeleteFunc(
+		ratio_setting.WithCompactModelVariants(models),
+		func(modelName string) bool {
+			return modelName == ratio_setting.WithCompactModelSuffix("codex-auto-review")
+		},
+	)
+	return modelVariants, nil

(requires adding "slices" to imports, mirroring relay/channel/codex/constants.go)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
modelVariants := make([]string, 0, len(models)*2)
modelVariants = append(modelVariants, models...)
for _, modelName := range models {
if modelName == "codex-auto-review" {
continue
}
modelVariants = append(modelVariants, ratio_setting.WithCompactModelSuffix(modelName))
}
return modelVariants, nil
modelVariants := slices.DeleteFunc(
ratio_setting.WithCompactModelVariants(models),
func(modelName string) bool {
return modelName == ratio_setting.WithCompactModelSuffix("codex-auto-review")
},
)
return modelVariants, nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/codex_channel_models.go` around lines 81 - 89, Update the model
variant construction to reuse the shared deduping WithCompactModelVariants
helper, adding the slices import if required by that helper’s established usage.
Remove the hand-rolled suffix loop around modelVariants while preserving the
exclusion of codex-auto-review and preventing duplicates when models already
contain compact-suffixed names.

Comment thread service/codex_models.go
Comment on lines +134 to +141
req, err := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL.String(), nil)
if err != nil {
return 0, nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("ChatGPT-Account-Id", accountID)
req.Header.Set("User-Agent", "codex-cli/"+clientVersion)
req.Header.Set("Accept", "application/json")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant file and nearby version logic.
git ls-files service/codex_models.go
wc -l service/codex_models.go
cat -n service/codex_models.go | sed -n '1,220p'

printf '\n--- search for codex headers/UA/originator ---\n'
rg -n 'originator|User-Agent|codex-cli|codex_cli_rs|ChatGPT-Account-Id|backend-api/codex' -S .

printf '\n--- search for version fields from GitHub releases ---\n'
rg -n 'tag_name|release\.Name|release\.TagName|clientVersion|fetchLatestCodexClientVersion' -S service .

Repository: QuantumNous/new-api

Length of output: 21046


🌐 Web query:

openai codex backend originator User-Agent codex_cli_rs /backend-api/codex/models 403

💡 Result:

The originator header codex_cli_rs and the User-Agent associated with it are part of the internal architecture of the OpenAI Codex CLI and its associated Rust-based components (codex-rs) [1][2][3]. The string codex_cli_rs is a hardcoded default value for the Originator HTTP header, which is used by OpenAI's backend-api/codex/models and other endpoints to identify the client making the request, facilitate enterprise compliance, and manage model availability [1][2][4]. A 403 Forbidden error when accessing /backend-api/codex/models with this header typically indicates an authorization or access restriction issue [5]. Common causes include: 1. Authentication Failures: The request may lack a valid or active authentication token. If the underlying session or API key is invalid, expired, or unauthorized to access the specific model registry endpoint, the server returns a 403 or 401 error [5]. 2. Client Identity Mismatches: The backend may be rejecting requests that identify as codex_cli_rs if the environment or user account is not permitted to use the CLI tool or if the client version is deemed incompatible [6][7]. 3. Server-Side Filtering: As an internal API, /backend-api/codex/models often enforces strict access controls [2][8]. Requests might be blocked if they originate from unauthorized IP addresses, lack required internal headers (such as specific residency or compliance headers), or originate from non-official client implementations [1][2][6]. For users encountering this error while using third-party tools or custom clients, it often stems from attempting to call an internal-only OpenAI endpoint that expects a specific context (like a logged-in session) that a simple script or unofficial client cannot provide [6][9]. Workarounds often involve using authenticated proxies or ensuring the client sends the correct, expected headers and authentication state [6][9][8].

Citations:


🌐 Web query:

openai codex default_client.rs originator user-agent codex_cli_rs

💡 Result:

In the OpenAI Codex codebase, default_client.rs is a source file responsible for defining a default HTTP client used for making requests [1][2][3]. This module manages essential metadata for requests, specifically the originator and User-Agent headers, to ensure that the backend can identify the originating client (e.g., CLI, VSCode extension, or application server) for purposes like compliance, analytics, and routing [1][4]. The codex_cli_rs value serves as the default originator string [1][4]. It functions as a logical identifier for the client making the request [5]. While codex_cli_rs is the default, the system allows for the originator to be set or overridden through mechanisms such as environment variables (e.g., CODEX_INTERNAL_ORIGINATOR_OVERRIDE) or via explicit calls to set_default_originator() at runtime, which locks in the value as an immutable singleton for the process [4]. The module also constructs a detailed User-Agent string, which typically includes the originator value, the package version, and OS-specific information (such as type, version, and architecture), along with any additional optional suffixes [1]. Recent structural changes in the codebase have included moving shared HTTP transport logic into dedicated http-client modules [3].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read only the implementation around the review target and the version fetcher.
sed -n '1,220p' service/codex_models.go

printf '\n--- direct symbol search around version fetch ---\n'
rg -n 'fetchLatestCodexClientVersion|release\.Name|release\.TagName|NewRequestWithContext|originator|User-Agent|codex-cli|codex_cli_rs' service/codex_models.go

Repository: QuantumNous/new-api

Length of output: 5400


🌐 Web query:

site:github.com openai codex default_client.rs originator codex_cli_rs User-Agent

💡 Result:

In the OpenAI Codex codebase, default_client.rs defines the standard HTTP client configuration used across various Codex services (such as the CLI, auth modules, and servers) [1][2][3]. The DEFAULT_ORIGINATOR constant is explicitly set to "codex_cli_rs", which serves as a default identifier for the client in internal API requests [1][4]. The User-Agent string is programmatically constructed using this originator and the application version [4]. Specifically: 1. Originator Header: By default, the originator header is set to codex_cli_rs [1][4]. The OpenAI Codex backend uses this header (and the User-Agent prefix) to identify and whitelist first-party clients, such as the Codex CLI, VS Code extension, and SDKs [5][6][7]. 2. User-Agent Construction: The User-Agent typically follows a pattern starting with {originator}/ (e.g., codex_cli_rs/0.0.1) [4][8]. Internal utilities like get_codex_user_agent() are used to generate this string, ensuring that request traffic can be properly categorized and validated by the backend [5][4]. 3. Overrides: While codex_cli_rs is the default, the originator can be overridden in certain contexts, such as via the CODEX_INTERNAL_ORIGINATOR_OVERRIDE environment variable or by explicitly calling a setter (like set_default_originator()) during application boot [1][7]. Note that recent architectural changes have migrated some of these utilities into a consolidated codex-http-client crate [2][9].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the Codex adaptor and any request-header plumbing that might already set originator/User-Agent.
sed -n '120,220p' relay/channel/codex/adaptor.go

printf '\n--- request header override plumbing ---\n'
rg -n 'RuntimeHeadersOverride|originator|user-agent|User-Agent' relay/common relay/channel service -S

printf '\n--- caller chain for FetchCodexModels ---\n'
sed -n '1,140p' service/codex_channel_models.go

Repository: QuantumNous/new-api

Length of output: 10664


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '120,220p' relay/channel/codex/adaptor.go

printf '\n---\n'
sed -n '1,140p' service/codex_channel_models.go

printf '\n---\n'
rg -n 'RuntimeHeadersOverride|originator|user-agent|User-Agent' relay/common relay/channel service -S

Repository: QuantumNous/new-api

Length of output: 10589


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the exact originator setup in the Codex channel adaptor.
cat -n relay/channel/codex/adaptor.go | sed -n '168,190p'

Repository: QuantumNous/new-api

Length of output: 1060


Match the Codex CLI headers
service/codex_models.go:134-141 should send originator: codex_cli_rs and User-Agent: codex_cli_rs/<version> here; codex-cli/<version> plus no originator doesn’t match the Codex client identity expected by this endpoint.

Proposed fix
 req.Header.Set("Authorization", "Bearer "+accessToken)
 req.Header.Set("ChatGPT-Account-Id", accountID)
-req.Header.Set("User-Agent", "codex-cli/"+clientVersion)
+req.Header.Set("originator", "codex_cli_rs")
+req.Header.Set("User-Agent", "codex_cli_rs/"+clientVersion)
 req.Header.Set("Accept", "application/json")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
req, err := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL.String(), nil)
if err != nil {
return 0, nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("ChatGPT-Account-Id", accountID)
req.Header.Set("User-Agent", "codex-cli/"+clientVersion)
req.Header.Set("Accept", "application/json")
req, err := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL.String(), nil)
if err != nil {
return 0, nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("ChatGPT-Account-Id", accountID)
req.Header.Set("originator", "codex_cli_rs")
req.Header.Set("User-Agent", "codex_cli_rs/"+clientVersion)
req.Header.Set("Accept", "application/json")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/codex_models.go` around lines 134 - 141, Update the request headers
configured after http.NewRequestWithContext in the models request: add the
originator header with value codex_cli_rs and change the User-Agent prefix from
codex-cli/ to codex_cli_rs/. Preserve the existing Authorization, account ID,
and Accept headers.

@CloudWaddie

Copy link
Copy Markdown

lgtm

@Calcium-Ion
Calcium-Ion merged commit 57746fc into QuantumNous:main Jul 18, 2026
fux-dev pushed a commit to fux-dev/new-api that referenced this pull request Jul 19, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
yiranxiaohui added a commit to yiranxiaohui/new-api that referenced this pull request Jul 25, 2026
Sync 14 upstream commits. The dominant change is structural: upstream
promoted the frontend from web/default to the web/ root and deleted the
classic theme entirely, so most of the diff is renames and deletions.

Notable upstream work:
- refactor(auth): stateless dashboard tokens replacing sessions (QuantumNous#6329)
- feat(channel): upstream model discovery for Codex and advanced custom
  channels (QuantumNous#6184, QuantumNous#5971)
- fix: CAS status update prevents duplicate suno task refunds (QuantumNous#6074)
- fix: no duplicate tool calls in Responses-to-Chat streaming (QuantumNous#6225)

Fork-side resolutions:
- Drop the classic theme, following upstream. electron/ and the
  release/electron-build workflows stay deleted as this fork already
  removed them; GHCR publishing continues via docker-build.yml.
- UserBase keeps the fork's per-user Ratio alongside upstream's new Role,
  AuthVersion and CacheSchema fields. GetUserCache adopts upstream's
  cache-population path, which returns ToBaseUser() and so still carries
  Ratio.
- web-router keeps the fork's dynamic index injector (SystemName/Logo
  templating) on top of upstream's renamed frontendFS. serveIndex collapses
  to the single-frontend WebAssets now that classic is gone.
- Restore the fork's invoices feature (5 files), which git's rename
  detection dropped during the web/default -> web/ move, and re-register
  its route in routeTree.gen.ts.

Backend builds and the full Go test suite passes. The frontend is not yet
type-checked or built locally.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Happy <[email protected]>
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
lizhongyi1209 pushed a commit to lizhongyi1209/new-api that referenced this pull request Jul 28, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
Jaykebc1 added a commit to AccelsRouter/AccelsRouter that referenced this pull request Jul 30, 2026
Bring aurora to parity with three rc.22 web/ frontend changes, additively —
no aurora customizations altered:

- Keys: unlimited-quota API keys now surface used quota. New UnlimitedQuotaBadge
  (Unlimited badge + popover showing Used: <amount>) replaces the bare label in
  the key columns and the mobile card list (QuantumNous#6224).
- Channels: add Codex (type 57) to the fetch-upstream-models set (QuantumNous#6184);
  update the type-23 key prompt to mention TokenHub (QuantumNous#6232). Advanced-custom
  model fetch (QuantumNous#5971, type 58) intentionally NOT wired — aurora's custom
  advanced-custom editor has no model-list-route concept, so it needs a
  separate design discussion rather than a forced fit.
- Models: fix the model edit drawer resetting the form when system options
  refetch mid-edit — read modelSettings via a ref and key the load effect on a
  hasModelSettings boolean instead of the object reference.

i18n zh+en (zh-TW regenerated). aurora build + typecheck clean (6 pre-existing,
no new). Verified only aurora/ files changed.
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* fix(i18n): clarify Go regex and field passthrough copy

* feat(channel): support Codex upstream model discovery

* Revert "fix(i18n): clarify Go regex and field passthrough copy"

This reverts commit d63d797.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants