611ce90d15bbbb2db2edcfc181da4f75ada3cccd
213
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d89f03aa92 |
settings: trayNoNumber is a key magpie settings sets, and GET /api/quit is the window's own (#4793, #4794)
|
||
|
|
ec104b8625 |
gateway: a Codex account can spend its credits before magpie moves to another account (jojonas_xyz on X)
jojonas_xyz on X: "我账号额度用完了自动给我切了别的号…找不到怎么关掉设置…你怎么知道 我不是想用 credits 呢". (Roughly: "my account ran out of quota and magpie switched me to another account by itself; I can't find a setting to turn that off; how do you know I didn't want to use the credits?") Cause. At 90% or 98% of a window, smart routing's tier put the account behind every account that still had room, whether or not it had ChatGPT credits. Codex's own sign-in (NextLogin / SwitchWhenSpent) moved at the spent share in the same way. The account's credits were spent only once every other account was used up, and the switch was a log line. The Use credits switches that existed (on, and "Only after other accounts" from |
||
|
|
7d1f2ecba3 |
claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from `magpie claude-code install`, and asked whether a magpie update touches it and how it updates. The download lives in <cache>/claude-code (/config/cache, on the volume), so a new image keeps it. But nothing ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it stayed at the version first installed until the user ran install again. claudecode.KeepCurrent now runs while magpie serves (a WhileServing loop): a minute after start and every six hours it asks downloads.claude.ai for the latest release and downloads a newer one, checked against the manifest's SHA-256 and size as install does. The version it replaced is removed on the next look rather than at once, since a run being started may hold its path (Install, the CLI's, still removes it at once; a folder with a .part download in it is left alone). It does nothing when magpie downloaded none, when the machine has its own `claude` (that one is run and updates itself), or when DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a version. A failed look keeps the download and is logged. It never downgrades. The status line of `magpie claude-code`, the Docker docs (en, zh, ja) and the bridge's subsystem page say so. Run: - wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v ./internal/claudecode/ -run 'Keep|Install|Find': all pass. - Broken by hand on WSL, each red: no newer() check (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own() check (the_machine's_own), pruning at install (UpdatesMagpiesDownload), no prune on the next look (UpdatesMagpiesDownload). - Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program with a fake 2.1.1 download ran KeepCurrent against the real downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to 2.1.316", the kept binary's --version said "2.1.316 (Claude Code)", 2.1.1 was still there for the next look, and the loop ended with its context. - mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of both packages, go vet ./internal/claudecode/, go build ., then go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m: VET-OK; claudecode ok 0.680s, cli ok 56.673s. - gofmt -l clean. Not tried: the Docker image itself (no docker on the test boxes), and a Windows run whose replaced binary is still in use (prune leaves what it can't remove for the next look). Full suite not run: the change is the claudecode package, one WhileServing line and one CLI status line. A WSL run of ./internal/cli/ at the default 10m timeout timed out while the box ran other sessions' full suites; the 45m run above replaces it. |
||
|
|
e42ee3b816 |
library: Magpie Browser's extension sits in ~/Magpie Browser Extension, dragged from the sheet onto chrome://extensions
The owner, on the v0.1.2442 sheet: the extension was written to ~/.config/magpie/browser-extension, a hidden folder no one can find to choose in Load unpacked. - Set up writes it to "Magpie Browser Extension" in the home folder (browserExtDir), where Finder and Explorer show it, and shows it selected in its parent (open -R on the Mac, explorer /select, on Windows, the home folder on Linux) rather than opened, to drag from. - On the Mac the sheet has the folder itself: a press on it that moves hands the folder to the system's drag (POST /api/library/browser/drag, filedrag_darwin.go: beginDraggingSession from the key window with a file URL and the folder's icon, only while the button is still down), so it drops onto chrome://extensions as from Finder. Chromium's extensions page loads a dropped folder as unpacked (drag_and_drop_handler.ts: entry.isDirectory -> loadUnpackedFromDrag), with Developer mode on, which step 2 asks for. - Elsewhere step 3 says to drag the folder from the window that opened, or Load unpacked and choose it. - Old installs: a browser that loaded the hidden folder still does, and that folder is kept up to date as long as it has a manifest; the sheet offers set up again, into the new folder. Run at |
||
|
|
5dfbca6274 |
cli: magpie settings list|get|set|reset, through the window's own save (#4745)
Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can be read and set from the terminal. - internal/settingsapi holds the save the handler made: Merge (the carry of keys a page leaves out, moved verbatim from api.go, plus upstream's RouterNote line), the vision/imageGen/searcher checks, settings.Save's own checks, catalog.Touched. POST /api/settings and `magpie settings` both call settingsapi.Apply, so a value is checked and saved one way. It sits outside internal/gui so the nogui build has it. - `magpie settings` (list, the default, with value, default and choices; get; set; reset to settings.Defaults()), --json on list and get. Body sends the whole file with one key changed, so a key the save keeps when absent (noBird, refusalRetries, ...) is set even to off. A flag where a key or value goes, an unknown key (with near matches named) or a refused value writes nothing and exits 1; --help prints usage. - Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent changed on its own; what the save takes must equal Keys), TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed (each /api route has a command or a reason in notYet, which later stages shrink; 36 have one now). - Item 3 of the stage (per-provider CLI-only fields in the window) is left for stage 2. - The open app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update re-check) run only from the window's save: #4752. Run (mote, at the pushed head |
||
|
|
5d63b3f995 |
accounts: a Claude import never writes an older sign-in over a newer one (#4532)
Importing a claude-swap export of the account Claude Code was signed in to wrote the file's sign-in over Claude Code's own (addLogin, using). cswap exports what it saved when it last switched; Claude Code has refreshed since, each refresh spending the refresh token before it, so the file's was spent and Claude Code was signed out. A saved account was replaced the same way. Only an identical refresh token was caught. Now a Claude sign-in for an account magpie already has (Claude Code's own, or a saved one that can still be used) with another refresh token is taken only when the file's expiresAt is later than what magpie has, the account's own config directory counted (claudeNewerKept). Otherwise it is "exists" with why, nothing written. cswapEntry and loginEntry read claudeAiOauth.expiresAt. The CLI prints the reason. Run (mote, -tags nogui): - TestImportCswapKeepsNewerSignIn: older-than-live, undated, newer-than- live, older-than-saved. Red with the check turned off by hand (three subtests: updated over live / saved), green with it. - go test ./internal/provider -run 'TestImport|Login' ok. - go vet ./internal/provider ./internal/cli on darwin, linux, windows; gofmt clean. Not tried: a real cswap export against a real Claude Code sign-in. A sign-in that was itself imported and never run is saved with expiresAt 1 (so Claude Code refreshes it first), so any dated file still replaces it. |
||
|
|
c688211d13 |
gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account, and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the additional_tools item (#2660) only to OpenAI's own API, so for an account the loaded tool went into the top-level tools and the cached prefix broke at the tools. Tried on the real ChatGPT backend first (owner's account, sandbox HOME on mote with a copied auth.json whose refresh_token was replaced, so the live token was never rotated; ~/.codex untouched). A probe client sent Claude Code's shape: ToolSearch with two deferred mcp tools, then the tool_reference result, then the calls, 4 requests per run. - additional_tools item (on, and this commit's default): request 2..4 read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and gpt-6-sol; the model called read_a and read_b from the item; no "turned away additional_tools" in the log. - tools top-level (off): request 2 and 3 read 0 from cache (8044 and 8163 tokens in), as the reporter saw. So the backend takes it, and this makes it the default for a ChatGPT account (p.Account.Agent == "codex"). Copilot and other sign-ins stay off: not tried. - loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an account is in only if it's Codex's, then OpenAI's API as before. - `magpie provider set <id> additional-tools=on|off|default`: off is new (AdditionalToolsOff, kept through an account's Save by accountSettings and through the GUI editor's save like AdditionalTools). The old "off"/"no" meant default; now they turn it off where the default is on. - The 400/422 fallback that names the item still applies, so a backend that stops taking it costs one retry and then sends tools top-level. - No prompt, instructions or identity line changed. Run (mote, at base |
||
|
|
788057340b |
library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP servers, image recognition, image generation and search, in the Library's Discover. Image generation and search were there; image recognition was an address to copy in Settings only (#4653). - `magpie mcp vision` (browsermcp.RunVision) relays stdio to the gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's relative image path is made one in the agent's folder on the way (imageFrom), since the gateway can't know where the agent runs; an absolute path, ~, a URL or a drive goes as written. - library: magpie-vision is a featured, opt-in server (no agents until picked), any binary's `mcp vision` is one server (serverKey), and it gets the 120s tool timeout (selfTimeout). - Settings › Models › Images: the Image recognition row has Give agents Magpie Image Recognition… / Turn on the Library, none with recognition off or in gateway mode. The three links are one helper, libWay, used by Image generation and Web search too (no budget raised: core 1,533,011 of 1,533,105). - Never a dead tool: Discover lists all three whatever is set up, and one that can't answer yet says why (gateway.OwnUnready, set by /api/library/market/servers as `unready`): a "Not set up yet" badge on its card with the reason as its title, and the reason in its sheet (nothing set up, or turned off in Settings / Plugins). It can still be added; its tools already answer with the same reason until then. - Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md. Run, all on mote (macOS 27) through mote-run, at this head's tree (rebased on |
||
|
|
b1fc435407 |
library: Magpie Web Search, magpie's search MCP server in Library › MCP (lutra_fs)
lutra_fs on Discord: magpie's search MCP shows in Settings › Models but not in Library › MCP servers. They were right. The gateway's web search MCP (/mcp/magpie/web-search) was only an address to copy in Settings › Models › Web search. It was never a Library server, so no agent could be given it from the Library, and the Library didn't list it. Change: - `magpie mcp search`: a stdio relay to the gateway's search MCP, made by widening browsermcp's Magpie Browser relay into a bridge with its own path, title and an optional session (search sends none, and has a 5 minute client). It takes no arguments. When magpie isn't running, it says "Magpie Web Search can't be reached: start magpie". - library: Magpie Web Search (magpie-web-search) is a featured, opt-in server beside Magpie Image and Magpie Browser. It is installed with no agents, so the user picks them in its sheet, and it switches per agent like any other row. Its command is the full binary path, and serverKey treats any binary's `mcp search` as the same server. Each agent's tool timeout is at least 120s. - Settings › Models › Web search › MCP server: under the address there is a "Give agents Magpie Web Search…" link that opens its Library sheet, or "Turn on the Library" while the Library is off, as Images does for Magpie Image. Gateway mode has no link. - The sheet's hint says where each search goes and what it costs. All strings are in en, zh, zh-TW, ja and de. - docs/subsystems/library.md names magpie's own servers and the new one. - An agent in WSL gets it through the MCP router, as Magpie Browser does. The image-only WSL side() is unchanged. - The sibling, Image recognition's MCP server, is still in Settings only. That is filed as #4653. Run, at this head (rebased on origin/main |
||
|
|
6f3dfc282f |
sessions: a scan's index is written at its end and on SIGTERM, not a minute later
A refresh's saves waited out saveGap (1 min) after the last one written,
the scan's checkpoints and its end too: the first checkpoint was written,
the rest waited. A magpie ended in that minute (quit, updated, `web` or
`serve` stopped by SIGTERM, whose handler died without sessions.Saved())
kept a few hundred of the files it read, and the next start read every
rollout again.
- A refresh that reads scanFiles (32) files or more is a scan: its
checkpoints wait scanSaveGap (15 s) and its last save waits for nothing.
A poll's few changed files still wait out saveGap. Saves folded into one
take the shortest gap asked, and a shorter one wakes a waiting save.
- The signal handler writes the index before dying, bounded by
saveOnSignal (5 s).
Real history in a sandbox HOME (11,994 Codex rollouts, 52.5 GB, plus
Claude projects; 17,140 files), index removed, `magpie web` killed by
SIGTERM ~44 s in (right after the first /api/sessions answered):
- v0.1.2521 tree: 1,200 entries kept (1,415 on a second try). Restart:
/api/sessions 23.63 s, 1:38 of CPU.
- this change: 17,140 kept. Restart: /api/sessions 1.30 s, 3.4 s of CPU.
Tests, on mote: TestScanSavedWithoutTheGap and
TestSignalSavesTheSessionIndex are new. Broken by hand: with the scan's
gaps left at saveGap the first fails ("a scan's last save waited out
saveGap"); with the save call taken out of the handler the second fails
("died without the session index saved"). go test ./internal/sessions/
./internal/cli/ ok. gofmt -l clean; go vet (darwin), GOOS=windows go vet,
GOOS=linux go vet -tags nogui of both packages ok.
Not run: the full suite; the GUI app's own quit and update paths (they
return to main, which already called Saved); Windows and Linux runs.
Picked onto
|
||
|
|
9162277b91 |
routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.
A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.
Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).
Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
through a rate limit, all used up, a seat gone, per pool, Forget,
Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
In order goes back to k1. Red without the Drained hook (request 3 went
to k1). A rate limit comes back to k1; drain is saved on a provider and
a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
languages, 1100px and 420px, Chromium and WebKit; red on the old assets
(20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.
Run on mote (macOS) at origin/main
|
||
|
|
699ddf1524 |
gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then the subscription's credits. Until now an account at 100% that holds credits either kept its place and spent them there (on) or was held (off). This adds a third way per account, "last": - settings: CodexCreditsLast []string, empty by default, so a setting saved before it keeps its order. provider.CodexCreditsLast, CodexCreditsMode and SetCodexCreditsMode(user, on|last|off); SetCodexCredits(on) still means "in its place" and clears last. - gateway: candidate.creditsLast is true for such an account once a window for the model is used up and it is going on its credits (a call ChatGPT counts in no window stays in its place). restLast orders ready, then resting, then those, and marks Weighed.CreditsLast. restLast runs over the asides too, so such an account goes behind a provider's reserves (Accounts at once, |
||
|
|
2c6b7c0632 |
gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.
A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.
Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.
Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).
Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).
Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.
Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main
|
||
|
|
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
|
||
|
|
323159f1cc |
usage: a Codex reset's confirmation picks which of the account's resets is used (01huadalang)
01huadalang on Discord: resets were used only automatically, or by hand
the one that runs out first. Which account was already the user's to pick
(each account's card has its own Use); which of its resets was not.
- Usage card's "Use a reset" and the menu bar panel's "Use one...": when
the account holds two or more resets listed with their ids, the
confirmation has a "Reset to use" pop-up (the app's menu, not <select>),
soonest first and picked unless another is. Once another is picked it
names the account and that reset ("The one used is me@'s reset that
runs out ..."), and says the sooner one is kept and lost if unused.
Escape closes the open menu first, not the confirmation.
- POST /api/usage/codex-reset takes an optional credit. The server reads
the account's resets again and spends that credit only if it is still
held; a gone one is refused and no other is spent in its place. With no
credit it is as before (the soonest). Auto-use is unchanged.
- ResetCard carries the credit id; `magpie quota reset --card n` is the
CLI's sibling, its prompt naming the reset.
- askReset's dialog moved out to resetask.js, imported when Use is
pressed (like signsheets.js), so the core's scripts are 1,530,733 bytes,
under the 1,533,105 budget with no raise (the pick alone took it 2,068
over). Five keys in zh, zh-TW, ja, de.
Run on mote (mote-run), at the base
|
||
|
|
0e90572274 |
browser: Magpie Browser, agents use the user's own browser and its sign-ins
The owner asked for a browser-use MCP of magpie's own, so an agent's browser keeps working when Claude Code switches accounts, and asked that it act in the browser the user uses every day: a fresh Playwright profile is signed in to nothing. Magpie Browser is an MV3 extension (internal/browserext, ID dmlhojidlfnkgamkekjhacgkpanbkeko, pinned by its key) that the user loads once in Chrome, Edge, Arc, Brave or another Chromium browser. It holds a WebSocket to the gateway's /v1/magpie/browser/extension and carries out each tool call with chrome.debugger (the DevTools protocol) in the user's own tabs. The socket is taken only from this computer, with a loopback Host (no DNS rebinding) and the extension's own Origin; a page or another extension that connected in its place would be handed every call. Agents reach it at /mcp/magpie/browser (Streamable HTTP) or through `magpie mcp browser` (stdio), and the Library's MCP market lists it as Magpie Browser, opt-in. Like the image server it is magpie's own, but it is never served to another computer, shared and with a key or not, and never to a web page, since it acts as the user wherever they are signed in. 17 tools: navigate (url, back, forward, reload), snapshot (an accessibility tree with refs, interactive-only on ask), click, type, press, select, hover, drag, upload, scroll, wait (text, gone, seconds), dialog, evaluate, text, screenshot (page, full page, element; JPEG or PNG), console and tabs (list, new, select, close). Each agent session goes on in its own tab; a link that opens a tab is followed, and a dialog a click opens is said in the reply. The Library's sheet for it has Set up the extension…, which writes the extension to ~/.config/magpie/browser-extension pointed at this gateway and shows the folder, the three steps to load it, and whether the browser is connected, polled while the sheet is open. Run: - TestBrowserToolsInARealBrowser: the extension magpie writes, loaded in a real Chrome for Testing 141 (Playwright's chromium-1234, headless=new) with --load-extension, connects, and all 17 tools act in a real tab of a fixture site. Green on mote (macOS 27), on xiaomi-gpu (Windows 11, win-run) and in magpie-desktop (Ubuntu 24.04, wsl-run). Under a test HOME Chrome needs --use-mock-keychain / --password-store=basic, or the extension's storage waits on a keychain and it never connects. - go test ./internal/gateway -run 'Browser|ReadOnly|Image', ./internal/ browserext, ./internal/browsermcp, ./internal/library, ./internal/gui -run 'Library|Browser', ./internal/cli on mote. - GUI: library-browser-setup.test.cjs (new) in Chromium and WebKit, en, zh, zh-TW, ja, de, at 1100 and 420 wide: 22/22. With i18n-keys and every library*.test.cjs: 915 pass, 1 fail, i18n-keys' "Unmarked", red on main since |
||
|
|
64cdb68035 |
accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie, and `magpie accounts import claude` didn't read cswap's export. It does now: parseLoginImport takes cswap's format-1 envelope ({version: 1, swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's transfer.py) and cswapEntry reads each account's credentials.claudeAiOauth and config.oauthAccount: email, account and organization uuid, and the organization's name. The tokens are kept as the file has them; magpie asks Anthropic nothing. Refused, each with what to do: an encrypted export (decrypt with gpg -d first), another format version, a Codex entry, and an API-key entry (added as a key instead). An entry with no refresh token is accessOnly, as for every other file. cswap's alias becomes the account's name in magpie (importNames) when the account was added or updated, has no name yet, and no other account is called that or signed in as it, so the name stays a selector for one account (the previous commit's rule). testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap export` output, made from its source in a sandbox HOME in WSL with two accounts and fake tokens (cswap's add step asked Anthropic once with the fake refresh token, which it called dead; no real account was involved). Run (mote unless said): - At this commit's tree (on origin/main |
||
|
|
149e763e9e |
accounts: a name you gave an account picks it wherever an email does (#4532)
StringKe (#4532): `magpie accounts switch claude work` failed when "work" was the alias; accountNamed matched the email only. provider.AccountByName resolves a name (magpie accounts alias) among an agent's accounts. It refuses a name two accounts share, and a name that is another account's email or email part, so a name never picks the wrong account. It is used by: - accountNamed: accounts switch/on/off/remove/alias/cap and the rest that take <email>; - provider pool --accounts; - accountRef (GUI and account-cap): the exact email first, then a name, so another account's alias never shadows an email; - account-cap's display, through AccountRefOf (it filtered by email). Run (mote, at this commit): - go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok (104.9s, 33.2s). - TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts and account-cap by name; a shared name and another account's email refused. Red with each part removed by hand: the accountNamed call, pool's resolution, the clash check, the shared-name check, accountRef's name step. Not run: the GUI suite (no GUI file changed); real accounts. |
||
|
|
15b83901ac |
accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch to the next account", and when every account was past its line the automatic switch stayed on the spent one, where cswap moves to the account with the most room left. - `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes the other accounts that are on in magpie, from the one after the account the agent is on, wrapping round: the first whose allowance is known and has room, else the one with the most room left, and says it is past its line. A saved Claude account not read yet is read first (readSpare), as the automatic switch's spares are. With no reading of any it refuses rather than guess; for any other agent it asks for the account by name. - NextLogin (shared by Codex and Claude Code): when the account the agent is on is spent and every spare is past its line too, it moves to the spare with the most room left (roomLeft: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has at least roomMargin (1 point) more than the one it is on, so two all but even accounts don't trade the agent each look. A held, failed or unknown reading is never moved to. One model's own window still counts for nothing, as before. - docs: reference.md (the automatic switch and `next`; its "a Claude account magpie knows nothing of is not moved to" was stale since readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja start pages' command table, `magpie help`. Run (on mote, sandbox HOME through the packages' TestMain): - go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok (144s, 44s), at this change's tree before the next commit's edits. - TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each over codex and claude with three accounts: green; red with the fallback taken out of NextLogin (the two "most room" cases, both agents) and with NextInOrder not starting after the signed-in account ("the one after it", both agents). The "none has more by the margin" case fails without roomMargin. - Built the nogui binary and ran in a fresh sandbox HOME on mote: `accounts switch claude next --help` (prints the accounts help), `switch claude next` and `switch codex next` with no accounts ("has no other account that is on"), `switch gemini next` (asks for a name), `switch claude nxt` (no such account), `switch claude` (usage). - gofmt -l clean. Cross-OS vet: run at the head of this stack. Not tried: a real switch between real Claude or Codex accounts; the CLI `next` with real saved accounts (the provider tests cover the choice). |
||
|
|
0ac26fb52d |
update: a magpie a package manager installed leaves updating to it (shuhai on Discord, AUR magpie-bin)
shuhai (Arch) installs magpie from the AUR's magpie-bin, which puts the desktop build at /usr/bin/magpie. magpie's own updater saw a folder it can't write and pkexec on the machine, so it downloaded the release and, on restart, replaced the package's file as root. pacman's database then no longer matched the file, and the next `yay` upgrade (magpie-bin lags the releases, 0.1.2342 against 0.1.2357 today) put an older magpie back. The two updaters fought each other. Now magpie asks first who owns the binary it runs from (update.PackagedBy): pacman's local database, dpkg's .list files, rpm (`rpm -qf`, only where /var/lib/rpm exists), a Homebrew Cellar path or /nix/store. Only a system path counts (/usr but not /usr/local, /bin, /sbin, /opt), with merged-/usr aliases, and packages named magpie* are looked at first. A packaged binary: - GUI: the update is shown as available with "pacman installed magpie (magpie-bin), so pacman updates it, not magpie: yay -S magpie-bin" (apt, dnf, brew likewise; Nix with no command). Nothing is downloaded, there is no Download or Install, the Update pill isn't lit, and /api/update/install does nothing (state available, stuck "package"). - `magpie update` says the same and exits 1 before downloading. This takes the place of the Homebrew-only check it had. An unpackaged magpie (~/.local/bin, /usr/local/bin, a file pacman doesn't list in /opt) updates itself as before. Run: - mote: go test -tags nogui -run 'Packaged|Homebrew|NotWritable|InContainer' ./internal/update ./internal/gui ./internal/cli ok; full go test -tags nogui -count=1 -timeout 45m ./... at |
||
|
|
33a284497e |
plugin options: a switch a provider plugin declares is saved where the plugin reads it (plugins#550)
`magpie plugin options cursor '{"wire_trace": true}'` wrote the entry's
options in plugins.json (a middleware's ctx.options), while a provider
plugin's switches (auth.options, the editor's Plugin options) are read
from settings' PluginOptions (input.magpie.option). The command said
"options set" and Wire trace stayed off.
Now a key that the plugin declares as a switch for one of its providers
(from the providers last listed, else asked of the plugin host) goes to
PluginOptions for that provider, through settings.EditPluginOptions, and
a running host is handed it (SetProviderOptions, 5s, best effort). Only
true or false is taken for a switch. The other keys go to plugins.json
as before; set with switches only, a middleware's options stay, less a
switch written there before. `off` puts every switch back to the
plugin's default and clears plugins.json's options. Shown with no value,
each switch is listed with its value. docs/reference.md and the plugins
page (en, zh, ja) say so.
Run at this head on mote: go test ./internal/cli ./internal/settings
./internal/plugin ok; gofmt -l clean; go vet darwin and GOOS=windows ok;
Linux go vet -tags gtk3 in WSL (magpie-desktop) ok.
Broken by hand: no key read as declared, and both new tests went red
(PluginOptions empty, the old switch left in plugins.json).
Not tried: the real CLI against a running magpie with the Cursor plugin
installed; a plugin not listed yet (the host path) is not in a test.
|
||
|
|
7b09d2c951 |
provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.
Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.
- Listed by the local id: Available, liveIDs/liveByID, Serving and
ListPrice translate through OwnModelID. /v1/models, agents' lists,
Resolve, routing groups and found groups (auto/<local>, merged with
every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
account's or a plugin's request is built from its list's id, which no
wire reaches.
- Two variants of one provider given one id: the latest given it wins,
and the earlier one is listed by its own id again. The CLI names it.
The editor refuses two rows given one id in one save. A model of the
provider's own id that a variant is listed by (plain grok-4.6 beside
grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
classifier/pick, the pickers' lists, every per-model setting
(Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
set by access) to the new id, but only where nothing is under the new
id yet. Agents' own files are not rewritten: an old provider/<own id>
still resolves and is sent as it is. Group match patterns and key
patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
The price is the own id's first.
CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.
Run (mote-run, at this tree rebased on
|
||
|
|
ceeb73a0f1 |
app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log while chasing a Codex "hit a snag" through the gateway, and had no such folder. Only the launch agent (magpie daemon install, written by launchd) and a gateway magpie tui left running wrote a log; the app opened from the Finder, the Dock or the Start menu logged to a stderr nobody reads, on every system. Now runGUI and runPanel (magpie, app, tray, panel, a window view, a magpie: link) call applog.Start before gui.Run. It sends the standard logger (the gateway, the plugin host, providers and Wails' error handler all log through it) to app.log as well as stderr, and points debug.SetCrashOutput at it so a panic's trace is there too: macOS ~/Library/Logs/magpie/app.log Windows %LOCALAPPDATA%\magpie\logs\app.log Linux $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log portable data/logs/app.log app.log, not serve.log: on a Mac launchd writes serve.log for the service, another process. The file is 0600. At 5 MiB it becomes app.old.log (two files at most); when another magpie (an update's new process) rotated it already, it is only opened again; when it can't be moved it is emptied. stderr goes first, through a writer that never fails, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr. Secrets: the log calls name header names and paths without queries; no key or token was found logged (grep of log.Print* in gateway, provider, plugin, gui, agent). scrub masks bearer/basic credentials, key/token query parameters and sk-, AIza, gh?_ and JWT shapes anyway. How a user finds it: Settings › About › Log, with the path, Copy and an Open that shows its folder (POST /api/settings/log/reveal; the row is hidden in magpie web, which writes no file). magpie log prints where every log is (the app's, app.old.log, the service's, the tui's background serve.log); --path the app's alone, -n N its last lines, -f follows it across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where is magpie's log?" and the CLI table) and privacy (files on your computer), en/zh/ja. Run: At 227ce6074 on origin/main |
||
|
|
fbb1b36d1f |
provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read |
||
|
|
b48881f507 |
provider: keep idle saved Claude accounts signed in, by Claude Code itself (#4532)
#4532: a saved Claude account switched on but not needed for weeks (switch-only) had nothing run on it, its refresh token sat idle, and it was found signed out when the switch wanted it. Codex's saved sign-ins already had a keep-alive (RenewLogins, every 8 days, one account an hourly look). The same loop now takes saved Claude accounts that are on, not Claude Code's own, not added by setup-token and not already signed out (claudeKeptAlive). For one that is due it has real Claude Code run /usage in the account's own CLAUDE_CONFIG_DIR, the path a card's refresh takes (readSavedClaudeUsage, inSavedClaudeDir), and syncSavedClaude keeps whatever sign-in Claude Code refreshed. magpie asks Anthropic nothing itself: no OAuth or usage endpoint, as removed in |
||
|
|
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
|
||
|
|
07a3312c53 |
library: sync and backup files carry the subagents
xixi_Sean_ on X asked why Sync leaves the Library's subagents out. There
was no reason: the library part of a bundle now carries them.
- library.Bundle.Subagents (*[]*Subagent): name, description, prompt,
the skills and MCP servers named, the agents ticked. Collect always
sets it, empty too. Applied.Subagents (which files magpie wrote here
and their hashes) stays out: each computer writes the files into its
own agents on the sync Put runs and records its own, so a file the
user edited there, or one of theirs by the same name, stays theirs.
- Put replaces the subagents with the bundle's, so one taken out on one
computer goes from the others. A nil list (a bundle from a magpie
before this) is unknown and keeps this computer's.
- check refuses a subagent whose name isn't one (it is a file name in
every agent) or comes twice; agent ids are carried as they come, so a
newer magpie's tick for an agent this one can't give subagents to
stays and writes nothing here.
- davsync: an empty list hashes as before the field, so upgrading with
no subagents syncs nothing.
- backup files go through the same Collect/Put; the CLI's backup line
counts subagents. The GUI's sync/export/import ticks say "instructions,
MCP servers, skills and subagents" in every language.
- webdav-settings-refresh's "Agents" tick locator also matched the
library tick's "subagents": it now asks for "Agents' models".
- library.md and sync-backup.md updated. Hooks still aren't carried.
Run (rebased on 0bf5adb11; Go runs at e0c57ffe2, same diff):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
./internal/cli ok; ./internal/library -run 'TestCarry|TestSubagent|
TestLocalServer|TestPutKeeps|TestPutSame|TestRestoreKeeps' ok
- wsl-run (Linux): ./internal/library ./internal/backup ./internal/davsync
whole packages ok
- win-run (Windows): the same three, -run 'Subagent|TestCarry|TestLibrary|
TestSyncLibrary' ok
- go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on the four
packages ok; gofmt -l clean
- GUI (wsl-run, Chromium + WebKit, every language): i18n-keys,
github-sync, s3-sync, sync-auto-restore, sync-not-backup,
sync-other-kind, sync-sign-in, sync-spin, sync-usage-error,
webdav-settings-refresh, library-backups-top, gui-de, gui-ja,
gui-zh-tw, settings-search, settings-sections: 170/173, then
webdav-settings-refresh green after the locator fix. The one red left,
i18n-keys "a plugin's words are its own" ("Unmarked" in
plugins/routing/i18n.js), is on main already: #4524.
mote ran five other GUI suites at load 18, where every WebKit
github-sync case timed out at launch, so the GUI run moved to Linux.
Broken by hand: with Collect not setting Subagents and Put ignoring
them, TestCarrySubagents, TestCarrySubagentKeepsUsersFiles,
TestCarryNewerSubagents, TestBackupFileCarriesSubagents,
TestSyncSubagents and TestNoSubagentsHashAsBefore went red; with Put
treating a missing list as empty, TestCarryOldBundleKeepsSubagents and
TestBackupFileCarriesSubagents went red.
Not tried: a real WebDAV/S3/GitHub remote between two real computers;
the fake DAV server carries it between two sandbox HOMEs.
|
||
|
|
e6b851b0fe |
update: magpie update in a terminal restarts the app with its gateway handed over
gaubeebangeel on X has an agent run the magpie upgrade at 4am and had
to give that agent its own provider: magpie couldn't serve it through
the upgrade.
Cause: `magpie update` put the new version in and printed "quit and
reopen magpie to use it" (a .app) or "updated to X" (a binary). The
running app never restarted, so the agent (or the user) had to restart
it by hand, and a plain restart closes the port and drops streams.
Measured before, on mote, a sandbox HOME `magpie serve` with a fake
upstream streaming 61 chunks at 100ms, restarted by SIGTERM + start:
- the stream was cut at chunk 15 of 61 (unexpected EOF); SIGTERM to exit
took ~18ms, no drain;
- requests during the restart: 289 answered, 5 refused over 87ms.
Now `magpie update`, once the new version is in, POSTs it to the
running app's /v1/magpie/restart (gateway/restart.go). It is answered
only to a program on this computer over loopback; a LAN caller, a page
(Origin / Sec-Fetch) and another Host get 403. The updater's
restartBeside (gui/update_beside.go) restarts only when its own exe was
the one replaced (replaced() now also compares a .app's binary,
bundleExe), takes the version as ready without the feed, and runs the
same restart as Settings' AutoRestart: at once when it cuts nothing
short, else through waitIdle. On macOS and Linux that restart is the
existing SCM_RIGHTS handover, so the port never closes and in-flight
streams finish in the old process. The command prints what happened:
restarting (handing the gateway over), waiting for N requests, another
copy (current), magpie serve (unsupported), not running, or too old
(404: the first update into this version still needs a manual
restart).
Tests:
- TestUpdateInATerminalRestartsTheAppWithoutCuttingIt (darwin, linux):
a stream through the gateway, the exe rewritten, magpie update's ask
answered "restarting" with handover; the successor serves a request
while the stream runs, the stream ends whole, the old one quits only
after it. Red by hand with the route removed ("magpie update's ask:
404").
- TestUpdateOfAnotherCopyLeavesTheAppBe, TestRestartAskedOnlyFromThisComputer
(refused cases never reach the restarter), TestUpdateAsksTheRunningMagpieToRestart
(each reply, a 404 magpie, none running).
Run at this tree:
- rebased on
|
||
|
|
88ecae1738 |
routing: By weight spreads a subscription's requests over its accounts
rubbzha on X (tweet 2116346330625036794): a Claude Max account and a Pro
one signed in to one subscription should share its requests by how much
each allows. The provider editor's Routing now offers By weight for
subscription accounts as it does for keys. With it picked, each account
in use shows "Weight N · S%" beside its name, the key weight's chip, and
a click edits it in place (POST /api/provider/accountweight {id, account,
weight}). CLI: `magpie provider account-weight <id> [account [n|default]]`.
The weight is kept per account by its lower-case name
(Provider.AccountWeights), and is moved with a rename (moveAccountSettings).
The gateway's keyWeight reads it from the candidate, with no file read, so
the smooth weighted pick treats accounts as it treats keys: Stays keeps a
conversation on its account, and a resting account is passed over while
the others share its requests. The default is 1. Nothing is prefilled from
the plan, and 1 is stored as no entry, so a value the user set is never
overridden.
Re-derived: ROUTINGS' weight text and routingsOf (the editor), the Routing
page's MODES, provider-row options and its "why first" text for an account,
the routing and accounts subsystem pages, the start docs (en, zh, ja), and
i18n in zh, zh-TW, ja and de (i18n.js and plugins/routing/i18n.js).
app.js is 74 bytes smaller than before (a long comment cut, keyWeight
reused), so neither script budget is raised.
key-weight.test.cjs read #status before accountAction's second round trip
(/api/state) had written it. The same race is now waited on in both tests:
with a 400ms delay injected on /api/state, the old read is red and the
new one is green.
Run (rebased on 03f3e1528; then on
|
||
|
|
3e5aa11519 |
provider: Qwen Cloud, Alibaba's international Qwen platform, is a preset with its regions and Token Plan (judi0713)
judi0713 on Discord (v0.1.2288) asked for Qwen Cloud (qwencloud.com).
Its keys are its own, made at home.qwencloud.com, and serve neither
DashScope's nor Bailian's hosts, so none of magpie's Qwen presets took
them.
Two presets, the way Alibaba's other pay-as-you-go/Token Plan pair is
modelled, because each key gets 401 at the other's host:
- qwencloud: pay as you go, sk-ws- keys, at
https://{region}.maas.qwencloudapi.com/compatible-mode/v1 (Chat) and
/apps/anthropic (Messages), in six regions named by their ids as
Alibaba's docs name them: ap-southeast-1 (the default), us-east-1,
eu-central-1, ap-northeast-1, cn-hongkong, cn-beijing. Catalog alibaba.
- qwencloud-token-plan: sk-sp- keys, token-plan.maas.qwencloudapi.com,
Singapore only, with the plan overview's text models.
Endpoints, regions, key prefixes and the plan's models are from
docs.qwencloud.com ("Regions and endpoints" and the Token Plan
overview), not guessed. Responses is left out, as in the other
Qwen presets.
The gateway's dashScope() now knows both presets and the
*.maas.qwencloudapi.com hosts, so a Qwen Cloud stream gets the same
enable_thinking handling a DashScope one does. Import (presetAt), the
CLI's region= and magpie://import?preset=qwencloud®ion=... map to it.
docs/reference.md, the CLI help and the site's import page (en, zh, ja)
name them. Region names are ids, so no string is new to i18n.js and
nothing in the GUI changed.
Run (mote, at 708213f65 on c272e5582; after it the commit was rebased on
|
||
|
|
fdf5e2c65f |
cli: claude-tui-helper ends on a signal its own way, not of magpie's handler
magpie's process-wide handler (endProbesOnSignal) re-raises SIGTERM. In claude-tui-helper it killed the helper (exit -15) before the shim's own handler could stop its Claude Code and remove what it wrote, so a run the gateway aborted left them behind. The helper's command now lets go of those signals (leaveSignals) before claudetui.Run. Run: go test ./internal/claudetui ./internal/cli on mote (macOS) and in WSL magpie-desktop (-tags nogui), ok; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build on mote, ok. Broken by hand: without leaveSignals, SIGTERM to a real helper in the sandbox gateway exited -15 and left its temp folder; with it, exit 1 and the folder removed (termimg.py). Not tried: SIGHUP from a closed terminal. |
||
|
|
e647a1fd54 |
plugins: an npm registry of the user's own is used for installs and lookups (timwangdev on X)
timwangdev asked on X for plugins to take a custom npm registry. Zero-config
first: Registry() (internal/plugin/registry.go) takes, in order, the one set
in magpie (settings npmRegistry: `magpie plugin registry <url>|default`, or
Plugins › Discover's new npm registry row), BUN_CONFIG_REGISTRY /
NPM_CONFIG_REGISTRY / npm_config_registry in magpie's environment, then the
login shell's (cached probe only, proc.LoginEnvKnown, never waits on a
shell), install.registry in the plugins folder's or the user's .bunfig.toml,
registry= in the plugins folder's or ~/.npmrc, then the 国内镜像 switch's
npmmirror, then npm's own. The switch no longer puts npmmirror over a
registry the user named: before, bun was handed BUN_CONFIG_REGISTRY=npmmirror
whenever it was on, over the user's .npmrc. bun is told the registry only
where it wouldn't find it itself (magpie's setting, the shell's, the
switch's). magpie's own npm questions (latest version for the market,
Update and the hourly check, README, search) go to the same registry, a
package's @scope:registry= to that scope's, with the .npmrc's
//host/path/:_authToken (${VAR} expanded, longest prefix) sent to that host
alone, dropped on a redirect to another host, never logged or shown.
Download counts stay npm's. Only http(s) with a host, no userinfo, query
or fragment is taken; anything else is refused and not saved, and a bad
value hand-written into settings.json is passed over. /api/plugins says
which registry is in use and where it came from.
The GUI row is in registry.js, imported when Discover draws it, so the
core script budget isn't raised (plugins.js is 292 bytes smaller than
before, one long comment there condensed).
Left out: bunfig [install.scopes] for magpie's own lookups (bun reads them
for installs), .npmrc _auth and username/password, NPM_CONFIG_USERCONFIG
and npm's global npmrc, and internal/agent/cliupdate.go's agent CLI update
lookups, which still ask npm's own.
Run (mote and wsl-run). First at this change on
|
||
|
|
45de2ddb96 |
provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.
Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.
Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
- a Free first group [paidv/m, mine/m] sends its first call to mine
once mine is marked, and the trace row says Free;
- EffectivePrice is still the listed 3/15;
- Cheapest picks mine first;
- unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
shows in `provider <id>`; free=maybe, an empty value and --help are
refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
ModelScope preset, a custom provider saved with the mark, and a Codex
account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
widths 900 and 440. It checks the Advanced fold, the check and save
POST bodies, that the row fits with no sideways scroll, and that each
string has a translation in I18N.
Core script budget: rebased on
|
||
|
|
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 |
||
|
|
43966a53fb |
claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.
`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).
A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.
claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.
The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.
Run (rebased on
|
||
|
|
b62fa332f3 |
provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and asked why "Send requests unmasked" (请求不脱敏) isn't offered for it. |
||
|
|
7bc602236b |
library: the MCP hub is called the MCP router
The owner asked why it was a "hub". Composio calls the same thing a Tool Router; "router" says what it does (one server that routes each call to the right one), and "gateway" is taken by magpie's LLM gateway. Only the words change: MCP router / MCP 路由 / MCP 路由 / MCP ルーター / MCP-Router, "Router address", and the CLI's `magpie library mcp router on|off`, where `hub` still works. The URL /mcp/magpie/hub, the mcpHub setting, the servers/hub API and the Go names stay, so nothing a user or an agent config holds changes. docs/subsystems/mcp-hub.md moves to mcp-router.md and the pages that link it follow. #4382's new words follow too: "Through the MCP router", "Not through the router" and their hints in every language, and the CLI's `magpie library mcp router <name> shared|direct` (`hub` works there too; library_hub_test.go says router for direct, hub for shared). Run at e2583df31 (this stack on |
||
|
|
a45a0f1c5d |
signin: Settings can keep sign-in pages out of the default browser (max2020)
max2020 on Discord signs in from a separate, fingerprint browser so the vendor never sees their default one. Every waiting sign-in already shows its link with Copy link (since |
||
|
|
3b5dccd527 |
accounts: a plugin account goes by its usage's name, not its id (#4416)
A Huawei Cloud CodeArts account is kept by its accountId, an IAM id (iam::<domain>:user:<name>), and every list showed that id while its quota card showed the masked phone the plugin's usage() names it by. Display only: an account now reads as the name the user gave it, else the `user` its plugin's last usage read gave (PluginUserOf: the in-memory read, else quotas.json), else its id. The id stays the key everything is kept by; nothing stored changes or migrates. A read that fails keeps the last good name; nothing read yet is the id, never blank. One rule in provider (AccountShown, AccountShownOf, AccountLabelOf), used by every list: cards' Alias (Usage page, tray panel, /v1/magpie/quotas, magpie quota), magpie accounts, magpie providers, the TUI's Providers rows and quota titles, usageapi's Account filter, the quota alert. The GUI gets it as /api/providers' accountUsers (accountShownOf in app.js): the editor's account rows (the id in the tooltip), the per-account proxy lines, Routing's userShown, the Providers search, Hide accounts. app.js's account lookups share one helper, so the core stays in its budget (1,536,561 of 1,536,586), with no room added. Run: - go test ./... -timeout 45m on mote at |
||
|
|
0621e70fb9 |
routing: leave a provider out of the groups magpie finds
chenxiang0010 on Discord asked to keep a provider or a model out of the auto-created routing groups. A model could already be kept out (remove its found group; magpie keeps it removed), but a provider could only be turned off per group or everywhere. Now Routing -> Groups, under "Find groups on their own", has "Leave out a provider..." (app menu, saved when it closes) and `magpie group auto skip <provider>...|none`. The providers chosen (providers.json autoGroupSkip) join no found group; a group the user made or changed keeps them, a found group left with one provider goes away, and a request for it is served by AutoStandIn from a provider still in, and agents on it are reseated (agent.Reseat). A rename carries the id along. en, zh, zh-TW, ja, de. Run at 383947fce (this change on origin/main |
||
|
|
65c7924108 |
cli: TestProviderAddressMovesALocalServer adds LM Studio in a folder of its own
The test added lmstudio in the package's shared config folder, so a
second run (-count=2 and up) found it there, added "LM Studio 2"
instead, and read the old provider back at localhost🔢 red on
origin/main
|
||
|
|
380032cda1 |
providers: Send requests unmasked is the user's switch at any address, with a caution while on for one not local (AcMilan)
AcMilan (Discord) runs a vLLM at http://llm.corp.lan:8000, and the editor never offered "Send requests unmasked": the switch showed only for a localhost, *.local or private-IP address. Asked, he said the choice should be the user's for each provider. provider.SkipsRedaction is now: Unredacted, no signed-in account, not another magpie, and at least one address. Nothing is looked up on the request path. The editor shows the row for every provider but an account or remote magpie. While it is ticked, an amber caution under it names an address not on this computer or the local network (awayHost). A name of the user's own DNS is asked about, only while ticked, through POST /api/local-hosts (provider.LocalHost -> netproxy.LocalName: every address loopback, private or link-local, 400ms lookup, kept 1 minute). That answer only words the caution. CLI help and `provider show` say the same. The 'away' i18n line is in zh, zh-TW, ja and de. To stay inside the core script budget, a few nearby editor comments were cut down (no raise). Run (logs in the worktree's logs/): - Full Go suite on mote at base |
||
|
|
995f84a0f9 |
codex: how early an expiring reset is used is a setting
A Codex reset card that would run out unused was spent 30 minutes before it expired, a fixed resetExpiryLead. Now the lead is codexResetLead in settings.json (minutes, 15 to 1440). Unset, out of range or unreadable reads as 30m, never 0, and magpie never writes it unless the user does. - settings: CodexResetLead and Settings.ResetLead(); the menu's values are 15m, 30m (default), 1h, 2h, 3h, 6h, 12h, 24h. - provider: the spend (expiringResetSpent) and routing (Allowance.Restarts, through nextResetLook) read the same resetLead(), so they still agree (#717, #718). The "near" look cadence follows it: lead + 30m, at least 1h, so a look lands inside a long lead. - GUI: Settings > Usage, under the Codex auto-use rows, a row "Codex: how early before one expires" with an app menu (no <select>), and the sub text says spending earlier loses what the windows have left. The four "before it expires" strings say the chosen lead. POST /api/settings/codex-reset-lead; the general save keeps the field. en, zh, zh-TW, ja, de. - CLI: magpie quota auto-reset lead [30m|3h|<minutes>|default]. - app.js budget: the auto-use rows moved out to lazy autoresetown.js (painted in the same draw once loaded), so app.js and the core script stay under their budgets with no raise. The button sizes to its widest label (a grid of every label), so picking one never rewraps the row. Run (all on mote through mote-run): - go vet: darwin, GOOS=linux -tags nogui, GOOS=windows; nogui build. - go test -tags nogui -timeout 45m ./... at 3955adccf (this change before the paint and sizer fixes, which touch only GUI assets): 81 ok. go test ./internal/gui at this head: ok. - GUI, Chromium: codex-reset-lead, codex-auto-reset, codex-auto-reset-settings, segs-press-redraw, i18n-keys: 62/62. WebKit: every case of those files failed at browserType.launch (180s timeout) before a page loaded, both runs; mote's browser launches hang under #4125 (load ~26), so WebKit is not run. - Rebased onto |
||
|
|
b889ffe813 |
library: a server can stay each agent's own entry with the MCP hub on (#4382)
cuipengcx90's #4382, Option A's first step (nifengfanpan asked on Discord): with the MCP hub on, every Library server went behind magpie's one entry, so a server that reads its project from the folder it starts in, or keeps a session's state, resolved the wrong repository or shared state across agents. A server now has a hub policy, Server.Hub ("hub" in library.json): "" (shared, the default, so nothing changes for existing users; "shared" is saved as "") or "direct". A direct server is left out of the hub through inHub, the test that already keeps magpie's own image server out, so each agent given it keeps its own entry written as with the hub off, beside the hub's entry for the rest. An agent whose every server is direct gets no hub entry. The hub neither lists nor runs a direct server, at /mcp/magpie/hub either, and hubPrune ends one it held. Switching goes through change(), so the agents are written again at once and the entry from the other policy is removed. An unknown policy is an error. - GUI: with the hub on, the server editor has a "Through the MCP hub" switch (role=switch, not a <select>; not shown with the hub off or for the image server), a direct server's row has a "Not through the hub" tag, and the hub's line and the Connect sheet name the direct servers with the image server as given directly. Strings are in zh, zh-TW, ja and de ("MCP 聚合" as the core uses it). - CLI: magpie library mcp hub <name> shared|direct (ServerHub), and magpie library marks a direct server. - TUI: an edit keeps the policy. - Not done: Option B (per-roots/project backends behind the hub, keying hubPool by roots). It is left for later; #4382 stays open for it. Run: - TestHubDirectServer (internal/library) and the extended TestLibraryMCPHub (internal/cli) on mote. Broken by hand: inHub back to !isSelf(s) makes TestHubDirectServer red ("codex with the hub on: [magpie], want [index magpie]"). - Real configs in a sandbox HOME on mote (fake claude on PATH, the real binary built from this tree): mcp add index + web for claude and codex, hub on, hub index direct, shared, then both direct. The direct index entry was in .claude.json and .codex/config.toml beside magpie's; with every server direct both files were byte-for-byte as with the hub off (json.tool diff and diff); shared again removed the index entry. - Full Go suite (-tags nogui -timeout 45m ./...) on mote at this tree rebased on origin/main |
||
|
|
4f2d5fc7e0 |
routing: a group can put its cheapest member first, by each one's price at that hour
liyuanzheng (#general) and lam_em (#feedback) both asked for the same thing. Off-peak, DeepSeek's own API should come first for deepseek-flash. At DeepSeek's peak (weekdays 01-04 and 06-10 UTC, billed 2x since v0.1.2173), another provider should come first, Ollama say. A schedule editor would make the user copy DeepSeek's hours into magpie. Instead, a group gets one more routing, "Cheapest first" (`cheap`). Each request sorts the members by what they cost right then: input + output price per million, at the peak rate when it is peak hours. A tie goes to the lower cache-read price. Free models count as 0. A member with no known price keeps its listed place after the priced ones. Prices come from the same priceOf the usage ledger bills with, so the user's own ModelPrices, list prices and maker prices all count, and so does a provider's rate windows. - routes: Seat carries Priced/Cost/CacheCost; Strategy.ByPrice; Cheapest is a stable sort, so equal prices keep the user's order. - gateway: weighRouted prices each seat at priceClock() (time.Now; a test holds it) through the new provider.PriceAt. The trace's Weighed row gets a price (input/output/cacheRead/peak) so Routing can say why. - It is a group's alone, like Manual. A provider saved with it drops it, and `magpie provider set … routing=cheap` refuses it. Groups take it in the GUI menu (one more item, no new controls), the TUI and `magpie group set <id> routing=cheap` (aliases cheapest, price, cost). - Routing's mode line says why the first one is first, e.g. "Cheapest first: deepseek-v4-flash costs least on ollama-cloud now — $0.150 in, $0.600 out a million tokens.", with peak and unpriced variants. en/zh/zh-TW/ja/de. - Docs: gateway-routing, plugin-runtime, reference (it also points at Time window and Pause rules for a fixed schedule) and the site's start pages (en/zh/ja). Run, at |
||
|
|
d99e213f5b |
codex: an account switch restarts nothing while Codex's provider takes no ChatGPT account
danzi002 on Discord: with requires_openai_auth = false on Codex's provider,
switching the Codex account in magpie still restarted the Codex app's
app-server and said the app and daemon were left on the old account.
Codex's provider with no requires_openai_auth = true goes by no ChatGPT
account: codex-rs ModelProviderInfo::account_state answers no account, and
resolve_provider_auth sends the table's key, never auth.json. So which
account auth.json holds is nothing a running Codex uses.
- provider.CodexNoAccount (set to agent.codexNoAccount): the config's top
model_provider is not openai, has a [model_providers] table, and the table
doesn't say requires_openai_auth = true. A profile, the built-in provider,
no table or an unreadable config count as false (may use the account).
- codexAppStep forgets a switch (and a spent switch) while it holds, so the
app-server is left running; a route change still restarts it.
- CodexAppStale / CodexDaemonStale say nothing, and `magpie accounts`'
switch line says nothing needs restarting.
- Kept: route-change restarts (model_provider, openai_base_url,
model_catalog_json, base_url, catalog hash: read only as the app-server
starts) and the daemon's model-list restarts; and switch restarts when
magpie writes requires_openai_auth = true (ChatGPT sign-in with room).
Run (mote-run; full suite at this change on
|
||
|
|
0804f2d97d |
search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (
|
||
|
|
acbd6b11ab |
search: a search API's URL given with the path magpie adds is its base, never …/search/search (plugins#509)
chenjiangzi set Tavily's url to https://api.tavily.com/search, and magpie appended /search again. Each vendor now names the paths magpie puts after its base (SearchVendor.Paths). A url that already ends in one of them, with or without a trailing slash and in any case, is cut back to its base. This happens when it is saved (SetSearchAPI) and again when it is read (SearchAPI.Base), so an entry saved before this change works too, and so does Tavily's quota URL built on the same base. Every vendor is covered: tavily, brave, exa, firecrawl, you (both paths), deepseek, volcengine, searxng, and wsa in the next commit. A path of the user's own (/my-search) is left alone. The url= help and gateway-routing.md say so. Run on mote (mote-run), at the rebased head: - go test -run 'SearchAPI|WSASearch|Volcengine|Search' ./internal/gateway/ ./internal/gui/ ./internal/provider/ ./internal/cli/: ok - go vet -tags nogui for darwin, GOOS=linux and GOOS=windows on provider, gateway, cli (and gui on darwin): ok; gofmt -l clean - GUI (no GUI file changes; the picker reads SearchVendors): search-api.test.cjs in Chromium 4/4 ok. Its WebKit cases and searcher-pick timed out at browserType.launch (180s) on mote, where ~57 WebKit pw_run launches from several sessions hang. Not a result about this change; WebKit not run. Broken by hand: ownBase returning the URL unchanged made TestSearchAPIBaseURLWithItsPath red ("asked /relay/tavily/search/search, want /relay/tavily/search"). Not tried: a real Tavily request; the full go test ./... (to follow). |
||
|
|
70a0c387cb |
agent: a provider named magpie written by hand is the user's, not connected (JFunfunfun on X)
Pi set up by hand on a provider of its own named magpie (magpie/<model> at the gateway) read as connected in magpie: every catalog change wrote magpie's list over that provider, RenameProvider rewrote its refs, Drift offered Reconnect, and Disconnect took the provider out. |
||
|
|
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 |