From 540454acecdf568a83d608a14635c8ffb0bbb5da Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 15:41:51 +0800 Subject: [PATCH] gateway: a turn on Codex's own ChatGPT sign-in is counted on that account, so the card's window holds see it (#2297, Edward4226, ggbdpq) codexUpstreamOn wrote the relay's ledger row as Provider: call.Provider ("openai") with no account. The account card's window holds key rows by codex + the sign-in's email (usage/window_holds.go), so every turn Codex relayed on its own sign-in was left out: the reporter's 7-day window read 2.3M/$0.31 where its calls were 19.0M/$64.26. codexServed (ggbdpq's patch) records such a relay as the codex account signed in to, or the account compactOn signed it with. An API-key call and a relay with no sign-in to name stay openai with no account. The Routing view's seat stays OpenAI. loggedAnswers (#1367) still leaves the relay out of a lead's answerers, as openai or as codex without a "host as email". Rows already written are not rewritten. On top of the patch: the relay goes out with the token Codex sent, which is the sign-in magpie reads only when it is the same ChatGPT account. A request whose chatgpt-account-id isn't the account auth.json here is signed in to (a Codex in WSL, another CODEX_HOME) stays openai rather than being put on this machine's account (provider.CodexSignedInAccount). TestCodexServedNamesTheAccountThatSigned is back and covers it. Run, go1.26.8 darwin/arm64, on 03eb0633a, -tags nogui -p 1: - go test ./internal/gateway -run 'TestCodex|TestSealedTaskFromChatGPTLead| TestLoggedAnswer|Lead': ok (48.8s). The four new tests -race -count=3: ok. - go test ./internal/provider -run 'TestSessionIdentit|TestCodex': ok; ./internal/usage -run 'Window|Hold': ok. - go vet ./internal/gateway ./internal/provider for darwin, GOOS=linux and GOOS=windows: clean. gofmt -l: nothing. Broken by hand, each red, then put back: - codexServed always "openai": TestCodexOwnModelRecordedAsCodexAccount (Provider:openai, no account) and TestCodexServedNamesTheAccountThatSigned. - chatgpt-account-id check dropped: TestCodexServedNamesTheAccountThatSigned ("another account's token: codex me@example.com"). - loggedAnswers back to provider == "openai" only: TestCodexOwnModelRecordedAsCodexAccount and TestCodexOwnRelayAnswersNoLead ("own sign-in answered a lead"). ggbdpq's own record (Windows, 38d25fe3/1d61458b on 01c41e8b): the same tests red with codex_backend.go reverted, green after; -race -count=5; vet/build for windows, linux, darwin. Not run: the full suite, GUI, a real Codex sign-in. Full suite: SUITE_LINE Co-authored-by: ggbdpq --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/codex_backend.go | 43 ++++++- internal/gateway/codex_backend_test.go | 169 +++++++++++++++++++++++++ internal/provider/session_identity.go | 12 ++ 4 files changed, 222 insertions(+), 4 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ce5494290..f52c1b083 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -98,7 +98,7 @@ recorded as a prediction failure (`noPrediction`). ## Constraints and failure behavior - A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another. -- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. +- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is. - Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing. The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 57ccc166d..e6bac814f 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -339,7 +339,11 @@ type loggedAnswer struct { // remembered (#1367). A call refused or failed answered nothing, a title // isn't the conversation's own turn, and Codex's own sign-in (the ChatGPT // backend, relayed as it came) is no provider here: a lead it answered is -// told of as one sealed by the ChatGPT backend. +// told of as one sealed by the ChatGPT backend. That relay is a row whose +// provider is openai (one written before it named the account, or a call +// sent with an API key) or codex with the API host alone. A row an account +// answered names that account in Host ("host as email", provider.Where) +// and still counts. func loggedAnswers(convs ...string) []loggedAnswer { convs = slices.DeleteFunc(slices.Clone(convs), func(c string) bool { return strings.TrimSpace(c) == "" }) if len(convs) == 0 { @@ -350,7 +354,10 @@ func loggedAnswers(convs ...string) []loggedAnswer { if r.Provider == "" || r.Provider == "magpie" || r.IsRejected() || r.IsReported() || r.Status <= 0 || r.Status >= 400 || r.Computer != "" || isTitleKind(r.Kind) { return } - if r.Provider == "openai" && strings.HasPrefix(r.Endpoint, CodexPath) { + // ponytail: host " as " is provider.Where. A relay that starts + // writing Host that way would be counted as a lead's answerer. + ownRelay := r.Provider == "openai" || (r.Provider == "codex" && !strings.Contains(r.Host, " as ")) + if ownRelay && strings.HasPrefix(r.Endpoint, CodexPath) { return // Codex's own sign-in } if !slices.Contains(convs, r.NativeSession) && !slices.Contains(convs, r.Session) { @@ -977,7 +984,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output) s.record(call) - rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Provider: call.Provider, Host: provider.HostOf(base), Model: call.Model, + servedProvider, servedAccount := codexServed(base, r.Header, on) + rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, + Provider: servedProvider, Host: provider.HostOf(base), ProviderAccount: servedAccount, Model: call.Model, Requested: call.Model, Served: served, Input: uu.Input, Output: uu.Output, CacheRead: uu.CacheRead, CacheWrite: uu.CacheWrite, Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, @@ -988,6 +997,34 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st appendUsage(r, rec) } +// codexServed is who a relay through codexUpstreamOn is recorded as. +// Codex's own ChatGPT sign-in is the codex account, and a compaction +// signed by another of its accounts (compactOn) is that account, so the +// account card's window counts the call. A call sent to OpenAI's API +// with Codex's key stays openai with no account. With no sign-in to +// name, or a request whose chatgpt-account-id isn't the sign-in's, it +// stays openai too, rather than a codex row that names the wrong account. +// Rows already written are not rewritten. +func codexServed(base string, h http.Header, on *provider.Provider) (id, account string) { + if base != provider.CodexBase || apiKey(h) { + return "openai", "" + } + if on != nil && on.Account != nil && on.Account.User != "" { + return on.ID, on.Account.User + } + // the token went out as Codex sent it: it is the sign-in magpie reads + // only when it names the same ChatGPT account. A Codex in WSL, or + // under another CODEX_HOME, signs with its own, which isn't named here + if acct := h.Get("chatgpt-account-id"); acct != "" && acct != provider.CodexSignedInAccount() { + return "openai", "" + } + p, err := provider.Find("codex") + if err != nil || p.Account == nil || p.Account.User == "" { + return "openai", "" + } + return p.ID, p.Account.User +} + // unreadableItem is the item OpenAI's refusal names: sealed content it // can't verify, or an id it doesn't have ("Item with id 'rs_…' not found"). var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`) diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go index 0daee5c51..781a0d17f 100644 --- a/internal/gateway/codex_backend_test.go +++ b/internal/gateway/codex_backend_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strconv" "strings" "testing" "time" @@ -80,6 +81,174 @@ func TestCodexOwnModelPassesThrough(t *testing.T) { } } +// codexChatGPTAuth signs this test's Codex in to a synthetic ChatGPT +// account. CODEX_HOME is the only auth.json it reads. +func codexChatGPTAuth(t *testing.T, email string) { + t.Helper() + dir := filepath.Join(t.TempDir(), "codex-home") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("CODEX_HOME", dir) + claims, err := json.Marshal(map[string]any{"email": email}) + if err != nil { + t.Fatal(err) + } + exp, err := json.Marshal(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}) + if err != nil { + t.Fatal(err) + } + token := func(payload []byte) string { + return "h." + base64.RawURLEncoding.EncodeToString(payload) + ".s" + } + auth, err := json.Marshal(map[string]any{ + "auth_mode": "chatgpt", + "tokens": map[string]string{ + "id_token": token(claims), + "access_token": token(exp), + "refresh_token": "rt-synthetic", + "account_id": "acct-synthetic", + }, + }) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "auth.json"), auth, 0o600); err != nil { + t.Fatal(err) + } + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) +} + +// A turn relayed on Codex's own ChatGPT sign-in is that codex account's +// in the ledger. Recorded as openai with no account, the card's window +// (keyed codex + the email) never sees it. The Routing view still calls +// the seat openai, and the row is still not a lead's answerer (#1367). +func TestCodexOwnModelRecordedAsCodexAccount(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`)) + }) + codexChatGPTAuth(t, "me@example.com") + s := New() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("session_id", "lead-own") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + u := usage.Load(time.Time{}) + if len(u) != 1 || u[0].Provider != "codex" || u[0].ProviderAccount != "me@example.com" || u[0].Input != 9 || u[0].Output != 2 { + t.Fatalf("usage %+v", u) + } + if strings.Contains(u[0].Host, " as ") { + t.Fatalf("relay host names an account, so it would count as a routed answer: %q", u[0].Host) + } + if a := loggedAnswers("lead-own"); len(a) != 0 { + t.Fatalf("own sign-in answered a lead: %+v", a) + } + st := s.Trace(t.Context(), 0, 0) + if len(st.Routes) != 1 || len(st.Routes[0].Usage) != 1 || st.Routes[0].Usage[0].Provider != "openai" { + t.Fatalf("routing view %+v", st.Routes) + } +} + +// An API-key call stays openai with no account, even while a ChatGPT +// sign-in is on disk: that spend is not the subscription card's. +func TestCodexAPIKeyRecordedAsOpenAI(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":4,"output_tokens":1}}}`)) + })) + t.Cleanup(up.Close) + was := codexAPIBase + codexAPIBase = up.URL + "/v1" + t.Cleanup(func() { codexAPIBase = was }) + codexChatGPTAuth(t, "me@example.com") + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`)) + req.Header.Set("Authorization", "Bearer sk-synthetic") + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + u := usage.Load(time.Time{}) + if len(u) != 1 || u[0].Provider != "openai" || u[0].ProviderAccount != "" || u[0].Input != 4 { + t.Fatalf("usage %+v", u) + } +} + +// A compaction signed by another account is that account's, not the +// sign-in the request would have relayed on. A request naming another +// ChatGPT account than the sign-in magpie reads (a Codex in WSL, or +// under another CODEX_HOME) is not put on that sign-in, and with no +// sign-in to name it stays openai, so no row is half a codex account. +func TestCodexServedNamesTheAccountThatSigned(t *testing.T) { + on := &provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "spare@example.com"}} + id, acct := codexServed(provider.CodexBase, http.Header{}, on) + if id != "codex" || acct != "spare@example.com" { + t.Fatalf("stand-in: %s %s", id, acct) + } + setHome(t, t.TempDir()) + codexChatGPTAuth(t, "me@example.com") + h := http.Header{} + h.Set("chatgpt-account-id", "acct-synthetic") + if id, acct = codexServed(provider.CodexBase, h, nil); id != "codex" || acct != "me@example.com" { + t.Fatalf("its own account: %s %s", id, acct) + } + h.Set("chatgpt-account-id", "acct-elsewhere") + if id, acct = codexServed(provider.CodexBase, h, nil); id != "openai" || acct != "" { + t.Fatalf("another account's token: %s %s", id, acct) + } + t.Setenv("CODEX_HOME", t.TempDir()) + provider.ForgetAccounts() + if id, acct = codexServed(provider.CodexBase, http.Header{}, nil); id != "openai" || acct != "" { + t.Fatalf("no sign-in: %s %s", id, acct) + } +} + +// Codex's own sign-in relay is not a lead's answerer, under the name it +// was logged by before (openai) or the codex account it is logged by now. +// A row an account answered — host "as email", or another provider, or +// /v1 — still is. One codex row is not counted twice. +func TestCodexOwnRelayAnswersNoLead(t *testing.T) { + setHome(t, t.TempDir()) + // usage.Path follows the first home a process reads; -count keeps + // writing there, so each run's sessions are its own. + stamp := strconv.FormatInt(time.Now().UnixNano(), 10) + now := time.Now() + row := func(name, prov, account, host, endpoint string) string { + t.Helper() + session := name + "-" + stamp + usage.Append(usage.Record{ + Time: now, Agent: "codex", Provider: prov, Host: host, ProviderAccount: account, + Model: "gpt-5.5", Input: 9, Output: 2, Status: 200, Endpoint: endpoint, Session: session, + }) + return session + } + relay := row("lead-relay", "openai", "", provider.HostOf(provider.CodexBase), CodexPath+"/responses") + row("lead-relay", "codex", "me@example.com", provider.HostOf(provider.CodexBase), CodexPath+"/responses") + if a := loggedAnswers(relay); len(a) != 0 { + t.Fatalf("own sign-in answered a lead: %+v", a) + } + routed := row("lead-routed", "codex", "me@example.com", "chatgpt.com as me@example.com", CodexPath+"/responses") + if a := loggedAnswers(routed); len(a) != 1 || a[0].provider != "codex" || a[0].who != "codex@me@example.com" { + t.Fatalf("routed account: %+v", a) + } + v1 := row("lead-v1", "codex", "me@example.com", "chatgpt.com as me@example.com", "/v1/responses") + if a := loggedAnswers(v1); len(a) != 1 || a[0].who != "codex@me@example.com" { + t.Fatalf("/v1 account: %+v", a) + } + other := row("lead-other", "sub2api", "", "relay.example.com", CodexPath+"/responses") + if a := loggedAnswers(other); len(a) != 1 || a[0].provider != "sub2api" { + t.Fatalf("relay: %+v", a) + } +} + // A turn on one of Codex's own models shows in the Routing view's live // trace, as those on magpie's do. func TestCodexOwnModelTraced(t *testing.T) { diff --git a/internal/provider/session_identity.go b/internal/provider/session_identity.go index 533ccb2f9..879bd733c 100644 --- a/internal/provider/session_identity.go +++ b/internal/provider/session_identity.go @@ -94,6 +94,18 @@ func codexSessionIdentity(b []byte) (SessionIdentity, bool) { UserID: cmp.Or(claimString(claims, "https://api.openai.com/auth", "chatgpt_user_id"), claimString(claims, "https://api.openai.com/auth", "user_id")), User: user}, id != "" && user != "" } +// CodexSignedInAccount is the ChatGPT account id (chatgpt-account-id) +// Codex's auth.json is signed in to now; "" when it is signed in to none, +// on an API key, or can't be read. +func CodexSignedInAccount() string { + b, err := readAccountFile(codexAuthPath()) + if err != nil { + return "" + } + id, _ := codexSessionIdentity(b) + return id.AccountID +} + func claudeSessionIdentity(b []byte) (SessionIdentity, bool) { var a struct { Account string `json:"accountUuid"`