Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: Volcengine Ark's monthly 429 rests the key until the reset it writes (+0800 CST), not 15 minutes (#3251 CNife, #3276 wyx1818)
yetone8278fd9b0ce1
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 8773a1485..faa19cb64 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -132,7 +132,7 @@ recorded as a prediction failure (`noPrediction`).- A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before.- A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.-- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or more than `longestWritten` (7 days) off isn't read. Zhipu's 1308 and 1310 (Z.ai and bigmodel.cn, GLM Coding Plan: "Your limit will reset at 2026-10-15 20:12:13", "您的限额将在 … 重置") write the time with no zone; it is Beijing's, and is read as UTC+8 in those words only (`zhipuResets`, `resetsZhipu`), never when a digit, colon or zone of its own follows (Player on Discord: read by nothing, the key rested `quotaRest` and the refusal said "not asked again before 17:12" while Z.ai said 20:12; `TestZhipuRestsUntilItsReset`). One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). Out of credit or quota on a model that costs credits, where the subscription serves other models free (`catalog.Model.Free`: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; `Provider.PaidBesideFree`), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, `TestOutOfCreditLeavesFreeModels`). A Credits window leaves the free models out the same way, so an account at 100% isn't ranked spent for them: the WorkBuddy plugin's lists them as `notModels` (0.1.23), and the built-in's scopes itself by the provider's last fetched list (`wbSpareFree`; with no list read, every model counts) (plugins#138, hheei: an account at 560 / 560 was still served deepseek-v4.1-flash; `TestWorkBuddyCreditsSpareFreeModels`). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. Cline's daily limit of one free model, 429 "Daily free limit reached on model deepseek/deepseek-v4-flash. Try again in 23h 59m" (the words Cline's own clients read it by, `isClineFreeModelLimitMessage`), rests that model alone (`clineFreeLimit`, `clineModelLimited`, keyed by `restID`) until the time it names (`clineBackIn`, `tryAgainIn`, held to `longestWritten`; `resets`), from a provider whose requests reach Cline's API (`ClinePinnable`: the ClinePass preset, one at cline.bot, the Cline plugin's). The key's other models, free or the plan's, are still served, and the model out of its day is answered with its refusal without asking Cline again (#1398, wuasakura: one free model's 429 sent the whole Cline account to the back; `TestClineFreeLimitRestsTheModel`, `TestClineFreeLimitLeavesOtherModels`). Another vendor's same words, and a Cline 429 that doesn't name the model's limit, rest the key as before. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (`brokeWords`), not a rate limit, on the built-in's raw body and the plugin's `insufficient_quota` alike (`TestCreditsExhaustedIsOutOfCredit`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.+- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669; Volcengine Ark's "You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST.", #3251, #3276) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, or its offset as Go prints one (four digits, then the zone's name, which isn't read), followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or further off than `longestSaid` isn't read: `longestWritten` (7 days), or `longestMonthly` (35 days) when the refusal says its allowance is a month's (`monthlyWords`: Ark's, Zhipu's 1310 "Weekly/Monthly Limit Exhausted"). Such a reset is the one rest out of quota held past `longestQuota`, to `longestMonthly`; a window read full or the user's own rest is still held to 8 days (`TestMonthlyWrittenResetRestsTheMonth`). Ark's windows as its AccessKey reads them (`volcPlanQuotas`) still reach only its usage card, not routing (#3251). Zhipu's 1308 and 1310 (Z.ai and bigmodel.cn, GLM Coding Plan: "Your limit will reset at 2026-10-15 20:12:13", "您的限额将在 … 重置") write the time with no zone; it is Beijing's, and is read as UTC+8 in those words only (`zhipuResets`, `resetsZhipu`), never when a digit, colon or zone of its own follows (Player on Discord: read by nothing, the key rested `quotaRest` and the refusal said "not asked again before 17:12" while Z.ai said 20:12; `TestZhipuRestsUntilItsReset`). One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). Out of credit or quota on a model that costs credits, where the subscription serves other models free (`catalog.Model.Free`: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; `Provider.PaidBesideFree`), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, `TestOutOfCreditLeavesFreeModels`). A Credits window leaves the free models out the same way, so an account at 100% isn't ranked spent for them: the WorkBuddy plugin's lists them as `notModels` (0.1.23), and the built-in's scopes itself by the provider's last fetched list (`wbSpareFree`; with no list read, every model counts) (plugins#138, hheei: an account at 560 / 560 was still served deepseek-v4.1-flash; `TestWorkBuddyCreditsSpareFreeModels`). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. Cline's daily limit of one free model, 429 "Daily free limit reached on model deepseek/deepseek-v4-flash. Try again in 23h 59m" (the words Cline's own clients read it by, `isClineFreeModelLimitMessage`), rests that model alone (`clineFreeLimit`, `clineModelLimited`, keyed by `restID`) until the time it names (`clineBackIn`, `tryAgainIn`, held to `longestWritten`; `resets`), from a provider whose requests reach Cline's API (`ClinePinnable`: the ClinePass preset, one at cline.bot, the Cline plugin's). The key's other models, free or the plan's, are still served, and the model out of its day is answered with its refusal without asking Cline again (#1398, wuasakura: one free model's 429 sent the whole Cline account to the back; `TestClineFreeLimitRestsTheModel`, `TestClineFreeLimitLeavesOtherModels`). Another vendor's same words, and a Cline 429 that doesn't name the model's limit, rest the key as before. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (`brokeWords`), not a rate limit, on the built-in's raw body and the plugin's `insufficient_quota` alike (`TestCreditsExhaustedIsOutOfCredit`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.- An account resting out of its window (a Claude account by the time Claude Code's refusal named, `resets`, or any by `window`) is back once magpie's reading of its windows (`provider.Allowances`) finds it full till sooner: the window used below `SpentShareOf`, or its reset passed, with no other window over the same models still full. The reading tells `provider.OnRenewed` as the account's `UsageAgent` and user, and `renewed` lifts that account's rests out of quota or by `window`; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in `restingOf`.- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more.- A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`).diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex a1be2b41f..97ac13608 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -212,12 +212,22 @@ var (// resetsWhen: a 429 that says in words when the account is back, as// WorkBuddy's do in both its builds (#1669): "将在 2026-10-11 20:16:02// UTC+8重置", "your usage will reset at 2026-10-11 12:37:53 UTC+8, ...".+ // Volcengine Ark's monthly one writes its time as Go prints one, the+ // offset as four digits and the zone's name after it (#3251 CNife,+ // #3276 wyx1818): "It will reset at 2026-10-25 23:59:59 +0800 CST.";+ // the offset is read, the name (CST is more than one zone) isn't.// Only the reset phrasing right beside a whole date and time with its// offset is read, and the offset must be followed by what follows it// there (重置, or a comma or full stop), so a refusal cut short after- // "UTC" or "UTC+" isn't read as UTC: another vendor's date in passing- // ("deprecated on …"), or one with no offset, is not a reset time.- resetsWhen = regexp.MustCompile(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?(?:\s*(?:重置|[,.;,。;]))`)+ // "UTC", "UTC+" or Ark's "+0800" isn't read as UTC: another vendor's+ // date in passing ("deprecated on …"), or one with no offset, is not a+ // reset time.+ resetsWhen = regexp.MustCompile(`(?i)(?:\bresets? at|将在|将于)\s*(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})\s*(?:(?:UTC|GMT)([+-])(\d{1,2})(?::?(\d{2}))?|([+-])(\d{2})(\d{2}) (?-i:[A-Z]{2,5}))(?:\s*(?:重置|[,.;,。;]))`)+ // monthlyWords: a refusal that says the allowance it used up is a+ // month's, as Ark's does ("You have exceeded the monthly usage quota")+ // and Zhipu's 1310 ("Weekly/Monthly Limit Exhausted"): the reset time+ // it writes can honestly be weeks off (longestSaid).+ monthlyWords = regexp.MustCompile(`(?i)\bmonthly\b|月度|每月|本月`)// otherModels: a refusal that says the account's other models still// answer ("切换其他模型", "switch to the other models"): its limit is// the model's, and the model alone rests@@ -691,7 +701,7 @@ var zhipuZone = time.FixedZone("UTC+8", 8*3600)// resetsZhipu is how long until the time a Zhipu 1308 or 1310 names// (zhipuResets), read in Beijing's time. Zero when there is none, it isn't// a real date, it is written with a zone of its own (resetsWritten reads-// those), it has passed, or it is over longestWritten off.+// those), it has passed, or it is further off than longestSaid.func resetsZhipu(body []byte, now time.Time) time.Duration {m := zhipuResets.FindSubmatch(wordsOf(body))if m == nil {@@ -712,7 +722,7 @@ func resetsZhipu(body []byte, now time.Time) time.Duration {if t.Year() != y || int(t.Month()) != mo || t.Day() != d || t.Hour() != h || t.Minute() != mi || t.Second() != sec {return 0}- if w := t.Sub(now); w > 0 && w <= longestWritten {+ if w := t.Sub(now); w > 0 && w <= longestSaid(body) {return w}return 0@@ -769,27 +779,49 @@ func spanWritten(m [][]byte) time.Duration {// time further off than a week is more likely a misreading than a reset.const longestWritten = 7 * 24 * time.Hour+// longestMonthly is the furthest off a written reset of a month's+// allowance is believed, and the longest an account or key out of one+// sits out: a month, and days over. Ark's monthly quota used up on the+// 22nd resets on the 31st, 9 days off; held to the week, it was read as+// no reset and asked again every quotaRest till the month turned (#3276).+const longestMonthly = 35 * 24 * time.Hour++// longestSaid is the furthest off a reset time a refusal writes is+// believed: longestMonthly when it says its allowance is a month's+// (monthlyWords), else longestWritten.+func longestSaid(body []byte) time.Duration {+ if monthlyWords.Match(wordsOf(body)) {+ return longestMonthly+ }+ return longestWritten+}+// resetsWritten is how long until the time a refusal names in words// (resetsWhen), read in the offset it is written with. Zero when there is-// none, it isn't a real date, it has passed, or it is over longestWritten-// off.+// none, it isn't a real date, it has passed, or it is further off than+// longestSaid.func resetsWritten(body []byte, now time.Time) time.Duration {m := resetsWhen.FindSubmatch(wordsOf(body))if m == nil {return 0}- n := make([]int, 9)- for i, g := range [][]byte{m[1], m[2], m[3], m[4], m[5], m[6], m[8], m[9]} {+ // the offset after UTC or GMT, else as Go prints it (Ark's +0800 CST)+ sign, oh, om := m[7], m[8], m[9]+ if len(sign) == 0 {+ sign, oh, om = m[10], m[11], m[12]+ }+ n := make([]int, 8)+ for i, g := range [][]byte{m[1], m[2], m[3], m[4], m[5], m[6], oh, om} {if len(g) > 0 {n[i], _ = strconv.Atoi(string(g))}}- y, mo, d, h, mi, sec, oh, om := n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]- if oh > 14 || om > 59 {+ y, mo, d, h, mi, sec, offH, offM := n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]+ if offH > 14 || offM > 59 {return 0}- off := oh*3600 + om*60- if string(m[7]) == "-" {+ off := offH*3600 + offM*60+ if string(sign) == "-" {off = -off}t := time.Date(y, time.Month(mo), d, h, mi, sec, 0, time.FixedZone("", off))@@ -797,7 +829,7 @@ func resetsWritten(body []byte, now time.Time) time.Duration {if t.Year() != y || int(t.Month()) != mo || t.Day() != d || t.Hour() != h || t.Minute() != mi || t.Second() != sec {return 0}- if w := t.Sub(now); w > 0 && w <= longestWritten {+ if w := t.Sub(now); w > 0 && w <= longestSaid(body) {return w}return 0@@ -888,7 +920,13 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo// asked again every hour, whatever rest the user set)d, r.By = w, "retry-after"}- d = min(d, longestQuota)+ // a month's allowance whose refusal named its reset is out till+ // then, past the week's cap (#3276); nothing else is held longer+ longest := longestQuota+ if r.By == "resets" && monthlyWords.Match(wordsOf(body)) {+ longest = longestMonthly+ }+ d = min(d, longest)case failRate:d, r.By, r.Failures = s.rateRest(c, header, body, sharedPool, now)// rate limited with quota left: to the back, where the order sinksdiff --git a/internal/gateway/written_reset_test.go b/internal/gateway/written_reset_test.goindex fae0fc1d4..1bbd669d6 100644--- a/internal/gateway/written_reset_test.go+++ b/internal/gateway/written_reset_test.go@@ -17,12 +17,27 @@ import ("github.com/yetone/magpie/internal/testenv")-// WorkBuddy's two refusals, as Natsumeretsu quoted them (#1669).+// WorkBuddy's two refusals, as Natsumeretsu quoted them (#1669), and+// Volcengine Ark's monthly one, as its reporters' curl printed it: arkCNife+// (#3251, a 429 with no Retry-After), resetting in 3 days, and arkWyx+// (#3276 wyx1818), resetting in 9.const (- wbZh = "WorkBuddy:您的使用量已超出频率限制,将在 2026-10-11 20:16:02 UTC+8重置,您也可以切换其他模型继续使用。"- wbEn = "WorkBuddy AI: usage exceeds frequency limit, but don't worry, your usage will reset at 2026-10-11 12:37:53 UTC+8, alternatively, you can switch to the other models to continue using it."+ wbZh = "WorkBuddy:您的使用量已超出频率限制,将在 2026-10-11 20:16:02 UTC+8重置,您也可以切换其他模型继续使用。"+ wbEn = "WorkBuddy AI: usage exceeds frequency limit, but don't worry, your usage will reset at 2026-10-11 12:37:53 UTC+8, alternatively, you can switch to the other models to continue using it."+ arkCNife = `{"error":{"code":"AccountQuotaExceeded","type":"TooManyRequests","message":"You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST. …"}}`+ arkWyx = `{+ "error": {+ "code": "AccountQuotaExceeded",+ "message": "You have exceeded the monthly usage quota. It will reset at 2026-10-31 23:59:59 +0800 CST."+ }+}`)+// arkAt is Ark's monthly refusal (arkCNife), saying it resets at t.+func arkAt(t time.Time) string {+ return strings.Replace(arkCNife, "2026-10-25 23:59:59", t.In(time.FixedZone("", 8*3600)).Format("2006-01-02 15:04:05"), 1)+}+// escaped is msg as a vendor's JSON error whose encoder escapes what// isn't ASCII as \uXXXX, as Python's json.dumps does by default.func escaped(msg, code string) string {@@ -85,6 +100,26 @@ func TestResetsWritten(t *testing.T) {// another vendor's date in passing is no reset{"deprecated", "This model will be deprecated on 2026-10-12 00:00:00 UTC+8, please switch to the other models.", at("2026-10-11 10:00:00"), 0},{"retry after", "Too many requests, retry after 2026-10-11 12:37:53 UTC+8.", at("2026-10-11 10:00:00"), 0},+ // Ark's monthly refusal, its offset as Go prints it with the+ // zone's name after it, believed weeks off as a month's (#3251,+ // #3276)+ {"ark", arkCNife, at("2026-10-22 16:52:00"), 3*24*time.Hour + 7*time.Hour + 7*time.Minute + 59*time.Second},+ {"ark 9 days off", arkWyx, at("2026-10-22 12:00:00"), 9*24*time.Hour + 11*time.Hour + 59*time.Minute + 59*time.Second},+ {"ark escaped", escaped("You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST.", "AccountQuotaExceeded"), at("2026-10-22 16:52:00"), 3*24*time.Hour + 7*time.Hour + 7*time.Minute + 59*time.Second},+ {"ark 35 days off", arkCNife, at("2026-09-20 23:59:59"), 35 * 24 * time.Hour},+ {"ark 36 days off", arkCNife, at("2026-09-19 23:59:58"), 0},+ {"ark past", arkCNife, at("2026-10-26 00:00:00"), 0},+ // Ark's cut short, or its form without the zone's name: not read+ {"ark cut after the offset", arkCNife[:strings.Index(arkCNife, " CST")], at("2026-10-22 16:52:00"), 0},+ {"ark cut in the offset", arkCNife[:strings.Index(arkCNife, "00 CST")], at("2026-10-22 16:52:00"), 0},+ {"ark cut after the zone", arkCNife[:strings.Index(arkCNife, ". …")], at("2026-10-22 16:52:00"), 0},+ {"ark without the zone", strings.Replace(arkCNife, " CST", "", 1), at("2026-10-22 16:52:00"), 0},+ {"ark offset +9900", strings.Replace(arkCNife, "+0800", "+9900", 1), at("2026-10-22 16:52:00"), 0},+ // the week's guard holds for a refusal that doesn't say it is a+ // month's, in Ark's form or WorkBuddy's+ {"ark's form, not monthly, 9 days off", strings.Replace(arkWyx, "monthly ", "", 1), at("2026-10-22 12:00:00"), 0},+ {"en 9 days off", wbEn, at("2026-10-02 12:00:00"), 0},+ {"retry after, Ark's form", "Too many requests, retry after 2026-10-11 12:37:53 +0800 CST.", at("2026-10-11 10:00:00"), 0},} {if got := resetsWritten([]byte(c.body), c.now); got != c.want {t.Errorf("%s: %v, want %v (%q)", c.name, got, c.want, c.body)@@ -170,6 +205,60 @@ func TestWrittenResetRestsUntilThen(t *testing.T) {}}+// Ark's monthly 429 rests the key until the reset it names, 3 days off as+// CNife's was (#3251) or 9 as wyx1818's (#3276), past the week a written+// reset is otherwise believed and the 8 days a quota's rest is held to: it+// is not asked again every quotaRest till the month turns. The same time+// in words that don't say the allowance is a month's keeps the week's+// guard, and rests quotaRest as before.+func TestMonthlyWrittenResetRestsTheMonth(t *testing.T) {+ old := allowances+ defer func() { allowances = old }()+ allowances = func(string) map[string]provider.Allowance { return nil }+ s := &Server{}+ c := candidate{p: provider.Provider{ID: "ark-plan"}, model: "deepseek-v4.1-flash", rest: "ark-plan#k"}+ near := func(d, want time.Duration) bool { return d > want-time.Minute && d <= want }+ for _, back := range []time.Duration{3*24*time.Hour + 7*time.Hour, 9*24*time.Hour + 12*time.Hour} {+ body := []byte(arkAt(time.Now().Add(back)))+ if f := failure(429, body); f != failQuota {+ t.Fatalf("%v: read as %s", back, f)+ }+ clearRest(c.restKey())+ r := s.restAfter(c, 429, http.Header{}, body)+ if r.Why != failQuota || r.By != "resets" || !near(time.Until(r.Until), back) {+ t.Fatalf("%v off: rests %v by %s (%s)", back, time.Until(r.Until), r.By, r.Why)+ }+ // as the agent's error, with the time keepRetry noted beside it+ clearRest(c.restKey())+ h := http.Header{}+ keepRetry(h, http.Header{}, body)+ r = s.restAfter(c, 429, h, []byte("Volcengine: "+provider.APIError(body, "")))+ if r.By != "resets" || !near(time.Until(r.Until), back) {+ t.Fatalf("%v off, noted: rests %v by %s (%s)", back, time.Until(r.Until), r.By, r.Why)+ }+ }+ clearRest(c.restKey())+ back := 9*24*time.Hour + 12*time.Hour+ notMonthly := []byte(strings.Replace(arkAt(time.Now().Add(back)), "monthly ", "", 1))+ if r := s.restAfter(c, 429, http.Header{}, notMonthly); r.By != "quota" || !near(time.Until(r.Until), quotaRest) {+ t.Fatalf("not monthly, 9 days off: rests %v by %s (%s), want %v", time.Until(r.Until), r.By, r.Why, quotaRest)+ }+ clearRest(c.restKey())++ // a month's refusal that names no time, on an account whose window+ // was read full 20 days off, is held to the 8 days as before: only+ // the time the vendor wrote is believed past them+ allowances = func(string) map[string]provider.Allowance {+ return map[string]provider.Allowance{"[email protected]": {{Used: 100, Resets: time.Now().Add(20 * 24 * time.Hour), Span: 30 * 24 * time.Hour}}}+ }+ a := candidate{p: provider.Provider{ID: "acct", Account: &provider.Account{Agent: "acct", User: "[email protected]"}}, model: "m", rest: "acct#[email protected]"}+ clearRest(a.restKey())+ if r := s.restAfter(a, 429, http.Header{}, []byte(`{"error":{"message":"You have exceeded the monthly usage quota."}}`)); r.By != "window" || !near(time.Until(r.Until), longestQuota) {+ t.Fatalf("monthly, window 20 days off: rests %v by %s (%s), want %v", time.Until(r.Until), r.By, r.Why, longestQuota)+ }+ clearRest(a.restKey())+}+// A rate limit whose refusal names when it's back rests until then, as far// as out of quota is believed; a Retry-After alone is still held to the// hour (#1669: the same words rested 8 days read as out of quota, an hourdiff --git a/internal/gateway/zhipu_resets_test.go b/internal/gateway/zhipu_resets_test.goindex f8bf736f6..fc85b17a9 100644--- a/internal/gateway/zhipu_resets_test.go+++ b/internal/gateway/zhipu_resets_test.go@@ -58,6 +58,10 @@ func TestResetsZhipu(t *testing.T) {{"hour 25", strings.Replace(zai1308, "20:12:13", "25:12:13", 1), player, 0},{"past", zai1308, time.Date(2026, 10, 15, 12, 13, 0, 0, time.UTC), 0},{"over a week off", zai1308, time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC), 0},+ // 1310 is a week's or a month's: a month's reset is believed+ // weeks off, as Ark's is (#3276)+ {"1310, 9 days off", zai1310, time.Date(2026, 10, 1, 13, 0, 6, 0, time.UTC), 9 * 24 * time.Hour},+ {"1310, 36 days off", zai1310, time.Date(2026, 9, 4, 13, 0, 6, 0, time.UTC), 0},// another vendor's words, without a zone: not taken as Beijing's{"WorkBuddy without its offset", strings.Replace(wbZh, " UTC+8", "", 1), player, 0},{"a date in passing", "this model is retired at 2026-10-15 20:12:13", player, 0},