codex: an account with bought credits goes on on them, heard as Codex hears them
123xtv03k on X (v0.1.4233): Codex alone goes on on an account's bought
credits once its plan is used up; through magpie the account stopped.
Codex itself sends no opt-in for credits. It reads
x-codex-credits-has-credits, -unlimited and -balance from every reply,
the 429 included, and `credits` on the codex.rate_limits event
(parse_credits_snapshot; both bools required). magpie knew of credits
only from /wham/usage, read about once a minute, so the 429 that used a
window up was taken as out, and the rest lasted till the window renewed.
- heardCodexCredits reads the headers on every Codex reply (routed and
the relay's 429), codexEventCredits the event; an image limit's are
left out. provider.NoteCodexCredits marks the account's windows and
allowance on credits and clears Held, so Usage doesn't call it out.
- A rest taken for a used-up window before the credits were known is
lifted once they are, heard or read (provider.OnCredits, creditsKnown),
only when the account's "Use credits" is on.
- The relay's hold for an account on credits refused twice is at most
fallbackCooldown (1 minute), like the routed path's, not till reset.
- No header or flag is sent that Codex doesn't send.
Run (mote, at this head rebased on b466aa280; 79b10c5a9 since touches only LESSONS.md): go vet for darwin, linux
and windows of internal/provider and internal/gateway; go test -count=1
-timeout 45m ./internal/provider ./internal/gateway: ok (provider 137s, gateway 907s). gofmt -l
clean.
Broken by hand: without the heardCodexCredits calls, the OnCredits
registration and the hold clamp, every new gateway subtest but "says
none" goes red.
Not tried: a real account holding credits (the owner's hold none). The
Usage card's balance text still comes from /wham/usage only.
This commit is contained in:
@@ -299,7 +299,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`.
|
||||
- Least used first spends credits about to lapse first (kudi3699 on X, 11-12: a WorkBuddy account half through a pack ending in March, with check-in credits ending tomorrow, ranked by the whole pool's share and was never picked). `Allowance.Lapsing` is what a window loses at `RunsOut` (`RunsOutLeft` of `Of`, at most what is left) as points of the used share, in full when it is within a week and not at all past it (11-12, kudi3699 again: a fade across the week left a 20-credit check-in reward under the threshold); an amount not told is zero, never guessed. `routes.Seat.Lapsing` at 0.1 points or more (`urgent`) puts a seat with room ahead of the rest, the soonest `Lapse` first, then the share used as before; one at 90% or more is not helped. Any plugin whose usage window sends `runsOutAt` and `runsOut` gets it. `TestLeastUsedSpendsLapsingFirst`, `TestLeastUsedSpendsWorkBuddyCheckInCreditsAboutToLapse`, `TestAllowanceLapsing`.
|
||||
- A session's call to another model than its main conversation's goes to the key or account that main conversation is on (`withSession`, `Affinity.Why` `lead` with `LeadModel`; #5655, jerrychoi, and iamnil on Discord). Each model's conversation is kept under its own scope (`p.ID/model`), so Claude Desktop's own Sonnet calls beside an Opus chat (`desktop-beside`), Claude Code's auto mode classifier and a title were routed as sessions of their own: put by `leastHeld`, or by Smart's order once their cache was cold, on another account, they ran one session on two accounts at once and drained the second one's 5 hours. The main conversation is the session's largest stick (cache read plus written) under another scope by the session's own id, one a header names (`sessionNamed`: a conversation known only by its opening's hash has no session, since unrelated ones that open alike share it; no `|agent:`), answered within `heldFor`, holding at least `cacheWorth` (a main with nothing cached goes where its own next turn is sent), and it leads only while larger than the call's own, so the two never follow each other. It is followed for Why `first`, `gone`, `cold`, `no-cache`, `cache` and `session`, by the model routing put first (in a group, another member on that account is another model and is never picked), and only to one `readyForNew`. It is not followed mid-turn (a kept `Within`), under Strict, In turn, nor for a subagent (`withLead` does that), nor past a rest, a reserve, credits or a fallback routing put first. A call moved off its own cache writes it once where the session goes on reading it. The Routing page says so ("Put on {first}, where this session's {model} is…", `routing-affinity-lead.test.cjs`). `session_lead_test.go`.
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`.
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), or as Codex itself hears it on every reply, the 429 included (`x-codex-credits-has-credits`, `-unlimited` and `-balance`, both bools required, an image limit's left out; and `credits` on a `codex.rate_limits` event: `heardCodexCredits`, `codexEventCredits`, `provider.NoteCodexCredits`; 123xtv03k on X, 11-15: an account used up on its plan stopped where Codex alone went on on its bought credits), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews (the relay's hold too, `noteCodexHold`); a rest taken for a used-up window before its credits were known is lifted once they are, heard or read (`provider.OnCredits`, `creditsKnown`), and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsHeardOnTheRefusal`, `TestCodexCreditsKnownLiftsTheRest`, `TestCodexCreditsRead`, `TestNoteCodexCreditsKeepsThem`, `TestReadingTellsCreditsBought`, `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`.
|
||||
- A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits <account> last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`.
|
||||
- A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits <account> first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`.
|
||||
- A provider can be set to be used first (hzh_1119 on Discord: ChatGPT Pro and Business come with monthly API credit, to be spent on an OpenAI API key before the subscription where both serve a model). *Use first* on a provider row's right-click (GUI `provider/usefirst`, `provider.SetUseFirst`, `Provider.UseFirst`, copied onto its accounts by `accountSettings`) makes its keys and accounts `routes.Seat.Lead`, and Smart (`leadFirst`) puts those under the spent tier (`seatTier` below 2) ahead of every other seat it weighs, each side in Smart's own order. Without it an API key, which tells no allowance, goes after every account with room. It counts where Smart weighs several providers together: a model's found group (`auto/<model>`) or a user's group routed Smart; within one provider every seat shares it, so nothing changes. One resting is passed over as any is, so a 429 `insufficient_quota` (out of credit, a half-hour rest) or a failure moves the request on to the others. Free quota by expiry orders its paid seats with Smart and so honours it too; the other strategies don't read it. Affinity still keeps a conversation on the one that answered it. The Routing page says why (`Weighed.UseFirst`, `firstWhy`), and `behindWhy` doesn't call one behind it renewing later. `TestSmartLeadFirst`, `TestUseFirstLeadsTheGroup`, `use-first.test.cjs`.
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -31,6 +32,9 @@ type resetBackend struct {
|
||||
credits map[string]bool
|
||||
edge map[string]int
|
||||
fails map[string]int
|
||||
// sayCredits: replies say the account's credits as ChatGPT's do,
|
||||
// x-codex-credits-has-credits and -unlimited
|
||||
sayCredits bool
|
||||
}
|
||||
|
||||
func newResetBackend(t *testing.T, accounts ...string) *resetBackend {
|
||||
@@ -60,6 +64,10 @@ func newResetBackend(t *testing.T, accounts ...string) *resetBackend {
|
||||
if refused && b.credits[acct] {
|
||||
b.edge[acct]--
|
||||
}
|
||||
if b.sayCredits {
|
||||
w.Header().Set("x-codex-credits-has-credits", strconv.FormatBool(b.credits[acct]))
|
||||
w.Header().Set("x-codex-credits-unlimited", "false")
|
||||
}
|
||||
if refused {
|
||||
w.WriteHeader(429)
|
||||
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
|
||||
|
||||
@@ -1342,6 +1342,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
// row, to sign in again (#1793)
|
||||
noteSignIn(ctx, on.Account, req, res)
|
||||
}
|
||||
if rest == "/responses" && res.StatusCode == http.StatusTooManyRequests {
|
||||
if acct, ok := codexRelayedAccount(base, r.Header, on); ok {
|
||||
// what the refusal says of the account's credits, for
|
||||
// asking again on them below (heardCodexCredits)
|
||||
heardCodexCredits(acct, res.Header)
|
||||
}
|
||||
}
|
||||
if !creditsAsked && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests && relayOnCredits(on) {
|
||||
// the account holds credits and was refused as out of its
|
||||
// allowance: ChatGPT may turn away the turn that uses the
|
||||
@@ -1467,7 +1474,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
// its credits and resets looked at above, a 429 that names
|
||||
// when the account is back holds it till then (codexHolds)
|
||||
noteCodexHold(holdKey, res.StatusCode, res.Header, msg)
|
||||
noteCodexHold(holdKey, res.StatusCode, res.Header, msg, relayOnCredits(on))
|
||||
if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(r, body) {
|
||||
// still too busy once asked again: the fallbacks answer
|
||||
said := provider.APIError(msg, res.Status)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// heardUsage is creditsUsage for Codex accounts whose credits are known
|
||||
// only from what their replies say (noteCodexCredits) or set: their
|
||||
// /wham/usage reading tells none. It returns the set, by lower-cased user.
|
||||
func heardUsage(t *testing.T, used map[string]float64) *sync.Map {
|
||||
t.Helper()
|
||||
var heard sync.Map
|
||||
oldA, oldN := allowances, noteCodexCredits
|
||||
t.Cleanup(func() { allowances, noteCodexCredits = oldA, oldN })
|
||||
noteCodexCredits = func(agent, user string, on bool) { heard.Store(strings.ToLower(user), on) }
|
||||
allowances = func(string) map[string]provider.Allowance {
|
||||
out := map[string]provider.Allowance{}
|
||||
for u, n := range used {
|
||||
c, _ := heard.Load(strings.ToLower(u))
|
||||
on, _ := c.(bool)
|
||||
out[u] = provider.Allowance{
|
||||
{Used: n, Resets: time.Now().Add(2 * time.Hour), Span: 5 * time.Hour, Credits: on},
|
||||
{Used: n, Resets: time.Now().Add(3 * 24 * time.Hour), Span: 7 * 24 * time.Hour, Credits: on},
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return &heard
|
||||
}
|
||||
|
||||
// @123xtv03k on X: Codex by itself goes on on the credits an account
|
||||
// bought once its plan's allowance runs out; through magpie the account
|
||||
// was benched until its window renewed. ChatGPT says the credits on the
|
||||
// 429 itself (x-codex-credits-has-credits, as Codex reads them), and the
|
||||
// refused turn is asked again of the same account at once, as one known
|
||||
// from /wham/usage to hold credits is (TestCodexCreditsAskedAgainAtTheEdge).
|
||||
func TestCodexCreditsHeardOnTheRefusal(t *testing.T) {
|
||||
t.Run("routed", func(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
b := newResetBackend(t, "acct-1")
|
||||
b.credits["acct-1"], b.edge["acct-1"], b.sayCredits = true, 1, true
|
||||
heardUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20})
|
||||
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := New()
|
||||
code, body := resetPost(t, srv)
|
||||
if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != "acct-1,acct-1" {
|
||||
t.Fatalf("%d %s tried %s", code, body, tried)
|
||||
}
|
||||
if ts := triesOf(srv); len(ts) != 2 || !ts[0].Credits || ts[0].Rest != nil {
|
||||
t.Fatalf("traced %+v", ts)
|
||||
}
|
||||
})
|
||||
t.Run("relayed", func(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
b := newResetBackend(t, "acct-1")
|
||||
b.credits["acct-1"], b.edge["acct-1"], b.sayCredits = true, 1, true
|
||||
heardUsage(t, map[string]float64{"me@example.com": 100})
|
||||
code, body := resetPost(t, New())
|
||||
if tried, _ := b.seen(); code != 200 || !strings.Contains(body, "pong") || tried != "acct-1,acct-1" {
|
||||
t.Fatalf("%d %s tried %s", code, body, tried)
|
||||
}
|
||||
})
|
||||
t.Run("relayed, refused twice", func(t *testing.T) {
|
||||
// asked again on its credits and refused again: held a moment, as
|
||||
// the accounts loop rests one (fallbackCooldown), not till the
|
||||
// window renews two hours on
|
||||
codexSignedIn(t)
|
||||
b := newResetBackend(t, "acct-1")
|
||||
b.credits["acct-1"], b.edge["acct-1"], b.sayCredits = true, 2, true
|
||||
heardUsage(t, map[string]float64{"me@example.com": 100})
|
||||
if code, _ := resetPost(t, New()); code != 429 {
|
||||
t.Fatalf("refused twice: %d", code)
|
||||
}
|
||||
h, ok := codexHeld("me@example.com", time.Now())
|
||||
if ok && time.Until(h.until) > fallbackCooldown {
|
||||
t.Fatalf("held %v", time.Until(h.until).Round(time.Second))
|
||||
}
|
||||
})
|
||||
t.Run("says none", func(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
b := newResetBackend(t, "acct-1")
|
||||
b.sayCredits = true
|
||||
heardUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20})
|
||||
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := New()
|
||||
if code, _ := resetPost(t, srv); code != 200 {
|
||||
t.Fatalf("%d", code)
|
||||
}
|
||||
if tried, _ := b.seen(); tried != "acct-1,acct-2" {
|
||||
t.Fatalf("tried %s", tried)
|
||||
}
|
||||
if ts := triesOf(srv); len(ts) == 0 || ts[0].Credits || ts[0].Rest == nil || time.Until(ts[0].Rest.Until) < time.Hour {
|
||||
t.Fatalf("traced %+v", ts)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An account turned away as out of its allowance before magpie knew it
|
||||
// held credits — bought after the plan ran out, or its reading failed —
|
||||
// rested until its window renewed. Once a reply or a reading says it holds
|
||||
// them (provider.OnCredits), the rest is lifted and it is asked again at
|
||||
// once; so is the hold of Codex's own sign-in, relayed.
|
||||
func TestCodexCreditsKnownLiftsTheRest(t *testing.T) {
|
||||
t.Run("routed", func(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
b := newResetBackend(t, "acct-1")
|
||||
heard := heardUsage(t, map[string]float64{"me@example.com": 100, "spare@example.com": 20})
|
||||
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := New()
|
||||
if code, _ := resetPost(t, srv); code != 200 {
|
||||
t.Fatalf("%d", code)
|
||||
}
|
||||
if tried, _ := b.seen(); tried != "acct-1,acct-2" {
|
||||
t.Fatalf("tried %s", tried)
|
||||
}
|
||||
if ts := triesOf(srv); len(ts) == 0 || ts[0].Rest == nil || time.Until(ts[0].Rest.Until) < time.Hour {
|
||||
t.Fatalf("not rested till its window renews: %+v", ts)
|
||||
}
|
||||
// credits bought: the next reply or reading says so
|
||||
b.mu.Lock()
|
||||
b.tried, b.credits["acct-1"] = nil, true
|
||||
b.mu.Unlock()
|
||||
heard.Store("me@example.com", true)
|
||||
provider.NoteCodexCredits("codex", "me@example.com", false) // what another test left
|
||||
provider.NoteCodexCredits("codex", "me@example.com", true)
|
||||
if code, body := resetPost(t, srv); code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
if tried, _ := b.seen(); tried != "acct-1" {
|
||||
t.Fatalf("with its credits known, tried %s", tried)
|
||||
}
|
||||
})
|
||||
t.Run("relayed", func(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
b := newResetBackend(t, "acct-1")
|
||||
heard := heardUsage(t, map[string]float64{"me@example.com": 100})
|
||||
srv := New()
|
||||
if code, _ := resetPost(t, srv); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("%d", code)
|
||||
}
|
||||
if _, ok := codexHeld("me@example.com", time.Now()); !ok {
|
||||
t.Fatal("not held")
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.tried, b.credits["acct-1"] = nil, true
|
||||
b.mu.Unlock()
|
||||
heard.Store("me@example.com", true)
|
||||
provider.NoteCodexCredits("codex", "me@example.com", false) // what another test left
|
||||
provider.NoteCodexCredits("codex", "me@example.com", true)
|
||||
if code, body := resetPost(t, srv); code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The x-codex-credits-* headers and a codex.rate_limits event's credits
|
||||
// are read as Codex reads them: both bools said, a spent balance none,
|
||||
// the image allowance's headers not the account's.
|
||||
func TestCodexCreditsRead(t *testing.T) {
|
||||
h := func(kv ...string) http.Header {
|
||||
out := http.Header{}
|
||||
for i := 0; i < len(kv); i += 2 {
|
||||
out.Set(kv[i], kv[i+1])
|
||||
}
|
||||
return out
|
||||
}
|
||||
for _, c := range []struct {
|
||||
h http.Header
|
||||
on, ok bool
|
||||
}{
|
||||
{h("x-codex-credits-has-credits", "true", "x-codex-credits-unlimited", "false", "x-codex-credits-balance", "28263.2358130000"), true, true},
|
||||
{h("x-codex-credits-has-credits", "True", "x-codex-credits-unlimited", "0"), true, true},
|
||||
{h("x-codex-credits-has-credits", "false", "x-codex-credits-unlimited", "1"), true, true},
|
||||
{h("x-codex-credits-has-credits", "false", "x-codex-credits-unlimited", "false"), false, true},
|
||||
{h("x-codex-credits-has-credits", "true", "x-codex-credits-unlimited", "false", "x-codex-credits-balance", "0"), false, true},
|
||||
{h("x-codex-credits-has-credits", "true"), false, false},
|
||||
{h("x-codex-credits-has-credits", "yes", "x-codex-credits-unlimited", "false"), false, false},
|
||||
{h("x-codex-active-limit", "imagegen_premium", "x-codex-credits-has-credits", "true", "x-codex-credits-unlimited", "false"), false, false},
|
||||
} {
|
||||
if on, ok := codexHeaderCredits(c.h); on != c.on || ok != c.ok {
|
||||
t.Errorf("%v: %v %v, want %v %v", c.h, on, ok, c.on, c.ok)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
data string
|
||||
on, ok bool
|
||||
}{
|
||||
{`{"type":"codex.rate_limits","rate_limits":{},"credits":{"has_credits":true,"unlimited":false,"balance":"12.5"}}`, true, true},
|
||||
{`{"type":"codex.rate_limits","credits":{"has_credits":true,"unlimited":false,"balance":null}}`, true, true},
|
||||
{`{"type":"codex.rate_limits","credits":{"has_credits":false,"unlimited":false}}`, false, true},
|
||||
{`{"type":"codex.rate_limits","rate_limits":{}}`, false, false},
|
||||
{`{"type":"codex.rate_limits","metered_limit_name":"gpt-5.5-pro","credits":{"has_credits":true,"unlimited":false}}`, false, false},
|
||||
{`{"type":"response.created","credits":{"has_credits":true,"unlimited":false}}`, false, false},
|
||||
} {
|
||||
if on, ok := codexEventCredits([]byte(c.data)); on != c.on || ok != c.ok {
|
||||
t.Errorf("%s: %v %v, want %v %v", c.data, on, ok, c.on, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,11 @@ func codexHoldKey(base string, on *provider.Provider) string {
|
||||
|
||||
// noteCodexHold holds who after ChatGPT refused a turn with res's 429,
|
||||
// when it named for how long (vendorSaidWhen), as rateRest reads it.
|
||||
func noteCodexHold(who string, status int, header http.Header, body []byte) {
|
||||
// onCredits: the account goes on past its allowance on credits
|
||||
// (relayOnCredits), so one refused as out of it is held only a moment, as
|
||||
// the accounts loop rests one (fallbackCooldown, "credits"), not until
|
||||
// the window renews with its credits unspent.
|
||||
func noteCodexHold(who string, status int, header http.Header, body []byte, onCredits bool) {
|
||||
if who == "" || status != http.StatusTooManyRequests || !vendorSaidWhen(header, body) {
|
||||
return
|
||||
}
|
||||
@@ -67,6 +71,9 @@ func noteCodexHold(who string, status int, header http.Header, body []byte) {
|
||||
now := time.Now()
|
||||
d := retryAfter(header, now)
|
||||
d = max(d, min(resetsNoted(header, now), longestQuota), min(resetsAt(body, now), longestQuota))
|
||||
if onCredits && why == failQuota {
|
||||
d = min(d, fallbackCooldown)
|
||||
}
|
||||
if d <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -42,13 +42,89 @@ func heardCodexLimits(p provider.Provider, res *http.Response) {
|
||||
if ls := codexHeaderLimits(res.Header, now); len(ls) > 0 {
|
||||
noteCodexLimits(agent, user, ls)
|
||||
}
|
||||
heardCodexCredits(p, res.Header)
|
||||
if res.Body != nil && res.StatusCode < 300 {
|
||||
res.Body = &codexLimitsTap{ReadCloser: res.Body, note: func(ls []provider.CodexLimit) {
|
||||
noteCodexLimits(agent, user, ls)
|
||||
}, credits: func(on bool) {
|
||||
noteCodexCredits(agent, user, on)
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
// noteCodexCredits is provider.NoteCodexCredits, which tests watch.
|
||||
var noteCodexCredits = provider.NoteCodexCredits
|
||||
|
||||
// heardCodexCredits keeps what h, a reply to p's Codex account, says of
|
||||
// its credits (codexHeaderCredits): ChatGPT says them on the 429 that
|
||||
// turns a turn away as out of the allowance too, which is then asked
|
||||
// again on them (creditsAgain) rather than the account benched.
|
||||
func heardCodexCredits(p provider.Provider, h http.Header) {
|
||||
if p.Account == nil || p.Account.Agent != "codex" || p.Account.User == "" {
|
||||
return
|
||||
}
|
||||
if on, ok := codexHeaderCredits(h); ok {
|
||||
noteCodexCredits(p.Account.UsageAgent(), p.Account.User, on)
|
||||
}
|
||||
}
|
||||
|
||||
// codexHeaderCredits is whether the account goes on past its allowance on
|
||||
// credits, as the x-codex-credits-* headers tell it, and whether they do:
|
||||
// as Codex 0.160.1 reads them (codex-api's parse_credits_snapshot), both
|
||||
// has-credits and unlimited said ("true"/"false", "1"/"0"), the balance
|
||||
// not needed. None when x-codex-active-limit names the image allowance,
|
||||
// whose headers they then are (codexHeaderLimits).
|
||||
func codexHeaderCredits(h http.Header) (on, ok bool) {
|
||||
if imageLimitName(h.Get("x-codex-active-limit")) {
|
||||
return false, false
|
||||
}
|
||||
has, ok1 := headerBool(h.Get("x-codex-credits-has-credits"))
|
||||
unlimited, ok2 := headerBool(h.Get("x-codex-credits-unlimited"))
|
||||
if !ok1 || !ok2 {
|
||||
return false, false
|
||||
}
|
||||
return provider.CodexGoesOnCredits(has, unlimited, h.Get("x-codex-credits-balance")), true
|
||||
}
|
||||
|
||||
// headerBool reads a header's bool as Codex does (parse_header_bool).
|
||||
func headerBool(v string) (bool, bool) {
|
||||
v = strings.TrimSpace(v)
|
||||
switch {
|
||||
case strings.EqualFold(v, "true") || v == "1":
|
||||
return true, true
|
||||
case strings.EqualFold(v, "false") || v == "0":
|
||||
return false, true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// codexEventCredits is what a codex.rate_limits event's data tells of the
|
||||
// account's credits ({"credits":{"has_credits","unlimited","balance"}}),
|
||||
// as codexHeaderCredits; none for any other event, or one of a limit
|
||||
// other than the account's own.
|
||||
func codexEventCredits(data []byte) (on, ok bool) {
|
||||
var ev struct {
|
||||
Type string `json:"type"`
|
||||
Metered string `json:"metered_limit_name"`
|
||||
Credits *struct {
|
||||
Has *bool `json:"has_credits"`
|
||||
Unlimited *bool `json:"unlimited"`
|
||||
Balance *string `json:"balance"`
|
||||
} `json:"credits"`
|
||||
}
|
||||
if json.Unmarshal(data, &ev) != nil || ev.Type != "codex.rate_limits" || ev.Credits == nil || ev.Credits.Has == nil || ev.Credits.Unlimited == nil {
|
||||
return false, false
|
||||
}
|
||||
if m := strings.ReplaceAll(strings.ToLower(strings.TrimSpace(ev.Metered)), "-", "_"); m != "" && m != "codex" {
|
||||
return false, false
|
||||
}
|
||||
balance := ""
|
||||
if ev.Credits.Balance != nil {
|
||||
balance = *ev.Credits.Balance
|
||||
}
|
||||
return provider.CodexGoesOnCredits(*ev.Credits.Has, *ev.Credits.Unlimited, balance), true
|
||||
}
|
||||
|
||||
// codexLearnAgain is how long a Codex account not known that answered is
|
||||
// not put first again to be learned (learns): its reply told nothing of
|
||||
// the week, or the reading still fails.
|
||||
@@ -158,8 +234,11 @@ func codexEventLimits(data []byte, now time.Time) []provider.CodexLimit {
|
||||
type codexLimitsTap struct {
|
||||
io.ReadCloser
|
||||
note func([]provider.CodexLimit)
|
||||
buf []byte
|
||||
done bool
|
||||
// credits: what the event said of the account's credits
|
||||
// (codexEventCredits), when it said
|
||||
credits func(on bool)
|
||||
buf []byte
|
||||
done bool
|
||||
}
|
||||
|
||||
func (t *codexLimitsTap) Read(p []byte) (int, error) {
|
||||
@@ -187,6 +266,9 @@ func (t *codexLimitsTap) look() {
|
||||
if ls := codexEventLimits(bytes.TrimSpace(data), time.Now()); len(ls) > 0 {
|
||||
t.note(ls)
|
||||
}
|
||||
if on, ok := codexEventCredits(bytes.TrimSpace(data)); ok && t.credits != nil {
|
||||
t.credits(on)
|
||||
}
|
||||
t.done, t.buf = true, nil
|
||||
return
|
||||
}
|
||||
|
||||
@@ -939,9 +939,40 @@ func liftRests(agent, user string, vendorTill bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// creditsKnown lifts the rests out of its allowance of a ChatGPT account
|
||||
// found to go on past it on credits (provider.OnCredits), whatever time
|
||||
// the refusal named: a turn turned away before magpie knew of the credits
|
||||
// — bought once the plan ran out, or its reading failed or not come yet —
|
||||
// rested the account until its window renewed, days on, while Codex by
|
||||
// itself goes on on them (@123xtv03k on X). A rate limit's rest, or one
|
||||
// out of the credits themselves, stands; so does Codex's own hold of a
|
||||
// relayed turn for them.
|
||||
func creditsKnown(agent, user string) {
|
||||
if agent != "codex" {
|
||||
return
|
||||
}
|
||||
restingUntil.Lock()
|
||||
now := time.Now()
|
||||
for k, r := range restingUntil.note {
|
||||
if r.agent != agent || !strings.EqualFold(r.user, user) || !(r.Why == failQuota || r.By == "window") {
|
||||
continue
|
||||
}
|
||||
delete(restingUntil.m, k)
|
||||
delete(restingUntil.note, k)
|
||||
liftedLocked(k, now)
|
||||
}
|
||||
restingUntil.Unlock()
|
||||
codexHolds.Lock()
|
||||
if h, ok := codexHolds.m[strings.ToLower(user)]; ok && h.why == failQuota {
|
||||
delete(codexHolds.m, strings.ToLower(user))
|
||||
}
|
||||
codexHolds.Unlock()
|
||||
}
|
||||
|
||||
func init() {
|
||||
provider.OnRenewed(renewed)
|
||||
provider.OnStarted(restarted)
|
||||
provider.OnCredits(creditsKnown)
|
||||
}
|
||||
|
||||
// staleAllowance is provider.StaleAllowance, swapped in tests.
|
||||
|
||||
@@ -2,7 +2,9 @@ package provider
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -157,3 +159,128 @@ func heardAllowance(a Allowance, heard []CodexLimit) Allowance {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// CodexGoesOnCredits is whether a ChatGPT account goes on past its
|
||||
// allowance on credits, told as Codex reads them (/wham/usage's credits,
|
||||
// the x-codex-credits-* headers, a codex.rate_limits event's credits):
|
||||
// unlimited, or holding them (has_credits) — a balance said and spent (0
|
||||
// or less) is none left, whatever has_credits says. A balance not said,
|
||||
// or not a number, is held.
|
||||
func CodexGoesOnCredits(has, unlimited bool, balance string) bool {
|
||||
if unlimited {
|
||||
return true
|
||||
}
|
||||
if !has {
|
||||
return false
|
||||
}
|
||||
n, err := strconv.ParseFloat(strings.TrimSpace(balance), 64)
|
||||
return err != nil || n > 0
|
||||
}
|
||||
|
||||
// NoteCodexCredits keeps what a reply said of the credits of agent's
|
||||
// account user (agent as its usage is read): whether it goes on past its
|
||||
// allowance on them (CodexGoesOnCredits). ChatGPT says it on every reply,
|
||||
// the 429 that turns a turn away as out of its allowance too, and Codex
|
||||
// reads it there (codex-api's parse_credits_snapshot) — /wham/usage alone,
|
||||
// read once a minute or failing, left an account that had bought credits
|
||||
// benched as used up until its window renewed, days on, where Codex by
|
||||
// itself went on on them (@123xtv03k on X). Turned on, those OnCredits
|
||||
// asked are told, once the account is let spend them (CodexCredits).
|
||||
func NoteCodexCredits(agent, user string, on bool) {
|
||||
if user == "" {
|
||||
return
|
||||
}
|
||||
key := agent + "/" + strings.ToLower(user)
|
||||
was := false
|
||||
c := &loginUsageCache
|
||||
c.Lock()
|
||||
if e, ok := c.m[key]; ok {
|
||||
for _, w := range e.q.Windows {
|
||||
was = was || w.Credits
|
||||
}
|
||||
e.q.Windows = creditsWindows(e.q.Windows, on)
|
||||
if e.read.Error == "" {
|
||||
e.read.Windows = creditsWindows(e.read.Windows, on)
|
||||
}
|
||||
if on && agent == "codex" {
|
||||
// the Codex app holds no account with credits (codexHeld)
|
||||
e.q.Held, e.read.Held = false, false
|
||||
}
|
||||
c.m[key] = e
|
||||
}
|
||||
c.Unlock()
|
||||
u := &usedCache
|
||||
u.Lock()
|
||||
m := u.m[agent]
|
||||
for name, a := range m {
|
||||
if !strings.EqualFold(name, user) {
|
||||
continue
|
||||
}
|
||||
was = was || a.OnCredits()
|
||||
a = creditsAllowance(a, on)
|
||||
kept := make(map[string]Allowance, len(m))
|
||||
for k, v := range m {
|
||||
kept[k] = v
|
||||
}
|
||||
kept[name] = a
|
||||
u.m[agent] = kept
|
||||
break
|
||||
}
|
||||
if h, ok := u.heard[key]; ok {
|
||||
u.heard[key] = heardOnly{h.user, creditsAllowance(h.a, on)}
|
||||
}
|
||||
u.Unlock()
|
||||
if on && !was && (agent != "codex" || CodexCredits(user)) {
|
||||
tellCredits(agent, user)
|
||||
}
|
||||
}
|
||||
|
||||
// creditsWindows is ws, copied, each window that counts every model told
|
||||
// whether the account goes on past it on credits.
|
||||
func creditsWindows(ws []QuotaWindow, on bool) []QuotaWindow {
|
||||
out := make([]QuotaWindow, len(ws))
|
||||
copy(out, ws)
|
||||
for i := range out {
|
||||
if !out[i].Aside && out[i].Model == "" {
|
||||
out[i].Credits = on
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// creditsAllowance is creditsWindows for an allowance as routing keeps it.
|
||||
func creditsAllowance(a Allowance, on bool) Allowance {
|
||||
out := make(Allowance, len(a))
|
||||
copy(out, a)
|
||||
for i := range out {
|
||||
if out[i].Model == "" && out[i].matches == nil {
|
||||
out[i].Credits = on
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OnCredits asks f to be told of a ChatGPT account found to go on past its
|
||||
// allowance on credits it was not known to hold (NoteCodexCredits, or a
|
||||
// reading of its usage), and let spend them: what held it as out of its
|
||||
// allowance holds it no more.
|
||||
func OnCredits(f func(agent, user string)) {
|
||||
creditsHooks.Lock()
|
||||
creditsHooks.fs = append(creditsHooks.fs, f)
|
||||
creditsHooks.Unlock()
|
||||
}
|
||||
|
||||
var creditsHooks struct {
|
||||
sync.Mutex
|
||||
fs []func(agent, user string)
|
||||
}
|
||||
|
||||
// tellCredits tells those OnCredits asked.
|
||||
func tellCredits(agent, user string) {
|
||||
creditsHooks.Lock()
|
||||
fs := creditsHooks.fs
|
||||
creditsHooks.Unlock()
|
||||
for _, f := range fs {
|
||||
f(agent, user)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -186,3 +188,126 @@ func TestNoteCodexLimitsKnowsAnUnreadAccount(t *testing.T) {
|
||||
t.Fatal("what a reply told outlived the reading that replaced it")
|
||||
}
|
||||
}
|
||||
|
||||
// creditsTold records the accounts OnCredits tells of, from now on.
|
||||
func creditsTold(t *testing.T) func() []string {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var told []string
|
||||
on := true
|
||||
OnCredits(func(agent, user string) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if on {
|
||||
told = append(told, agent+"/"+user)
|
||||
}
|
||||
})
|
||||
t.Cleanup(func() { mu.Lock(); on = false; mu.Unlock() })
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
out := slices.Clone(told)
|
||||
told = nil
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// @123xtv03k on X: a ChatGPT account whose plan ran out goes on on credits
|
||||
// it bought, which Codex reads from every reply, the refusal too. What a
|
||||
// reply says of them is routing's and the Usage page's at once, held by
|
||||
// the Codex app no more, and those OnCredits asked are told when it is
|
||||
// newly so — not again, not when it says none, and not for an account
|
||||
// set not to spend them.
|
||||
func TestNoteCodexCreditsKeepsThem(t *testing.T) {
|
||||
isolate(t)
|
||||
resetUsed(t)
|
||||
told := creditsTold(t)
|
||||
now := time.Now()
|
||||
five, week := now.Add(2*time.Hour), now.Add(4*24*time.Hour)
|
||||
usedCache.Lock()
|
||||
usedCache.m["codex"] = map[string]Allowance{
|
||||
"Me@example.com": {{Used: 100, Resets: five, Span: 5 * time.Hour}, {Used: 100, Resets: week, Span: 7 * 24 * time.Hour}},
|
||||
"spare@example.com": {{Used: 20, Resets: five, Span: 5 * time.Hour}},
|
||||
}
|
||||
usedCache.at["codex"] = now
|
||||
usedCache.Unlock()
|
||||
loginUsageCache.Lock()
|
||||
loginUsageCache.m = map[string]loginUsageEntry{"codex/me@example.com": {at: now,
|
||||
q: SubscriptionQuota{Provider: "codex", Held: true, Windows: []QuotaWindow{
|
||||
{Name: "5 hours", Used: 100, ResetsAt: &five, Span: 5 * time.Hour},
|
||||
{Name: "7 days", Used: 100, ResetsAt: &week, Span: 7 * 24 * time.Hour}}}}}
|
||||
loginUsageCache.Unlock()
|
||||
|
||||
NoteCodexCredits("codex", "me@example.com", true)
|
||||
m := Allowances("codex")
|
||||
if !m["Me@example.com"].OnCredits() || m["spare@example.com"].OnCredits() {
|
||||
t.Fatalf("after the reply: %+v", m)
|
||||
}
|
||||
loginUsageCache.Lock()
|
||||
e := loginUsageCache.m["codex/me@example.com"]
|
||||
loginUsageCache.Unlock()
|
||||
if e.q.Held || !e.q.Windows[0].Credits || !e.q.Windows[1].Credits {
|
||||
t.Fatalf("the Usage page's reading: held %v, %+v", e.q.Held, e.q.Windows)
|
||||
}
|
||||
if got := told(); !slices.Equal(got, []string{"codex/me@example.com"}) {
|
||||
t.Fatalf("told %v", got)
|
||||
}
|
||||
NoteCodexCredits("codex", "me@example.com", true)
|
||||
if got := told(); len(got) != 0 {
|
||||
t.Fatalf("told again: %v", got)
|
||||
}
|
||||
NoteCodexCredits("codex", "me@example.com", false)
|
||||
if Allowances("codex")["Me@example.com"].OnCredits() {
|
||||
t.Fatal("a reply saying none left it on its credits")
|
||||
}
|
||||
if err := SetCodexCredits("me@example.com", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
NoteCodexCredits("codex", "me@example.com", true)
|
||||
if got := told(); len(got) != 0 {
|
||||
t.Fatalf("told of an account set not to spend them: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Credits bought after the plan ran out show first in a reading: routing
|
||||
// is told (OnCredits) as the reading finds them, not only when a reply
|
||||
// says so.
|
||||
func TestReadingTellsCreditsBought(t *testing.T) {
|
||||
signIn(t)
|
||||
rememberLogins(true)
|
||||
resetUsed(t)
|
||||
told := creditsTold(t)
|
||||
readAgain := func(credits bool) {
|
||||
five := time.Now().Add(2 * time.Hour)
|
||||
loginUsageCache.Lock()
|
||||
loginUsageCache.m = map[string]loginUsageEntry{"codex/me@example.com": {at: time.Now(),
|
||||
q: SubscriptionQuota{Provider: "codex", Windows: []QuotaWindow{{Name: "5 hours", Used: 100, ResetsAt: &five, Span: 5 * time.Hour, Credits: credits}}}}}
|
||||
loginUsageCache.Unlock()
|
||||
usedCache.Lock()
|
||||
usedCache.at["codex"] = time.Time{}
|
||||
usedCache.Unlock()
|
||||
Allowances("codex")
|
||||
for {
|
||||
usedCache.Lock()
|
||||
done := usedCache.loading["codex"]
|
||||
usedCache.Unlock()
|
||||
if done == nil {
|
||||
break
|
||||
}
|
||||
<-done
|
||||
}
|
||||
}
|
||||
readAgain(false)
|
||||
readAgain(false)
|
||||
if got := told(); len(got) != 0 {
|
||||
t.Fatalf("told with no credits: %v", got)
|
||||
}
|
||||
readAgain(true)
|
||||
if got := told(); !slices.Equal(got, []string{"codex/me@example.com"}) {
|
||||
t.Fatalf("told %v", got)
|
||||
}
|
||||
readAgain(true)
|
||||
if got := told(); len(got) != 0 {
|
||||
t.Fatalf("told again: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -962,7 +962,7 @@ func readAllowances(agent string) map[string]Allowance {
|
||||
}
|
||||
c.read[key] = st
|
||||
}
|
||||
var renewed, restarts []string
|
||||
var renewed, restarts, credits []string
|
||||
for user, a := range all {
|
||||
key := agent + "/" + strings.ToLower(user)
|
||||
if c.renewed[key] > began {
|
||||
@@ -979,6 +979,11 @@ func readAllowances(agent string) map[string]Allowance {
|
||||
if a.startedAgain(was.a, was.at, share, now) {
|
||||
restarts = append(restarts, user)
|
||||
}
|
||||
if a.OnCredits() && !was.a.OnCredits() {
|
||||
// credits it was not read to hold: bought once
|
||||
// its allowance ran out (NoteCodexCredits)
|
||||
credits = append(credits, user)
|
||||
}
|
||||
}
|
||||
c.seen[key] = reading{a, now}
|
||||
}
|
||||
@@ -1013,6 +1018,11 @@ func readAllowances(agent string) map[string]Allowance {
|
||||
for _, user := range restarts {
|
||||
tellStarted(agent, user)
|
||||
}
|
||||
for _, user := range credits {
|
||||
if agent != "codex" || CodexCredits(user) {
|
||||
tellCredits(agent, user)
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1220,17 +1220,7 @@ func codexWindows(ctx context.Context, token, accountID string) (plan string, ou
|
||||
// or less) is none left, whatever has_credits says.
|
||||
func codexGoesOnCredits(u codexUsage) bool {
|
||||
c := u.Credits
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
if c.Unlimited {
|
||||
return true
|
||||
}
|
||||
if !c.Has {
|
||||
return false
|
||||
}
|
||||
n, err := strconv.ParseFloat(strings.TrimSpace(c.Balance), 64)
|
||||
return err != nil || n > 0
|
||||
return c != nil && CodexGoesOnCredits(c.Has, c.Unlimited, c.Balance)
|
||||
}
|
||||
|
||||
// codexUsage is what /wham/usage tells of a ChatGPT account.
|
||||
|
||||
Reference in New Issue
Block a user