gateway, gui: a gateway key's limit can run every N days, and Reset usage counts it from 0 again (#1509, PennyVibe)

PennyVibe asked for a key limit on a cycle of N days rather than a
calendar day, week or month, and for a way to zero a key's usage by
hand. Both are in.

Every N days (N from 1 to 3650):
- access.Limit gains Days and Since. Since is magpie's own: the
  limit-key action always works it out, and a value a client sends is
  ignored.
- The cycle starts when the limit is set. Each cycle is N×24h of
  absolute time from Since, so a restart, a time-zone change or a DST
  shift doesn't move it.
- Changing only the caps or "count cache reads" keeps the cycle.
  Changing N or the period, or turning the limit on, starts a new
  cycle now.
- A hand-written "days" limit with no Since runs from the Unix epoch.
- The GUI window menu offers "Every N days" with a Days field. The CLI
  takes `magpie gateway-key limit <id> 10d`. The refusal and status
  name the cycle ("for this 1-day cycle").

Reset usage:
- A new action, reset-limit-key, is on the editor's "Reset usage"
  button (after a confirm) and on `magpie gateway-key limit <id> reset`.
- It sets Since to now, so tokens and cost both count from 0 together.
- An N-day key starts a new cycle then.
- A day, week or month key keeps its window's end, so it stays on the
  calendar. Only the calls before the reset stop counting.
- The usage log is not touched. Authenticate reloads keys each request,
  so the reset takes effect at once.

Keys saved before keep their JSON byte for byte (omitzero, nothing
written on load).

Docs: reference.md documents the cycle and reset rules. The docker page
(en, zh, ja) mentions every-N-days.

Run:
- go test -tags nogui ./... with a temp HOME.
- New Go tests:
  - TestLimitDaysCycle covers the NY DST, UTC and UTC+8 boundaries.
  - TestLimitCalendarReset.
  - TestLimitSetAndReset covers keep/restart, an old key's JSON left
    untouched, and errors.
  - TestKeyLimitDaysCycleAndReset covers the 429 text and header, a
    restart, the cycle boundary, and Reset clearing the token and cost
    caps together.
  - TestKeyLimitCalendarReset.
  - TestGatewayKeyLimitCLI covers 10d, reset and bad args.
- Broken by hand: with reset leaving Since alone,
  TestLimitSetAndReset, TestKeyLimitDaysCycleAndReset and
  TestKeyLimitCalendarReset go red.
- gofmt -l is clean. GOOS=linux and GOOS=windows go vet -tags nogui
  pass on ., access, budget, gateway and gui.
- GUI: the new gateway-key-cycle.test.cjs runs in chromium and webkit ×
  en, zh, zh-TW, ja and de, with a narrow-width check. Also run, in both
  engines: every test using the caller-keys fixture, i18n-keys,
  gui-ja, gui-de and gui-zh-tw (80 pass).
- Real use:
  - Sandbox magpie (temp HOME, gateway 127.0.0.1:3691, dev UI 3692)
    with a fake OpenAI upstream (300+50 tokens a call).
  - `gateway-key limit <id> 1d --tokens 700` allowed 2 calls with curl,
    then a 429 "for this 1-day cycle" with X-Magpie-Limit-Reset a day
    after it was set.
  - Pressed Reset usage in the GUI with Playwright and confirmed. The
    badge was no longer spent and showed 0 of 700, and curl passed 2
    calls again before the next 429.
This commit is contained in:
yetone
2026-10-10 22:53:11 +08:00
parent f5c0626770
commit 3541ec2fd5
17 changed files with 771 additions and 53 deletions
+16 -1
View File
@@ -380,6 +380,8 @@ magpie gateway-key rotate <id> # prints the replacement; identity stays
magpie gateway-key remove <id> # revokes remote access
magpie gateway-key limit <id> week --tokens 2m --cost 5 # its own limit
magpie gateway-key limit <id> # limit, used, left and reset
magpie gateway-key limit <id> 10d --tokens 5m # every 10 days, from now
magpie gateway-key limit <id> reset # count its usage from 0 again
magpie gateway-key limit <id> off # no limit
magpie gateway-key models <id> openai/gpt-5 anthropic/* # only these models
magpie gateway-key models <id> all # every model
@@ -389,7 +391,12 @@ magpie gateway-key accounts <id> all # every account
Each gateway key can have its own **limit**: a token total, an estimated
cost in US$, or both, per day, week or month (calendar windows in local
time: from midnight, from Monday, from the 1st). Set it with **Limit** on
time: from midnight, from Monday, from the 1st), or every N days (#1509;
N from 1 to 3650). An N-day cycle starts when the limit is set and runs
N×24 hours, then the next one starts where it ended, so a restart, a
time-zone change or a daylight-saving shift doesn't move it. Changing only
the caps or **Count cache reads too** keeps the cycle; changing N or the
period, or turning the limit on, starts a new one then. Set it with **Limit** on
the key's row (saved with Save) or `magpie gateway-key limit`; the row shows
what the key has used, what is left and when it resets. Tokens counted are a
call's uncached input, output and cache writes, plus cache reads when **Count
@@ -402,6 +409,14 @@ counts are read from the usage log, so they survive a restart. A request in
flight holds a reservation (its body's size in tokens plus the key's mean
output per call), so requests sent at once overshoot by about one call; a
streamed reply is settled when it ends with the usage its vendor reported.
**Reset usage** in the key's limit editor (or `magpie gateway-key limit
<id> reset`) counts the key's tokens and cost from 0 together, from now. An
N-day key starts a new N-day cycle then. A day, week or month key keeps
its window's end (midnight, Monday, the 1st): only the calls before the
reset stop counting, so it doesn't drift off the calendar. The reset is
stored with the key (`since` in caller-keys.json, magpie's own: a value a
client sends is ignored), so it survives a restart; the usage log itself is
untouched. Keys saved before keep their JSON as it was.
A key can read its own status with `GET /v1/magpie/limit`. Requests from
this computer that send no gateway key are not limited; a gateway key used
from this computer is.
+29 -9
View File
@@ -119,19 +119,33 @@ func gatewayKeysTo(out io.Writer, args []string) error {
//
// magpie gateway-key limit <id> what it has used of its limit
// magpie gateway-key limit <id> off no limit
// magpie gateway-key limit <id> day|week|month [--tokens N] [--cost USD] [--cache-reads]
// magpie gateway-key limit <id> day|week|month|<N>d [--tokens N] [--cost USD] [--cache-reads]
// magpie gateway-key limit <id> reset count from 0 again, a new N-day cycle from now (#1509)
func gatewayKeyLimit(out io.Writer, args []string) error {
usage := fmt.Errorf("usage: magpie gateway-key limit <id> [off | day|week|month [--tokens N] [--cost USD] [--cache-reads]]")
usage := fmt.Errorf("usage: magpie gateway-key limit <id> [off | reset | day|week|month|<N>d [--tokens N] [--cost USD] [--cache-reads]]")
if len(args) == 0 {
return usage
}
id := args[0]
if len(args) > 1 {
var lim *access.Limit
if args[1] != "off" {
if args[1] == "reset" {
if len(args) > 2 {
return usage
}
if _, err := access.Update("reset-limit-key", access.Change{Key: id}); err != nil {
return err
}
} else if args[1] != "off" {
lim = &access.Limit{Period: args[1]}
if !slices.Contains(access.Periods, lim.Period) {
return fmt.Errorf("a limit's period is day, week or month, not %q", lim.Period)
if n, ok := strings.CutSuffix(args[1], "d"); ok {
days, err := strconv.Atoi(n)
if err != nil || days < 1 || days > access.MaxDays {
return fmt.Errorf("an N-day cycle is a whole number of days from 1 to %d, like 10d: %q", access.MaxDays, args[1])
}
lim = &access.Limit{Period: "days", Days: days}
} else if !slices.Contains(access.Periods, lim.Period) || lim.Period == "days" {
return fmt.Errorf("a limit's period is day, week, month or <N>d (every N days), not %q", lim.Period)
}
rest := args[2:]
for i := 0; i < len(rest); i++ {
@@ -177,8 +191,10 @@ func gatewayKeyLimit(out io.Writer, args []string) error {
} else if len(args) > 2 {
return usage
}
if _, err := access.Update("limit-key", access.Change{Key: id, Limit: lim}); err != nil {
return err
if args[1] != "reset" {
if _, err := access.Update("limit-key", access.Change{Key: id, Limit: lim}); err != nil {
return err
}
}
}
keys, err := access.List()
@@ -197,7 +213,7 @@ func gatewayKeyLimit(out io.Writer, args []string) error {
}
w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
fmt.Fprintf(w, "Key\t%s (%s)\n", k.Name, k.ID)
fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", st.Period, st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04"))
fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", (&access.Limit{Period: st.Period, Days: st.Days}).Per(), st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04"))
if st.TokenLimit > 0 {
counted := "input, output and cache writes"
if st.CacheReads {
@@ -274,7 +290,11 @@ func limitWords(k access.Key, now time.Time) string {
if st.CostLimit > 0 {
parts = append(parts, fmt.Sprintf("$%.2f/$%.2f", st.Cost, st.CostLimit))
}
s := strings.Join(parts, " ") + " per " + st.Period
per := " per " + st.Period
if st.Period == "days" {
per = fmt.Sprintf(" every %d days", st.Days)
}
s := strings.Join(parts, " ") + per
if st.Spent {
s += " (spent until " + st.Reset.Format("01-02 15:04") + ")"
}
+23 -1
View File
@@ -159,17 +159,39 @@ func TestGatewayKeyLimitCLI(t *testing.T) {
t.Fatal(got)
}
for _, args := range [][]string{{"limit"}, {"limit", id, "hour", "--tokens", "5"}, {"limit", id, "day"}, {"limit", id, "day", "--tokens", "lots"},
{"limit", id, "day", "--cost"}, {"limit", id, "day", "--what"}, {"limit", "missing", "day", "--tokens", "5"}, {"limit", id, "off", "extra"}} {
{"limit", id, "day", "--cost"}, {"limit", id, "day", "--what"}, {"limit", "missing", "day", "--tokens", "5"}, {"limit", id, "off", "extra"},
{"limit", id, "0d", "--tokens", "5"}, {"limit", id, "3651d", "--tokens", "5"}, {"limit", id, "xd", "--tokens", "5"}, {"limit", id, "days", "--tokens", "5"}, {"limit", id, "reset", "extra"}} {
if _, err := call(args...); err == nil {
t.Error("accepted", args)
}
}
// every 10 days (#1509), and Reset
if got, err = call("limit", id, "10d", "--cost", "800"); err != nil || !strings.Contains(got, "this 10-day cycle") {
t.Fatal(got, err)
}
keys, _ = access.List()
if l := keys[0].Limit; l == nil || l.Period != "days" || l.Days != 10 || l.Cost != 800 || l.Since.IsZero() {
t.Fatalf("limit kept as %+v", keys[0].Limit)
}
if got, _ := call("list"); !strings.Contains(got, "$0.00/$800.00 every 10 days") {
t.Fatal(got)
}
since := keys[0].Limit.Since
if got, err = call("limit", id, "reset"); err != nil || !strings.Contains(got, "this 10-day cycle") {
t.Fatal(got, err)
}
if keys, _ = access.List(); keys[0].Limit.Since.Before(since) || keys[0].Limit.Cost != 800 {
t.Fatalf("reset kept %+v", keys[0].Limit)
}
if got, err := call("limit", id, "off"); err != nil || !strings.Contains(got, "no limit") {
t.Fatal(got, err)
}
if keys, _ = access.List(); keys[0].Limit != nil {
t.Fatal("off kept", keys[0].Limit)
}
if _, err := call("limit", id, "reset"); err == nil {
t.Fatal("reset a key with no limit")
}
}
func TestGatewayKeyModelsCLI(t *testing.T) {
+18 -1
View File
@@ -16,6 +16,7 @@ import (
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/edit"
@@ -250,6 +251,9 @@ type Change struct {
Secret string `json:"secret,omitempty"`
}
// Now is when Update sets or resets a limit. A variable for the tests.
var Now = time.Now
// Update writes the named key store atomically.
func Update(action string, in Change) (string, error) {
mu.Lock()
@@ -307,7 +311,20 @@ func Update(action string, in Change) (string, error) {
if err != nil {
return "", err
}
if lim != nil {
lim.Since = sinceOf(keys[i].Limit, lim, Now().Round(0))
}
keys[i].Limit = lim
case "reset-limit-key":
// what the key has used is counted again from now (#1509),
// its tokens and cost together: a "days" cycle starts anew,
// a calendar window keeps its end
if !keys[i].Limit.Limited() {
return "", errors.New("This key has no limit to reset")
}
l := *keys[i].Limit
l.Since = Now().Round(0)
keys[i].Limit = &l
case "models-key":
ms, err := CleanModels(in.Models)
if err != nil {
@@ -334,7 +351,7 @@ func Update(action string, in Change) (string, error) {
default:
return "", fmt.Errorf("unknown key action %q", action)
}
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "models-key" && action != "accounts-key" {
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" {
mirror = &keys[i]
}
}
+83 -11
View File
@@ -2,32 +2,46 @@ package access
import (
"errors"
"fmt"
"math"
"time"
)
// Limit is a gateway key's budget for a calendar window in local time
// (#585): a day from midnight, a week from Monday's midnight, a month
// from the 1st's. Tokens counts each call's uncached input, output
// (reasoning included) and cache writes, and its cache reads too when
// CacheReads is set; Cost is an estimate in US dollars at the prices
// magpie shows on the Usage page, not a vendor's bill. A cap of 0 is no
// cap; a limit with neither is no limit.
// Limit is a gateway key's budget for a window: a calendar one in local
// time (#585), a day from midnight, a week from Monday's midnight, a
// month from the 1st's; or a cycle of Days days (#1509, period "days"),
// the first from when the limit was set, each next one Days×24h after
// the last. Tokens counts each call's uncached input, output (reasoning
// included) and cache writes, and its cache reads too when CacheReads is
// set; Cost is an estimate in US dollars at the prices magpie shows on
// the Usage page, not a vendor's bill. A cap of 0 is no cap; a limit with
// neither is no limit.
type Limit struct {
Period string `json:"period"`
Period string `json:"period"`
// Days is a "days" limit's cycle, 1 to MaxDays; 0 for the others.
Days int `json:"days,omitempty"`
Tokens int64 `json:"tokens,omitempty"`
Cost float64 `json:"cost,omitempty"`
CacheReads bool `json:"cacheReads,omitempty"`
// Since is magpie's, never the caller's (Update sets it): for "days",
// when the first cycle began, the limit set or last reset; for a
// calendar period, when it was last reset, so a call before it in
// the same window doesn't count. Zero for a calendar limit never
// reset, as every limit from before #1509 is.
Since time.Time `json:"since,omitzero"`
}
// Periods are the windows a limit can be set for.
var Periods = []string{"day", "week", "month"}
var Periods = []string{"day", "week", "month", "days"}
// MaxDays is the longest "days" cycle, ten years.
const MaxDays = 3650
// Limited: l caps something.
func (l *Limit) Limited() bool { return l != nil && (l.Tokens > 0 || l.Cost > 0) }
// Valid is l as it is kept: nil for no limit, an error for one that
// can't be.
// can't be. Since is left as it came; Update decides it.
func (l *Limit) Valid() (*Limit, error) {
if l == nil {
return nil, nil
@@ -44,13 +58,71 @@ func (l *Limit) Valid() (*Limit, error) {
}
switch v.Period {
case "day", "week", "month":
v.Days = 0
case "days":
if v.Days < 1 || v.Days > MaxDays {
return nil, fmt.Errorf("A limit's cycle is a whole number of days from 1 to %d", MaxDays)
}
default:
return nil, errors.New("A limit's period is day, week or month")
return nil, errors.New("A limit's period is day, week, month or every N days")
}
v.Cost = math.Round(v.Cost*1e4) / 1e4
return &v, nil
}
// Per is the window as a sentence ends it: "day", "week", "month" or
// "10-day cycle".
func (l *Limit) Per() string {
if l.Period == "days" {
return fmt.Sprintf("%d-day cycle", l.Days)
}
return l.Period
}
// sinceOf is the Since a limit set as next keeps, with prev the key's
// limit before: its own while the period and cycle stay the same (a new
// cap doesn't restart the window), else a new cycle from now for "days"
// and none for a calendar period.
func sinceOf(prev, next *Limit, now time.Time) time.Time {
if prev != nil && prev.Period == next.Period && prev.Days == next.Days && (next.Period != "days" || !prev.Since.IsZero()) {
return prev.Since
}
if next.Period == "days" {
return now
}
return time.Time{}
}
// epoch is where a "days" cycle written by hand without a Since runs from.
var epoch = time.Unix(0, 0)
// Window is the window l counts in at now, in now's location: when it
// began and when the next begins. A "days" cycle is counted in absolute
// time, 24h a day whatever the clocks do, so a restart or a change of
// time zone or summer time keeps it; one with no Since runs from the Unix
// epoch. A calendar window starts at Since instead when the key was reset
// in it.
func (l *Limit) Window(now time.Time) (start, reset time.Time) {
loc := now.Location()
if l.Period == "days" {
n := time.Duration(min(max(l.Days, 1), MaxDays)) * 24 * time.Hour
anchor := l.Since
if anchor.Before(epoch) {
anchor = epoch
}
if now.Before(anchor) { // the clock was set back past the start
return anchor.In(loc), anchor.Add(n).In(loc)
}
start = anchor.Add(now.Sub(anchor) / n * n)
return start.In(loc), start.Add(n).In(loc)
}
start, reset = Window(l.Period, now)
if l.Since.After(start) && l.Since.Before(reset) {
start = l.Since.In(loc)
}
return start, reset
}
// Window is the calendar window of period that now is in, in now's
// location: its start and when the next begins.
func Window(period string, now time.Time) (start, reset time.Time) {
+173 -1
View File
@@ -1,6 +1,8 @@
package access
import (
"os"
"strings"
"testing"
"time"
)
@@ -40,9 +42,179 @@ func TestLimitValid(t *testing.T) {
if l, err := (&Limit{Tokens: 5}).Valid(); err != nil || l.Period != "day" {
t.Fatal("a period is a day unless said", l, err)
}
for _, bad := range []Limit{{Period: "hour", Tokens: 1}, {Period: "day", Tokens: -1}, {Period: "day", Cost: -2}} {
if l, err := (&Limit{Period: "week", Days: 9, Tokens: 5}).Valid(); err != nil || l.Days != 0 {
t.Fatal("a calendar period has no days", l, err)
}
if l, err := (&Limit{Period: "days", Days: 10, Cost: 800}).Valid(); err != nil || l.Days != 10 {
t.Fatal(l, err)
}
for _, bad := range []Limit{{Period: "hour", Tokens: 1}, {Period: "day", Tokens: -1}, {Period: "day", Cost: -2},
{Period: "days", Tokens: 1}, {Period: "days", Days: -3, Tokens: 1}, {Period: "days", Days: MaxDays + 1, Tokens: 1}} {
if _, err := bad.Valid(); err == nil {
t.Error("accepted", bad)
}
}
}
// An N-day cycle (#1509) runs from when the limit was set, each next one
// N×24h of absolute time after the last: the same instants whatever the
// time zone the clock is read in, and a summer-time change doesn't move
// them.
func TestLimitDaysCycle(t *testing.T) {
ny, err := time.LoadLocation("America/New_York")
if err != nil {
t.Skip("no tz database:", err)
}
// set at 15:30 two days before New York's clocks went back (2026-11-01)
since := time.Date(2026, 10, 30, 15, 30, 0, 0, ny)
day := 24 * time.Hour
l := &Limit{Period: "days", Days: 10, Cost: 800, Since: since}
for _, c := range []struct {
now time.Time
start, rest time.Duration // from since
}{
{since, 0, 10 * day},
{since.Add(10*day - time.Nanosecond), 0, 10 * day},
{since.Add(10 * day), 10 * day, 20 * day},
{since.Add(57*day + 3*time.Hour), 50 * day, 60 * day},
} {
for _, loc := range []*time.Location{ny, time.UTC, time.FixedZone("UTC+8", 8*3600)} {
start, reset := l.Window(c.now.In(loc))
if !start.Equal(since.Add(c.start)) || !reset.Equal(since.Add(c.rest)) {
t.Errorf("at %s: %s – %s, want %s – %s", c.now.In(loc), start, reset, since.Add(c.start), since.Add(c.rest))
}
if start.Location() != loc {
t.Errorf("the window is said in %s, not the clock's %s", start.Location(), loc)
}
}
}
// across the change the day is 24 hours, so the wall clock moves
one := &Limit{Period: "days", Days: 1, Tokens: 5, Since: since}
start, reset := one.Window(since.Add(2*day + time.Hour))
if reset.Sub(start) != day || reset.Hour() != 14 || reset.Minute() != 30 {
t.Errorf("across summer time: %s – %s", start, reset)
}
// the clock set back before it was set: the first cycle
if start, reset := l.Window(since.Add(-time.Hour)); !start.Equal(since) || !reset.Equal(since.Add(10*day)) {
t.Errorf("before since: %s – %s", start, reset)
}
// written by hand without a since: from the Unix epoch, the same on every read
hand := &Limit{Period: "days", Days: 7, Tokens: 5}
a, _ := hand.Window(since)
b, _ := hand.Window(since.Add(time.Hour))
if !a.Equal(b) || a.Sub(time.Unix(0, 0))%(7*day) != 0 {
t.Errorf("hand-written cycle: %s, %s", a, b)
}
}
// A calendar limit reset (#1509) counts from the reset to the window's
// own end; a reset in an earlier window doesn't move the next one.
func TestLimitCalendarReset(t *testing.T) {
loc := time.FixedZone("X", 8*3600)
now := time.Date(2026, 10, 7, 18, 0, 0, 0, loc) // a Wednesday
reset := time.Date(2026, 10, 7, 9, 15, 0, 0, loc)
l := &Limit{Period: "week", Tokens: 5, Since: reset}
start, end := l.Window(now)
if !start.Equal(reset) || !end.Equal(time.Date(2026, 10, 12, 0, 0, 0, 0, loc)) {
t.Fatalf("reset this week: %s – %s", start, end)
}
start, end = l.Window(now.AddDate(0, 0, 7))
if !start.Equal(time.Date(2026, 10, 12, 0, 0, 0, 0, loc)) || !end.Equal(time.Date(2026, 10, 19, 0, 0, 0, 0, loc)) {
t.Fatalf("the week after: %s – %s", start, end)
}
// never reset: the calendar's
l.Since = time.Time{}
if start, _ := l.Window(now); !start.Equal(time.Date(2026, 10, 5, 0, 0, 0, 0, loc)) {
t.Fatal(start)
}
}
// Setting a limit: an N-day cycle starts when it is set and keeps its
// start while only its caps change; a new period or cycle starts over; a
// since the caller sends is never kept; a key from before #1509 keeps its
// calendar window untouched; Reset counts from now, tokens and cost both.
func TestLimitSetAndReset(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
clock := time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC)
Now = func() time.Time { return clock }
t.Cleanup(func() { Now = time.Now })
// a key as an older magpie kept it
old := `[{"id":"k1","name":"Old","secret":"sk-magpie-key-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","limit":{"period":"week","tokens":5000}}]`
if err := os.MkdirAll(strings.TrimSuffix(Path(), "caller-keys.json"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(Path(), []byte(old), 0o600); err != nil {
t.Fatal(err)
}
limitOf := func() *Limit {
t.Helper()
keys, err := List()
if err != nil || len(keys) != 1 {
t.Fatal(keys, err)
}
return keys[0].Limit
}
set := func(l *Limit) {
t.Helper()
if _, err := Update("limit-key", Change{Key: "k1", Limit: l}); err != nil {
t.Fatal(err)
}
}
if l := limitOf(); l.Period != "week" || l.Tokens != 5000 || !l.Since.IsZero() {
t.Fatalf("an old limit read as %+v", l)
}
// renamed: the limit is as it was, byte for byte
if _, err := Update("rename-key", Change{Key: "k1", Name: "Older"}); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(Path()); strings.Contains(string(b), "since") || strings.Contains(string(b), "days") {
t.Fatalf("a rename wrote %s", b)
}
set(&Limit{Period: "week", Tokens: 6000})
if l := limitOf(); !l.Since.IsZero() {
t.Fatalf("a calendar limit's new cap gave it a since: %+v", l)
}
set(&Limit{Period: "days", Days: 10, Cost: 800, Since: clock.Add(-99 * time.Hour)})
if l := limitOf(); l.Period != "days" || l.Days != 10 || !l.Since.Equal(clock) {
t.Fatalf("a 10-day cycle set at %s: %+v", clock, l)
}
set1 := clock
clock = clock.Add(50 * time.Hour)
set(&Limit{Period: "days", Days: 10, Cost: 900, Tokens: 1000})
if l := limitOf(); !l.Since.Equal(set1) || l.Cost != 900 {
t.Fatalf("a new cap restarted the cycle: %+v", l)
}
set(&Limit{Period: "days", Days: 7, Cost: 900})
if l := limitOf(); !l.Since.Equal(clock) {
t.Fatalf("a new cycle length kept the old start: %+v", l)
}
clock = clock.Add(time.Hour)
if _, err := Update("reset-limit-key", Change{Key: "k1"}); err != nil {
t.Fatal(err)
}
if l := limitOf(); !l.Since.Equal(clock) || l.Days != 7 || l.Cost != 900 {
t.Fatalf("reset: %+v", l)
}
// the store reloads as a restart would
if who, ok := Authenticate("sk-magpie-key-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); !ok || !who.Limit.Since.Equal(clock) {
t.Fatalf("after a reload: %+v", who.Limit)
}
set(&Limit{Period: "month", Tokens: 10})
if l := limitOf(); !l.Since.IsZero() || l.Days != 0 {
t.Fatalf("back to a calendar month: %+v", l)
}
clock = clock.Add(time.Hour)
if _, err := Update("reset-limit-key", Change{Key: "k1"}); err != nil {
t.Fatal(err)
}
if l := limitOf(); !l.Since.Equal(clock) || l.Period != "month" {
t.Fatalf("a calendar reset: %+v", l)
}
set(nil)
if _, err := Update("reset-limit-key", Change{Key: "k1"}); err == nil {
t.Fatal("reset a key with no limit")
}
if _, err := Update("reset-limit-key", Change{Key: "nope"}); err == nil {
t.Fatal("reset a missing key")
}
}
+12 -7
View File
@@ -5,8 +5,11 @@
// expected to use, and those are settled with what the call recorded.
//
// The rules:
// - A call counts in the window it started in (its record's time), and
// windows are calendar ones in local time (access.Window).
// - A call counts in the window it started in (its record's time).
// Windows are calendar ones in local time, or cycles of N days from
// when the limit was set (access.Limit.Window). A reset (#1509)
// starts the window again from then: what came before it doesn't
// count, tokens and cost alike.
// - Tokens are a call's uncached input, output and cache writes, and
// its cache reads when the limit says so; cost is an estimate at the
// Usage page's prices, and a call with no known price adds none.
@@ -145,7 +148,9 @@ func Append(rec usage.Record) {
// Status is a key's limit and what it has used of it.
type Status struct {
Period string `json:"period"`
Period string `json:"period"`
// Days is a "days" period's cycle
Days int `json:"days,omitempty"`
Start time.Time `json:"start"`
Reset time.Time `json:"reset"`
Calls int `json:"calls"`
@@ -167,7 +172,7 @@ type Status struct {
}
func status(keyID string, l *access.Limit, s *sums, h *held, reset time.Time) Status {
st := Status{Period: l.Period, Start: s.start, Reset: reset, Calls: s.calls, Tokens: s.tokens(l), Cost: s.cost, Unpriced: s.unpriced,
st := Status{Period: l.Period, Days: l.Days, Start: s.start, Reset: reset, Calls: s.calls, Tokens: s.tokens(l), Cost: s.cost, Unpriced: s.unpriced,
TokenLimit: l.Tokens, CostLimit: l.Cost, CacheReads: l.CacheReads}
if h != nil {
st.InFlight, st.Reserved, st.ReservedCost = h.n, h.tokens, h.cost
@@ -190,7 +195,7 @@ func Of(k access.Key, now time.Time) *Status {
if !k.Limit.Limited() {
return nil
}
start, reset := access.Window(k.Limit.Period, now)
start, reset := k.Limit.Window(now)
s := read(k.ID, start)
state.Lock()
h := state.held[window{slot(k.ID), start.Unix()}]
@@ -222,7 +227,7 @@ func (r *Refusal) Error() string {
what += fmt.Sprintf(", with %d requests in flight holding the rest", r.InFlight)
}
return fmt.Sprintf("magpie gateway key %q has used %s for this %s; it resets at %s",
r.Key, what, r.Period, r.Reset.Format("2006-01-02 15:04 MST"))
r.Key, what, (&access.Limit{Period: r.Period, Days: r.Days}).Per(), r.Reset.Format("2006-01-02 15:04 MST"))
}
// RetryAfter is how long until the window resets, in whole seconds.
@@ -239,7 +244,7 @@ func Reserve(who access.Identity, body int64, model string, now time.Time) (rele
if who.KeyID == "" || !l.Limited() {
return func() {}, nil
}
start, reset := access.Window(l.Period, now)
start, reset := l.Window(now)
state.Lock()
defer state.Unlock()
k := window{slot(who.KeyID), start.Unix()}
+132 -1
View File
@@ -270,7 +270,10 @@ func TestKeyLimitReservationsStayInTheirWindow(t *testing.T) {
lim := &access.Limit{Period: period, Tokens: cap.tokens, Cost: cap.cost}
who := access.Identity{KeyID: "key", KeyName: "Key", Limit: lim}
at := time.Date(2026, 10, 4, 12, 0, 0, 0, time.FixedZone("UTC+8", 8*3600))
_, after := access.Window(period, at)
if period == "days" {
lim.Days, lim.Since = 3, at.Add(-50*time.Hour)
}
_, after := lim.Window(at)
before := after.Add(-time.Second)
reserve := func(at time.Time) func() {
t.Helper()
@@ -314,3 +317,131 @@ func TestKeyLimitReservationsStayInTheirWindow(t *testing.T) {
}
}
}
// A key held to every N days (#1509): refused once spent, with the cycle
// named; the cycle survives a restart and ends N×24h after it began;
// Reset lets it in again at once, both caps counted from 0, and the next
// cycle runs N days from the reset.
func TestKeyLimitDaysCycleAndReset(t *testing.T) {
fresh(t)
budget.Forget()
t.Cleanup(budget.Forget)
calls := limitedUpstream(t, 0)
// 300 input tokens a call at $1000 a million: $0.30 a call
in, zero := 1000.0, 0.0
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{
"plan/m1": {Input: &in, Output: &zero, CacheRead: &zero, CacheWrite: &zero},
}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Cycle")
set := time.Now().Add(-time.Hour).Round(0)
access.Now = func() time.Time { return set }
t.Cleanup(func() { access.Now = time.Now })
setLimit(t, keys[0].ID, &access.Limit{Period: "days", Days: 1, Tokens: 100000, Cost: 0.5})
access.Now = time.Now
h := New().Handler()
call := func() *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// a call from before the cycle began never counts
budget.Append(usage.Record{Time: set.Add(-time.Minute), Provider: "plan", Model: "m1", Input: 900000, Status: 200, CallerKeyID: keys[0].ID})
for i := range 2 {
if w := call(); w.Code != 200 {
t.Fatal("within the limit", i, w.Code, w.Body.String())
}
}
w := call()
if w.Code != 429 || calls.Load() != 2 {
t.Fatal("spent key let in", w.Code, calls.Load())
}
if !strings.Contains(w.Body.String(), "this 1-day cycle") {
t.Fatal("refusal says", w.Body.String())
}
if got := w.Header().Get("X-Magpie-Limit-Reset"); got != set.Add(24*time.Hour).Format(time.RFC3339) {
t.Fatal("resets at", got, "not a day after", set)
}
stored := func() access.Key {
t.Helper()
ks, err := access.List()
if err != nil {
t.Fatal(err)
}
return ks[0]
}
// a restart: still spent, the cycle where it was
budget.Forget()
if w := call(); w.Code != 429 {
t.Fatal("a restart forgot the cycle", w.Code)
}
st := budget.Of(stored(), time.Now())
if st.Days != 1 || !st.Start.Equal(set) || st.Tokens != 700 || st.Cost < 0.59 || !st.Spent {
t.Fatalf("status %+v (set %s)", st, set)
}
// the next cycle, a day after it was set
who := access.Identity{KeyID: keys[0].ID, KeyName: "Cycle", Limit: stored().Limit}
if _, refused := budget.Reserve(who, 10, "", set.Add(24*time.Hour-time.Second)); refused == nil {
t.Fatal("let in before the cycle ended")
}
release, refused := budget.Reserve(who, 10, "", set.Add(24*time.Hour))
if refused != nil {
t.Fatal("the next cycle still spent", refused)
}
release()
// Reset: in again now, tokens and cost both from 0, a day from now
if _, err := access.Update("reset-limit-key", access.Change{Key: keys[0].ID}); err != nil {
t.Fatal(err)
}
st = budget.Of(stored(), time.Now())
if st.Tokens != 0 || st.Cost != 0 || st.Calls != 0 || st.Spent || st.CostLeft != 0.5 || st.TokensLeft != 100000 {
t.Fatalf("after Reset: %+v", st)
}
if !st.Reset.Equal(st.Start.Add(24*time.Hour)) || st.Start.Before(set.Add(time.Hour-time.Minute)) {
t.Fatalf("the new cycle: %s – %s", st.Start, st.Reset)
}
if w := call(); w.Code != 200 {
t.Fatal("refused after Reset", w.Code, w.Body.String())
}
if w := call(); w.Code != 200 {
t.Fatal("refused after Reset", w.Code, w.Body.String())
}
if w := call(); w.Code != 429 || calls.Load() != 4 {
t.Fatal("spent again after Reset", w.Code, calls.Load())
}
}
// A calendar limit's Reset counts from the reset to the window's own end.
func TestKeyLimitCalendarReset(t *testing.T) {
fresh(t)
budget.Forget()
t.Cleanup(budget.Forget)
limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Monthly")
setLimit(t, keys[0].ID, &access.Limit{Period: "month", Tokens: 350})
h := New().Handler()
call := func() int {
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
if call() != 200 || call() != 429 {
t.Fatal("the month's limit")
}
if _, err := access.Update("reset-limit-key", access.Change{Key: keys[0].ID}); err != nil {
t.Fatal(err)
}
if c := call(); c != 200 {
t.Fatal("refused after Reset", c)
}
ks, _ := access.List()
st := budget.Of(ks[0], time.Now())
if _, end := access.Window("month", time.Now()); !st.Reset.Equal(end) || st.Tokens != 350 {
t.Fatalf("after Reset: %+v", st)
}
}
+6 -1
View File
@@ -2123,7 +2123,12 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
#gatewayKeys .klf-check { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--fg-2); }
#gatewayKeys .klf-err { color: var(--red); }
#gatewayKeys .klf .klf-period { width: 100%; max-width: none; height: 28px; justify-content: space-between; color: var(--fg); }
@media (max-width: 520px) { #gatewayKeys .klf { grid-template-columns: 1fr; } }
#gatewayKeys .klf.with-days { grid-template-columns: minmax(0, 1fr) minmax(0, 0.6fr) minmax(0, 1fr) minmax(0, 1fr); }
#gatewayKeys .klf-days[hidden] { display: none; }
#gatewayKeys .klf-used { display: flex; align-items: center; gap: 8px; min-width: 0; }
#gatewayKeys .klf-used .key-limit { flex: 1 1 auto; }
#gatewayKeys .klf-used .klf-reset { flex: none; }
@media (max-width: 520px) { #gatewayKeys .klf, #gatewayKeys .klf.with-days { grid-template-columns: 1fr; } #gatewayKeys .klf-used { flex-wrap: wrap; } }
/* the models a key may use (#882): a long model's id is cut, and the
badge gives way first on a narrow window */
#gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; }
+74 -11
View File
@@ -321,8 +321,18 @@ function gatewayModelsBadge(k) {
// ---- a gateway key's own limit (#585) ----
const limitPeriods = ["day", "week", "month"];
const limitPer = { day: "per day", week: "per week", month: "per month" };
// "days" is every N days from when the limit is set or reset (#1509)
const limitPeriods = ["day", "week", "month", "days"];
const limitPer = { day: "per day", week: "per week", month: "per month", days: "Every N days" };
// perWords is a limit's window as the badge says it: "per week", "every 10 days"
const perWords = (period, days) => period === "days"
? (days === 1 ? t("every 1 day") : t("every {n} days", { n: days }))
: t(limitPer[period] || period);
// limitDays reads a cycle's days: a whole number from 1 to 3650, else NaN
function limitDays(v) {
const s = String(v ?? "").trim();
return /^\d{1,4}$/.test(s) && +s >= 1 && +s <= 3650 ? +s : NaN;
}
// limitTokens reads a count as typed: 2000000, 2,000,000, 500k, 2M, 1.5m,
// 100万, 1亿; "" for none, NaN for what isn't one.
@@ -352,7 +362,7 @@ function gatewayLimitBadge(k) {
const parts = [];
if (u.tokenLimit) parts.push(fmtN(u.tokens) + " / " + fmtN(u.tokenLimit));
if (u.costLimit) parts.push(usd(u.cost) + " / " + usd(u.costLimit));
b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + t(limitPer[u.period] || u.period);
b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days);
}
b.title = t(u ? "Change this key's limit" : "Set a limit for this key");
b.setAttribute("aria-label", b.title);
@@ -362,7 +372,7 @@ function gatewayLimitBadge(k) {
if (gatewayLimit?.id === k.id) gatewayLimit = null;
else {
const l = k.limit || {};
gatewayLimit = { id: k.id, period: l.period || "day", tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads };
gatewayLimit = { id: k.id, period: l.period || "day", days: l.days ? String(l.days) : "", tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads };
}
renderGatewayKeys();
};
@@ -393,7 +403,8 @@ function gatewayLimitEditor(k) {
box.onclick = (e) => e.stopPropagation();
const kept = k.limit || {};
const changed = () => d.period !== (kept.period || "day") || limitTokens(d.tokens) !== (kept.tokens || 0)
|| limitCost(d.cost) !== (kept.cost || 0) || d.cacheReads !== !!kept.cacheReads;
|| limitCost(d.cost) !== (kept.cost || 0) || d.cacheReads !== !!kept.cacheReads
|| (d.period === "days" && limitDays(d.days) !== kept.days);
const fields = el("div", "klf");
// the app's own menu, not a native select
const period = el("button", "sess-pick klf-period");
@@ -404,7 +415,15 @@ function gatewayLimitEditor(k) {
const paintPeriod = () => {
period.dataset.value = d.period;
period.replaceChildren(el("span", "", t(limitPer[d.period])), svg(CHEV, 11, 1.6));
fields.classList.toggle("with-days", d.period === "days");
dl.hidden = d.period !== "days";
};
// the days of a cycle, shown for "every N days"
const days = input(d.days, "10");
days.setAttribute("aria-label", t("Days in a cycle"));
days.inputMode = "numeric";
const dl = el("label", "klf-field klf-days");
dl.append(el("span", "klf-name", t("Days")), days);
paintPeriod();
const tokens = input(d.tokens, t("No token cap"));
tokens.setAttribute("aria-label", t("Token limit"));
@@ -418,20 +437,21 @@ function gatewayLimitEditor(k) {
cl.append(el("span", "klf-name", t("Estimated cost, US$")), cost);
const pl = el("label", "klf-field");
pl.append(el("span", "klf-name", t("Window")), period);
fields.append(pl, tl, cl);
fields.append(pl, dl, tl, cl);
const cache = el("label", "klf-check");
const cb = el("input");
cb.type = "checkbox";
cb.checked = d.cacheReads;
cache.append(cb, el("span", "", t("Count cache reads too")));
const hint = el("div", "hint", t("Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday). Requests from this computer without a key aren't limited."));
const hint = el("div", "hint", t("Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days from when the limit is set or reset. Requests from this computer without a key aren't limited."));
const err = el("div", "hint klf-err");
const unsaved = el("span", "hint munsaved", t("unsaved"));
unsaved.title = t("Made when you Save; Cancel drops it");
const save = el("button", "text primary", t("Save"));
const update = () => {
const bad = Number.isNaN(limitTokens(d.tokens)) ? t("Tokens is a count, like 2000000 or 2M")
: Number.isNaN(limitCost(d.cost)) ? t("The cost is US dollars, like 5 or 2.50") : "";
const bad = d.period === "days" && Number.isNaN(limitDays(d.days)) ? t("Days is a whole number from 1 to 3650")
: Number.isNaN(limitTokens(d.tokens)) ? t("Tokens is a count, like 2000000 or 2M")
: Number.isNaN(limitCost(d.cost)) ? t("The cost is US dollars, like 5 or 2.50") : "";
err.textContent = bad;
err.hidden = !bad;
unsaved.hidden = !changed();
@@ -445,13 +465,15 @@ function gatewayLimitEditor(k) {
d.period = v;
paintPeriod();
update();
if (v === "days") days.focus({ preventScroll: true });
}, "Limit window", "sess-menu");
};
days.oninput = () => { d.days = days.value; update(); };
tokens.oninput = () => { d.tokens = tokens.value; update(); };
cost.oninput = () => { d.cost = cost.value; update(); };
cb.onchange = () => { d.cacheReads = cb.checked; update(); };
const close = () => { gatewayLimit = null; renderGatewayKeys(); };
for (const i of [tokens, cost]) i.onkeydown = (e) => {
for (const i of [days, tokens, cost]) i.onkeydown = (e) => {
e.stopPropagation();
if (e.key === "Escape") close();
else if (e.key === "Enter" && !save.disabled) save.click();
@@ -463,6 +485,7 @@ function gatewayLimitEditor(k) {
save.disabled = true;
const tk = limitTokens(d.tokens), c = limitCost(d.cost);
const limit = tk || c ? { period: d.period, tokens: tk, cost: c, cacheReads: d.cacheReads } : null;
if (limit && d.period === "days") limit.days = limitDays(d.days);
const out = await gatewayKeyAction("limit-key", { key: k.id, limit });
if (!out) { update(); return; }
status(t(limit ? "Limit saved for {name}" : "Limit removed for {name}", { name: k.name }), "ok");
@@ -477,8 +500,48 @@ function gatewayLimitEditor(k) {
}
foot.append(cancel, save);
box.append(fields, hint, err);
if (k.used) box.append(gatewayLimitLine(k));
if (k.used) {
// count from 0 again, tokens and cost together (#1509)
const zero = el("button", "text klf-reset", t("Reset usage"));
zero.title = t("Count this key's use from 0 again, tokens and cost together");
zero.onclick = (e) => { e.stopPropagation(); askResetLimit(k); };
const used = el("div", "klf-used");
used.append(gatewayLimitLine(k), zero);
box.append(used);
}
box.append(foot);
update();
return box;
}
// askResetLimit confirms a key's Reset (#1509): what it has used goes back
// to 0, tokens and cost together; an N-day cycle starts again from now, a
// calendar window keeps its end.
function askResetLimit(k) {
const u = k.used || {};
const ed = el("div", "editor");
const head = el("div", "ehead");
head.append(el("b", "", t("Reset {name}'s usage?", { name: k.name })));
ed.append(head, el("p", "lib-confirm", u.period === "days"
? t("The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.", { name: k.name, n: u.days })
: t("The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.", { name: k.name, when: resetClock(new Date(u.reset)) })));
const bar = el("div", "bar");
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = (e) => { e.stopPropagation(); closeConfirmAsk(); };
const go = el("button", "text primary", t("Reset usage"));
go.onclick = async (e) => {
e.stopPropagation();
if (go.disabled) return;
go.disabled = true;
const out = await gatewayKeyAction("reset-limit-key", { key: k.id });
if (!out) { go.disabled = false; return; }
closeConfirmAsk();
status(t("Usage reset for {name}", { name: k.name }), "ok");
};
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
cancel.focus({ preventScroll: true });
}
+52 -4
View File
@@ -289,13 +289,25 @@ const I18N = {
"Estimated cost limit, US$": "估算费用限额(美元)",
"Estimated cost, US$": "估算费用(美元)",
"Count cache reads too": "缓存读取也计入",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday). Requests from this computer without a key aren't limited.": "Token 计未命中缓存的输入、输出和缓存写入。费用按用量页价格估算,非账单。周期按本机时间的自然日、周、月(每周从周一起)。本机无密钥的请求不受限额。",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token 计未命中缓存的输入、输出和缓存写入。费用按用量页价格估算,非账单。周期按本机时间的自然日、周、月(每周从周一起),或从设置或重置额度时起每 N 天。本机无密钥的请求不受限额。",
"Tokens is a count, like 2000000 or 2M": "Token 应为数量,例如 2000000、2M 或 200万",
"The cost is US dollars, like 5 or 2.50": "费用以美元计,例如 5 或 2.50",
"Made when you Save; Cancel drops it": "保存后生效",
"Limit saved for {name}": "已保存 {name} 的限额",
"Limit removed for {name}": "已取消 {name} 的限额",
"Clears the caps; Save makes it": "清空上限,保存后生效",
"every {n} days": "每 {n} 天",
"every 1 day": "每 1 天",
"Every N days": "每 N 天",
"Days": "天数",
"Days in a cycle": "每个周期的天数",
"Days is a whole number from 1 to 3650": "天数应为 1 到 3650 的整数",
"Reset usage": "重置额度",
"Count this key's use from 0 again, tokens and cost together": "此密钥已用的 Token 和费用一起从 0 重新计算",
"Reset {name}'s usage?": "重置 {name} 的额度?",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和费用一起清零,并从现在开始新的 {n} 天周期。",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} 已用的 Token 和费用一起清零,本周期内此前的调用不再计入;周期仍在 {when} 重置。",
"Usage reset for {name}": "已重置 {name} 的额度",
"All gateway keys": "全部网关密钥",
"All accounts": "全部账号",
"account not recorded": "未记录账号",
@@ -4364,13 +4376,25 @@ const I18N = {
"Estimated cost limit, US$": "估算費用限額(美元)",
"Estimated cost, US$": "估算費用(美元)",
"Count cache reads too": "快取讀取也計入",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday). Requests from this computer without a key aren't limited.": "Token 計未命中快取的輸入、輸出和快取寫入。費用按用量頁價格估算,非帳單。週期按本機時間的自然日、週、月(每週從週一起)。本機無金鑰的請求不受限額。",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token 計未命中快取的輸入、輸出和快取寫入。費用按用量頁價格估算,非帳單。週期按本機時間的自然日、週、月(每週從週一起),或從設定或重置額度時起每 N 天。本機無金鑰的請求不受限額。",
"Tokens is a count, like 2000000 or 2M": "Token 應為數量,例如 2000000、2M 或 200萬",
"The cost is US dollars, like 5 or 2.50": "費用以美元計,例如 5 或 2.50",
"Made when you Save; Cancel drops it": "儲存後生效",
"Limit saved for {name}": "已儲存 {name} 的限額",
"Limit removed for {name}": "已取消 {name} 的限額",
"Clears the caps; Save makes it": "清空上限,儲存後生效",
"every {n} days": "每 {n} 天",
"every 1 day": "每 1 天",
"Every N days": "每 N 天",
"Days": "天數",
"Days in a cycle": "每個週期的天數",
"Days is a whole number from 1 to 3650": "天數應為 1 到 3650 的整數",
"Reset usage": "重置額度",
"Count this key's use from 0 again, tokens and cost together": "此金鑰已用的 Token 和費用一起從 0 重新計算",
"Reset {name}'s usage?": "重置 {name} 的額度?",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} 已用的 Token 和費用一起歸零,並從現在開始新的 {n} 天週期。",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} 已用的 Token 和費用一起歸零,本週期內此前的呼叫不再計入;週期仍在 {when} 重置。",
"Usage reset for {name}": "已重置 {name} 的額度",
"All gateway keys": "全部閘道金鑰",
"All accounts": "全部帳號",
"account not recorded": "未記錄帳號",
@@ -8400,13 +8424,25 @@ const I18N = {
"Estimated cost limit, US$": "推定費用の上限(米ドル)",
"Estimated cost, US$": "推定費用(米ドル)",
"Count cache reads too": "キャッシュ読み取りも数える",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday). Requests from this computer without a key aren't limited.": "トークンは各呼び出しのキャッシュされない入力、出力、キャッシュ書き込みの合計です。費用は使用量ページの価格による推定で、請求額ではありません。期間はこのコンピュータの時刻によるカレンダー単位です(週は月曜日から)。このコンピュータからのキーなしのリクエストは制限されません。",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days from when the limit is set or reset. Requests from this computer without a key aren't limited.": "トークンは各呼び出しのキャッシュされない入力、出力、キャッシュ書き込みの合計です。費用は使用量ページの価格による推定で、請求額ではありません。期間はこのコンピュータの時刻によるカレンダー単位(週は月曜日から)か、上限を設定またはリセットした時から N 日ごとです。このコンピュータからのキーなしのリクエストは制限されません。",
"Tokens is a count, like 2000000 or 2M": "トークンは数で指定します(例:2000000 や 2M)",
"The cost is US dollars, like 5 or 2.50": "費用は米ドルで指定します(例:5 や 2.50)",
"Made when you Save; Cancel drops it": "保存すると反映され、キャンセルすると破棄されます",
"Limit saved for {name}": "{name} の上限を保存しました",
"Limit removed for {name}": "{name} の上限を解除しました",
"Clears the caps; Save makes it": "上限を消去します。保存すると反映されます",
"every {n} days": "{n} 日ごと",
"every 1 day": "1 日ごと",
"Every N days": "N 日ごと",
"Days": "日数",
"Days in a cycle": "1 周期の日数",
"Days is a whole number from 1 to 3650": "日数は 1〜3650 の整数です",
"Reset usage": "使用量をリセット",
"Count this key's use from 0 again, tokens and cost together": "このキーのトークンと費用の使用量を一緒に 0 から数え直します",
"Reset {name}'s usage?": "{name} の使用量をリセットしますか?",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "{name} が使ったトークンと費用を一緒に 0 に戻し、今から新しい {n} 日の周期を始めます。",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "{name} が使ったトークンと費用を一緒に 0 に戻します。この期間のこれまでの呼び出しは数えなくなり、リセットは引き続き {when} です。",
"Usage reset for {name}": "{name} の使用量をリセットしました",
"All gateway keys": "すべてのゲートウェイキー",
"All accounts": "すべてのアカウント",
"account not recorded": "アカウント未記録",
@@ -12454,13 +12490,25 @@ const I18N = {
"Estimated cost limit, US$": "Limit geschätzte Kosten, US$",
"Estimated cost, US$": "Geschätzte Kosten, US$",
"Count cache reads too": "Cache-Lesen mitzählen",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday). Requests from this computer without a key aren't limited.": "Token sind je Aufruf die nicht gecachte Eingabe, die Ausgabe und das Cache-Schreiben. Die Kosten sind eine Schätzung zu den Preisen der Seite „Nutzung“, keine Rechnung. Zeitfenster sind Kalenderzeiträume in der Zeit dieses Computers (eine Woche ab Montag). Anfragen von diesem Computer ohne Schlüssel werden nicht begrenzt.",
"Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token sind je Aufruf die nicht gecachte Eingabe, die Ausgabe und das Cache-Schreiben. Die Kosten sind eine Schätzung zu den Preisen der Seite „Nutzung“, keine Rechnung. Zeitfenster sind Kalenderzeiträume in der Zeit dieses Computers (eine Woche ab Montag) oder alle N Tage ab dem Setzen oder Zurücksetzen des Limits. Anfragen von diesem Computer ohne Schlüssel werden nicht begrenzt.",
"Tokens is a count, like 2000000 or 2M": "Token ist eine Anzahl, z. B. 2000000 oder 2M",
"The cost is US dollars, like 5 or 2.50": "Die Kosten sind US-Dollar, z. B. 5 oder 2.50",
"Made when you Save; Cancel drops it": "Wird mit „Speichern“ übernommen; „Abbrechen“ verwirft es",
"Limit saved for {name}": "Limit für {name} gespeichert",
"Limit removed for {name}": "Limit für {name} entfernt",
"Clears the caps; Save makes it": "Leert die Obergrenzen; „Speichern“ übernimmt es",
"every {n} days": "alle {n} Tage",
"every 1 day": "alle 24 Stunden",
"Every N days": "Alle N Tage",
"Days": "Tage",
"Days in a cycle": "Tage je Zyklus",
"Days is a whole number from 1 to 3650": "Tage sind eine ganze Zahl von 1 bis 3650",
"Reset usage": "Nutzung zurücksetzen",
"Count this key's use from 0 again, tokens and cost together": "Zählt Token und Kosten dieses Schlüssels zusammen wieder ab 0",
"Reset {name}'s usage?": "Nutzung von {name} zurücksetzen?",
"The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0, und jetzt beginnt ein neuer Zyklus von {n} Tagen.",
"The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.": "Die von {name} verbrauchten Token und Kosten gehen zusammen auf 0. Bisherige Aufrufe in diesem Zeitraum zählen nicht mehr; zurückgesetzt wird weiterhin {when}.",
"Usage reset for {name}": "Nutzung von {name} zurückgesetzt",
"All gateway keys": "Alle Zugangsschlüssel",
"All accounts": "Alle Konten",
"account not recorded": "Konto nicht erfasst",
+9 -1
View File
@@ -124,9 +124,17 @@ function fixture(lang, theme, events, options = {}) {
if (action === "limit-key") {
// what a key has used is the fixture's; a new limit starts unused
k.limit = body.limit || undefined;
k.used = body.limit ? { period: body.limit.period, start: new Date().toISOString(), reset: new Date(Date.now() + 864e5).toISOString(),
k.used = body.limit ? { period: body.limit.period, days: body.limit.days, start: new Date().toISOString(), reset: new Date(Date.now() + (body.limit.days || 1) * 864e5).toISOString(),
calls: 0, tokens: 0, cost: 0, tokenLimit: body.limit.tokens, costLimit: body.limit.cost, tokensLeft: body.limit.tokens, costLeft: body.limit.cost, spent: false } : undefined;
}
if (action === "reset-limit-key") {
// what it used goes back to 0, tokens and cost together (#1509);
// an N-day cycle starts again now, a calendar window keeps its end
const u = k.used, now = Date.now();
k.used = { ...u, start: new Date(now).toISOString(), calls: 0, tokens: 0, cost: 0, inFlight: 0, unpriced: 0, spent: false,
tokensLeft: u.tokenLimit || 0, costLeft: u.costLimit || 0,
reset: u.period === "days" ? new Date(now + u.days * 864e5).toISOString() : u.reset };
}
if (action === "models-key") k.models = body.models?.length ? body.models : undefined;
if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined;
if (action === "copy-key") secret = k.id === lanKeyID ? lanSecret : secrets.get(k.id);
@@ -0,0 +1,140 @@
// A gateway key's limit every N days and its Reset (#1509, PennyVibe):
// the window menu offers "Every N days" with its days beside it, and Reset
// usage, after a confirm, counts the key from 0 again, tokens and cost
// together. In every language, both engines, and at a narrow width.
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const src = fs.readFileSync(path.resolve(__dirname, "../assets/i18n.js"), "utf8");
const I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
const day = 864e5;
const limits = () => ({
laptop: {
limit: { period: "days", days: 10, cost: 800, since: new Date(Date.now() - 4 * day).toISOString() },
used: { period: "days", days: 10, start: new Date(Date.now() - 4 * day).toISOString(), reset: new Date(Date.now() + 6 * day).toISOString(), calls: 90,
tokens: 4000000, cost: 812.5, costLimit: 800, tokensLeft: 0, costLeft: 0, spent: true },
},
server: {
limit: { period: "month", tokens: 1000000 },
used: { period: "month", start: new Date(Date.now() - 3 * day).toISOString(), reset: new Date(Date.now() + 3 * day).toISOString(), calls: 40,
tokens: 400000, cost: 2, tokenLimit: 1000000, tokensLeft: 600000, costLeft: 0, spent: false },
},
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a key's limit every N days, and Reset usage`, async (t) => {
const tr = (k, vars = {}) => {
const s = lang === "en" ? k : I18N[lang][k];
assert.equal(typeof s, "string", `${lang} has ${k}`);
return s.replace(/\{(\w+)\}/g, (_, v) => String(vars[v]));
};
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 1000, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true, limits: limits() }));
await page.goto("http://magpie.test/?view=gateway");
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
const sent = (action) => events.filter((e) => e.action === action);
const badge = row("laptop").locator(".amodels.limit");
assert.match(await badge.textContent(), new RegExp(tr("every {n} days", { n: 10 })));
assert.equal(await row("laptop").locator(".amodels.limit.spent").count(), 1);
const view = page.locator("#view-gateway");
const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)];
const at = await scrolled();
// its editor: the window is "Every N days", its days 10
await row("laptop").getByRole("button", { name: tr("Change this key's limit"), exact: true }).click();
const ed = row("laptop").locator(".key-limit-ed");
await ed.waitFor();
const win = ed.getByRole("button", { name: tr("Limit window"), exact: true });
assert.equal(await win.getAttribute("data-value"), "days");
assert.equal((await win.textContent()).trim(), tr("Every N days"));
const daysIn = ed.getByRole("textbox", { name: tr("Days in a cycle"), exact: true });
assert.equal(await daysIn.inputValue(), "10");
assert.equal(await ed.locator(".munsaved").isVisible(), false, "nothing changed yet");
for (const sel of [".klf-reset", ".klf-used"]) {
assert.equal(await ed.locator(sel).evaluate((e) => getComputedStyle(e).borderLeftStyle), "none");
}
// Reset usage: asked first; Cancel sends nothing
const resetBtn = ed.getByRole("button", { name: tr("Reset usage"), exact: true });
await resetBtn.click();
const modal = page.locator("#modal");
await modal.getByText(tr("Reset {name}'s usage?", { name: "Laptop" })).waitFor();
assert.match(await modal.textContent(), new RegExp(tr("The tokens and cost {name} has used go back to 0 together, and a new {n}-day cycle starts now.", { name: "Laptop", n: 10 }).replace(/[.?()]/g, "\\$&")));
await modal.getByRole("button", { name: tr("Cancel"), exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.equal(sent("reset-limit-key").length, 0, "Cancel reset the key");
await resetBtn.click();
await modal.getByRole("button", { name: tr("Reset usage"), exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(sent("reset-limit-key").map((e) => e.body), [{ key: "laptop" }]);
assert.equal(sent("limit-key").length, 0, "Reset changed the limit");
assert.equal(await row("laptop").locator(".amodels.limit.spent").count(), 0, "still spent after Reset");
assert.match(await row("laptop").locator(".key-limit").first().textContent(), /\$0\.00/);
assert.deepEqual(await scrolled(), at, "Reset moved the page");
await ed.getByRole("button", { name: tr("Cancel"), exact: true }).click();
await ed.waitFor({ state: "detached" });
// a calendar limit's Reset keeps its window's end
await row("server").getByRole("button", { name: tr("Change this key's limit"), exact: true }).click();
const sed = row("server").locator(".key-limit-ed");
await sed.waitFor();
assert.equal(await sed.getByRole("textbox", { name: tr("Days in a cycle"), exact: true }).isVisible(), false, "a month has no days field");
await sed.getByRole("button", { name: tr("Reset usage"), exact: true }).click();
const calendar = tr("The tokens and cost {name} has used go back to 0 together. Calls so far in this window stop counting; it still resets {when}.", { name: "Server", when: "\u0000" }).split("\u0000")[0];
assert(((await modal.textContent()) || "").includes(calendar), "the calendar Reset says the window keeps its end");
await modal.getByRole("button", { name: tr("Reset usage"), exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(sent("reset-limit-key").at(-1).body, { key: "server" });
await sed.getByRole("button", { name: tr("Cancel"), exact: true }).click();
await sed.waitFor({ state: "detached" });
// a new limit every 3 days: the days are checked, then sent with it
await row("work").getByRole("button", { name: tr("Set a limit for this key"), exact: true }).click();
const wed = row("work").locator(".key-limit-ed");
await wed.waitFor();
assert.equal(await wed.locator("select").count(), 0, "no native select");
await wed.getByRole("textbox", { name: tr("Token limit"), exact: true }).fill("2M");
await wed.getByRole("button", { name: tr("Limit window"), exact: true }).click();
await page.locator(".proto-menu .pm-item", { hasText: tr("Every N days") }).click();
const wdays = wed.getByRole("textbox", { name: tr("Days in a cycle"), exact: true });
assert.equal(await wdays.isVisible(), true);
assert.equal(await wed.getByRole("button", { name: tr("Save"), exact: true }).isDisabled(), true, "no days yet");
assert.equal(await wed.locator(".klf-err").textContent(), tr("Days is a whole number from 1 to 3650"));
for (const bad of ["0", "3651", "2.5", "x"]) {
await wdays.fill(bad);
assert.equal(await wed.getByRole("button", { name: tr("Save"), exact: true }).isDisabled(), true, bad);
}
await wdays.fill("3");
assert.equal(await wed.locator(".klf-err").isVisible(), false);
// narrow, under the editor's one-column width: it and its days fit
await page.setViewportSize({ width: 500, height: 740 });
await page.waitForFunction(() => getComputedStyle(document.querySelector("#gatewayKeys .klf")).gridTemplateColumns.split(" ").length === 1);
assert.equal(await wed.evaluate((e) => e.scrollWidth > e.clientWidth || e.getBoundingClientRect().right > window.innerWidth), false, "the editor overflows at 500px");
const box = await wdays.boundingBox();
assert(box && box.width > 100 && box.x + box.width <= 500, "the days field is squeezed");
// the app's own narrow width (the nav's labels need more below it)
await page.setViewportSize({ width: 560, height: 740 });
await page.waitForTimeout(100);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, "the page overflows at 560px");
await page.setViewportSize({ width: 1000, height: 700 });
assert.equal(sent("limit-key").length, 0, "sent before Save");
await wed.getByRole("button", { name: tr("Save"), exact: true }).click();
await wed.waitFor({ state: "detached" });
assert.deepEqual(sent("limit-key").map((e) => e.body), [{ key: "work", limit: { period: "days", days: 3, tokens: 2000000, cost: 0, cacheReads: false } }]);
assert.match(await row("work").locator(".amodels.limit").textContent(), new RegExp(tr("every {n} days", { n: 3 })));
assert.deepEqual(errors, []);
});
}
}
+1 -1
View File
@@ -96,7 +96,7 @@ const usage = `magpie — one place to pick every agent's model
magpie serve run the gateway alone (the app runs it too)
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key limit <id> [off|day|week|month --tokens N --cost USD --cache-reads] a key's own limit, and what it used
magpie gateway-key limit <id> [off|reset|day|week|month|<N>d --tokens N --cost USD --cache-reads] a key's own limit, and what it used
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d)
+1 -1
View File
@@ -163,7 +163,7 @@ docker logs magpie</pre>
<h2 id="share"><a class="anchor" href="#share">Gateway keys and other machines</a></h2>
<ol class="steps">
<li><b>Make a key for each client</b><span class="ui">Gateway</span> → <span class="ui">Gateway keys</span>, or in a terminal <code>docker exec magpie magpie gateway-key add "Laptop"</code>, which prints the new <code>sk-magpie-key-…</code>. Every request from outside the container, the host’s own included, must carry an enabled gateway key, and one without gets 401. A key can have its own daily, weekly or monthly limit and its own list of models (<code>magpie gateway-key limit</code>, <code>magpie gateway-key models</code>).</li>
<li><b>Make a key for each client</b><span class="ui">Gateway</span> → <span class="ui">Gateway keys</span>, or in a terminal <code>docker exec magpie magpie gateway-key add "Laptop"</code>, which prints the new <code>sk-magpie-key-…</code>. Every request from outside the container, the host’s own included, must carry an enabled gateway key, and one without gets 401. A key can have its own daily, weekly, monthly or every-N-days limit and its own list of models (<code>magpie gateway-key limit</code>, <code>magpie gateway-key models</code>).</li>
<li><b>Publish the port</b>Recreate the container with <code>-p 3425:3425</code>, or bound to the NAS’s LAN or VPN address (<code>-p 192.168.1.20:3425:3425</code>), and with <code>-e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425</code>.</li>
</ol>
<p>On each other computer, point the agent at the gateway with one of those keys as its API key: <code>http://192.168.1.20:3425/v1</code> for an OpenAI client, <code>http://192.168.1.20:3425</code> for an Anthropic or Gemini one. Model ids are <code>provider/model</code>, or a routing group’s; <code>GET /v1/models</code> lists them. If that computer runs magpie itself, add the container as a <a href="/docs/remote">Remote magpie</a> instead, and magpie wires its agents for you.</p>
+1 -1
View File
@@ -163,7 +163,7 @@ docker logs magpie</pre>
<h2 id="share"><a class="anchor" href="#share">ゲートウェイキーとほかのマシン</a></h2>
<ol class="steps">
<li><b>クライアントごとにキーを作る</b><span class="ui">ゲートウェイ</span> → <span class="ui">ゲートウェイキー</span>、またはターミナルで <code>docker exec magpie magpie gateway-key add "Laptop"</code>。新しい <code>sk-magpie-key-…</code> が表示されます。コンテナの外からのリクエストは、ホスト自身のものも含め、有効なゲートウェイキーが必要で、ないものは 401 になります。キーごとに日・週・月の上限と使えるモデルを決められます(<code>magpie gateway-key limit</code>、<code>magpie gateway-key models</code>)。</li>
<li><b>クライアントごとにキーを作る</b><span class="ui">ゲートウェイ</span> → <span class="ui">ゲートウェイキー</span>、またはターミナルで <code>docker exec magpie magpie gateway-key add "Laptop"</code>。新しい <code>sk-magpie-key-…</code> が表示されます。コンテナの外からのリクエストは、ホスト自身のものも含め、有効なゲートウェイキーが必要で、ないものは 401 になります。キーごとに日・週・月、または N 日ごとの上限と使えるモデルを決められます(<code>magpie gateway-key limit</code>、<code>magpie gateway-key models</code>)。</li>
<li><b>ポートを公開する</b><code>-p 3425:3425</code>(または NAS の LAN や VPN のアドレスに限定して <code>-p 192.168.1.20:3425:3425</code>)と <code>-e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425</code> を付けてコンテナを作り直します。</li>
</ol>
<p>ほかのコンピューターでは、エージェントをゲートウェイに向け、そのキーのどれかを API キーにします:OpenAI クライアントなら <code>http://192.168.1.20:3425/v1</code>、Anthropic や Gemini なら <code>http://192.168.1.20:3425</code>。モデル ID は <code>provider/model</code> かルーティンググループの名前で、<code>GET /v1/models</code> が一覧を返します。そのコンピューターでも magpie を動かしているなら、コンテナを<a href="/docs/ja/remote">リモート magpie</a> として追加すれば、magpie がエージェントを設定します。</p>
+1 -1
View File
@@ -163,7 +163,7 @@ docker logs magpie</pre>
<h2 id="share"><a class="anchor" href="#share">网关密钥与其他机器</a></h2>
<ol class="steps">
<li><b>给每个客户端生成一个密钥</b><span class="ui">网关</span> → <span class="ui">网关密钥</span>,或在终端里 <code>docker exec magpie magpie gateway-key add "Laptop"</code>,它会打印新的 <code>sk-magpie-key-…</code>。容器外的每个请求(包括宿主机自己的)都必须带一个启用的网关密钥,不带的返回 401。每个密钥可以有自己的每日、每周或每月上限和可用模型(<code>magpie gateway-key limit</code>、<code>magpie gateway-key models</code>)。</li>
<li><b>给每个客户端生成一个密钥</b><span class="ui">网关</span> → <span class="ui">网关密钥</span>,或在终端里 <code>docker exec magpie magpie gateway-key add "Laptop"</code>,它会打印新的 <code>sk-magpie-key-…</code>。容器外的每个请求(包括宿主机自己的)都必须带一个启用的网关密钥,不带的返回 401。每个密钥可以有自己的每日、每周、每月或每 N 天的上限和可用模型(<code>magpie gateway-key limit</code>、<code>magpie gateway-key models</code>)。</li>
<li><b>发布端口</b>用 <code>-p 3425:3425</code>(或绑定到 NAS 的局域网或 VPN 地址,<code>-p 192.168.1.20:3425:3425</code>)并加上 <code>-e MAGPIE_PUBLIC_URL=http://192.168.1.20:3425</code> 重新创建容器。</li>
</ol>
<p>在其他电脑上,把 Agent 指向这个网关,用其中一个密钥作为 API key:OpenAI 客户端用 <code>http://192.168.1.20:3425/v1</code>,Anthropic 或 Gemini 客户端用 <code>http://192.168.1.20:3425</code>。模型 id 是 <code>provider/model</code> 或路由组的名字,<code>GET /v1/models</code> 会列出它们。如果那台电脑自己也运行 magpie,就把容器添加为<a href="/docs/zh/remote">远程 magpie</a>,由 magpie 替你配置 Agent。</p>