diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ad2385d77..6130b06a9 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -252,7 +252,7 @@ recorded as a prediction failure (`noPrediction`). - An error's own status beats the words (#4855). A provider that already sent its 200 can only say what went wrong in an in-stream error frame — a plugin's runtime watching a clock, aborting at 285s and emitting `{"error":{…,"code":"upstream_timeout","status":504}}` — and the frame is relayed to the client as it came. The status it names on a member of the error object (`namedStatusOf`, a number 400–599, `status` first, Gemini's relays' `code`; a string code is not one) is what the failure fails and rests as, before `streamStatus` guesses one from the message's words, wherever the frame is read: a held stream's error event (`errOf` in `streamEvent`), a whole 200 body that is only an error (`errorReply`), a carried error's words (`carriedStatus`), and a reply already streaming, whose turn rests at the status the sniffer noted on the try (`namedStatusHeader`, kept from the client; `failedNamed`/`restAfterMarked`) — so a terse frame naming 429 rests as a rate limit, not `other` at a word-guessed 502, and the rest says "Gateway Timeout", not "OK". With no such member, a status the words name as one, "(HTTP 503)" or "(HTTP 503)" (`textStatus`, `httpSaid`), counts too, for a 429 or a 5xx only, since a 4xx a message quotes may be someone else's ("the image link answered (HTTP 404)"): wps-lingxi's AuditFailed and AIError frames name theirs that way (mycf_711). A reply already streaming when its frame came is booked at that status as well, in Routing and Usage, though the client's 200 went out. Words magpie wrote itself (`magpieSaid`: the loop guard's `loopGuardSaid`, `emptyReply`, `reloopedError`) and words saying the request is too long name no status, whatever members they carry: a LAN peer's loop guard frame carries 502 in its Gemini shape, and is no failure of the provider, so it neither rests the route nor is booked as one (`lateRests`). An error naming no status reads exactly as before. `TestRelayStreamErrorFrameSaysItsStatus`, `TestRelayStreamErrorFrameWithoutStatusAsBefore`, `TestRelayStreamErrorFrameNamesItsStatusInWords`, `TestNamedStatusOf` in [`stream_frame_status_test.go`](../../internal/gateway/stream_frame_status_test.go). - 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`; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (`failedRow` in `serve`, written once the next try begins): a Claude subscription run that failed after Anthropic's `message_start` had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; `relay` keeps the reply start's usage on a failure, `TestClaudeSubscriptionFailedTryKeepsItsTokens`). A try that failed before anything was billed has no record; `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. - A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`). -- 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; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way, on Codex's own sign-in (`codexUpstreamOn`) too, which before set only the route's `tier`, so a `/fast` turn there showed nothing (Anotiaww on X). The Routing page's request row shows a try's tier as a quiet tag beside the model (`fast` for `priority`, `Ultrafast`, `flex`; an in-flight row the route's asked tier), with the served tier in its title when the reply said another (`rowTier` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), `routing-service-tier.test.cjs`). 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). +- 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; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way, on Codex's own sign-in (`codexUpstreamOn`) too, which before set only the route's `tier`, so a `/fast` turn there showed nothing (Anotiaww on X). The Routing page's request row shows a try's tier as a quiet tag beside the model (`fast` for `priority`, `Ultrafast`, `flex`; an in-flight row the route's asked tier), with the served tier in its title when the reply said another (`rowTier` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), `routing-service-tier.test.cjs`). A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Through a Remote magpie the other magpie's word is taken (JackyFill on X: Codex → magpie1 → magpie2 → a ChatGPT account, Fast on in magpie2 alone, was logged `default` on magpie1): a try asked by another magpie (`magpieAsks`) says on its reply's header the tier it sent its vendor (`X-Magpie-Tier-Sent`, `none` for none) and, when that vendor's `auto`/`default` tell nothing, `X-Magpie-Tier-Unsaid: 1` (`stampTier`, from the holdWriter's `writeHeader`). The asking magpie takes them from a remote magpie's reply alone (`tierThere` in `heardReply`; a vendor's `X-Magpie-` headers are never passed) and records them as its try's `tier_sent` (`sentThere`) and an unknown `tier_served` (`servedThere`); a chain of magpies passes the farthest one's on. A reply whose headers a keepalive sent before the try answered carries neither, and the asking magpie keeps its own record. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "/" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`. - Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`. diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index baf108f46..3362c4f1e 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -2749,6 +2749,9 @@ type holdWriter struct { // upstreamKeys are the headers of the vendor's reply heardUpstream put // in header (#4145) upstreamKeys []string + // tierStamp, on a try for another magpie, says on the reply's header + // the tier the request went out at (stampTier), once it has a status + tierStamp func(http.Header) // over, when another candidate stands behind the try, reads what // passes before its answer begins for a refusal to hand to the next @@ -2802,6 +2805,9 @@ func (h *holdWriter) writeHeader(code int) { return } h.status = code + if h.tierStamp != nil { + h.tierStamp(h.header) + } if h.hold && code >= 400 { return } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 09c9ce488..e136a0e87 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4203,6 +4203,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro ctx = withFallback(ctx) } hw.stop = stop + if magpieAsks(r) { + // another magpie asked: its log is told the tier this + // one sent (stampTier) + p := c.p + hw.tierStamp = func(h http.Header) { stampTier(h, p, at.tier) } + } if sentBy(c.p) == "claude" { // the entry point its Claude Code run takes, for the // try's row (Try.Entry) @@ -4417,6 +4423,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro wentAt = at.effort } wentTier = at.tier + if t, ok := hw.sentThere(); ok && c.p.IsRemoteMagpie() { + // the tier the remote magpie sent its vendor (stampTier) + wentTier = t + } ended = time.Now() try := Try{ID: c.rest, Model: c.model, Effort: wentAt, Picked: picked, Fixed: fixed, RuleEffort: ruled, MappedFrom: mappedFrom, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: ended.Sub(began).Milliseconds(), Error: call.Error, Queued: queued, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Pin: c.p.ClinePassAsked(c.model), Tier: wentTier, TierServed: call.Usage.Tier, Auto: autoPicked(), @@ -5673,7 +5683,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P liveOfInflight(inflightOf(r.Context())).routed(p.ID, unprefixed(model)) // the tier the reply said, unknown where the vendor's word tells // nothing (servedTierAt) - defer func() { call.Usage.Tier = servedTierAt(p.VendorHost(), call.Usage.Tier) }() + defer func() { call.Usage.Tier = servedThere(w, p, servedTierAt(p.VendorHost(), call.Usage.Tier)) }() // Normalize for the actual destination, separately on each fallback. // Native ChatGPT accounts accept standalone tool outputs themselves. if from == provider.Responses && (p.Account == nil || p.Account.Agent != "codex") { diff --git a/internal/gateway/remote_tier_test.go b/internal/gateway/remote_tier_test.go new file mode 100644 index 000000000..acd1574fc --- /dev/null +++ b/internal/gateway/remote_tier_test.go @@ -0,0 +1,112 @@ +package gateway + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// JackyFill on X: Codex → magpie1 → (Remote magpie) → magpie2 → a ChatGPT +// account, Fast on in magpie2 alone (here its gateway key's tier). +// magpie1's log said "default", the ChatGPT backend's word in the body +// that tells nothing, and nothing of the priority magpie2 sent. It now +// records what magpie2 sent its vendor, and the served tier unknown, as +// magpie2 does; a request magpie2 sends at none says none. +func TestRemoteMagpieTierRecorded(t *testing.T) { + tried := tierAccounts(t, nil, nil, func(string) (string, string) { return "auto", "default" }) + to, _ := url.Parse(provider.CodexBase) + old := provider.CodexBase + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = old }) + cfg := settings.Load() + cfg.LAN = true + if err := settings.Save(cfg); err != nil { + t.Fatal(err) + } + secret, err := access.Update("add-key", access.Change{Name: "Remote"}) + if err != nil { + t.Fatal(err) + } + keys, _ := access.List() + var keyID string + for _, k := range keys { + if k.Name == "Remote" { + keyID = k.ID + } + } + + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + if r.URL.Host == "chatgpt.com" { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + } + return http.DefaultTransport.RoundTrip(r) + })} + h := s.Handler() + there := httptest.NewServer(h) + t.Cleanup(there.Close) + id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Key: secret, Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(there.URL, "http://")}) + if err != nil { + t.Fatal(err) + } + office, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + if _, err := office.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + + for _, c := range []struct{ set, want string }{{"fast", "priority"}, {"standard", ""}} { + if _, err := access.Update("tier-key", access.Change{Key: keyID, ServiceTier: c.set}); err != nil { + t.Fatal(err) + } + model := id + "/codex/gpt-6-luna" + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"`+model+`","stream":true,"input":"ping"}`))) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", c.set, rec.Code, rec.Body) + } + if got := tried(); len(got) == 0 || got[len(got)-1] != "acct-plus:"+c.want { + t.Fatalf("%s: backend asked %v, want acct-plus:%s", c.set, got, c.want) + } + var here *usage.Record + recs := usage.Load(time.Time{}) + for i := len(recs) - 1; i >= 0; i-- { + if recs[i].Provider == id { + here = &recs[i] + break + } + } + if here == nil { + t.Fatalf("%s: no record of the request here: %+v", c.set, recs) + } + if here.TierSent != c.want || here.TierServed != "" { + t.Errorf("%s: recorded here sent %q served %q, want sent %q served unknown", c.set, here.TierSent, here.TierServed, c.want) + } + s.trace.mu.Lock() + var tr *Route + for _, r := range s.trace.routes { + if r.Model == model { + tr = r + } + } + var try Try + if tr != nil && len(tr.Tries) > 0 { + try = tr.Tries[len(tr.Tries)-1] + } + s.trace.mu.Unlock() + if tr == nil || try.Tier != c.want || try.TierServed != "" { + t.Errorf("%s: route's try %+v, want tier %q", c.set, try, c.want) + } + } +} diff --git a/internal/gateway/reply_headers.go b/internal/gateway/reply_headers.go index 9d960fc4b..9659ae062 100644 --- a/internal/gateway/reply_headers.go +++ b/internal/gateway/reply_headers.go @@ -41,7 +41,7 @@ func heardReply(ctx context.Context, p provider.Provider, res *http.Response) { if !ok || res == nil || s.id != p.ID { return } - s.put(p.PassedReplyHeaders(res.Header)) + s.put(tierThere(p, res.Header, p.PassedReplyHeaders(res.Header))) } // passReplyHeaders puts what the vendor's reply res passes on into dst, diff --git a/internal/gateway/tier_record.go b/internal/gateway/tier_record.go index b2f03008b..882b21457 100644 --- a/internal/gateway/tier_record.go +++ b/internal/gateway/tier_record.go @@ -8,8 +8,10 @@ package gateway // doesn't offer Ultrafast is asked for priority in its place. import ( + "cmp" "context" "encoding/json" + "net/http" "strings" "github.com/tidwall/gjson" @@ -118,3 +120,88 @@ func upstreamTier(b []byte) string { } return "" } + +// A reply passed back to another magpie (a Remote magpie provider there) +// says the tier the request went to its vendor at here, and whether the +// vendor's own word in the body tells anything. That magpie records them +// as its own: its request goes to this one at the tier it asked, this +// one's Fast or a key's tier may send another, and the body's +// "default" from the ChatGPT backend is no tier at all (JackyFill on X: a +// Codex turn sent as Fast by the remote magpie was recorded "default" on +// the magpie Codex asked). +const ( + // tierSentHeader is the tier the reply's request went to the vendor + // at, as the log keeps it (Record.TierSent); tierNone for none + tierSentHeader = "X-Magpie-Tier-Sent" + // tierUnsaidHeader is "1" when the reply's "auto"/"default" tell + // nothing (servedTierAt) + tierUnsaidHeader = "X-Magpie-Tier-Unsaid" + tierNone = "none" +) + +// stampTier says on h, a try's reply header to another magpie, the tier +// sent went to p at, and whether p's "auto"/"default" tell nothing. Those +// p is a remote magpie that said them stand: they are its vendor's. +func stampTier(h http.Header, p provider.Provider, sent string) { + if !p.IsRemoteMagpie() || h.Get(tierSentHeader) == "" { + h.Set(tierSentHeader, cmp.Or(sent, tierNone)) + } + if !p.IsRemoteMagpie() { + h.Del(tierUnsaidHeader) + } + if servedTierAt(p.VendorHost(), "default") == "" { + h.Set(tierUnsaidHeader, "1") + } +} + +// tierThere adds to passed, the headers of a remote magpie's reply that go +// to the try, what it said of its tier (stampTier). Only a remote magpie's +// are read: a vendor's X-Magpie- headers are never taken. +func tierThere(p provider.Provider, got, passed http.Header) http.Header { + if !p.IsRemoteMagpie() { + return passed + } + sent, unsaid := tierWord(got.Get(tierSentHeader)), got.Get(tierUnsaidHeader) == "1" + if sent == "" && !unsaid { + return passed + } + if passed == nil { + passed = http.Header{} + } + if sent != "" { + passed.Set(tierSentHeader, sent) + } + if unsaid { + passed.Set(tierUnsaidHeader, "1") + } + return passed +} + +// sentThere is the tier a remote magpie's reply says it sent its vendor +// (tierThere); ok false when it said none, as a magpie before it didn't. +func (h *holdWriter) sentThere() (string, bool) { + h.mu.Lock() + defer h.mu.Unlock() + v := h.header.Get(tierSentHeader) + if v == tierNone { + return "", true + } + return v, v != "" +} + +// servedThere is t, the tier a reply from p said, unknown ("") where p is +// a remote magpie whose vendor's "auto"/"default" tell nothing. +func servedThere(w http.ResponseWriter, p provider.Provider, t string) string { + if t != "auto" && t != "default" || !p.IsRemoteMagpie() { + return t + } + if hw, ok := w.(*holdWriter); ok { + hw.mu.Lock() + unsaid := hw.header.Get(tierUnsaidHeader) == "1" + hw.mu.Unlock() + if unsaid { + return "" + } + } + return t +}