provider: an account's window can be capped at a fixed amount of its unit

A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.

- AccountWindowAmounts keeps it per account and window (capId). An
  amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
  and NearCap. CapHeld and capReached hold the account once the window's
  count reaches the amount (past), and rest it as the percentage cap
  does: the next account takes the request. cappedError and the trace
  say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
  applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
  place (provider/windowcap with amount). It shows only on a window
  with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
  --amount <n|off>.

Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.

Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
  vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
  ./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
  TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
  420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
  earlier webkit run lost the amount test's page once ("Target page,
  context or browser has been closed"); it passed in 2 more full-file
  runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
  this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).

Reported-by: 9won_25273 (Discord)
This commit is contained in:
yetone
2026-11-09 18:19:02 +08:00
parent 3245b730d2
commit 40cbdaa7e8
18 changed files with 644 additions and 66 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+22
View File
@@ -94,6 +94,28 @@ func TestAccountCapCmd(t *testing.T) {
if c := provider.AccountCapsOf("codex", "me@example.com"); c.Windows != nil {
t.Fatalf("default left %+v", c)
}
// a fixed amount of a window's unit (9won_25273 on Discord): 300
// credits a day, then off; a bad amount, or one with no window, refused
if err := providerCmd([]string{"provider", "account-cap", "codex", "me@example.com", "--window", "Daily credits", "--amount", "1,000"}); err != nil {
t.Fatal(err)
}
if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts["daily credits"] != 1000 {
t.Fatalf("amount %+v", c)
}
for _, bad := range [][]string{{"--window", "Daily credits", "--amount", "-3"}, {"--window", "Daily credits", "--amount", "lots"}, {"--amount", "300"}, {"--window", "Daily credits", "--amount", "300", "50"}} {
if err := providerCmd(append([]string{"provider", "account-cap", "codex", "me@example.com"}, bad...)); err == nil {
t.Errorf("%q taken", bad)
}
}
if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts["daily credits"] != 1000 {
t.Fatalf("a refused amount changed it: %+v", c)
}
if err := providerCmd([]string{"provider", "account-cap", "codex", "me@example.com", "--window=Daily credits", "--amount=off"}); err != nil {
t.Fatal(err)
}
if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts != nil {
t.Fatalf("off left %+v", c)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil {
t.Fatal(err)
}
+58 -16
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"log"
"maps"
"math"
"os"
"path/filepath"
"slices"
@@ -87,6 +88,9 @@ const providerUsage = `usage:
magpie provider account-cap <id> <account> --window <name> [percent|none|default]
a share for one window alone (e.g. "5 hours" 50): none is no cap on it,
default has it follow the account's cap
magpie provider account-cap <id> <account> --window <name> --amount <n|off>
a fixed amount of a window counted in a unit (e.g. "Daily credits" 300),
by the vendor's count, spending outside magpie included
magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]
a subscription's accounts as one pool: which are in use and in what order,
each one's cap, --stop: answer 429 at the caps rather than go on to the
@@ -1665,28 +1669,37 @@ func accountModelsCmd(rest []string) error {
// accountCapCmd shows, or sets with a share or off, the usage cap of a
// subscription's accounts: the share of each window one is used to at most
// (provider.AccountCaps); with --window <name>, the share of that window
// alone (provider.AccountWindowCaps).
// alone (provider.AccountWindowCaps); with --amount too, a fixed amount of
// that window's own unit, credits or requests (provider.AccountWindowAmounts).
func accountCapCmd(rest []string) error {
usage := fmt.Errorf("magpie provider account-cap <id> [account [percent|off]]\n magpie provider account-cap <id> <account> --window <name> [percent|none|default]")
usage := fmt.Errorf("magpie provider account-cap <id> [account [percent|off]]\n magpie provider account-cap <id> <account> --window <name> [percent|none|default]\n magpie provider account-cap <id> <account> --window <name> --amount <n|off>")
window, windowSet := "", false
amount, amountSet := "", false
for i := 0; i < len(rest); i++ {
a := rest[i]
if v, ok := strings.CutPrefix(a, "--window="); ok {
window, windowSet = v, true
rest = slices.Delete(slices.Clone(rest), i, i+1)
i--
continue
}
if a == "--window" {
if i+1 >= len(rest) {
return usage
for _, f := range []struct {
name string
v *string
set *bool
}{{"--window", &window, &windowSet}, {"--amount", &amount, &amountSet}} {
if v, ok := strings.CutPrefix(a, f.name+"="); ok {
*f.v, *f.set = v, true
rest = slices.Delete(slices.Clone(rest), i, i+1)
i--
break
}
if a == f.name {
if i+1 >= len(rest) {
return usage
}
*f.v, *f.set = rest[i+1], true
rest = slices.Delete(slices.Clone(rest), i, i+2)
i--
break
}
window, windowSet = rest[i+1], true
rest = slices.Delete(slices.Clone(rest), i, i+2)
i--
}
}
if len(rest) < 1 || windowSet && (len(rest) < 2 || strings.TrimSpace(window) == "") {
if len(rest) < 1 || windowSet && (len(rest) < 2 || strings.TrimSpace(window) == "") || amountSet && (!windowSet || len(rest) != 2) {
return usage
}
p, err := provider.Find(rest[0])
@@ -1696,6 +1709,18 @@ func accountCapCmd(rest []string) error {
if p.Account == nil {
return fmt.Errorf("%s has keys, not subscription accounts with usage windows to cap", p.Name)
}
if amountSet {
n, err := parseWindowAmount(amount)
if err != nil {
return err
}
if err := provider.SetWindowAmount(p.ID, rest[1], []string{window}, n); err != nil {
return err
}
if p, err = provider.Find(p.ID); err != nil {
return err
}
}
if len(rest) > 2 {
if windowSet {
cap, err := parseWindowCap(rest[2])
@@ -1736,7 +1761,7 @@ func accountCapCmd(rest []string) error {
caps := p.CapsOf(r)
if caps.All > 0 {
fmt.Printf("%s · capped at %d%% of each usage window\n", r, caps.All)
} else if len(caps.Windows) > 0 {
} else if len(caps.Windows) > 0 || len(caps.Amounts) > 0 {
fmt.Println(r, muted.Render("· no cap on its other windows: used to 100%"))
} else {
fmt.Println(r, muted.Render("· no cap: used to 100%"))
@@ -1748,10 +1773,27 @@ func accountCapCmd(rest []string) error {
fmt.Printf(" %s · capped at %d%%\n", w, c)
}
}
for _, w := range slices.Sorted(maps.Keys(caps.Amounts)) {
fmt.Printf(" %s · capped at %s of its unit\n", w, strconv.FormatFloat(caps.Amounts[w], 'f', -1, 64))
}
}
return nil
}
// parseWindowAmount reads a window's fixed amount as the CLI takes it: a
// number above 0, "300" or "1,000", or off (0) to lift it.
func parseWindowAmount(s string) (float64, error) {
t := strings.ToLower(strings.TrimSpace(s))
if t == "off" || t == "none" || t == "default" || t == "0" {
return 0, nil
}
n, err := strconv.ParseFloat(strings.ReplaceAll(t, ",", ""), 64)
if err != nil || !(n > 0) || math.IsInf(n, 0) {
return 0, fmt.Errorf("a window's amount is a number above 0, in the window's own unit, or off, not %q", s)
}
return n, nil
}
// parseWindowCap reads a window's own share as the CLI takes it: "50",
// "50%", none (off, 100) for no cap on that window, default (-) to follow
// the account's cap.
@@ -0,0 +1,77 @@
package gateway
import (
"fmt"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// 9won_25273 on Discord: an account capped at 300 of a day's 1000 credits
// is held once the vendor's count of the day reaches 300, and the request
// goes to the next account; under it, it is used; every account at its
// cap is refused, named with the count and the amount.
func TestWindowAmountHoldsTheAccount(t *testing.T) {
codexSignedIn(t, "spare@example.com")
b := newResetBackend(t)
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
for _, u := range []string{"me@example.com", "spare@example.com"} {
if err := provider.SetWindowAmount("codex", u, []string{"Daily credits"}, 300); err != nil {
t.Fatal(err)
}
}
try := func(count map[string]float64) (int, string, string, *Server) {
t.Helper()
old := allowances
t.Cleanup(func() { allowances = old })
day := time.Now().Add(5 * time.Hour)
allowances = func(string) map[string]provider.Allowance {
out := map[string]provider.Allowance{}
for u, n := range count {
out[u] = provider.Allowance{{Name: "Daily credits", Used: n / 10, Amount: n, Of: 1000, Unit: "credits", Resets: day, Span: 24 * time.Hour}}
}
return out
}
b.mu.Lock()
b.tried = nil
b.mu.Unlock()
srv := New()
code, body := resetPost(t, srv)
tried, _ := b.seen()
return code, body, tried, srv
}
code, body, tried, srv := try(map[string]float64{"me@example.com": 320, "spare@example.com": 40})
if code != 200 || tried != "acct-2" {
t.Fatalf("320 of 300 credits: %d %s tried %s", code, body, tried)
}
var left []string
for _, r := range srv.Trace(t.Context(), 0, 0).Routes {
for _, w := range r.Left {
if w.Capped > 0 && !w.Barred {
left = append(left, fmt.Sprintf("%s %g/%g %s", w.Who, w.CapCount, w.CapAmount, w.CapUnit))
}
}
}
if len(left) != 1 || left[0] != "me@example.com 320/300 credits" {
t.Fatalf("traced as capped: %v", left)
}
if code, body, tried, _ := try(map[string]float64{"me@example.com": 299, "spare@example.com": 40}); code != 200 || tried != "acct-1" {
t.Fatalf("299 of 300 credits: %d %s tried %s", code, body, tried)
}
code, body, tried, _ = try(map[string]float64{"me@example.com": 300, "spare@example.com": 412.5})
if code != 429 || tried != "" {
t.Fatalf("both at their amount: %d tried %q", code, tried)
}
for _, want := range []string{"usage cap reached", "(me@example.com) has used 300 credits", "(spare@example.com) has used 412.5 credits", "past its cap of 300"} {
if !strings.Contains(body, want) {
t.Errorf("no %q in %s", want, body)
}
}
}
+1
View File
@@ -462,6 +462,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate,
}
w := pl.left[i]
w.Unlisted, w.Capped, w.CapBack = false, 0, nil
w.CapAmount, w.CapCount, w.CapUnit = 0, 0, ""
pl.left = slices.Delete(slices.Clone(pl.left), i, i+1)
back, order = append(back, c), append(order, w)
}
+1
View File
@@ -96,6 +96,7 @@ func unhold(order, left []Weighed, c candidate) ([]Weighed, []Weighed) {
}
w := left[i]
w.Unlisted, w.Capped, w.CapBack, w.NoCredits = false, 0, nil, false
w.CapAmount, w.CapCount, w.CapUnit = 0, 0, ""
return append(slices.Clip(order), w), slices.Delete(slices.Clone(left), i, i+1)
}
+19 -5
View File
@@ -107,10 +107,14 @@ type candidate struct {
// renews (zero when one doesn't say). noCredits: it is a Codex account
// held at 100% as it is set not to spend its credits (cap is 100 then).
type capHold struct {
cap int
used float64
back time.Time
noCredits bool
cap int
used float64
// amount: held at a window's fixed amount (provider.CapHold.Amount),
// count of it used, in unit
amount, count float64
unit string
back time.Time
noCredits bool
// unread: held by a careful provider as its usage can't be told, why
// (carefulDoubt), cap then the account's own
unread string
@@ -954,7 +958,7 @@ func capHeld(p, acct provider.Provider, model string, now time.Time) *capHold {
}
return nil
}
return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits}
return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits, amount: h.Amount, count: h.Count, unit: h.Unit}
}
// cappedError says why a request for model went nowhere when every account
@@ -1013,6 +1017,9 @@ func heldReasons(ws []Weighed, now time.Time) ([]string, time.Time) {
continue
}
s := fmt.Sprintf("%s (%s) is at %.0f%% of a usage window, past its %d%% cap", w.Name, w.Who, w.Used, w.Capped)
if w.CapAmount > 0 {
s = fmt.Sprintf("%s (%s) has used %s %s of a usage window, past its cap of %s", w.Name, w.Who, amountText(w.CapCount), w.CapUnit, amountText(w.CapAmount))
}
if w.SpendCap > 0 {
s = fmt.Sprintf("%s (%s) has spent %s of the %s spend cap set on it %s, as magpie's usage prices its calls", w.Name, w.Who, usd(w.Spent), usd(w.SpendCap), spendPeriod(w.SpendPeriod, w.SpendSince, now))
}
@@ -1052,6 +1059,12 @@ func spendOnly(ws []Weighed) bool {
return n > 0
}
// amountText is a window's count as a cap at a fixed amount says it: whole
// when it is, else to two places.
func amountText(v float64) string {
return strconv.FormatFloat(math.Round(v*100)/100, 'f', -1, 64)
}
// usd is an amount in dollars as a spend cap is told: cents kept.
func usd(v float64) string {
return "$" + strconv.FormatFloat(math.Floor(v*100+0.5)/100, 'f', 2, 64)
@@ -1170,6 +1183,7 @@ func barredOf(cs []candidate, q provider.Provider, fallback bool, from provider.
w.Unlisted, w.Via = true, via
if h := c.capped; h != nil {
w.Capped, w.Used, w.NoCredits, w.Unread = h.cap, h.used, h.noCredits, h.unread
w.CapAmount, w.CapCount, w.CapUnit = h.amount, h.count, h.unit
if sp := h.spend; sp != nil {
w.SpendCap, w.Spent, w.SpendPeriod = sp.usd, sp.spent, sp.period
if sp.period == provider.SpendTotal {
+5
View File
@@ -401,6 +401,11 @@ type Weighed struct {
// share, CapBack when the last window at or past it renews
Capped int `json:"capped,omitempty"`
CapBack *time.Time `json:"capBack,omitempty"`
// CapAmount: held (Capped) at a window's fixed amount of its own unit
// rather than a share: CapCount of it used, in CapUnit
CapAmount float64 `json:"capAmount,omitempty"`
CapCount float64 `json:"capCount,omitempty"`
CapUnit string `json:"capUnit,omitempty"`
// NoCredits: held at 100% (Capped), a Codex account the user set not
// to spend its credits once its allowance is used up
NoCredits bool `json:"noCredits,omitempty"`
+33 -10
View File
@@ -14125,9 +14125,18 @@ function accountCapOf(p, user) { return p?.accountCaps?.[String(user).toLowerCas
function windowOwnCapOf(p, user, w) {
return (w?.capId && p?.accountWindowCaps?.[String(user).toLowerCase()]?.[w.capId]) || 0;
}
function windowCapsOf(p, user) { return Object.keys(p?.accountWindowCaps?.[String(user).toLowerCase()] || {}).length; }
// windowCapOf: the share the window holds the account at, 0 for none
function windowCapsOf(p, user) { const k = String(user).toLowerCase(); return Object.keys({ ...p?.accountWindowCaps?.[k], ...p?.accountWindowAmounts?.[k] }).length; }
// A window's cap at a fixed amount of its own unit (provider.AccountWindowAmounts,
// 9won_25273 on Discord), by capId: 0 when it has none.
function windowAmountOf(p, user, w) {
return (w?.capId && p?.accountWindowAmounts?.[String(user).toLowerCase()]?.[w.capId]) || 0;
}
// windowCapOf: the share the window holds the account at, 0 for none; an
// amount as a share of the window's total, which a window read without one
// leaves aside
function windowCapOf(p, user, w) {
const amount = windowAmountOf(p, user, w);
if (amount && w?.limit > 0) return amount / w.limit * 100;
const own = windowOwnCapOf(p, user, w);
if (own) return own >= 100 ? 0 : own;
return w?.ownCap ? 0 : accountCapOf(p, user);
@@ -14156,7 +14165,7 @@ function capHeldOf(q, capFor) {
if (!r) h.unknown = true; else h.back = Math.max(h.back, r);
}
const h = all.n ? all : some.n ? some : null;
return h && { used: h.used, cap: h.cap, back: h.unknown ? 0 : h.back, all: h === all, some: some.names };
return h && { used: h.used, cap: Math.ceil(h.cap), back: h.unknown ? 0 : h.back, all: h === all, some: some.names };
}
// directNote: why the cap can't stop agent, signed in to the account and
// asking its vendor itself, with no other account on to move it to
@@ -14192,7 +14201,7 @@ function capMark(track, w, cap) {
if (!cap || !w.capped) return;
const mk = el("span", "aq-cap");
mk.style.left = (quotaLeft ? 100 - cap : cap) + "%";
mk.title = t("Usage cap {n}%", { n: cap });
mk.title = t("Usage cap {n}%", { n: Math.round(cap) });
track.classList.add("capped");
track.append(mk);
}
@@ -14223,14 +14232,22 @@ function pillNumber(at, val, ph, cls, label, parse, bad, own, set) {
// sets the window's own cap, a family's its models' (tiers); not on-demand's.
function windowCapMeter(m, p, user, w) {
const ids = (w.tiers || [w]).map((x) => x.capId), owns = ids.map((capId) => windowOwnCapOf(p, user, { capId }));
if (!ids.every(Boolean) || w.ownCap && !(owns[0] % 100)) return m;
const amounts = ids.map((capId) => windowAmountOf(p, user, { capId }));
const amount = new Set(amounts).size > 1 ? 0 : amounts[0];
if (!ids.every(Boolean) || w.ownCap && !(owns[0] % 100) && !amount) return m;
const own = new Set(owns).size > 1 ? 0 : owns[0], cap = accountCapOf(p, user);
const name = t(w.name);
const b = spanBtn(el("span", m.className + " aq-set" + (own ? " own" : "")));
// a window counted in a unit, with its total, can be capped at an amount
// of it in place of a share
const unit = w.limit > 0 && w.unit ? t(w.unit) : "";
const amountText = (v) => (countFormat.format(v) + " " + unit).trim();
const b = spanBtn(el("span", m.className + " aq-set" + (own || amount ? " own" : "")));
b.append(...m.childNodes);
if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own })));
if (amount) b.append(el("span", "aq-own", t("Cap {n}", { n: amountText(amount) })));
else if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own })));
const reset = m.title || (w.resetsAt ? resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString(intlLang())) : "");
b.title = [reset, own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name })
b.title = [reset, amount ? t("{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change", { window: name, n: amountText(amount) })
: own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name })
: own ? t("{window} has a cap of its own: magpie counts this account as used up once {window} is at {n}%, until it renews. Click to change", { window: name, n: own })
: t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n");
b.setAttribute("aria-haspopup", "menu");
@@ -14240,6 +14257,10 @@ function windowCapMeter(m, p, user, w) {
: v >= 100 ? t("{window} of {who} has no cap", { window: name, who: user })
: t("{who} stops at {n}% of {window}", { who: user, n: v, window: name }));
const other = () => pillNumber(b, own && own < 100 ? String(own) : "", "1–99", "acap-in", t("Cap for {window}, in percent", { window: name }), capOf, t("A cap is a share from 1% to 99%"), own, set);
const setAmount = (v) => accountAction("provider/windowcap", { id: p.id, account: user, window: w.capId, ...w.tiers && { windows: ids }, amount: v },
t("{who} stops at {n} of {window}", { who: user, n: amountText(v), window: name }));
const amountOf = (v) => { v = Number(v.replace(/[\s,]/g, "")); return v > 0 && Number.isFinite(v) ? v : null; };
const otherAmount = () => pillNumber(b, amount ? String(amount) : "", unit, "acap-in", t("Cap for {window}, in {unit}", { window: name, unit }), amountOf, t("An amount above 0"), amount, setAmount);
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
@@ -14251,9 +14272,11 @@ function windowCapMeter(m, p, user, w) {
];
for (const n of shares) opts.push({ v: n, name: n + "%", note: "", literalName: true });
opts.push({ v: -1, name: "Other…", note: "A share of your own, 1–99%" });
openProtoMenu(b, opts, own, (v) => {
if (unit) opts.push({ v: -2, name: t("Amount…"), note: amount ? amountText(amount) : t("At most this much {unit}", { unit }), literalName: true });
openProtoMenu(b, opts, amount ? -2 : own, (v) => {
if (v === -1) return other();
if (v !== own) set(v);
if (v === -2) return otherAmount();
if (v !== own || amount) set(v);
}, t("Cap for {window}", { window: name }), "sess-menu");
};
return b;
+28
View File
@@ -4042,6 +4042,13 @@ const I18N = {
"{window} of {who} has no cap": "{who} 的{window}不设上限",
"{who} stops at {n}% of {window}": "{who} 的{window}用到 {n}% 即停",
"Cap for {window}, in percent": "{window}的上限,百分比",
"Cap {n}": "上限 {n}",
"{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}有自己的上限:这个账号的{window}用到 {n} 后,magpie 就当它已用完,直到{window}重置。点击更改",
"{who} stops at {n} of {window}": "{who} 的{window}用到 {n} 即停",
"Cap for {window}, in {unit}": "{window}的上限,单位:{unit}",
"An amount above 0": "上限是大于 0 的数量",
"Amount…": "固定数量…",
"At most this much {unit}": "最多用这么多{unit}",
"Account's cap · {n}%": "账号上限 · {n}%",
"Account's cap · none": "账号上限 · 无",
"As the account's other windows": "与账号的其他窗口相同",
@@ -8775,6 +8782,13 @@ const I18N = {
"{window} of {who} has no cap": "{who} 的{window}不設上限",
"{who} stops at {n}% of {window}": "{who} 的{window}用到 {n}% 即停",
"Cap for {window}, in percent": "{window}的上限,百分比",
"Cap {n}": "上限 {n}",
"{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}有自己的上限:這個帳號的{window}用到 {n} 後,magpie 就當它已用完,直到{window}重置。點擊變更",
"{who} stops at {n} of {window}": "{who} 的{window}用到 {n} 即停",
"Cap for {window}, in {unit}": "{window}的上限,單位:{unit}",
"An amount above 0": "上限是大於 0 的數量",
"Amount…": "固定數量…",
"At most this much {unit}": "最多用這麼多{unit}",
"Account's cap · {n}%": "帳號上限 · {n}%",
"Account's cap · none": "帳號上限 · 無",
"As the account's other windows": "與帳號的其他時段相同",
@@ -13522,6 +13536,13 @@ const I18N = {
"{window} of {who} has no cap": "{who} の{window}は上限なし",
"{who} stops at {n}% of {window}": "{who} は{window}の {n}% で停止",
"Cap for {window}, in percent": "{window}の上限(%)",
"Cap {n}": "上限 {n}",
"{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}には独自の上限があります:このアカウントが{window}を {n} 使うと、magpie はリセットまで使い切ったものとみなします。クリックで変更",
"{who} stops at {n} of {window}": "{who} は{window}を {n} 使うと停止",
"Cap for {window}, in {unit}": "{window}の上限({unit})",
"An amount above 0": "上限は 0 より大きい量です",
"Amount…": "固定量…",
"At most this much {unit}": "{unit}をこの量まで",
"Account's cap · {n}%": "アカウントの上限 · {n}%",
"Account's cap · none": "アカウントの上限 · なし",
"As the account's other windows": "アカウントの他のウィンドウと同じ",
@@ -18284,6 +18305,13 @@ const I18N = {
"{window} of {who} has no cap": "{window} von {who} hat kein Limit",
"{who} stops at {n}% of {window}": "{who} stoppt bei {n} % von {window}",
"Cap for {window}, in percent": "Limit für {window}, in Prozent",
"Cap {n}": "Limit {n}",
"{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window} hat ein eigenes Limit: Sobald dieses Konto {n} von {window} verbraucht hat, gilt es für magpie als aufgebraucht, bis {window} sich erneuert. Klicke zum Ändern",
"{who} stops at {n} of {window}": "{who} stoppt bei {n} von {window}",
"Cap for {window}, in {unit}": "Limit für {window}, in {unit}",
"An amount above 0": "Eine Menge über 0",
"Amount…": "Menge…",
"At most this much {unit}": "Höchstens so viele {unit}",
"Account's cap · {n}%": "Limit des Kontos · {n} %",
"Account's cap · none": "Limit des Kontos · keins",
"As the account's other windows": "Wie die anderen Zeitfenster des Kontos",
+15 -3
View File
@@ -181,6 +181,9 @@ type providerJSON struct {
// one for that window apart, by the account and then the window's
// capId (provider.AccountWindowCaps); 100 is none on that window
AccountWindowCaps map[string]map[string]int `json:"accountWindowCaps,omitempty"`
// AccountWindowAmounts: a window capped at a fixed amount of its own
// unit in place of a share (provider.AccountWindowAmounts)
AccountWindowAmounts map[string]map[string]float64 `json:"accountWindowAmounts,omitempty"`
// the names the user gave its accounts, by the account in lower
// case (provider.AccountNames, #1515), and the name of the key plan
// each account was found to stand in for (provider.SeatNameOf): the
@@ -768,7 +771,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate,
@@ -1665,6 +1668,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// Windows, for windowcap, in place of Window: a family's
// windows, which the GUI shows as one meter
Windows []string `json:"windows"`
// Amount, for windowcap in place of Cap: a fixed amount of the
// window's own unit the account is used to at most, 0 to lift it
// (provider.AccountWindowAmounts)
Amount *float64 `json:"amount"`
// Weight, for accountweight: the account's share under By
// weight routing, 1 to provider.MaxKeyWeight (0 or 1: none)
Weight int `json:"weight"`
@@ -2094,7 +2101,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// limits on requests at once, with accountconcurrency, and
// their weights, with accountweight
if old != nil {
in.AccountCaps, in.AccountWindowCaps = old.AccountCaps, old.AccountWindowCaps
in.AccountCaps, in.AccountWindowCaps, in.AccountWindowAmounts = old.AccountCaps, old.AccountWindowCaps, old.AccountWindowAmounts
in.AccountConcurrency = old.AccountConcurrency
in.AccountWeights = old.AccountWeights
in.AccountNames = old.AccountNames // with accountname
@@ -2372,7 +2379,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if len(req.Windows) == 0 {
req.Windows = []string{req.Window}
}
if err := provider.SetWindowCaps(in.ID, req.Account, req.Windows, req.Cap); err != nil {
set := func() error { return provider.SetWindowCaps(in.ID, req.Account, req.Windows, req.Cap) }
if req.Amount != nil {
// a fixed amount of the window's unit, 0 to lift it
set = func() error { return provider.SetWindowAmount(in.ID, req.Account, req.Windows, *req.Amount) }
}
if err := set(); err != nil {
fail(rw, err)
return
}
+63 -8
View File
@@ -51,6 +51,13 @@ const past = () => ({
const aside = (name, used) => ({ ...win(name, used, 600), ownCap: true });
const credits = (plan) => ({ provider: "codex", windows: [aside("Credits", plan), aside("Extra credits", 0), win("Total credits", plan / 4, 600)] });
const split = () => ({ "me@example.com": credits(60), "Friend@Example.com": credits(60) });
// a window counted in a unit with its total (9won_25273 on Discord: a
// day's credits) can be capped at an amount of it instead: me has used 120
// of the day's 1000 credits
const daily = () => ({
"me@example.com": { provider: "codex", windows: [win("5 hours", 10, 4), { ...win("Daily credits", 12, 20), amount: 120, limit: 1000, unit: "credits" }] },
"Friend@Example.com": under()["Friend@Example.com"],
});
function serve(lang, posts, use) {
const ps = fresh();
@@ -71,11 +78,17 @@ function serve(lang, posts, use) {
posts.push(body);
const p = providers.providers.find((x) => x.id === body.id);
const all = structuredClone(p.accountWindowCaps || {}), k = body.account.toLowerCase();
const caps = all[k] || {};
if (body.cap) caps[body.window] = body.cap;
else delete caps[body.window];
const amts = structuredClone(p.accountWindowAmounts || {});
const caps = all[k] || {}, amt = amts[k] || {};
// an amount and a share on one window replace each other
delete caps[body.window];
delete amt[body.window];
if (body.amount) amt[body.window] = body.amount;
else if (body.cap) caps[body.window] = body.cap;
if (Object.keys(caps).length) all[k] = caps; else delete all[k];
if (Object.keys(amt).length) amts[k] = amt; else delete amts[k];
p.accountWindowCaps = all;
p.accountWindowAmounts = amts;
return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
@@ -86,11 +99,11 @@ function serve(lang, posts, use) {
}
const words = {
en: { cap: (n) => `Cap ${n}%`, none: "No cap", byWindow: "Caps by window", held: "At its cap · back in 3h", head: "Cap for 5 hours", account: "Account's cap · none", off: "No cap on this window", other: "Other…" },
zh: { cap: (n) => `上限 ${n}%`, none: "不设上限", byWindow: "按窗口设上限", held: "已达上限 · 3 小时后恢复", head: "5 小时的上限", account: "账号上限 · 无", off: "此窗口不设上限", other: "其他…" },
"zh-TW": { cap: (n) => `上限 ${n}%`, none: null, byWindow: "按時段設上限", held: null, head: "5 小時的上限", account: "帳號上限 · 無", off: "此時段不設上限", other: null },
ja: { cap: null, none: null, byWindow: "ウィンドウごとの上限", held: null, head: "5 時間の上限", account: "アカウントの上限 · なし", off: "このウィンドウは上限なし", other: null },
de: { cap: null, none: null, byWindow: "Limits je Zeitfenster", held: null, head: "Limit für 5 Stunden", account: "Limit des Kontos · keins", off: "Kein Limit für dieses Zeitfenster", other: null },
en: { cap: (n) => `Cap ${n}%`, none: "No cap", byWindow: "Caps by window", held: "At its cap · back in 3h", head: "Cap for 5 hours", account: "Account's cap · none", off: "No cap on this window", other: "Other…" , amount: "Amount…", own: "Cap 300 credits" },
zh: { cap: (n) => `上限 ${n}%`, none: "不设上限", byWindow: "按窗口设上限", held: "已达上限 · 3 小时后恢复", head: "5 小时的上限", account: "账号上限 · 无", off: "此窗口不设上限", other: "其他…" , amount: "固定数量…", own: "上限 300 积分" },
"zh-TW": { cap: (n) => `上限 ${n}%`, none: null, byWindow: "按時段設上限", held: null, head: "5 小時的上限", account: "帳號上限 · 無", off: "此時段不設上限", other: null , amount: "固定數量…", own: "上限 300 積分" },
ja: { cap: null, none: null, byWindow: "ウィンドウごとの上限", held: null, head: "5 時間の上限", account: "アカウントの上限 · なし", off: "このウィンドウは上限なし", other: null , amount: "固定量…", own: "上限 300 クレジット" },
de: { cap: null, none: null, byWindow: "Limits je Zeitfenster", held: null, head: "Limit für 5 Stunden", account: "Limit des Kontos · keins", off: "Kein Limit für dieses Zeitfenster", other: null , amount: "Menge…", own: "Limit 300 Credits" },
};
const NEW = [
"No cap on {window}: it is used to 100%, whatever this account's cap. Click to change",
@@ -100,6 +113,8 @@ const NEW = [
"Cap for {window}, in percent", "Account's cap · {n}%", "Account's cap · none", "As the account's other windows",
"No cap on this window", "Use this window to 100%", "Cap for {window}", "Caps by window",
"A window can have a cap of its own: click its meter below",
"Cap {n}", "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change",
"{who} stops at {n} of {window}", "Cap for {window}, in {unit}", "An amount above 0", "Amount…", "At most this much {unit}",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -198,6 +213,46 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
test(`${label}: a window counted in a unit is capped at an amount of it, typed, and lifted`, async (t) => {
const { page, errors, posts } = await open(t, "amount", daily);
// the day's credits: Amount… last, after Other…
await still(page, "me@example.com", meter(page, "me@example.com", 1));
await menu(page).waitFor();
const names = await menu(page).locator(".pm-name").allTextContents();
assert.equal(names.length, 9);
assert.equal(names[8], w.amount);
let n = posts.length;
await item(page, w.amount).click();
const typed = row(page, "me@example.com").locator("input.acap-in");
await typed.waitFor();
await typed.fill("0");
await typed.press("Enter");
await page.waitForTimeout(150);
assert.equal(posts.length, n, "0 posted as an amount");
await still(page, "me@example.com", meter(page, "me@example.com", 1));
await item(page, w.amount).click();
await typed.waitFor();
await typed.fill("300");
await typed.press("Enter");
assert.deepEqual(await posted(posts, n), { id: "codex", account: "me@example.com", window: "daily credits", amount: 300 });
await row(page, "me@example.com").locator(".aq-own").first().waitFor();
assert.equal(await row(page, "me@example.com").locator(".aq-own").first().textContent(), w.own);
// the mark stands at 300 of 1000; 120 used is under it
assert.deepEqual(await row(page, "me@example.com").locator(".aq-cap").evaluateAll((ms) => ms.map((m) => m.style.left)), ["30%"]);
assert.equal(await row(page, "me@example.com").locator(".acap-held").count(), 0);
// the amount is current in the menu; the five hours, with no unit, has no Amount…
await still(page, "me@example.com", meter(page, "me@example.com", 1));
assert.equal(await menu(page).locator(".pm-item.on .pm-name").textContent(), w.amount);
// back to the account's: 0, the amount goes
n = posts.length;
await item(page, w.account).click();
assert.deepEqual(await posted(posts, n), { id: "codex", account: "me@example.com", window: "daily credits", cap: 0 });
await page.waitForFunction(() => !document.querySelector('.editor .acc[data-account-id="me@example.com"] .aq-own'));
await still(page, "me@example.com", meter(page, "me@example.com", 0));
assert.equal(await menu(page).locator(".pm-name").count(), 8);
assert.deepEqual(errors, []);
});
test(`${label}: a window's cap is set from its meter in the app's menu, typed, and lifted`, async (t) => {
const { page, errors, posts } = await open(t, "set", under);
// me's five hours: the menu, headed by the window, no native select
+187 -19
View File
@@ -22,6 +22,20 @@ package provider
// while any window is at or past its own share. The on-demand windows
// (Aside) are not the allowance and never count.
//
// A window whose reading counts it in a unit, with its total (WorkBuddy's
// credits, a plan's requests or tokens), can instead be capped at a fixed
// amount of that unit (9won_25273 on Discord: at most N credits a day of a
// daily-credits window, then the next account), kept per account and
// window (AccountWindowAmounts). The account is held once the window's
// count is at or past the amount, as at a share; a window read without a
// total leaves the amount aside and takes the account's share. A window
// has a share of its own or an amount, never both: setting one clears the
// other.
//
// The cap reads the vendor's own count of the window, so what the account
// spent outside magpie (the vendor's app, another machine) counts toward
// it as the vendor reports it; magpie can only hold back its own requests.
//
// The cap is the user's, not the vendor's: what it holds back never spends
// a Codex reset. The resets are spent on the vendor's own 100% (weekUsedUp,
// usedUp, BackAt, heldUp), which the cap doesn't touch.
@@ -29,6 +43,7 @@ package provider
import (
"fmt"
"maps"
"math"
"slices"
"strconv"
"strings"
@@ -71,6 +86,9 @@ func AccountCapOf(id, user string) int {
type WindowCaps struct {
All int
Windows map[string]int
// Amounts are the windows capped at a fixed amount of their own unit
// instead, by WindowCapID (AccountWindowAmounts)
Amounts map[string]float64
Credits bool
}
@@ -94,6 +112,34 @@ func (c WindowCaps) Of(name string) (share int, credits bool) {
return share, false
}
// limitShare is the share at which a window holds the account, as Of
// (own when aside), with an amount cap on it read against the window's
// count: amount is then the cap in the window's unit, and share that
// amount as a share of the window's total of. A window read without a
// total (of 0) leaves its amount aside.
func (c WindowCaps) limitShare(name string, of float64, aside bool) (share float64, credits bool, amount float64) {
if a := c.Amounts[WindowCapID(name)]; a > 0 && of > 0 {
return a / of * 100, false, a
}
if aside {
return float64(c.own(name)), false, 0
}
n, credits := c.Of(name)
return float64(n), credits, 0
}
// past says whether a window at used percent, count of its unit, is at or
// past the cap limitShare gave: by its count when the cap is an amount.
func past(share, amount, used, count float64) bool {
if share <= 0 {
return false
}
if amount > 0 {
return count >= amount
}
return used >= share
}
// own is the share at which a window set aside holds the account (Limit's
// aside): only a cap the user set on that window itself, never the
// account's or the credits', 0 for none.
@@ -110,6 +156,11 @@ func (c WindowCaps) Holds() bool {
if c.All > 0 || c.Credits {
return true
}
for _, v := range c.Amounts {
if v > 0 {
return true
}
}
for _, v := range c.Windows {
if v >= MinCap && v <= MaxCap {
return true
@@ -122,21 +173,21 @@ func (c WindowCaps) Holds() bool {
// and its windows' own. As with AccountCap, an account made afresh beside
// the agent's own reads them from providers.json.
func (p Provider) CapsOf(user string) WindowCaps {
caps, wins := p.AccountCaps, p.AccountWindowCaps
if caps == nil && wins == nil {
caps, wins, amts := p.AccountCaps, p.AccountWindowCaps, p.AccountWindowAmounts
if caps == nil && wins == nil && amts == nil {
if s, ok := storedPicks(p.ID); ok {
caps, wins = s.AccountCaps, s.AccountWindowCaps
caps, wins, amts = s.AccountCaps, s.AccountWindowCaps, s.AccountWindowAmounts
}
}
k := accountKey(user)
return WindowCaps{All: caps[k], Windows: wins[k]}
return WindowCaps{All: caps[k], Windows: wins[k], Amounts: amts[k]}
}
// AccountCapsOf is CapsOf of the provider id.
func AccountCapsOf(id, user string) WindowCaps {
if s, ok := storedPicks(id); ok {
k := accountKey(user)
return WindowCaps{All: s.AccountCaps[k], Windows: s.AccountWindowCaps[k]}
return WindowCaps{All: s.AccountCaps[k], Windows: s.AccountWindowCaps[k], Amounts: s.AccountWindowAmounts[k]}
}
return WindowCaps{}
}
@@ -177,9 +228,10 @@ func SetWindowCaps(id, ref string, windows []string, cap int) error {
return fmt.Errorf("%s has no account %q", p.Name, ref)
}
k := accountKey(r)
if !slices.ContainsFunc(ws, func(w string) bool { return p.AccountWindowCaps[k][w] != cap }) {
if !slices.ContainsFunc(ws, func(w string) bool { return p.AccountWindowCaps[k][w] != cap || p.AccountWindowAmounts[k][w] > 0 }) {
return nil
}
p.AccountWindowAmounts = withoutAmounts(p.AccountWindowAmounts, k, ws)
all := map[string]map[string]int{}
for u, m := range p.AccountWindowCaps {
all[u] = maps.Clone(m)
@@ -201,6 +253,96 @@ func SetWindowCaps(id, ref string, windows []string, cap int) error {
return Save(*p)
}
// SetWindowAmount caps the windows named windows of the account ref of the
// subscription id at amount of their own unit (credits, requests, tokens),
// in place of a share of their own; 0 lifts it, and the windows follow the
// account's cap again.
func SetWindowAmount(id, ref string, windows []string, amount float64) error {
if amount < 0 || math.IsNaN(amount) || math.IsInf(amount, 0) {
return fmt.Errorf("a window's cap is an amount above 0, not %v", amount)
}
var ws []string
for _, w := range windows {
if w = WindowCapID(w); w == "" {
return fmt.Errorf("name the usage window to cap")
}
ws = append(ws, w)
}
if len(ws) == 0 {
return fmt.Errorf("name the usage window to cap")
}
p, err := Find(id)
if err != nil {
return err
}
if p.Account == nil {
return fmt.Errorf("%s has keys, not subscription accounts with usage windows to cap", p.Name)
}
r, ok := p.accountRef(ref)
if !ok {
return fmt.Errorf("%s has no account %q", p.Name, ref)
}
k := accountKey(r)
if !slices.ContainsFunc(ws, func(w string) bool {
_, own := p.AccountWindowCaps[k][w]
return p.AccountWindowAmounts[k][w] != amount || own
}) {
return nil
}
amts := withoutAmounts(p.AccountWindowAmounts, k, nil)
if amount > 0 {
if amts == nil {
amts = map[string]map[string]float64{}
}
if amts[k] == nil {
amts[k] = map[string]float64{}
}
for _, w := range ws {
amts[k][w] = amount
}
} else {
amts = withoutAmounts(amts, k, ws)
}
p.AccountWindowAmounts = amts
// an amount stands in for the window's own share
if own := p.AccountWindowCaps[k]; own != nil {
all := map[string]map[string]int{}
for u, m := range p.AccountWindowCaps {
all[u] = maps.Clone(m)
}
for _, w := range ws {
delete(all[k], w)
}
if len(all[k]) == 0 {
delete(all, k)
}
p.AccountWindowCaps = all
}
return Save(*p)
}
// withoutAmounts is a copy of m with account k's amounts on windows ws
// left out (none for a nil ws); nil for none left.
func withoutAmounts(m map[string]map[string]float64, k string, ws []string) map[string]map[string]float64 {
var out map[string]map[string]float64
for u, as := range m {
c := maps.Clone(as)
if u == k {
for _, w := range ws {
delete(c, w)
}
}
if len(c) == 0 {
continue
}
if out == nil {
out = map[string]map[string]float64{}
}
out[u] = c
}
return out
}
// SetAccountCap caps the account ref of the subscription id at cap percent
// of its windows; 0 lifts the cap.
func SetAccountCap(id, ref string, cap int) error {
@@ -289,6 +431,29 @@ func normalWindowCaps(m map[string]map[string]int) map[string]map[string]int {
return out
}
// normalWindowAmounts is m as it is kept: accounts and windows in lower
// case, amounts above 0, empty ones left out; nil for none.
func normalWindowAmounts(m map[string]map[string]float64) map[string]map[string]float64 {
var out map[string]map[string]float64
for u, ws := range m {
u = accountKey(u)
for w, a := range ws {
w = WindowCapID(w)
if u == "" || w == "" || !(a > 0) || math.IsInf(a, 0) {
continue
}
if out == nil {
out = map[string]map[string]float64{}
}
if out[u] == nil {
out[u] = map[string]float64{}
}
out[u][w] = a
}
}
return out
}
// CapHold is how an account is held by its caps for a model: the share
// used of the fullest window holding it, that window's cap, when the last
// of those windows renews (zero when one doesn't say), and Credits when
@@ -298,6 +463,11 @@ type CapHold struct {
Cap int
Back time.Time
Credits bool
// Amount is the cap when the fullest window holding it is capped at a
// fixed amount (AccountWindowAmounts): Count of it used, in Unit. Cap
// is then that amount as a share, rounded up.
Amount, Count float64
Unit string
}
// CapHeld says how an allowance, as last known, holds the account for
@@ -312,11 +482,8 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol
var h *CapHold
unknown, byCap := false, false
for _, l := range a.capLimits(model) {
share, credits := caps.Of(l.Name)
if l.aside {
share, credits = caps.own(l.Name), false
}
if share <= 0 || l.Used < float64(share) {
share, credits, amount := caps.limitShare(l.Name, l.Of, l.aside)
if !past(share, amount, l.Used, l.Amount) {
continue
}
if !l.Resets.IsZero() && !l.Resets.After(now) {
@@ -326,7 +493,11 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol
h = &CapHold{}
}
if l.Used > h.Used || h.Cap == 0 {
h.Used, h.Cap = l.Used, share
h.Used, h.Cap = l.Used, min(int(math.Ceil(share)), 100)
h.Amount, h.Count, h.Unit = 0, 0, ""
if amount > 0 {
h.Amount, h.Count, h.Unit = amount, l.Amount, l.Unit
}
}
byCap = byCap || !credits
if l.Resets.IsZero() {
@@ -356,11 +527,8 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti
}
model = strings.ToLower(model)
for _, l := range a.capLimits(model) {
share, _ := caps.Of(l.Name)
if l.aside {
share = caps.own(l.Name)
}
if share <= 0 || l.Used < float64(share)-points {
share, _, amount := caps.limitShare(l.Name, l.Of, l.aside)
if share <= 0 || l.Used < share-points && (amount <= 0 || l.Amount < amount) {
continue
}
if !l.Resets.IsZero() && !l.Resets.After(now) {
@@ -377,8 +545,8 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti
// caps reach nothing.
func capReached(q SubscriptionQuota, caps WindowCaps, now time.Time) bool {
for _, w := range q.Windows {
share, _ := caps.Of(w.Name)
if share <= 0 || w.Aside || w.Model != "" || w.Used < float64(share) {
share, _, amount := caps.limitShare(w.Name, w.Limit, false)
if w.Aside || w.Model != "" || !past(share, amount, w.Used, w.Amount) {
continue
}
if w.ResetsAt != nil && !w.ResetsAt.After(now) {
@@ -0,0 +1,115 @@
package provider
import (
"math"
"testing"
"time"
)
// 9won_25273 on Discord: an account capped at a fixed amount of a window
// counted in a unit (at most 300 of a day's 1000 credits) is held once
// the vendor's count reaches it, and its share is the amount's share of
// the total; a window read without a total leaves the amount aside.
func TestWindowAmountCapHeld(t *testing.T) {
now := time.Now()
day := now.Add(5 * time.Hour)
read := func(count float64) Allowance {
return allowanceOf([]QuotaWindow{
{Name: "Daily credits", Used: count / 10, Amount: count, Limit: 1000, Unit: "credits", ResetsAt: &day, Span: 24 * time.Hour},
}, now)
}
caps := WindowCaps{Amounts: map[string]float64{"daily credits": 300}}
if !caps.Holds() {
t.Fatal("an amount cap holds nothing")
}
if h := read(299).CapHeld("gpt-6", caps, now); h != nil {
t.Fatalf("299 of 300 credits, held: %+v", h)
}
h := read(300).CapHeld("gpt-6", caps, now)
if h == nil || h.Amount != 300 || h.Count != 300 || h.Unit != "credits" || h.Cap != 30 || !h.Back.Equal(day) || h.Credits {
t.Fatalf("300 of 300 credits: %+v", h)
}
// the amount's share rounds up: 250.5 of 1000 holds at 26%, not 25%
odd := WindowCaps{Amounts: map[string]float64{"daily credits": 250.5}}
if h := read(260).CapHeld("gpt-6", odd, now); h == nil || h.Cap != 26 {
t.Fatalf("250.5 of 1000: %+v", h)
}
// the amount stands in for the account's own share on that window
both := WindowCaps{All: 10, Amounts: map[string]float64{"daily credits": 300}}
if h := read(200).CapHeld("gpt-6", both, now); h != nil {
t.Fatalf("200 credits, at 20%% past the account's 10%%, held: %+v", h)
}
// near the cap by a few points of its share
if !read(290).NearCap("gpt-6", caps, 2, now) || read(200).NearCap("gpt-6", caps, 2, now) {
t.Fatal("NearCap by the amount's share")
}
// renewed since it was read
if h := read(400).CapHeld("gpt-6", caps, day.Add(time.Minute)); h != nil {
t.Fatalf("held by a renewed window: %+v", h)
}
// a reading with no total: the amount can't be told, the account's
// share goes on
noTotal := allowanceOf([]QuotaWindow{{Name: "Daily credits", Used: 50, Amount: 900, ResetsAt: &day}}, now)
if h := noTotal.CapHeld("gpt-6", caps, now); h != nil {
t.Fatalf("an amount read against no total held: %+v", h)
}
if h := noTotal.CapHeld("gpt-6", both, now); h == nil || h.Cap != 10 || h.Amount != 0 {
t.Fatalf("no total, the account's 10%%: %+v", h)
}
// capReached, for the agent signed in, goes by the count too
ws := []QuotaWindow{{Name: "Daily credits", Used: 31, Amount: 310, Limit: 1000, Unit: "credits", ResetsAt: &day}}
if !capReached(SubscriptionQuota{Windows: ws}, caps, now) {
t.Fatal("310 of 300 credits not reached")
}
ws[0].Amount, ws[0].Used = 100, 10
if capReached(SubscriptionQuota{Windows: ws}, caps, now) {
t.Fatal("100 of 300 credits reached")
}
}
// An amount and a share on one window replace each other; 0 lifts the
// amount; a bad amount is refused; settings keep it in lower case.
func TestSetWindowAmount(t *testing.T) {
signIn(t) // me@example.com on codex
if err := SetWindowCap("codex", "me@example.com", "Weekly", 40); err != nil {
t.Fatal(err)
}
if err := SetWindowAmount("codex", "ME@example.com", []string{"Weekly"}, 300); err != nil {
t.Fatal(err)
}
c := AccountCapsOf("codex", "me@example.com")
if c.Amounts["weekly"] != 300 || c.Windows != nil {
t.Fatalf("the amount beside the week's own share: %+v", c)
}
if err := SetWindowCap("codex", "me@example.com", "weekly", 50); err != nil {
t.Fatal(err)
}
c = AccountCapsOf("codex", "me@example.com")
if c.Amounts != nil || c.Windows["weekly"] != 50 {
t.Fatalf("a share set over the amount: %+v", c)
}
if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, 12.5); err != nil {
t.Fatal(err)
}
for _, bad := range []float64{-1, math.NaN(), math.Inf(1)} {
if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, bad); err == nil {
t.Errorf("%v taken", bad)
}
}
if err := SetWindowAmount("codex", "me@example.com", []string{" "}, 10); err == nil {
t.Error("a window with no name taken")
}
if p, _ := Find("codex"); p.AccountWindowAmounts["me@example.com"]["weekly"] != 12.5 {
t.Fatalf("saved as %+v", p.AccountWindowAmounts)
}
if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, 0); err != nil {
t.Fatal(err)
}
if p, _ := Find("codex"); p.AccountWindowAmounts != nil || p.AccountWindowCaps != nil {
t.Fatalf("lifted, still %+v %+v", p.AccountWindowAmounts, p.AccountWindowCaps)
}
got := normalWindowAmounts(map[string]map[string]float64{"ME@Example.com": {" Weekly ": 5, "five": 0, "inf": math.Inf(1), "nan": math.NaN()}, "": {"x": 1}})
if len(got) != 1 || len(got["me@example.com"]) != 1 || got["me@example.com"]["weekly"] != 5 {
t.Fatalf("normal: %+v", got)
}
}
+2 -2
View File
@@ -394,8 +394,8 @@ func roomLeft(q SubscriptionQuota, share float64, caps WindowCaps, now time.Time
continue
}
line := share
if c, _ := caps.Of(w.Name); c > 0 && float64(c) < line {
line = float64(c)
if c, _, _ := caps.limitShare(w.Name, w.Limit, false); c > 0 && c < line {
line = c
}
room = min(room, line-w.Used)
}
+1
View File
@@ -166,6 +166,7 @@ func moveAccountSettings(id string, moves map[string]string) error {
moved = moveKey(p.AccountModels, from, to) || moved
moved = moveKey(p.AccountCaps, from, to) || moved
moved = moveKey(p.AccountWindowCaps, from, to) || moved
moved = moveKey(p.AccountWindowAmounts, from, to) || moved
moved = moveKey(p.AccountConcurrency, from, to) || moved
moved = moveKey(p.AccountWeights, from, to) || moved
moved = moveKey(p.AccountNames, from, to) || moved
+15 -1
View File
@@ -484,6 +484,12 @@ type Provider struct {
// and then the window's WindowCapID: 1–99, or 100 for none on it. A
// window not in it takes the account's AccountCaps.
AccountWindowCaps map[string]map[string]int `json:"accountWindowCaps,omitempty"`
// AccountWindowAmounts is, for a subscription, the fixed amount of a
// window's own unit (credits, requests, tokens) an account is used to
// at most where the user set one in place of a share (9won_25273 on
// Discord), by account and window as AccountWindowCaps. A window has
// one or the other.
AccountWindowAmounts map[string]map[string]float64 `json:"accountWindowAmounts,omitempty"`
// CapStop, for a subscription whose accounts are capped, ends there
// (plugins#349): while every account is held at its cap, a request is
// answered 429, as the vendor would, rather than sent on to Fallback.
@@ -905,6 +911,13 @@ func (p Provider) clone() Provider {
}
p.AccountWindowCaps = m
}
if p.AccountWindowAmounts != nil {
m := make(map[string]map[string]float64, len(p.AccountWindowAmounts))
for k, v := range p.AccountWindowAmounts {
m[k] = maps.Clone(v)
}
p.AccountWindowAmounts = m
}
p.AccountConcurrency = maps.Clone(p.AccountConcurrency)
p.AccountWeights = maps.Clone(p.AccountWeights)
p.Contexts = maps.Clone(p.Contexts)
@@ -1011,7 +1024,7 @@ func accountSettings(a, pk Provider) Provider {
// plugin's provider too (isee1_1 on Discord)
a.Unredacted = pk.Unredacted
a.Proxy, a.AccountProxies, a.AccountModels, a.AccountModelsAll = pk.Proxy, pk.AccountProxies, pk.AccountModels, pk.AccountModelsAll
a.AccountCaps, a.AccountWindowCaps = pk.AccountCaps, pk.AccountWindowCaps
a.AccountCaps, a.AccountWindowCaps, a.AccountWindowAmounts = pk.AccountCaps, pk.AccountWindowCaps, pk.AccountWindowAmounts
a.CapStop, a.CapCareful = pk.CapStop, pk.CapCareful
a.UseFirst = pk.UseFirst
a.AccountNames = pk.AccountNames
@@ -1677,6 +1690,7 @@ func normalize(p Provider) Provider {
p.AccountModelsAll = normalModelsAll(p.AccountModelsAll, p.AccountModels)
p.AccountCaps = normalAccountCaps(p.AccountCaps)
p.AccountWindowCaps = normalWindowCaps(p.AccountWindowCaps)
p.AccountWindowAmounts = normalWindowAmounts(p.AccountWindowAmounts)
p.AccountNames = normalAccountNames(p.AccountNames)
p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps)
p.KeyOwnBalances = normalKeyOwnBalances(p.KeyOwnBalances)