Commit Graph
15 Commits
Author SHA1 Message Date
yetone e215d335a6 gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.

- access: Key and Change get MaxConcurrency, and Identity carries it, the
  issuer's cap included. The concurrency-key action refuses a value
  below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
  key's cap, however the request came (loopback, LAN, a Remote magpie, a
  Responses socket's turn). One request too many waits in the key's
  queue in arrival order. It shows as "slot" in Active, and its wait goes
  into the try's Queued. A request whose agent goes away while it waits
  leaves the queue and sends nothing. A stream holds its slot until it
  ends. serve's routes (chat, responses, messages, ollama, gemini, the
  Codex backend) wait inside the try, after keepQueued, so a streaming
  agent gets keepalives while it waits. The other model routes (images,
  embeddings, rerank, audio, videos, search, decisions, native) wait
  before their handler runs. forward and codexUpstreamOn take the slot
  too, so nothing reaches a vendor without one. A key issued under
  another waits for its own slot, then for its issuer's.
  /v1/magpie/concurrency lists each capped key under "keys", and counts
  its waiters in "waiting". A key's limit (key_limit) reports the cap.
  Not held, as a provider's MaxConcurrency doesn't hold them: GET,
  HEAD, OPTIONS, count_tokens, :countTokens and MCP.
  TestKeySlotEveryRoute fails when a route is judged neither held nor
  free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
  negative, over 1000, a fraction, a word, --help or an extra argument
  with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
  style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
  and Other… takes a number typed in place. A value that isn't a whole
  number up to 1000 is refused and nothing is sent. Browser and
  read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
  de. An unset badge, which a hover shows, gives way before the masked
  key (flex-shrink 8). Without that, at 420px in en and de, the extra
  badge squeezed the key until its copy button slid under the pointer
  that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.

Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto 627fd1a3b,
which touches none of these files, and the budgets were run again):
- go test -timeout 45m ./internal/access ./internal/gateway ./internal/cli
  ./internal/gui: access, gateway (839s) and cli ok. gui had one red,
  TestGatewayModeStatsNameTheGatewaySessions, run at 00:40 PST: its
  record an hour back falls on yesterday in a day's first hour. It
  passes from 01:09, so it is unrelated; filed as #5690. The Budget/Size
  tests were run again after the CSS change: ok.
- gofmt -l: clean. go vet for darwin, plus GOOS=linux and GOOS=windows
  (-tags nogui), on those packages: ok.
- GUI (node --test, Chromium and WebKit, 1100 and 420 wide, en, zh,
  zh-TW, ja and de): every file that loads the gateway keys (59) plus
  i18n-keys and i18n-en-no-cjk. The reds left are the same on
  origin/main and already filed: gateway-key-models en (#5233, #4081),
  i18n-keys "a plugin's words are its own" (#5332), phone-connect-menu
  at 420 (#4706, #4707). After the flex-shrink fix:
  gateway-connect-keys, gateway-key-arrange, -concurrency, -mcp,
  -own-rotate and -quotas passed 104/104 in both engines, against
  84/84 on base.
- The tests:
  - TestKeyConcurrency, over LAN with cap 2: 2 of 3 requests reach the
    vendor and the third is shown as "slot". Another key isn't held. A
    cancelled waiter leaves the queue and never reaches the vendor. The
    third goes once one ends, every lane is given back, and its Queued
    is at least 40ms.
  - TestKeyConcurrencyKeepsStreamAlive: a waiting stream gets 200 and
    keepalives.
  - TestKeyConcurrencyEager: on embeddings an issued key waits on its
    parent's lane, a cancelled waiter leaves, never more than 1 runs at
    once, and a GET takes no slot.
- A real `serve` in a sandbox HOME (built from this tree, MAGPIE_ADDR
  127.0.0.1:38612) against a fake slow SSE upstream. Steps: `provider
  add fake url=…`, `gateway-key add`, `gateway-key concurrency <id> 1`,
  then three concurrent keyed streams. /v1/magpie/concurrency showed the
  key at busy 1, waiting 2, limit 1 (two in "slot"). The upstream's
  most at once was 1, and it saw 3 requests one after another (200s at
  1.9s, 3.7s and 5.5s, each with [DONE]). Afterwards "keys" was empty.
  `concurrency <id> 2000` exited 1 with its usage.

Broken by hand (each went red, then restored):
- keySlot returns nil: TestKeyConcurrency ("timed out waiting for c
  queued") and KeepsStreamAlive.
- The issuer's lane skipped: TestKeyConcurrencyEager.
- The eager take skipped: TestKeyConcurrencyEager.
- The CLI's bounds check removed: "accepted [concurrency id 0]".
- The GUI's bounds check removed: gateway-key-concurrency.
- Without the flex-shrink line: gateway-key-arrange chromium/webkit en
  and de 420px.

Not tried / not done:
- Full suite not run at push (neither `go test ./...` nor the whole GUI
  suite).
- Not tried with a real vendor account or a second computer on the LAN.
  The LAN path is covered by TestKeyConcurrency's lanServer.
- The key's badge shows the cap, not live running or waiting counts.
  /v1/magpie/concurrency has those.

Reported-by: young02036 (Discord)
2026-11-08 17:52:09 +08:00
yetone d55881730d gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some
MCP servers and tools, as keys already are to models (#882).

A key's MCP list (caller-keys.json "mcp") holds entries "server" (every
tool of it) or "server/tool"; "-" alone is no MCP server; an empty list
is every server, as before. A key issued under another is held to its
issuer's list too.

Every MCP route checks it:
- magpie's own servers (web search, vision, image, Magpie Browser, plugin
  tools) through serveMCP: initialize/tools/list/tools/call are refused
  or filtered per server and tool, and /v1/magpie/key-limits names "mcp";
- the Library hub ("magpie"): only the backing servers and tools the key
  may use are listed, and a call by name or by fallback is refused;
- /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is
  filtered in JSON and SSE replies, tools/call refused; a reply the
  filter can't read (an encoded body) is a 502, never passed through.

GUI: "MCP servers" in the key row's menu opens the app's own picker (no
native select) with All, No MCP server, each server and its tools (GET
/api/caller-keys/mcp lists magpie's own servers and the Library's). A
key held to some shows a badge saying which, that opens the same list;
a free key shows nothing more in its row, on hover either. A hover badge
was tried first: it pushed the row past 560px (gateway-caller-keys) and
squeezed the masked key under a drag at 420px (gateway-key-arrange).
CLI: magpie gateway-key mcp <id> github fs/read_file | none | all.
zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and
library subsystem pages.

Not covered: a model's own built-in web search (a vendor tool, not MCP).

GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its
list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed
caught it at the rebased head).

Run on mote (mote-run), at the pushed head:
- go test ./internal/access ./internal/cli ./internal/gui
  ./internal/library ./internal/gateway at a9c40186d (this change on
  2ce44dc28): ok except internal/gui's TestMainWindowCorners/macOS_26_SDK
  (#3949, the same message on macOS 27). After the rebase onto a9667daad
  (no file in common): TestCoreScriptBudget, TestCallerKey*,
  TestEveryRoute*, TestGatewayKey*, TestKeyMCP*, internal/access and
  go vet ./internal/... at d36f89224's tree: ok.
- gateway-caller-keys chromium en reads wider than 560px 4 of 6 runs
  alone on this branch and 4 of 6 on origin/main a9667daad: #3797,
  recorded there.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: clean; darwin, linux (nogui) and windows builds ok; gofmt -l
  clean.
- GUI: gateway-key-mcp.test.cjs in chromium and webkit, widths 1100 and
  420, en/zh/zh-TW/ja/de: 20/20. Every gateway-key*, gateway-keys* and
  i18n* file in both engines: ok except gateway-key-models en (red on
  origin/main ecc26a339 too, #4081/#5233) and i18n-keys "a plugin's words
  are its own" (red on main, #5332).
- The whole GUI suite (both engines, every language) with the hover
  badge: 91 reds in 25 files. Rerun alone on this branch and on
  origin/main 54dc257f1: only gateway-caller-keys (560px sideways),
  gateway-key-readonly, models-fold and models-select-all-api were red
  on the branch alone; the badge moved into the row menu for the first
  two. After it, every gateway-key*, gateway-caller-keys, gateway-card,
  gateway-connect-keys, api-key-theme and i18n* file passes in both
  engines, except i18n-keys "a plugin's words are its own" (red on main,
  #5332, none of the three strings are this change's) and 1 of 20
  models-select-all-api "the click scrolled" (#4389; models-fold is
  #4071). The rest are red on origin/main too and each has an issue:
  account-weight #4644, codex-auto-reset #2360, header-centre #3479,
  images-codex-one #4618, key-replace #4126, menu-input-scroll #3402,
  mobile-web #3952, model-chip-steady #4388, model-copy-id #4621,
  models-works-only #4391, nav-timeout #4787, omarchy #4624,
  page-width-steady #5013, phone-connect-menu #4706/#4707,
  plugin-move-unserved #4392.

Broken by hand, each went red: the serveMCP server gate, call check and
list filter, the own-server list filter and key-limits "mcp"
(TestKeyMCPOwnServer); hubTools, hubServersOf, the hubToolNamed
fallback and hubMCPRun (TestKeyMCPHub); /mcp/run (TestKeyMCPRun); the
/mcp/<name> guard and filter (TestKeyMCPProxy); the GUI's "No MCP
server" being exclusive (gateway-key-mcp).
gateway-key-readonly chromium 420 ja was red with the hover badge (the
sibling run, the whole suite and its rerun; green on origin/main) and
passes with the badge in the row menu.

Not tried: a real Library server through a live gateway, the hub with a
real agent, and running on Windows or Linux (vet and build only).

Reported-by: wakaka
2026-11-07 03:21:57 +08:00
yetone e1eeeed734 browser: the extension's key connects Magpie Browser and nothing else; own needs this computer; a key turned off closes its browser
483b131ef wrote a full-access gateway key ("Magpie Browser") into the
extension zip in Downloads. Anyone with a copy of the zip could use every
model, MCP server and stat, and, with own = key == OwnBrowserKey(), could
connect from another machine as this computer's own browser and receive
this computer's agents' browser calls (page data out, prompt injection
in). A keyed WebSocket also stayed open after its key was turned off.

- access: Key.Browser / Identity.Browser. A browser key is also ReadOnly
  (so a magpie from before reads it as read-only) and never issues keys.
  access-key and issuer-key refuse it. ScopeBrowser(id) holds an existing
  key to the browser with the same secret; the sharing key is never
  scoped. Current(who) says whether a key Check took is still on by the
  same secret (Identity carries the secret's SHA-256, set on the legacy
  sharing-key fallback too, so a legacy caller's identity is the same
  before and after its migration).
- gateway readOnlyGuard, the one place every route passes after the key
  is known: a browser key gets 403 gateway_key_browser_only on every
  pattern except GET /v1/magpie/browser/extension.
- own: the key must be OwnBrowserKey() and the request local(r)
  (loopback peer, not proxied, not the page port).
- browserConn keeps its key's identity. call() refuses a connection whose
  key is no longer Current, and a 5s watcher closes it (1008).
- gui browserKey: a new key is made Browser; the recorded key is reused
  only once ScopeBrowser holds it.
- GUI key row: "Browser only" tag (zh, zh-TW, ja, de), no access toggle.
  CLI prints "browser" access. agent gatewayTakes skips a browser key.

Old data: an existing "Magpie Browser" key (OwnBrowserKey) is rescoped in
place, same id and secret, when the gateway starts (ScopeOwnBrowserKey)
and again on the next extension download. Installed extensions keep
connecting with no reinstall. Every copy of an old zip loses models, MCP,
stats and writes, and from another machine it is no longer this
computer's browser. A user who downgrades reads the key as read-only.
Keys a user made themselves are untouched.

Regression, filed as #5529: Magpie in Docker with the host's Chrome
reaches the container from 172.17.0.1, not loopback, so its agents no
longer get the host's browser as their own. #5529 proposes pairing in
its place. docs/reference.md and site docker pages (en, zh, ja) say so.

Docs: docs/subsystems/gateway-routing.md (browser key), library.md
(Download), docs/reference.md (Docker), site/public/docs{,/zh,/ja}/docker.html.

Run on mote at origin/main 2000ae439 + this change:
- gofmt -l internal cmd: empty.
- go vet darwin, GOOS=windows, GOOS=linux -tags nogui over access,
  gateway, gui, agent, cli: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ./internal/gui ./internal/access ./internal/library ./internal/agent
  ./internal/cli: all ok except access's
  TestLegacyLANFallbackBeforeMigration, red from this change (the legacy
  fallback had no secret sum). Fixed here, then ./internal/access in full:
  ok.
- GUI, 21 files (gateway-key-*, i18n-*, library-browser-*), chromium and
  webkit, every language: 332 of 334. The 2 reds fail the same on
  origin/main 6f5d48ea0 run alone: i18n-keys "a plugin's words are its
  own" (#5332, #5426, #5482) and gateway-key-models' 560px width check
  (#4081, commented).

Rebased onto 6f5d48ea0 (remote_prove: a new POST /v1/magpie/prove route
and edits to readonly.go and gateway.go, so not a -run rerun): gofmt -l
empty, vet on all three ok, go test -count=1 ./internal/gateway
./internal/access ok, ./internal/gui -run Browser ok. A browser key gets
403 on the prove route too (TestBrowserKeyEveryRoute walks every pattern).

Broken by hand, each red on mote:
- guard off: TestBrowserKeyEveryRoute (/v1/ 200, /v1/models read_only
  not browser_only).
- no migrate: TestBrowserKeyEveryRoute (/v1/models 200).
- own without local(r): TestOwnBrowserKeyIsThisComputers.
- no watcher: TestBrowserKeyOffClosesItsBrowser (stayed connected).
- no Current check in call(): TestBrowserKeyOffClosesItsBrowser.
- Current ignoring the secret: TestCurrent.
- gui reuse without ScopeBrowser / new key without Browser:
  TestBrowserExtensionDownload (both).

Not tried: a real Chrome with the real extension, a real Docker
container, a real old key in a live HOME, the TUI. No CLI test for the
"browser" access word. Tests reach no network (httptest, loopback only).
2026-11-06 22:11:02 +08:00
yetone 1f439ecc5e gateway keys: a limit can count only some models or providers (zola_xynb)
zola_xynb on X asked for a cap per model or per provider under one
gateway key. A key limit can now name models (access.Limit.Models,
"<provider>/<model>" or "<provider>/*"), so one key can have, for
example, a month of $20 on openai/* next to a month for the whole key.
Limits without models still cover the whole key, as before.

- budget: sums are kept per window and scope, and count a ledger row only
  when its provider/model matches (any of the model's ids). reserve holds
  a request to a scoped limit only when the model it names is served
  there. windowsOf keeps every scope's sums, so the ledger is not read
  again on each request.
- gateway: keyLimited puts the key's spent scopes on the caller
  (withSpent), count_tokens included. A direct request for a spent model
  gets a 429 with Retry-After and no X-Magpie-Limit-Reset, so a remote
  magpie rests only that model. A routing group, a provider's fallback
  and embedding/image/video/decision groups skip spent members
  (groupKeeps, allowedCandidates) and get a 429 only when none is left.
  System One, count_tokens and magpie's own calls for the key are held
  too. Model lists are unchanged. A refusal turned away before routing
  now records its ErrType in the ledger.
- CLI: magpie gateway-key limit <id> add month --cost 20 --model openai/*
  (--model repeatable, --models a,b).
- GUI: the key limit editor has a Models field that opens the app menu
  (multi-pick: All models, every model of a provider, each model). It has
  no <select> and no new screen. The badge, line and tabs name the models.
  Strings are in every language.
- docs: reference.md and subsystems/gateway-routing.md.

Run at d52725d32 (this change on 4ef47b3f4), on mote:
- go test ./... -timeout 45m, under the shared lock, with the log kept
  whole: every package ok except three reds outside this change. None of
  the three touches what changed:
  - TestClosedBeforeSentEveryTimeSaysWhy (#5031, passes alone 3/3)
  - TestMainWindowCorners/macOS_26_SDK (#3949, red alone on macOS 27)
  - TestMoveToPlugin TempDir cleanup (filed #5524, passes alone 2/2)
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./..., go build ./...: ok. gofmt -l: nothing.
- GUI, chromium + webkit: gateway-key-*.test.cjs, gateway-keys-*,
  i18n-keys, i18n-en-no-cjk and usage-remote-key-limits passed 244/246.
  The new gateway-key-model-limit runs in every language at 1100 and
  420px. The two reds also fail on origin/main 3cbb7e042:
  - gateway-key-models en at 560px (#4081, #4616, #5233)
  - i18n-keys "a plugin's words are its own" (#5327, #5332, #5426, #5482)

Broken by hand; each one turned the named tests red:
- groupKeeps' spent skip removed: ItsModelsAlone and MediaGroups.
- modelAllowed's spent check removed: ItsModelsAlone and AFallback.
- withSpent on count_tokens removed: ItsModelsAlone.
- the scoped refusal sending X-Magpie-Limit-Reset: ItsModelsAlone and
  SystemOne.
- sums counting every model: ItsModelsAlone, TestScopedLimitCountsItsModels
  and TestScopedBesideTheWholeKey.
- embeddings' keyGroupRefusal back to keyModelRefusal: MediaGroups.
- the turned-away row's ErrType dropped: ItsModelsAlone.
- keyHolds not holding for Spent: ItsModelsAlone, AFallback and
  MediaGroups.
- decide.go's 429 back to a 403 stayed green. keyLimited's reserve
  refuses a direct decider first, so that line is a second guard.

Not tried:
- a real vendor account or a real remote magpie.
- the Codex backend path and a video group: they go through the same
  keyLimited/groupKeeps code, but no test of their own.
- the whole GUI suite: only the files above.
- Windows and Linux test runs: vet only.
2026-11-06 20:47:21 +08:00
yetone d136d0fe98 gateway-key: rotating a key can give it a value of the user's own (isaac_bai)
isaac_bai on Discord: a gateway key's value is random, and only rotate
changes it, to another random one; they want to set one easy to pass on.
Adding a key could take an own value since 6b6113aa; an existing key
couldn't.

- access: rotate-key takes Change.Secret. Given, it is checked as an
  added key's own value (ownSecret: 8-256 printable ASCII, no space, not
  sk-magpie-, no other key's value; its own current value is allowed);
  empty, magpie makes one as before. The key keeps its id, name, limits,
  models and accounts, and Named counts a request from this computer
  with it as that key.
- ownSecret now refuses a value that is one of the user's provider keys
  (a provider's Key or any of its Keys, constant-time), for add-key too:
  a client sending it would spend that provider directly.
- CLI: `magpie gateway-key rotate <id> --key <value|->`; docs/reference.md.
- GUI (plugins/gateway/keys.js, outside the core budget): the Rotate key
  dialog has a hidden "Your own key (optional)" field; Enter rotates,
  Escape cancels; an own value says "Gateway key changed. Clients that
  send this key reach magpie now." Strings in zh, zh-TW, ja, de.

Tests: TestRotateToOwnValue (bad values refused, old value still works
after a refusal, trimmed own value authenticates as the same key, is
Named, listed masked; empty makes a new key; add-key refuses a provider
key). TestRotatedOwnValueKeepsTheKeysLimit: after rotating to an own
value the old one is 401 from another computer, the own one 200 from
another computer and from 127.0.0.1, and a 700-token day limit stops
the third request from either (429), every record under the key.
gateway-key-own-rotate.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de,
1000 and 400px.

Run (mote): at the pushed head: TestCoreScriptBudget ok, ./internal/access ok, the
own-key/caller-key gateway tests ok. At f37742e14 with this change (no file the rebase touched):
gofmt -l clean; go vet GOOS=linux and windows (./internal/access ./internal/gateway, cli with
-tags nogui on linux) ok; ./internal/cli red on TestEveryRouteHasACommandOrIsNamed only,
/api/context/reply (#5026, 0872bc2a0, the same at main); GUI: gateway-key-own-rotate 20/20,
every gateway-key-*, redact-*, masking-*, privacy-* file and i18n-keys pass.
Broken by hand: the rotate own-value path off made TestRotateToOwnValue and
TestRotatedOwnValueKeepsTheKeysLimit red (401 from another computer); the provider-key check off
made TestRotateToOwnValue red ("accepted upstream-first-key").
Not run: the whole GUI suite (two runs lost: one to another run of this tree, one to mote
rebooting mid-run); it runs after the push. Not tried: a real client on another computer with
the own value, the real app.
2026-11-03 20:17:00 +08:00
yetone 5a56bc7d73 gateway: a CI job trades its OIDC token for a short-lived key (#4531)
xazaj on X asked for GitHub OIDC: a GitHub Actions job should get a
gateway key without a long-lived magpie key in the repository's secrets.

A rule (magpie gateway-key oidc add --key <id> --repo owner/name
[--ref …] [--environment …] [--claim k=v] [--ttl 1h] [--issuer URL]
[--audience a]; oidc list, oidc remove) names an issuer (GitHub Actions'
by default, any https issuer), an audience (magpie-<rule id> by default,
so a token asked for one rule opens no other, and the workflow needn't
know the gateway's address), claims (exact or path.Match globs) and the
gateway key the keys are issued under, which must be let issue. A GitHub
rule names the repository or its owner with no wildcard, or every
repository on GitHub could get in. No rule, no exchange.

POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an
optional {"ttl","models"} verifies the token (RS256 only, keys from the
issuer's discovery document's https jwks_uri, exp required, nbf/iat with
a minute's leeway, the rule's aud and claims, a jti traded once) and
issues a key through access.IssueKey under the rule's key, named
repo@ref (run N), living no longer than the rule. Everything issued keys
guarantee holds: bounded by the issuer's models and accounts, its spend
counted against the issuer, stopped when the issuer is turned off.

- A token is judged only against rules naming its iss, so it can't make
  magpie fetch from a URL of its choosing.
- Keys are cached an hour per issuer, read by one request at a time with
  no lock held across the fetch, asked again for an unknown kid at most
  every 10s, and kept while the issuer is down; with none ever read,
  nothing is let in.
- The route is lanGuard's one exemption from remoteKeyed (that exact
  path, POST, no gateway key): only while shared, past the allow list,
  and a refused token counts against tooManyAuthFails (429 past the
  burst). A read-only key is refused it.

The issue's open questions, decided: rules are generic from the start
(the GitHub repository rule applies to GitHub's issuer); rules are CLI
and file only for now (oidc-rules.json), no GUI.

Docs: docs/subsystems/gateway-routing.md (Trading an OIDC token for a
key, routes table) and site/public/docs remote in en, zh and ja, with
the workflow snippet.

Tests: TestOIDCTokenTradedForKey (no rule, a traded key that works on
chat with its TTL capped and its name, a model past the issuer, another
branch, no token, 51 bad tokens -> 429, issuer turned off, a token on a
model route, loopback, not shared -> 403); TestMatchEachCheck (14 bad
tokens, list aud, replay, the refusal naming the claims);
TestKeysCachedAndKept (8 concurrent tokens one fetch, rotation, a made-up
kid inside and past the gap, the issuer down 2h later, an unnamed issuer
never fetched); TestUnreadKeysLetNothingIn; TestAddRefuses;
TestGatewayKeyOIDCCLI; TestReadOnlyKeyEveryRoute with the new route.
A JWKS from an httptest TLS server, never the network.

Broken by hand, each red then restored: the signature check, the claims
match, the jti check, the exp check, the refetch gap, the GitHub scope
rule, the lanGuard exemption, the throttle and the TTL cap.

Run at this head (rebased on 6a7a690be), on mote: go test ./internal/oidc/...
./internal/cli (whole packages) and go test -run 'OIDC|ReadOnlyKeyEveryRoute|
KeysEndpoint|IssuedKey|AuthThrottle|Route' ./internal/gateway: ok; gofmt -l
clean. At the 13aa33eac base: go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows): ok; node --test site/*.test.mjs: 63 pass.
Full suite (-tags nogui -timeout 45m ./...) on the Linux box at the
13aa33eac base, still running when this was pushed (mote had two other
sessions' suites at load 291); so far every package ok except
internal/agent's TestInstalledVersion, TestGrokInstalled,
TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir,
the WSL box's fake-binary reds filed as #4033 and #3548. The rest of the
run goes on #4531.

Not tried: a real GitHub Actions run against a shared magpie; a
connection open when an exchanged key expires.
2026-11-01 05:39:02 +08:00
yetone 2eac916170 gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
2026-10-31 13:44:29 +08:00
yetone 333e7f573b gateway: gateway keys are dragged into the order you want, kept with the keys (alextjy on Discord)
alextjy asked on Discord whether gateway keys can be reordered. They
could not: the Gateway page listed them in the order caller-keys.json
held them, and nothing changed that order.

- access: a "move-key" action puts one key at a place in the list,
  under the same file lock as every other key change. Nothing else
  about the key changes, and the sharing key's mirror in settings is
  left alone (its pointer would otherwise land on another key).
- GUI: the Gateway page's key rows are dragged the way search APIs'
  rows are (shared dragRows, a grip shown on hover only, Alt+Up/Down,
  the existing "Drag to reorder" title). A refused move puts the list
  back from the server. New strings in zh, zh-TW, ja and de.
- CLI: `magpie gateway-key move <id> <place>` (from 1); list already
  prints the stored order.
- Usage > Requests: the key filter lists keys in the user's order,
  removed keys after. The Overview stays a ranking by use.

Run (worktree at 14b451c11, then rebased on origin/main):
- gofmt -l clean; go vet (darwin) on access, cli, usageapi, gui;
  GOOS=linux -tags nogui and GOOS=windows go vet on access, cli,
  usageapi (mote).
- go test access, cli, usageapi: ok (mote). internal/gui: every test
  ok except the real-window AppKit tests #4125 lists
  (TestCoveredWindowStaysUp, TestPanelCloseHidesIt and 7 more), killed
  at their deadlines with pboard not running on mote.
- Broken by hand: with move-key removed, TestMoveKeyKeepsOrder,
  TestGatewayKeyCLIMove and TestLedgerKeyFilterInKeyOrder go red; with
  the mirror exclusion removed and the filter left unsorted,
  TestMoveKeyKeepsOrder ("the sharing key's mirror moved") and
  TestLedgerKeyFilterInKeyOrder go red.
- GUI (WSL): gateway-key-arrange 20/20 (chromium and webkit; en, zh,
  zh-TW, ja, de; 1100 and 420px). Red by hand: no arrange (20 red),
  grip always shown (chromium 10/10 red), drop commits nothing (webkit
  10/10 red).
- GUI (WSL), the 68 files the change can reach (every caller-keys
  fixture user, gateway-*, search-*, usage-ledger*, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, key-page, phone-rows, api-key-*): 900/923. The
  reds were run again at origin/main 43966a53f and fail the same there
  (api-key-theme webkit, gateway-key-limit webkit, gateway-key-models
  webkit, search-first, usage-ledger-open-settled, usage-ledger-ttft,
  usage-ledger), each filed: #3307, #3523, #4081, #3795, #4262,
  #3104/#1876, and #4489 (usage-ledger-ttft, new). phone-rows,
  search-keys and connect-snippet-shell reds of the first run passed
  when run again at the head. usage-ledger's "zh: request routing
  links" went red once at the head (Usage view position on return) and
  passed in the first run.

At the rebased head (on 2ac423f4f): TestCoreScriptBudget and the
other Budget/I18n/Asset tests in internal/gui ok (mote);
gateway-key-arrange, i18n-keys and gateway-caller-keys 27/28 in WSL.
The red is gateway-caller-keys webkit en "wider than 560 right after
the resize" (#3797, red alone on main). A probe of that file, printing
the page width and any element past it, read 560/560 with nothing
wider in both engines, in two runs beside the arrange file.

Not tried: dragging in the real app (WebKitGTK, WKWebView, WebView2),
the full Go suite (started after the push).
2026-10-31 03:48:27 +08:00
yetone f2c6831a31 gateway: a read-only gateway key reads quotas and usage and uses nothing (Steven on Discord)
Steven's ESP32 desk display polls magpie (Docker, on his LAN) every 15s
on GET /v1/magpie/quotas and /v1/magpie/usage and never sends a model
request. Only a key held to nothing was told the usage summary, so the
key kept in the device's flash had to be one that could spend every
account.

A gateway key can now be read-only (access.Key.ReadOnly):
- `magpie gateway-key add <name> --read-only`, `magpie gateway-key access
  <id> [read-only|full]` (`gateway-key --help` lists it; `list` has an
  ACCESS column), and "Make read-only" / "Give full access" in the key's
  menu in Gateway -> Gateway keys, with a "Read only" tag on its row.
- readOnlyGuard (internal/gateway/readonly.go), after callerGuard and
  before withCaller/keyLimited, judges the pattern ServeMux.Handler routes
  the request to. A read-only key is answered GET /, /v1, the quotas,
  their history and cards, the usage summary and its requests, its limit
  and the concurrency. Every other route is refused with 403
  gateway_key_read_only: every model route, count_tokens, the Responses
  WebSocket's upgrade, every MCP server, Codex's and Gemini's backends,
  /v1/models and the Ollama routes, the catch-all, the trace and route,
  debug profiles, and every write (usage ingest, quotas refresh). It is
  default deny, so a route added later is refused until it is classified.
- The key is held to nothing else, so heldKey leaves it alone: it reads the
  usage summary and every account's quotas, as a key held to nothing does.
  None of those routes holds a key's secret.
- The sharing key can't be made read-only, since magpie gives it to its own
  agents (LANSecret). Update refuses it, and the GUI item is off with why.

Older versions: a magpie from before this commit doesn't know `readOnly`
and treats such a key as a full one, so downgrading magpie widens the key.

Tests:
- TestReadOnlyKeyEveryRoute (internal/gateway/readonly_test.go) takes the
  patterns from the router itself (routes() records each HandleFunc). It
  fails when a pattern is in neither readOnlyRoutes nor its refused list.
  It sends every refused pattern, by each method it takes, from
  192.168.1.9 and from loopback, plus a WebSocket upgrade and an unclean
  chat path, and expects 403 gateway_key_read_only with the upstream never
  reached. It checks that every allowed route answers, that no body holds
  any key's secret or the upstream key, that the usage summary names the
  other key's use, and that a full key and a key made full again still
  reach the model.
- TestReadOnlyKey (access) covers add-key and access-key on and off,
  Authenticate, List, and the sharing key refused.
- TestGatewayKeyCLIReadOnly covers --read-only before and after the name
  and beside --key, access, the list column, bad values, and --help.
- gateway-key-readonly.test.cjs runs Chromium and WebKit, 1100 and 420px,
  in en/zh/zh-TW/ja/de. It covers the tag, both menu items and what they
  post, the status line, the sharing key's item off with its why, no
  scroll on click, no sideways scroll, no select, and no left stripe.
  gateway-card.test.cjs now expects the menu's 4th item.
- TestClientPathCoversHandler takes the patterns from routes() instead of
  parsing Handler's source, which moved into routes().

Broken by hand:
- readOnlyGuard passing everything: TestReadOnlyKeyEveryRoute red (103
  lines, /v1/models 200 onward).
- A new `POST /v1/new-thing` route in routes(): red, "in neither
  readOnlyRoutes nor readOnlyRefused".
- The GUI item not off for the sharing key: gateway-key-readonly red 10 of
  10 in Chromium.

Run at the pushed head (on origin/main 0911a65e7), on mote: TestReadOnly*,
TestHeldKey*, TestClientPathCoversHandler, TestGatewayKey*, TestCaller*
in access, cli and gateway ok; TestCoreScriptBudget ok; on Linux
(wsl-run, both engines) gateway-key-readonly, gateway-card, i18n-keys,
gateway-caller-keys and gateway-key-quotas 68/68.

Full Go suite on mote (macOS) at the same change on origin/main
dca3e2d71 (94630237d), -timeout 45m: 78 packages ok; internal/gateway
red only on the four TestAntigravityTurned* and
TestCodexSpentGrokFailingIsTold (red the same at origin/main, #4362);
internal/gui red only on ten AppKit window tests that hit their 30s
bar while mote's launchd throttled every app launch (#4125).

Run on mote (macOS) on origin/main dca3e2d71:
- go test ./internal/access ./internal/cli ./internal/gateway: access ok;
  cli red only on TestLibraryMCPHub's TempDir cleanup (#4140); gateway
  red only on the four TestAntigravityTurned* and
  TestCodexSpentGrokFailingIsTold, red the same at origin/main (#4362).
  TestReadOnly*, TestHeldKey*, TestClientPathCoversHandler,
  TestGatewayKeyCLIReadOnly pass.
- TestCoreScriptBudget ok (no budget raised). gofmt clean; go vet
  darwin (access, cli, gateway), GOOS=windows ./... and GOOS=linux
  -tags nogui ./... clean.
- GUI, earlier at 807048470 on mote: gateway-key-readonly,
  gateway-key-quotas, i18n-keys, gateway-card, api-key-theme,
  gateway-connect-keys and gateway-caller-keys 34/34 in both engines.
  At this tree mote's WebKit hung at launch for every test (#4125), so
  the 43 gateway-*/key-*/api-key-*/caller-*/menu-*/i18n-* files ran on
  Linux (wsl-run, both engines): 501 of 514. The reds in api-key-theme,
  gateway-key-limit, gateway-key-models, key-replace and menu-input-scroll
  are red the same at origin/main e8d42c02d (#4120, #3523, #4081, #4126,
  #3402); gateway-keys-empty's WebKit wait was red 1 in ~13 runs here and
  0 in 4 at main, filed as #4383 (this change doesn't touch its path).
- Full Go suite on Linux (wsl-run, at 807048470 with this change): reds
  only where Linux can't build the GUI (no gtk4/webkitgtk) and in
  internal/agent's install tests (#4033) and the gateway reds above,
  each red the same at origin/main dca3e2d71; plus
  TestClientPathCoversHandler, which parsed Handler's source and is now
  read from routes() (fixed here).

Not tried: a real ESP32 or Docker magpie; a remote client against a
running gateway (only httptest through lanGuard/Handler); the Windows
test runs (vet only); the whole GUI suite (mote's WebKit hung, #4125).
2026-10-30 14:33:01 +08:00
yetone 05a6087e1f access: a key with accounts and no model may use only its accounts' providers' models
Linka on Discord (#feedback): in a gateway key's "Models this key can
use", ticking only an account and no model let the key list and use
every model of every provider.

Cause: Key.Models empty meant "every model", and Key.Accounts (#905)
held only the providers it names, so every other provider stayed open.

Change: access.HeldModels gives a key with accounts and no models the
models "<provider>/*" of each account's provider. Authenticate builds
the Identity with it, so every route's existing model gate narrows:
/v1/models, /v1beta/models, chat, responses, messages, Gemini,
count_tokens, embeddings, images, the Codex backend path, System One,
groups and fallbacks. A key that lists models is unchanged (#905: its
accounts still hold only the providers they name); a key with neither
is unchanged. The CLI's MODELS column and `gateway-key models` say so,
and the GUI editor's hint, the "not used" notes on providers no model
or account reaches, and the save status follow (en, zh, zh-TW, ja, de).

Tests:
- TestGatewayKeyAccountsOnlyHoldTheModels: each route above is 403 for
  the accounts-only key and no upstream call reaches the other
  provider, the decider or the image provider; its own provider, a
  group of it and a key that also lists models work. Red on the old
  code on every route (list showed spare/m2, chat/count_tokens/
  embeddings/systemone 200).
- TestHeldModels (access).
- gateway-key-accounts.test.cjs: hint, notes and status; 4/4 red on
  the old assets, green on the new.
- TestGatewayKeyAccountsListModels / SystemOne / OfANamedProvider and
  TestHeldKeyToldItsOwnQuotas now encode the new rule (the held key is
  told only its own provider's quotas).

Run on mote: gofmt -l clean; go vet darwin, linux -tags nogui, windows
on access, cli, gateway, gui ok; go test -timeout 45m ./internal/access
./internal/cli ./internal/gui ./internal/gateway: ok except gui's
TestMainWindowCorners/macOS_26_SDK (#3949, not this change) and
gateway's TestHeldKeyToldItsOwnQuotas, updated and rerun ok. After the
rebase on 1f03d7546 the key tests ran again ok. GUI: gateway-key*,
i18n-keys, gui-de, gui-ja, gui-zh-tw in Chromium and WebKit: 131 pass.

Not tried: a plugin-served provider (same model gate), a real
account, Windows and Linux test runs (vet only).
2026-10-30 01:25:57 +08:00
yetone 6bffcfe178 gateway-key: a key's monthly limit can be set from the CLI again
`magpie gateway-key limit <id> month --cost 5` (and `add month`) failed
with "an N-hour cycle is a whole number of hours …: \"month\"":
parseKeyLimit cut an h off any window ending in one before it looked
for a named period, and month ends in an h. A named period (day, week,
month) is now taken as itself before the <N>d and <N>h forms are read.
Found while trying every command for the magpie-setup skill in a
sandbox HOME.

Run: go test ./internal/cli -run TestGatewayKey -count=1 ok; the new
month cases in TestGatewayKeyLimitCLI fail on the old parseKeyLimit
(reverted by hand) and pass with it. Tried the built binary in a
sandbox HOME: limit <id> month --cost 5 sets "this month".
2026-10-25 19:34:55 +08:00
yetone 3d3a834d62 gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.

With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
  lists of it: a key with some of a provider's models is told nothing of
  it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
  matched by the card's User against AccountIDs (a name two accounts
  share needs both; a card no account is known by only where the key's
  list names none of that provider's); a provider's only key's card,
  named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
  naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
  the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.

Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
  GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
  rebase onto 7be68467f (#2227's several limits; conflicts in access,
  the CLI usage and test, keys.js and providers-accounts.md resolved by
  keeping both): every package ok but internal/gateway, whose
  TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
  400ms deadline also covers the response headers; filed #2248) and
  passed 5 of 5 alone. Before the rebase the whole suite was ok, with
  agent and gateway rerun at -timeout 40m after the 10m timeout under
  load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
  a key with A/m1 sees nothing of A, an account-held key sees only its
  key's card, a provider's only key, a key told nothing gets 403 from
  the cards route, Quotas-off still 403 everywhere, refreshes outside
  the scope 403. Broken by hand, each red: scope returned nil (every
  card told), every[id] forced true (partial models), the account check
  skipped, the refresh check removed, the only-key rule removed, and the
  told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
  its Remote magpie provider, through a key held to alpha's Two, shows
  office/alpha's Two card beside the key's own; a key told none shows its
  own card alone. Red with the told-none 403 removed ("nothing read on
  that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
  and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
  value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
  row is hovered (the row had no room left at 390px: gateway-connect-keys
  went red in en until it did), and on a phone it is shown like the
  row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
  web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
  besides phone-rows (since fixed, above): quota-count-wrap and
  quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
  usage-fold chromium en/zh (#2163), each red alike on a fresh
  origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
  gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
  phone-rows and key-limit file, both engines: 210/210.

Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
2026-10-15 02:29:11 +08:00
yetone f299faef48 gateway keys: a key holds several limits at once, every one must pass, and the 429 names the one that resets last (#2227, oxsean)
A key may now hold up to five limits, each in its own window (5 hours
and a week, say). A request needs every one: budget.Reserve checks
each, holds one reservation per window and settles each, and when some
are spent refuses with the spent limit that resets last, so
X-Magpie-Limit-Reset and Retry-After say when the key is really back.
Two limits in one window are refused (change that one instead).

Saved format: the first limit stays in "limit", which older magpie
reads, the rest go in "moreLimits". A file without moreLimits reads as
before.

- access: Change.Index adds (index = len), replaces (keeps its Since)
  or removes (nil) one limit; reset-limit-key with an index resets one,
  without resets all; the plain limit-key replaces all, as before.
- /v1/magpie/limit: "limit" is the binding one (what older clients
  read), "limits" is each. A remote key card shows a window per cap of
  each limit and falls back to "limit" from an older remote.
- CLI: magpie gateway-key limit <id> list | add <period> ... |
  remove <n> | reset [<n>]; the single-limit form still replaces all.
- GUI: the key's badge names the limit holding it most and "+N limit(s)",
  a line per limit under the row, and the editor has a tab per limit
  with Add a limit / Remove this limit. Strings in en, zh, zh-TW, ja, de.
- docs/reference.md and docs/subsystems/gateway-routing.md say so.

Run (worktree on e98440ae6, sandbox HOME):
- go test ./internal/access/ ./internal/budget/ ./internal/gateway/
  ./internal/cli/ ./internal/provider/ ./internal/gui/: all ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags=nogui, GOOS=windows
  on those packages: clean.
- GUI (Playwright 1.62.0) chromium and webkit: the new
  gateway-key-limits test (5 languages x 1100/420), gateway-key*,
  gateway-caller-keys, gateway-keys-off, gateway-own-key,
  gateway-connect-keys: 94/94; i18n-keys ok. quota-name-translated
  webkit en is red with HEAD's assets too, filed as #2228.
- Broken by hand, each went red: Reserve checking the first limit only;
  the refusal naming the first spent limit, not the latest reset; the
  endpoint without "limits"; every limit saved in moreLimits; duplicate
  windows allowed; the remote card ignoring "limits"; the CLI plain form
  adding instead of replacing; the GUI save without its index; the GUI
  badge taking the first limit.

Not tried: against a real remote magpie or real accounts. Known gaps:
two N-day cycle limits are both named "this cycle" on a remote card;
an older magpie that rewrites the keys file keeps only the first limit.
2026-10-15 01:54:28 +08:00
yetone f70c0525aa access, gui, cli: a gateway key's limit can run every N hours, a 5-hour cycle among them (#2102)
A key's limit window was a calendar day, week or month, or every N days
(#1509). #2102 asks for a shorter cycle, every 5 hours, like a vendor's
own 5-hour window. Limit gains period "hours" with Hours (1..8760),
counted in absolute time from Since, as the N-day cycle is; a change to
N or from days restarts the cycle, a cap change keeps it, Reset starts
a new one. Budget status, the 429's wording ("this 5-hour cycle"),
X-Magpie-Limit-Reset, /v1/magpie/limit and a remote magpie's key card
carry Hours. The GUI's window menu has "Every N hours" with an Hours
field beside it (no native select); the CLI takes `<N>h`
(magpie gateway-key limit <id> 5h --tokens 200k). Docs: reference.md
and docker.html (en, zh, ja). Strings in zh, zh-TW, ja, de.

Run:
- go test ./internal/access (TestLimitHoursCycle across NY DST, UTC,
  UTC+8; TestLimitHoursSetAndReset), -tags nogui ./internal/cli
  (5h, rejects 0h/8761h/xh/1.5h/hours), ./internal/gateway
  (TestKeyLimitHoursCycle: 429 and reset header, /v1/magpie/limit,
  Reserve at the boundary, Reset; remote key card 5h), plus the full
  access, budget, cli, gateway, provider and gui packages. The gateway
  package hit go test's 10-minute default once with the load average
  near 270; rerun with -timeout 40m it passed in 1536s.
- Broke cycle() for hours by hand: TestLimitHoursSetAndReset and
  TestKeyLimitHoursCycle went red; restored.
- GUI: gateway-key-cycle (extended with the hours case: menu, field,
  validation, Save body, badge, Reset confirm, one-column at 500px)
  in chromium and webkit x en/zh/zh-TW/ja/de, 10/10; i18n-keys,
  gateway-key-limit, gateway-caller-keys, phone-rows, gateway-keys-off,
  gateway-own-key, api-key-theme 63/63; an ad-hoc check of the hours
  editor at 1100 and 420 in both engines and 5 languages (no overflow,
  screenshots looked at).
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: a real gateway under load across a 5-hour boundary; the
Windows box.
2026-10-14 15:34:31 +08:00
yetone 23e764d0e0 cli: magpie's commands move from the root into internal/cli; the root keeps only main.go
The root held 89 .go files (30 commands, 59 tests). They move as they are
to internal/cli (package cli), with git mv so history follows them. The
only code change is main() becoming cli.Main(version): the root's new
main.go keeps `var version` in package main, so -ldflags "-X
main.version=…" in the Makefile, the Dockerfile and magpie-releases, and
every workflow, work unchanged. go-winres's rsrc_windows_*.syso still land
next to package main in the root.

Tests that read testdata by a root-relative path now go up one level
(../plugin/testdata/fake, ../sessions/testdata). Five subsystem doc links
point at internal/cli/.

Run:
- go build ./..., gofmt -l, go vet on darwin, linux and windows (nogui)
- builds with tags production, dev, "production nogui"; windows
  -H windowsgui; linux CGO_ENABLED=0
- make release-cli TARGETS="darwin/arm64 linux/amd64 windows/amd64
  android/arm64" VERSION=9.9.9-tidy: all four built, binary prints
  "magpie 9.9.9-tidy"
- docker build --build-arg VERSION=7.7.7-tidy: container prints
  "magpie 7.7.7-tidy"
- go test ./internal/cli (default and nogui): 152 tests, the same count
  as the root on main
- go test ./...: all packages pass (agent, gateway, library, provider
  timed out at 10m under other sessions' load and passed rerun alone
  with -timeout 40m; none of them changed)
- the built binary in a sandbox HOME: version, help, ls, providers,
  claude, and an unknown command's error
2026-10-12 20:40:22 +08:00