diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index fa3ec7b09..501383ea1 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -65,7 +65,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | | Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | -| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, and neither `/wham/usage` (`additional_rate_limits` is null) nor the reply headers (`x-codex-primary-*`, `x-codex-secondary-*`) tell it. So the row says *Used up* with the reset time while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244) and *Unknown* otherwise, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `codex-image-row.test.cjs`). Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | +| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, `TestRemoteSelectNoneStillShowsItsCards`). One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 3aab4f70a..39e4898d7 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1410,6 +1410,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } body = b } + if rest == "/images/generations" || rest == "/images/edits" { + if acct, ok := codexRelayedAccount(base, r.Header, on); ok { + // Codex's own drawing, relayed: the image window its reply + // tells is the account's image row (#6412) + heardCodexImage(acct, res.Header) + } + } if rest == "/responses" { if acct, ok := codexRelayedAccount(base, r.Header, on); ok { // the windows the reply tells of the account it went out on diff --git a/internal/gateway/codex_image_limits.go b/internal/gateway/codex_image_limits.go new file mode 100644 index 000000000..fbbc1cd9e --- /dev/null +++ b/internal/gateway/codex_image_limits.go @@ -0,0 +1,94 @@ +package gateway + +import ( + "net/http" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/lazyre" + "github.com/yetone/magpie/internal/provider" +) + +// ChatGPT's images API tells the image allowance of the account it drew on +// in every reply, a 200 as well as a 429 (#6412, hqqqqqqqh): it names the +// limit counted, x-codex-active-limit: imagegen_premium, and the window in +// the x-codex-primary-* headers (window-minutes 1440, reset-at), or, as +// Codex 0.160.1 reads it (codex-api rate_limits.rs, parse_all_rate_limits), +// in a family named for the limit: x-imagegen-premium-primary-*, or +// x-image-gen-primary-* for image_gen. That window is the image row's +// (provider.ImageLane), never the account's 5-hour or weekly one: it is +// kept apart from them (provider.NoteCodexLimits is never told it), and a +// chat reply that names an image limit tells no chat window either. + +// imageLimitName is a limit id of the image allowance: imagegen_premium, +// image_gen, as x-codex-active-limit or a header family names it. +func imageLimitName(name string) bool { + n := strings.ReplaceAll(strings.ToLower(strings.TrimSpace(name)), "-", "_") + return strings.HasPrefix(n, "imagegen") || strings.HasPrefix(n, "image_gen") +} + +// imageFamily is a header of a limit's own family's window +// (x-imagegen-premium-primary-window-minutes), with the limit's name. +var imageFamily = lazyre.New(`^x-(.+)-(?:primary|secondary)-window-minutes$`) + +// codexImageHeaderLimit is the image window h tells: of the family named +// for the image limit first, else, when x-codex-active-limit names an +// image limit, of the x-codex-* family; false when it tells none. +func codexImageHeaderLimit(h http.Header, now time.Time) (provider.CodexLimit, bool) { + var fams []string + for k := range h { + if m := imageFamily.FindStringSubmatch(strings.ToLower(k)); m != nil && m[1] != "codex" && imageLimitName(m[1]) { + fams = append(fams, m[1]) + } + } + if imageLimitName(h.Get("x-codex-active-limit")) { + fams = append(fams, "codex") + } + for _, fam := range fams { + if ls := headerLimitsOf(h, "x-"+fam+"-", now); len(ls) > 0 { + l := ls[0] + for _, o := range ls[1:] { + // of two windows, the fuller is the one that holds + if o.Used > l.Used { + l = o + } + } + return l, true + } + } + return provider.CodexLimit{}, false +} + +// codexImageHeard is the image window each ChatGPT account's last reply +// told, by agent (as its usage is read)/lower-cased user. +var codexImageHeard = struct { + sync.Mutex + m map[string]provider.CodexLimit +}{m: map[string]provider.CodexLimit{}} + +func init() { provider.ImageHeard = imageHeardOf } + +// heardCodexImage keeps the image window h tells of p's ChatGPT account. +func heardCodexImage(p provider.Provider, h http.Header) { + if p.Account == nil || p.Account.Agent != "codex" || p.Account.User == "" || h == nil { + return + } + l, ok := codexImageHeaderLimit(h, time.Now()) + if !ok { + return + } + codexImageHeard.Lock() + codexImageHeard.m[p.Account.UsageAgent()+"/"+strings.ToLower(p.Account.User)] = l + codexImageHeard.Unlock() +} + +// imageHeardOf is the image window a reply last told of agent's account +// user, while it has not renewed: one with no reset said, or one past +// it, tells nothing of now. +func imageHeardOf(agent, user string, now time.Time) (provider.CodexLimit, bool) { + codexImageHeard.Lock() + l, ok := codexImageHeard.m[agent+"/"+strings.ToLower(user)] + codexImageHeard.Unlock() + return l, ok && l.Resets.After(now) +} diff --git a/internal/gateway/codex_image_limits_test.go b/internal/gateway/codex_image_limits_test.go new file mode 100644 index 000000000..e07ae918d --- /dev/null +++ b/internal/gateway/codex_image_limits_test.go @@ -0,0 +1,212 @@ +package gateway + +import ( + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// forgetImageHeard forgets every image window heard, now and when t ends. +func forgetImageHeard(t *testing.T) { + t.Helper() + clear := func() { + codexImageHeard.Lock() + codexImageHeard.m = map[string]provider.CodexLimit{} + codexImageHeard.Unlock() + } + clear() + t.Cleanup(clear) +} + +// imageRowOf is the image row of user's ChatGPT card as it is handed out. +func imageRowOf(t *testing.T, user string) provider.QuotaWindow { + t.Helper() + in := []provider.SubscriptionQuota{{Provider: "codex", User: user, Windows: []provider.QuotaWindow{{Name: "5 hours", Used: 40}, {Name: "7 days", Used: 10}}}} + out := provider.WithImageLane(in, time.Now()) + if len(out[0].Windows) != 3 || out[0].Windows[2].Lane != provider.ImageLane { + t.Fatalf("windows = %+v", out[0].Windows) + } + return out[0].Windows[2] +} + +// #6412 (hqqqqqqqh): a drawing's 200 carries the account's image window, +// x-codex-active-limit: imagegen_premium with x-codex-primary-* of 1440 +// minutes, as the reporter captured it on a Pro account. The image row +// then says when it renews, not "unknown"; and those headers are never +// taken for the account's 5-hour or weekly window. +func TestCodexImageRowFromA200sHeaders(t *testing.T) { + codexSignedIn(t) + forgetImageHeard(t) + at := time.Now().Add(12 * time.Hour).Truncate(time.Second) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + // the reporter's capture, its reset moved to the test's time + w.Header().Set("x-codex-active-limit", "imagegen_premium") + w.Header().Set("x-codex-plan-type", "pro") + w.Header().Set("x-codex-primary-used-percent", "0") + w.Header().Set("x-codex-primary-window-minutes", "1440") + w.Header().Set("x-codex-primary-reset-after-seconds", strconv.FormatInt(int64(time.Until(at)/time.Second), 10)) + w.Header().Set("x-codex-primary-reset-at", strconv.FormatInt(at.Unix(), 10)) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}],"usage":{"input_tokens":5,"output_tokens":196}}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + var mu sync.Mutex + var chat []provider.CodexLimit + old := noteCodexLimits + noteCodexLimits = func(_, _ string, ls []provider.CodexLimit) { mu.Lock(); chat = append(chat, ls...); mu.Unlock() } + t.Cleanup(func() { noteCodexLimits = old }) + + if w := imageRowOf(t, "me@example.com"); w.Display != "Unknown" || w.ResetsAt != nil { + t.Fatalf("before any drawing the row = %+v", w) + } + code, _, raw := postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"codex/gpt-image-2","prompt":"a magpie","size":"1024x1024"}`) + if code != 200 { + t.Fatalf("%d %s", code, raw) + } + w := imageRowOf(t, "me@example.com") + if w.ResetsAt == nil || !w.ResetsAt.Equal(at) || w.Display != "Available" || !w.Text || !w.Aside || w.Used != 0 { + t.Fatalf("after a drawing the row = %+v, want available until %v, no share", w, at) + } + if w.ResetSecs < int64(11*time.Hour/time.Second) { + t.Fatalf("resets in %ds, want about 12h", w.ResetSecs) + } + if other := imageRowOf(t, "other@example.com"); other.ResetsAt != nil { + t.Fatalf("another account's row took it: %+v", other) + } + mu.Lock() + defer mu.Unlock() + if len(chat) != 0 { + t.Fatalf("the image window was taken for the account's own: %+v", chat) + } +} + +// A refusal whose body names no reset, as Codex's own test has +// imagegen_premium's (app-server imagegen_extension.rs), rests the image +// model until the window its headers tell renews, in the limit's own +// family (x-imagegen-premium-primary-*), not quotaRest's 15 minutes: the +// card said "2 minutes" of a 24-hour window (#6412). +func TestCodexImageRefusalRestsUntilItsWindow(t *testing.T) { + codexSignedIn(t) + forgetImageHeard(t) + at := time.Now().Add(20 * time.Hour).Truncate(time.Second) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("x-codex-active-limit", "imagegen_premium") + w.Header().Set("x-imagegen-premium-primary-used-percent", "100") + w.Header().Set("x-imagegen-premium-primary-window-minutes", "1440") + w.Header().Set("x-imagegen-premium-primary-reset-at", strconv.FormatInt(at.Unix(), 10)) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"image limit reached","resets_at":null,"plan_type":"plus"}}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + t.Cleanup(func() { + restingUntil.Lock() + var keys []string + for k, r := range restingUntil.note { + if strings.EqualFold(r.user, "me@example.com") { + keys = append(keys, k) + } + } + restingUntil.Unlock() + for _, k := range keys { + clearRest(k) + } + }) + + code, _, raw := postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"codex/gpt-image-2","prompt":"a magpie"}`) + if code != http.StatusTooManyRequests { + t.Fatalf("%d %s", code, raw) + } + // the model rests until then, so the next drawing asks another account first + if until, ok := imageRestOf("codex", "me@example.com", time.Now()); !ok || until.Sub(at).Abs() > 2*time.Second { + t.Fatalf("rests until %v (%v), want %v", until, ok, at) + } + w := imageRowOf(t, "me@example.com") + if w.ResetsAt == nil || w.ResetsAt.Sub(at).Abs() > 2*time.Second || w.Display != "Used up" { + t.Fatalf("after the refusal the row = %+v, want used up until %v", w, at) + } +} + +// Codex's own drawing, relayed to ChatGPT with its sign-in the only +// account, tells the image row too. +func TestCodexRelayedImageWindowHeard(t *testing.T) { + codexSignedIn(t) + forgetImageHeard(t) + at := time.Now().Add(6 * time.Hour).Truncate(time.Second) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("x-codex-active-limit", "imagegen_premium") + w.Header().Set("x-codex-primary-used-percent", "100") + w.Header().Set("x-codex-primary-window-minutes", "1440") + w.Header().Set("x-codex-primary-reset-at", strconv.FormatInt(at.Unix(), 10)) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/images/generations", strings.NewReader(`{"model":"gpt-image-2","prompt":"a magpie"}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("chatgpt-account-id", "acct-1") + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if w := imageRowOf(t, "me@example.com"); w.ResetsAt == nil || !w.ResetsAt.Equal(at) || w.Display != "Used up" { + t.Fatalf("row = %+v, want used up until %v", w, at) + } +} + +// Which headers tell the image window: the limit's own family, or the +// x-codex-* one when x-codex-active-limit names an image limit; and then +// never the account's own windows. A chat reply's are as they were. +func TestCodexImageHeaders(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + h := http.Header{} + h.Set("x-codex-primary-used-percent", "0") + h.Set("x-codex-primary-window-minutes", "1440") + h.Set("x-codex-primary-reset-after-seconds", "600") + if _, ok := codexImageHeaderLimit(h, now); ok { + t.Fatal("x-codex-* with no image limit named taken for the image window") + } + if ls := codexHeaderLimits(h, now); len(ls) != 1 { + t.Fatalf("a chat reply's window lost: %+v", ls) + } + for _, name := range []string{"imagegen_premium", "image_gen", "imagegen_basic"} { + h.Set("x-codex-active-limit", name) + if l, ok := codexImageHeaderLimit(h, now); !ok || l.Span != 24*time.Hour || !l.Resets.Equal(now.Add(10*time.Minute)) { + t.Fatalf("%s: %+v %v", name, l, ok) + } + if ls := codexHeaderLimits(h, now); ls != nil { + t.Fatalf("%s: the image window taken for the account's: %+v", name, ls) + } + } + f := http.Header{} + f.Set("x-codex-active-limit", "image_gen") + f.Set("x-image-gen-primary-used-percent", "100") + f.Set("x-image-gen-primary-window-minutes", "1440") + f.Set("x-image-gen-primary-reset-at", "1800003600") + if l, ok := codexImageHeaderLimit(f, now); !ok || l.Used != 100 || l.Resets.Unix() != 1800003600 { + t.Fatalf("image_gen's own family: %+v %v", l, ok) + } +} diff --git a/internal/gateway/codex_limits.go b/internal/gateway/codex_limits.go index 7eae7fe74..339e85c24 100644 --- a/internal/gateway/codex_limits.go +++ b/internal/gateway/codex_limits.go @@ -77,11 +77,23 @@ func codexAnsweredLately(agent, user string, now time.Time) bool { // codexHeaderLimits are the windows the x-codex-primary-* and // x-codex-secondary-* headers tell; one that doesn't say how long it runs -// is left out, as no window read can be told to be it. +// is left out, as no window read can be told to be it. None when +// x-codex-active-limit names the image allowance, whose window they then +// are (codexImageHeaderLimit). func codexHeaderLimits(h http.Header, now time.Time) []provider.CodexLimit { + if imageLimitName(h.Get("x-codex-active-limit")) { + // the x-codex-* windows are the image allowance's (#6412) + return nil + } + return headerLimitsOf(h, "x-codex-", now) +} + +// headerLimitsOf are the windows of the header family fam (x-codex-, +// x-imagegen-premium-) tells: its primary- and secondary- ones. +func headerLimitsOf(h http.Header, fam string, now time.Time) []provider.CodexLimit { var out []provider.CodexLimit for _, which := range []string{"primary", "secondary"} { - pre := "x-codex-" + which + "-" + pre := fam + which + "-" used, err := strconv.ParseFloat(strings.TrimSpace(h.Get(pre+"used-percent")), 64) if err != nil { continue diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index f089bfa15..892c15848 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -1312,24 +1312,40 @@ func (s *Server) drawOnAccounts(ctx context.Context, r *http.Request, p provider // restDrawer rests the image model on c's account when the account is out // of its quota for it, until the reset the refusal names (Antigravity's -// "Your quota will reset after 3h19m30s.", resetsAt), else quotaRest. Only -// the model rests (restID), never the account: its text models draw on -// allowances of their own. The next drawing then asks the accounts that -// still have it first (restLast in candidates), and a chat on that image -// model goes past it too, where before every drawing asked the spent -// account first again (01huadalang on Discord). A failure of any other -// kind rests nothing, as before: a key, a request refused, a vendor down; -// nor does any on a provider set never to rest for a limit (LimitRestOff). +// "Your quota will reset after 3h19m30s.", resetsAt), or a ChatGPT +// account's image window's as its headers told it (imageHeardOf), else +// quotaRest; a 429 the headers said came with that window full is out of +// quota whatever its words. Only the model rests (restID), never the +// account: its text models draw on allowances of their own. The next +// drawing then asks the accounts that still have it first (restLast in +// candidates), and a chat on that image model goes past it too, where +// before every drawing asked the spent account first again (01huadalang +// on Discord). A failure of any other kind rests nothing, as before: a +// key, a request refused, a vendor down; nor does any on a provider set +// never to rest for a limit (LimitRestOff). func restDrawer(c candidate, code int, msg string) { - if c.p.Account == nil || c.p.LimitRestOff || c.model == "" || failure(code, []byte(msg)) != failQuota { + if c.p.Account == nil || c.p.LimitRestOff || c.model == "" { return } now := time.Now() + agent, user := c.p.Account.UsageAgent(), c.p.Account.User + // the image window a ChatGPT account's reply told (#6412) + heard, told := imageHeardOf(agent, user, now) + told = told && strings.HasPrefix(c.model, codexDrawerFamily) + if failure(code, []byte(msg)) != failQuota && (code != http.StatusTooManyRequests || !told || heard.Used < 100) { + // a 429 whose words read as a short rate limit ("image limit + // reached") is the allowance's when the headers said it is full + return + } r := Rest{Why: failQuota, Status: code, By: "quota", Key: c.restID(), Model: c.model, - agent: c.p.Account.UsageAgent(), user: c.p.Account.User, said: msg} + agent: agent, user: user, said: msg} d := quotaRest if w := resetsAt([]byte(msg), now); w > 0 { d, r.By = min(w, longestQuota), "resets" + } else if told { + // a ChatGPT image refusal whose body names no reset: its window's, + // as the reply's headers told it, not quotaRest's guess + d, r.By = min(heard.Resets.Sub(now), longestQuota), "resets" } r.Until = now.Add(d) restingUntil.Lock() @@ -1499,6 +1515,11 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url, return nil, 502, err } defer res.Body.Close() + if drawsCodex(p) { + // the image window a ChatGPT account's reply tells, a 200's too, + // for its card and a refusal's rest (#6412) + heardCodexImage(p, res.Header) + } answered := time.Since(asked) rb := &tracked{r: res.Body, last: time.Now()} b, err := io.ReadAll(io.LimitReader(rb, 256<<20)) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index bec6b7eda..272a1405f 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2380,6 +2380,7 @@ const I18N = { "Droid Core · 30 days": "Droid Core · 30 天", "Extra usage": "额外用量", "Used up": "已用完", + "Available": "可用", "Usage credits": "额外用量额度", "Gift plans to claim in the ZCode app": "待在 ZCode 客户端领取的赠送额度", "ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 赠送额度(-Trial 模型)需要 ZCode 登录", @@ -7525,6 +7526,7 @@ const I18N = { "Droid Core · 30 days": "Droid Core · 30 天", "Extra usage": "額外用量", "Used up": "已用完", + "Available": "可用", "Usage credits": "額外用量額度", "Gift plans to claim in the ZCode app": "待在 ZCode 用戶端領取的贈送額度", "ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode 贈送額度(-Trial 模型)需要 ZCode 登入", @@ -12646,6 +12648,7 @@ const I18N = { "Droid Core · 30 days": "Droid Core · 30日", "Extra usage": "追加使用量", "Used up": "使い切り", + "Available": "利用可能", "Usage credits": "追加使用量のクレジット", "Gift plans to claim in the ZCode app": "ZCode アプリで受け取れるギフト枠", "ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode のギフト枠(-Trial モデル)には ZCode でのサインインが必要", @@ -17798,6 +17801,7 @@ const I18N = { "Droid Core · 30 days": "Droid Core · 30 Tage", "Extra usage": "Zusätzliche Nutzung", "Used up": "Aufgebraucht", + "Available": "Verfügbar", "Usage credits": "Nutzungsguthaben", "Gift plans to claim in the ZCode app": "In der ZCode-App abzuholen", "ZCode gift plans (-Trial models) need ZCode's sign-in": "ZCode-Geschenkpläne (-Trial-Modelle) brauchen die ZCode-Anmeldung", diff --git a/internal/gui/tests/codex-image-row.test.cjs b/internal/gui/tests/codex-image-row.test.cjs index 3dffdbb90..879eaae11 100644 --- a/internal/gui/tests/codex-image-row.test.cjs +++ b/internal/gui/tests/codex-image-row.test.cjs @@ -18,14 +18,16 @@ const chat = [{ name: "5 hours", used: 40, resetSecs: 3600 }, { name: "7 days", const quotas = [ { provider: "codex", name: "Codex", icon: "codex-color", user: "spent@example.com", windows: [...chat, img({ display: "Used up", resetsAt: soon, resetSecs: 10800 })] }, { provider: "codex", name: "Codex", icon: "codex-color", user: "fresh@example.com", windows: [...chat, img({})] }, + // a drawing's 200 told the window's renewal (#6412) + { provider: "codex", name: "Codex", icon: "codex-color", user: "drew@example.com", windows: [...chat, img({ display: "Available", resetsAt: soon, resetSecs: 10800 })] }, ]; const words = { - en: { name: "Image generation", used: "Used up", unknown: "Unknown" }, - zh: { name: "生图模型", used: "已用完", unknown: "未知" }, - "zh-TW": { name: "生圖模型", used: "已用完", unknown: "未知" }, - ja: { name: "画像生成", used: "使い切り", unknown: "不明" }, - de: { name: "Bilderzeugung", used: "Aufgebraucht", unknown: "Unbekannt" }, + en: { name: "Image generation", used: "Used up", unknown: "Unknown", ok: "Available" }, + zh: { name: "生图模型", used: "已用完", unknown: "未知", ok: "可用" }, + "zh-TW": { name: "生圖模型", used: "已用完", unknown: "未知", ok: "可用" }, + ja: { name: "画像生成", used: "使い切り", unknown: "不明", ok: "利用可能" }, + de: { name: "Bilderzeugung", used: "Aufgebraucht", unknown: "Unbekannt", ok: "Verfügbar" }, }; function serve(lang) { @@ -66,7 +68,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#subscriptionUsage .quota").first().waitFor(); await page.locator(".quota-more").click(); const w = words[lang]; - for (const [user, text, resets] of [["spent@example.com", w.used, true], ["fresh@example.com", w.unknown, false]]) { + for (const [user, text, resets] of [["spent@example.com", w.used, true], ["fresh@example.com", w.unknown, false], ["drew@example.com", w.ok, true]]) { const mine = page.locator(`[data-card="codex|${user}"] + .quota-windows`); const row = mine.locator(".quota", { hasText: w.name }); await row.waitFor(); diff --git a/internal/provider/image_lane.go b/internal/provider/image_lane.go index 4dd9d77b7..303cb186d 100644 --- a/internal/provider/image_lane.go +++ b/internal/provider/image_lane.go @@ -7,12 +7,14 @@ import ( // ImageLane is the name of a ChatGPT account's image window (QuotaWindow.Lane). // Drawing with gpt-image-2 counts against an allowance of its own, apart from -// Codex's 5-hour and weekly windows (#6160), and the backend tells no share of -// it: /wham/usage has no image window (additional_rate_limits is null) and a -// reply carries no x-codex-* header for one. What magpie knows is the refusal -// it got, usage_limit_reached with the time it comes back, which the gateway -// keeps as the image model's rest (ImageRest). So the row says that time, or -// "unknown": never a share, which nothing told. +// Codex's 5-hour and weekly windows (#6160). /wham/usage has no image window +// (additional_rate_limits is null), but each reply of the images API tells +// it, a 200's too: x-codex-active-limit names the image limit and its +// window's headers say when it renews (#6412), which the gateway keeps +// (ImageHeard). A refusal, usage_limit_reached, rests the image model until +// the time it names, or that window's renewal (ImageRest). So the row says +// that time, or "unknown": never a share, as the share the headers tell +// stayed 0 on an account that had drawn. const ImageLane = "images" // ImageRest is, set by the gateway, when the image model of the ChatGPT @@ -20,11 +22,17 @@ const ImageLane = "images" // vendor's refusal keeps it resting; false when it is not. var ImageRest func(agent, user string, now time.Time) (time.Time, bool) +// ImageHeard is, set by the gateway, the image window the ChatGPT account +// user's last reply of the images API told, while it has not renewed; +// false when none told one. +var ImageHeard func(agent, user string, now time.Time) (CodexLimit, bool) + // WithImageLane is qs with a row for the image allowance added to each // ChatGPT account's card that was read: Text and Aside, so no share is told -// and routing never reads it, with ResetsAt when a refusal named the time it -// comes back and no time otherwise. A card of another magpie is as it came; -// qs and its windows, which the caches share, are left as they were. +// and routing never reads it, with ResetsAt when a refusal or a reply's +// headers named the time it comes back and no time otherwise. A card of +// another magpie is as it came; qs and its windows, which the caches share, +// are left as they were. func WithImageLane(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota { out := make([]SubscriptionQuota, len(qs)) for i, q := range qs { @@ -39,6 +47,17 @@ func WithImageLane(qs []SubscriptionQuota, now time.Time) []SubscriptionQuota { } } w := QuotaWindow{Name: "Image generation", Lane: ImageLane, Text: true, Aside: true, Display: "Unknown"} + if ImageHeard != nil { + // the window the last drawing's reply told: its renewal, and + // used up when it said so; "Available" while it was not + if l, ok := ImageHeard("codex", strings.ToLower(q.User), now); ok { + until := l.Resets + w.Display, w.ResetsAt, w.ResetSecs = "Available", &until, int64(until.Sub(now)/time.Second) + if l.Used >= 100 { + w.Display = "Used up" + } + } + } if ImageRest != nil { if until, ok := ImageRest("codex", strings.ToLower(q.User), now); ok { w.Display, w.ResetsAt, w.ResetSecs = "Used up", &until, int64(until.Sub(now)/time.Second)