ac4af582301a4e8a29245dbba767eba31334ddf9
62
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c056b7c8c3 |
provider: a Responses provider's turns may go over the Responses WebSocket (#5781)
A provider the user added with an http(s) Responses address can now send its Responses turns over the Responses WebSocket that magpie already speaks to chatgpt.com (codexSocket), with `socket=auto|on|off`: - off, or absent: today's behaviour exactly. Provider.Via hides any socket value an outer context carried, so such a provider never dials. - auto: tries the socket, falls back to HTTP when the handshake is refused or the socket ends before the reply, and speaks HTTP to a host for 10 minutes once it refused the handshake (codexShun). - on: the same fallback, but never shuns; the socket is tried each turn. Provider.Via puts the provider's Responses host and path in the request's context (withSocket); codexSocket's gate is provider.SocketTurn, which takes a ChatGPT turn as before, or a POST to that host at <Responses>/responses. The rest is the ChatGPT leg's: the kept socket and its delta (codexKeepKey now also hashes the scheme, X-Api-Key and Api-Key), the error frames, 1009 handling. A provider's reply with no Content-Type is marked text/event-stream, since it is read as one. Routing, keys, limits, usage and masking are unchanged: only the transport under the request differs. Set with `magpie provider set <id> socket=auto|on|off` (refused on a provider with an account, no http(s) Responses address, or Vertex, TakesSocket), saved in providers.json as "socket", shown by `provider show`, and in the editor's Advanced as a WebSocket tick beside HTTP version (ticked saves auto, keeps a CLI's on, unticked saves off; shown only while the Responses address is http(s) and there is no account). docs/subsystems/providers-accounts.md describes it. app.js pays for its rows by three long comments cut to one line (renderMove, the vendors' status pages, header rows): the core's scripts are 478 bytes smaller than on |
||
|
|
40cbdaa7e8 |
provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.
- AccountWindowAmounts keeps it per account and window (capId). An
amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
and NearCap. CapHeld and capReached hold the account once the window's
count reaches the amount (past), and rest it as the percentage cap
does: the next account takes the request. cappedError and the trace
say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
place (provider/windowcap with amount). It shows only on a window
with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
--amount <n|off>.
Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.
Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
earlier webkit run lost the amount test's page once ("Target page,
context or browser has been closed"); it passed in 2 more full-file
runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).
Reported-by: 9won_25273 (Discord)
|
||
|
|
b0926e81a2 |
import: a link can say where its key's balance is read (balance=, balance_path=, balance_method=)
A relay's "Add to magpie" link can now name the URL that tells a key its balance, where the amount sits in the reply, and GET or POST. magpie takes it only on the host of one of the link's own base URLs, over https, with no userinfo or fragment, so a link can't send the key anywhere its requests don't already go; anything else refuses the whole link. balance_path or balance_method without balance is an error. No header or token is taken from a link: an account-wide token is worth more than a key, and a URL stays in browser history. - provider.ParseImport: linkBalance checks and sets BalanceURL, BalancePath and BalanceMethod. - CLI: the import preview shows the balance URL and doesn't ask it before yes (showProviderAsking). - GUI: the import dialog shows method, URL and field (.imp-bal). - Docs: docs/import in en, zh and ja (table rows, a note on headers, the builder's three fields with the same host check, a security bullet); docs/reference.md's parameter table. Run on mote at this tree (rebased on |
||
|
|
37df73b1bb |
balance: a key holds several credits that expire, each added and removed on its own
tenacious_eagle_96548 (Discord, 11-08) has two promotional credits on one
key, one ending tomorrow and one the day after. v0.1.3305 kept one grant
per key, and its form showed the date only after Enter or a blur, with no
button to confirm.
- OwnBalance.Expiring is now a list (`expirings`, up to 20). Spending
goes to the grant that ends soonest first (ties by when it was typed),
and each grant drops out at its day. A write prunes ended grants.
- The pill and the menu say "Expires in N days" per grant, amber from 7
days. The menu has a Remove item per grant, "Add credit that
expires…" and "No credit that expires" to clear them all.
- The form shows the amount and the last day together, the day filled in
30 days ahead, with an Add button; Enter adds, Escape cancels, a bad
amount or a past day is refused in place. The app's own menu, no
native select, no stripes. A pill with two or more grants wraps at a
grant on a narrow row (a class, not :has(), for Safari before 15.4).
- CLI: `--expiring amount@day` can be given several times, `--expiring
off` clears all, `--expiring-remove [amount@]day` removes one. --help
prints usage; a day that isn't a date, or is past, is refused.
- /api/provider/keyexpiring adds `{expiring:{amount,until}}`, removes
`{expiring:{at,until},remove:true}`, clears `{expiring:null}`.
Old data: a v0.1.3305 single `expiring` grant is read as the first grant
and saved as `expirings` on the next write, for every user. An older
magpie reading the new file sees no grants (the balance itself stays).
Run on mote at
|
||
|
|
c736906b17 |
providers: part of a key's typed balance may expire on a day
tenacious_eagle_96548 (Discord, #general): some vendors split a balance
into money that stays and credit good until a date. A key's balance typed
by hand can now carry that part (`expiring`: {amount, until, at}, in the
balance's currency, until = the last day it counts).
- Spending order: the expiring part is spent first, as DeepSeek spends
its granted balance before money topped up. It takes the spend from its
`at` up to its end (midnight after `until`, local time) or now; only
what it took after `From` comes off the rest, so a refill or typing the
balance again doesn't count it twice.
- Left is the whole balance. From its end the remainder counts no more,
and unspent credit is gone.
- Typing the balance again keeps the part in the same currency and drops
it in the other, where its amount would mean another sum.
- A balance saved before has no part and reads exactly as it did
(TestTypedBalanceSavedBeforeExpiring).
- Set from the pill's menu: "Credit that expires…" asks the amount, then
the last day (a day gone by, or the other currency's sign, refused);
"No credit that expires" takes it off. GUI route provider/keyexpiring;
CLI `magpie provider key-balance <id> <key> --expiring amount@yyyy-mm-dd|off`.
- Shown: the pill "≈$100.00 left · $30.00 expires in 30 days", the Usage
page and panel line "Expires in 30 days ≈$30.00", amber from 7 days;
TUI and `magpie quota` "($30.00 until Dec 7)". New strings in zh,
zh-TW, ja and de.
Run (mote):
- go test of internal/provider, internal/gui, internal/cli (with
TestCoreScriptBudget: the days' lines in app.js are paid for by five
balance comments cut there, no raise; core 1,533,559 of 1,533,802); the new tests
again with TZ=UTC and TZ=Pacific/Kiritimati (every clock held);
gofmt -l clean; GOOS=linux and GOOS=windows go vet of those packages.
- GUI: key-balance-expiring.test.cjs 20/20 (chromium and webkit, 400px,
en/zh/zh-TW/ja/de), with every balance-*, key-*, i18n-* file: 768
pass, 6 red, each red the same alone on origin/main
|
||
|
|
ae58ec9b44 |
providers: a key's provider can have its model list off
axelburks on Discord: Ark's pay-as-you-go list names models that can't be asked for, and each one is asked by an endpoint id the user made. A key's provider can now have its list off (Provider.ListOff): nothing asks its vendor for a list (Fetch, Refetch, List, RefreshLists, a test, a new key's prefill, a resting key's probe), a list fetched before and models.dev's are not read, and only the ids added by hand are served. The editor shows it as "Fetch the model list", ticked by default; unticked, Fetch models and Forget go. A save that doesn't name listOff keeps it. CLI: `magpie provider set <id> list=off`. Accounts and plugins list as their sign-in does, so they don't take it. Broken by hand: ListAsks returning false for a list-off provider turns TestListOffAsksNoListAndServesTheIDsAdded red; dropping the keep in the save turns TestProviderSaveListOff red. Run, on this stack over origin/main |
||
|
|
0fc3455e2a |
providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).
- A balance may be typed in yuan ("¥100", "100元", or a bare number while
Settings shows costs in CNY). What magpie counts spent stays in USD and
is turned into yuan at fx.Known(): the rate internal/fx last fetched
(cached 12h, fetched again in the background, never on a request).
fx.Known never returns fx.Fallback, so with no rate fetched and
something spent, what is left is unknown (left null; the card says
why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
day) or weekly on a weekday, at midnight in the user's local time.
Nothing is stored on a refill: the spend counts from the last boundary
after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
Refills each week… (the app's menu of weekdays) and Never refills;
provider/keybalancerefill; keyownbalance takes currency cny. CLI:
magpie provider key-balance <id> <key> [usd|¥cny|off]
[--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
ja, de. docs/subsystems/providers-accounts.md updated.
Run on mote at this tree (base origin/main
|
||
|
|
d32a7a70cb |
remote magpie: once magpie updates, the Remote magpies it uses update too
nnlrl_75403 on Discord: a magpie used as another's Remote magpie stayed on
its old version after the local one updated, and had to be updated by
hand on the other computer. Now nothing needs setting up:
- provider.KeepRemotesUpdated (started by the app's updater and by
magpie serve) runs UpdateRemotes 30 s after start and hourly. A
released build with automatic updates on reads each Remote magpie's
version (GET /v1) and, when it is older, asks it through
POST /v1/magpie/update?version=<v> with the provider's key, at most
once in six hours per version. Off here, or a dev build: nothing asked.
- The remote updates as its own automatic update would: the app
downloads and restarts once idle (updater.updateAsked → download,
waitIdle); magpie serve puts the latest in where it runs from, one at
a time, never elevated, and serveFollow restarts into it. Automatic
updates or downloads off there: it answers "off" and stays.
- A copy that can't replace itself says why: a container (docker pull
ghcr.io/yetone/magpie:latest), a package manager's (its command), a
folder it can't write, a build from source. A magpie from before the
route answers 404 ("too old"), a read-only or held key is "refused".
The provider's row on the Providers page adds a short status to its
line ("updating to v…" for 30 min, or "can't update itself" etc.),
with the reason and the command in its tooltip. en/zh/zh-TW/ja/de.
- The route replaces the program, so it takes the Codex reset's
admission: another machine only while shared, never a browser page,
an enabled key with full access from loopback too (401 without one),
read-only 403 gateway_key_read_only, held 403 gateway_key_held. It is
in readOnlyRefused and the CORS route list.
App.js stays under TestCoreScriptBudget by cutting two comments; the
budget is not raised.
Run (on mote, at the tree committed here):
- gofmt -l internal/: clean. go vet of gateway, gui, cli, provider for
darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/gui ./internal/cli ./internal/provider
./internal/gateway: gui and cli ok but for #5644's two settings tests
(red on main since
|
||
|
|
f8525323dd |
providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL, no relay query found), so their keys showed none. Now the user types what the vendor's page says is left, on the key's row in the provider editor (Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`. The key's card shows that less what magpie's usage priced the calls it sent on the key since it was typed (usage.KeySpent, the spend caps' count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its title saying what was typed, when, and what was counted since. Typing it again counts from then; No balance takes it off. A balance the vendor tells always wins: a provider with a Balance URL, a plan source, Cline's or OpenCode Zen's card takes none typed, and a relay whose query is found shows its own; when the probe finds none (errNoBalance) the typed one is shown. A typed balance stays saved as the user left it: the editor's save keeps it, a key's replaced value carries it. An estimate is never kept in the balance history and tells routing nothing (the routing allowances cache is left alone). keybalance.js is loaded by keyspend.js (itself loaded when the editor draws a key) for a provider that takes one, so app.js and the core's script budget are unchanged. Words in zh, zh-TW, ja and de. Run at this tree (mote): - go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of gui, provider, cli and usage; - go test -tags nogui -count=1 ./internal/gui ./internal/provider ./internal/cli ./internal/usage: provider and usage ok; gui and cli red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main) - the provider tests under -race -count=3; - GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de, 900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de, gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk: 104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the same on origin/main |
||
|
|
abe7b00631 |
gateway: a key+URL provider is sent the agent's own User-Agent by default, through a remote magpie too
nb5p runs a gateway of their own behind magpie and saw nearly every request arrive as "magpie/<version>". The agent's User-Agent now goes on as the agent sent it, wherever magpie isn't itself the client. What each path sends now: - Key+URL providers (official vendor keys and custom OpenAI/Anthropic compatible ones), on chat, Anthropic, Responses, Gemini, count_tokens, embeddings, images and videos: the agent's User-Agent, as sent. Before, this was the opt-in passUserAgent (#1851) and the default was magpie's. The opt-out is magpieUserAgent: `magpie provider set <id> user-agent=magpie`, or untick "Send the agent's own User-Agent" in the editor. passUserAgent is no longer a field, so a file that set it true reads the same as the new default. A provider someone turned back off after opting in can't be told apart from one never touched, and now sends the agent's too. - When the agent sent no User-Agent, and on magpie's own requests (classifier magpie-router/1, vision, search, the image tool, model lists): magpie's, unchanged. - A header.User-Agent the user set: still wins over both. - Subscription accounts (Claude, Codex, Copilot, Google, ZCode…), plugins, and OpenCode/Cline/Kilo: unchanged. Their signing sets the official client's UA (provider.PassesUserAgent still refuses an Account or OwnClient). - Claude Code and Codex header copies: unchanged. - Remote magpie: the near magpie still asks as magpie/<v>, because the far end trusts X-Magpie-Agent/Via only from that. It now adds X-Magpie-User-Agent (passOnUA, on forwardOnce, embeddings, draw and video; the classifier's decision request names none). The far end takes it only from a magpie/ request (callerFrom) and strips it on arrival (withCaller). agentUA/callerUA then hand it to userAgentFor, so the far vendor sees the agent's. A client that writes the header itself, straight to a magpie, is ignored. magpie's own UAs are never relayed (magpiesOwn). Vendor check: invalid-key requests with magpie/, claude-cli, a Chrome UA and pi's went to Anthropic, OpenAI, Gemini, DeepSeek, Moonshot, Kimi For Coding, Zhipu, OpenRouter, xAI, DashScope, MiniMax, Volcengine Ark, Groq and Mistral. Every vendor gave the same auth error for every UA, so no edge-level UA gating was seen. Kimi For Coding's agent allow-list sits behind a valid key, which wasn't tried. Run (mote): - go test -run 'UserAgent|RemoteMagpie|ZCode|Blocked' ./internal/gateway: ok - go test ./internal/provider ./internal/cli ./internal/gui: ok - node --test provider-user-agent, provider-native-compaction and i18n-keys (chromium and webkit; en/zh/zh-TW/ja/de; 900 and 440 wide): 123 of 124 pass. The red is i18n-keys "a plugin's words are its own" (plugins' words said in files this change doesn't touch), already filed as #5327/#5332, #5426 and #5482. - gofmt -l clean; go vet; GOOS=linux -tags nogui and GOOS=windows vet: ok at the rebased head (on |
||
|
|
8cbaeecae9 |
providers: errors=pass sends a vendor's error to the agent as it came, asked once
ne9ko9 on Discord wants errors handled explicitly, not by inference, and a mode that passes them straight through. A custom or API-key provider (no account, an endpoint of its own, not a subscription) now takes `passErrors` in its config: "magpie handles" (the default, unchanged) or "Pass through". Nothing sets it but the user, and an edit that doesn't send it keeps the saved value. With it on, for that provider: - no rewriting: on the client's own API, upstream's status, Content-Type and bytes go out (passError); on another API, the client's shape is built with the vendor's own type, message and raw code and param (a numeric code stays a number). Retry-After and *ratelimit* headers go with it; - no too-long inference, no busy words, no 413 hint, no policy rewording (settle never runs: the try is passing); - no gateway retry: forward()'s Retries loop, refit, firstWait, the loop's re-asks, reloop, empties retry and streamTranslated's cont.again all stop; - no fallback and no rest: the candidate loop's one choke point, newHoldWriter(…, !pass && …), lets the try pass, so nothing after it is tried, and restAfterMarked answers By "off". magpie's own file-id re-ask (dsRetryGone) still runs, as it fixes magpie's own upload, not the vendor's answer. CLI: `magpie provider set <id> errors=pass|magpie`; a bad value is refused and keeps the old one; an account is refused. `provider show` says "errors pass". GUI: Edit → Advanced → Errors, a quiet app-menu picker (openProtoMenu, no native select) with "magpie handles" and "Pass through", shown only where takesPassErrors; zh, zh-TW, ja, de. It is drawn by passerrors.js, imported when the editor draws the row (old-webkit's lazy list names it), and app.js pays for its few lines by two comments cut, so app.js is smaller than before and TestCoreScriptBudget's numbers are unchanged. Tests: - internal/gateway/pass_errors_test.go: TestPassErrorsAskedOnce (503, 429, 404 with numeric codes, alone and as a group's first member: exact bytes and status, asked once, the second member never asked, no rest), TestPassErrorsNotInferred (a too-long 400 byte-for-byte), TestPassErrorsOtherAPI (Anthropic 403 code 20031 to a Chat client, streamed and not). - internal/provider/pass_errors_test.go, internal/cli/errors_cli_test.go. - internal/gui/tests/provider-pass-errors.test.cjs: every language, 1100 and 420 wide, Chromium and WebKit. Run, through mote-run at this commit: - go test -count=1 -timeout 45m ./internal/gateway ./internal/provider ./internal/cli ./internal/gui (at the parent 19c45d5d4's tree): gateway, provider, cli ok; gui red only in TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 (#3949). TestCoreScriptBudget ok. - Rebased on |
||
|
|
8fbf8e0af6 |
gateway: DeepSeek's own API gets an agent's images once, by file id, not on every turn (#5407)
DeepSeek's API is stateless, so every turn re-sent every inline image in
the history. Now, on api.deepseek.com only (never a relay or another
base), for a model with "flash" in its name (deepseek-flash sees images;
deepseek-v4-pro reads them as "[Unsupported Image]"), each base64 data:
image goes up once through POST /files (purpose=user_data, expires_after
a day) with the candidate's own key, and later turns name it by file id:
- Chat: {"type":"file","file_id":…} (flat, as DeepSeek's vision guide);
- Responses: input_image with file_id in place of image_url;
- Anthropic: source {"type":"file","file_id":…} plus anthropic-beta
files-api-2025-04-14.
Shapes checked against api-docs.deepseek.com files_api, vision,
responses_api and anthropic_api. The Anthropic guide names the "file"
source type and the beta; the field name file_id is Anthropic's Files
API's, which DeepSeek says it follows. Not confirmed with a real call.
Ids are kept per key hash + image sha256 in deepseek-files.json beside
providers.json (temp+rename, unparseable file moved to .bad), reuploaded
with under an hour left. One upload per image and key however many
requests want it; a request waits at most 8s for its uploads, and what
isn't up goes inline this turn. A failed upload leaves the image inline
and rests that key's uploads for 10 minutes. A 4xx naming a file-api id
or a missing/expired file forgets the ids, uploads again and asks once
more; refused again, the request goes inline. detail:low stays inline.
`magpie provider set <id> image-files=off` turns it off (kept on GUI
save). Doc: docs/subsystems/gateway-routing.md.
Run (mote, at this tree on
|
||
|
|
9d0c9b41ea |
serve: follow an update put in where it runs from; a replaced magpie.real is magpie
acezan on Discord (Linux 5.15, 0.1.2959 to 0.1.2960): `magpie web` as a system unit updated /root/.local/bin/magpie.real, and the user unit's `magpie serve` (`magpie daemon install`) ran on for good from "magpie.real (deleted)". The panel said an older magpie served the gateway, and its "close it here" then said the port holder "isn't magpie" and left it. Why serve stayed old: the app and `magpie web` follow the program they started from (gui's followReplaced) and restart into an update; plain `magpie serve` had no such look, and answered `magpie update`'s restart ask (gateway.RestartPath) "unsupported". Nothing else can restart it reliably: a system unit doesn't reach the user's `systemctl --user`, and on a Mac the launch agent's serve (#4335) is the same serve. So serve now looks itself (internal/cli/serve_follow.go): every 5s it checks its program with update.Replaced; once replaced, it waits until the gateway is idle (nothing in flight, 10s since the last end, as gui's idle rule; after an hour, nothing in flight is enough), ends the plugin hosts and runs the new program in its own place (update.Reexec: exec in place on Unix, same PID, so systemd and launchd keep tracking it; a new process on Windows). The restart ask now answers restarting/waiting/current. A build that isn't a release never does it. Why "not magpie": proc.IsMagpie judged the file name, and "magpie.real" (the program the installer's wrapper script runs) didn't match. It now trims ".real". And proc.RunsMagpie, used by the takeover and the port check, also reads Go's build info of the running program (on Linux through /proc/<pid>/exe, which still reads after the file is replaced) and calls it magpie when its main package is github.com/yetone/magpie. A process that isn't magpie is still never ended (the existing "other-server" case passes unchanged). Tests, each red on the old code: - cli TestServeRestartsIntoAnUpdate: a copy of the test binary named magpie.real runs `serve` on a free port; a script renamed over it is run in its place with the same pid and args, and the old port stops answering. Old code: "serve ran on as the old version" after 40s. - cli TestServeFollowWaitsForIdle: current / waiting / tool-chain gap / waitMost with a request in flight / idle / non-release. - gui TestGatewayFixQuitsAReplacedMagpieReal: a fake older gateway named magpie.real, its file removed after start, is quit and the gateway served here. Old code: {OK:false Reason:not-magpie}, acezan's case. - proc TestIsMagpie magpie.real case; TestRunsMagpieByItsBuild: a copy named server.real, its file removed, is told by its build (Linux /proc/<pid>/exe), and is not magpie with the real main path. Run: the targeted tests above on Linux (wsl-run, magpie-desktop, -tags nogui) and macOS (mote-run), all pass. Broken by hand on Linux: dropped the ".real" trim, made RunsMagpie only IsMagpie, and set serve's follow to nil; all four new tests went red (output above), restored after. gofmt -l clean; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) and builds on mote. Not tried: a real systemd user unit or launch agent with a real update; the Windows restart path (Reexec starts a new process) beyond vet; the macOS TCC part of #4335 (this restarts the launch agent's serve into the new bundle path only if that path is where it started from). #4335 stays open, and ggbdpq's daemon.RestartReplaced patch there is not applied. |
||
|
|
00d8aac596 |
routing: Free quota by expiry spends the soonest-lapsing free quota first (wowbbs)
wowbbs (and shamen_xiaohong) keep check-in free accounts in one group:
WorkBuddy CN x2, MiniMax Code, TraeCode CN and Qoder CN. They asked that
the group spend the free quota that lapses soonest first, go on to the next
when one is used up or has lapsed, and use a paid account only when no free
quota is left.
This adds `expiring` (provider.FreeExpiring, routes.FreeExpiring). It is a
group's only, picked in the Routing page's group menu, with
`magpie group set <g> routing=expiring` or in the TUI. Nothing changes for a
group or provider that doesn't pick it. A provider keeps refusing it, as it
refuses `cheap`.
- routes: Seat.FreePlan and Strategy.ByPlan. FreeExpiring has three tiers:
- free seats (Free, a model at no cost, or FreePlan) by Expires, the
earliest of the window renewals and Lapse, to the hour; an unknown
expiry goes last and ties keep their listed order;
- then the paid seats, as Smart orders them;
- then the spent and resting seats, by when they come back.
- provider.FreePlan reads an account's plan word: free, trial, 免费, 试用,
体验, 體驗.
- gateway: weighRouted fills FreePlan when the strategy asks. The trace's
Weighed rows gain `expires`, so the Routing page's story can say "its free
quota is lost soonest, in 1d 2h". There are also lines for "a free one with
no expiry told" and "no free quota left, so the paid one".
- GUI: an option in the group menu, the mode line, the story lines, and
i18n in zh, zh-TW, ja and de. app.js only adds `expiring` to ROTATION,
paid for by a shorter comment beside it, so the core is 11 bytes smaller
than at its base.
- docs: gateway-routing.md (order of keys and accounts) and
plugin-runtime.md (Seat and Strategies).
Plugins whose usage doesn't say when their free quota lapses got issues
rather than edits:
- magpie-community/plugins#718: Trae sums its packs; the soonest end comes
from any pack, spent or past, and there is no runsOutAt.
- magpie-community/plugins#719: Qoder's plan is the raw userType
personal_standard, which doesn't read as free, and its add-on, shared and
dedicated pools have no expiry.
WorkBuddy (Free plan, resetsAt and runsOutAt) and MiniMax (Free, runsOutAt
on credits) already report what this needs.
Run, all on mote via mote-run at this tree (base
|
||
|
|
6c201095d8 |
gateway: in Docker, other containers on the host are shown the host's Docker bridge address
jiezhengj (Discord #feedback) runs magpie in Docker on a NAS at 192.168.31.218. The web UI's host address, http://192.168.31.218:3425, works for other devices. Other containers on the NAS couldn't use it, and not the container's own 172.17.0.x either. What works for them is the host's Docker bridge address, http://172.17.0.1:3425. On Linux, host.docker.internal is there only in a container given extra_hosts. magpie showed no such address. - gateway.ContainerHostURL: in a container on a bridge network, the gateway of /proc/net/route's default route (172.17.0.1 on the default bridge, a compose network's own otherwise), on the gateway's port. It is "" outside a container and on the host's network (`network_mode: host`, told by the host's docker0/br-*/veth*/podman* interfaces). In that case ContainerAddrs is false too, since the addresses are the host's own. - The GUI gets it as /api/providers' gateway.containerHost, /api/settings' lanContainerHost and boot's sideGateway.containerHost. - settings.js lanShown is fed by the new gwLAN(g) for Gateway, Connect, the sidebar and the key page. Each case lists: - Opened at the host: the host's address first, then the bridge address, labelled "Other containers on this host". - At localhost: the bridge address alone, with that label, and a line that the host's own is MAGPIE_PUBLIC_URL's. - No default route: as before. The container's own 172.17.0.x is no longer offered beside them. The sidebar line and the key page prefer an address other machines reach. The scheme comes from the URL, not a hard-coded http. Three new strings are in zh, zh-TW, ja and de. - CLI: `magpie web` and the share banner print "other containers on this host <url>". - docs/reference.md and site docs/docker (en, zh, ja): the log example and a new "Other containers on the same host" paragraph. Run on mote, at this change on |
||
|
|
e41ef6288c |
providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted credits that other docker services spend from too, and they want magpie to stop at a share of it. Their workaround was two magpies behind a gateway-key limit. What changed - provider: KeySpendCaps on a provider, keyed by the key's fingerprint (key_spend.go): USD over a local calendar day, a local calendar month, or in all since it was set. Since is kept while the cap stays one in all. SetKeySpendCap and ParseSpendCap refuse an amount outside 0 < usd <= 1,000,000 and an unknown period, and leave the saved cap as it was. Subscriptions are refused, since an account has its own usage-window cap. - usage: KeySpent(keyID, start) is what magpie's own calls on the key cost at the Usage page's prices. Turned-away calls and app-reported ones are left out. It reads usage.jsonl once per key and start, keeps the sum for 5 minutes, and Append counts each new call into it (spentNew). A read that a write races is read again. - gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap holds an account. The next key serves, then the fallbacks. With none, the reply is 429 "spend cap reached: ..." naming each key, what it spent of which cap, and how to go on. Retry-After is when the soonest period renews; a cap in all gives none. A spend hold is not a usage cap: Stop at the caps and strictKeep don't end at it (capHeldOnly). The trace's barred row carries the cap, the spend and the period. - GUI: a pill on each key's row in the provider editor, for example "$7.50 of $20.00 today". It opens the app's menu (No spend cap, Per day..., Per month..., In all...) and then takes the amount in place, as the lane-limit pill does. A key at its cap gets a line under its row: "At its spend cap · back in ...". Every string is in all five languages. The pill and the line are in keyspend.js, which app.js imports when it draws a key's row, so the core's script budget is not raised. /api/providers' keyList carries spend, and POST provider/keyspendcap sets it. - CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]] lists each key's spend and sets or removes a cap. - docs: providers-accounts.md and gateway-routing.md. Caveats, also in the tooltips: - What counts is magpie's priced usage, not OpenAI's bill. - A model with no known price counts $0. - Requests already under way when the cap is reached still finish, so a key can go a little past it. Run on mote at the pre-rebase head ( |
||
|
|
c47fc516a4 |
provider: Tencent Cloud's Token Plan is at tokenhub.tencentmaas.com/plan (ysm119)
ysm119 (Discord) showed Tencent's docs: Token Plan's OpenAI base is now https://tokenhub.tencentmaas.com/plan/v3 and the Anthropic one on tokenhub.tencentmaas.com is the recommended one, with api.lkeap.cloud.tencent.com marked as going away. Tencent's current pages (product/1823/130060 个人版 overview, 130070 Claude Code, 130071 Codex, 130119 quickstart, 136601 CC Switch, all updated 10-15 to 10-22) give 个人版 the same endpoints as 企业版 China (130659): chat/responses at https://tokenhub.tencentmaas.com/plan/v3, messages at https://tokenhub.tencentmaas.com/plan/anthropic, one sk-tp- key for 通用 and Hy plans. - The tencent-cloud preset's plan region (and the preset default) are at those endpoints, with Responses added (Codex's page uses wire_api "responses"). magpie tells regions apart by endpoint, so the personal and China enterprise regions, now one address, are one: "plan", models the union of both lists. "enterprise" stays an alias (regionAliases, RegionID): a key saved on it, an import link with region=enterprise and `region=enterprise` on the CLI land on plan. Singapore 企业版 (enterprise-intl) is unchanged. - A Tencent Cloud provider saved at the old lkeap /plan/v3 or /plan/anthropic is moved to TokenHub at load (moveEndpoints in normalize), and gains the Responses endpoint when it had chat. A Responses address the user set stays. A provider of no preset (a custom one the user typed lkeap into) keeps its address: that is the user's value, and lkeap still answers today. - An app config still at lkeap (Tencent's OpenClaw page, 130062, still gives it) imports as tencent-cloud at the new endpoints. - Usage: DescribeTokenPlan is 企业版's API (api/1823/132270 lists enterprise products only), and Guangzhou's endpoint now serves 个人版 too, so a Guangzhou provider with no SecretId no longer gets the card asking for one (tcSharedRegion); Singapore's still does. The editor shows the optional SecretId/SecretKey at the plan region, so a personal user sees them too. - docs/subsystems/providers-accounts.md says all of this. Run at the pushed head's base |
||
|
|
4dfdd0cd63 |
provider: a provider switched off is asked for nothing, its plugin's model list included
ChangQiu on Discord switched a provider off long ago, and magpie still reached it. Routing, fallback, usage and balance reads, warmups, check-ins and keepalive were already held back (On(), leftAlone, KeepListsFresh). These were not: - The plugin host's providers listing ran every plugin's models hook, which asks the vendor, and its sign-in renewal (fresh), for every plugin provider, on or off. Go now passes the ids switched off (plugin.ListingOff, provider.pluginsOff: the provider's id and the plugin's own id, read from providers.json alone). host.js lists such an id without running a hook (info(..., quiet)), so its row stays and keepListed keeps the last list. - Sync (POST /api/sync, `magpie sync`) fetched every ready provider's list. Both now go through provider.RefreshLists, which skips one switched off. - Saving or switching on in the GUI fetched the list even for one left off; PrefillNewKeys asked one switched off too. What still asks one switched off, by the user's own click: the TUI's refetch, the provider Test button and `magpie provider models <id>` refetch. Tests: TestOffPluginProviderAskedNoModels (the fake plugin's models endpoint counts its hits: 0 while off, the list kept, asked again once switched on), TestPrefillAsksNoProviderSwitchedOff, TestPluginsOffNamesThePluginsOwnIDs and TestRefreshListsAsksNoProviderSwitchedOff. Run on mote at this head (first at |
||
|
|
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 |
||
|
|
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
|
||
|
|
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
|
||
|
|
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. |
||
|
|
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
|
||
|
|
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
|
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
e887139e7a |
providers: Best in family serves the newest model of each family a provider lists
Steven on Discord #feedback asked for a provider to serve only the newest model of each family, so a newer one (Opus 5.6) takes the old one's place without re-picking. The provider editor's Models control gets a fourth option, beside Vendor's list / Picked only / Usage only: Best in family. It is also on the CLI as `magpie provider models <id> best`. With nothing picked, the provider serves only the newest model of each family in the vendor's list, up to 24. A family is the id with its version numbers taken out (catalog.FamilyOf/BestInFamily in internal/catalog/family.go). A dated snapshot counts as its alias, and sizes and suffixes (mini, flash, -fast, -thinking) stay part of the name. Provider.Exposed applies it, and so does Codex's native list (CodexNativePicked). A provider/model a request names explicitly is still served, since resolve doesn't go through Exposed. A pick, Select none or Usage only clears the flag (normalize), and a providers.json without bestInFamily reads as before, so every existing mode is unchanged. The editor draws the family's newest as dashed (m.best) before saving. Every language has the wording (zh, zh-TW, ja, de). The design reference is docs/subsystems/providers-accounts.md (Model picks). Tests: family_test.go is a table of real ids, including the models.dev Claude list in testdata (no network). There are also best_in_family_test.go (provider), TestProviderModelsBest (cli), provider_save_best_test.go (gui save keeps/clears), codex_best_in_family_test.go (gateway) and provider-best-in-family.test.cjs (5 languages x chromium/webkit x 1100/420). Broken by hand: with the BestInFamily filter in Exposed and in CodexNativePicked turned off, the 4 new Go tests went red. Budget: after the rebase app.js went over appScriptBudget. Comments were cut and the tooltip and hint merged into one string, so app.js is 1,311,399 of 1,311,735. Neither budget was raised. Run at this head, on origin/main |
||
|
|
b4267de595 |
gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:
- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
the group as routed, Live) hands its members to planLevel
(planFallbackGroup): the group's own routing, its sink and asides, and
its pause rules (serve passes provider.PausedOut for the agent's folder).
Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
a model named earlier, or another fallback group's member is left out
where it comes second. Groups have no fallbacks of their own and a
member's fallbacks are not followed, so nothing leads back. A group that
is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
provider.FallbackModels: redaction (unredactedRoute: an unmasked
provider with a fallback group holding a remote model is masked),
careful accounts (carefulOf), native compaction, Codex's own turns
(codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
moves from provider.Resolve to ResolveRoute, as the gateway reads
fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
groups); its usage and error now say so. Pinned by
TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
(providers.gateway.groups) beside the models as chips with the Routing
fan and a muted "routing group" tell; a picked group's row has the same
fan and tell, and a gone one says "No routing group {id} now; it is
skipped". A filter matches a group's name, id and its members'
providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.
Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.
Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
(TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
…) killed at their 30s bars while four other sessions' GUI suites held
mote at load 70-110. Run alone, all ten
pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
red at base
|
||
|
|
08b02cf18c |
providers: a pool stops at its caps and reads usage again near them (plugins#349)
What was adopted on magpie-community/plugins#349 (1939869736luosi): one
place, in the GUI and the CLI, for a subscription's account pool, and an
opt-in conservative mode.
- Stop at the caps (Provider.CapStop, off by default): once every account
in use is held at its cap, the request is answered 429 rather than going
on to the provider's fallbacks (plan returns restLast). Off, as before.
- Check usage again near a cap (Provider.CapCareful, off by default,
internal/gateway/cap_careful.go): before planning, a capped account's
usage is read again when its reading is over 15s old within 5 points of
a cap, or over 5m old at all; the request waits at most 10s, and a
failed account is asked again at most every 15s. An account whose usage
was never read, whose last read failed, or whose reading is still that
old is then held as one at its cap is (capHold "unread", traced as
Weighed.Unread, named in the 429 with "--careful off"). Generic: it
goes by provider.UsageRead/ReadUsageNow, so every subscription that
reports usage windows (Codex, Claude, plugins) gets it.
- provider: usedCache records each account's read state; a failed read
keeps the last good reading's time. ReadUsageNow no longer reports
false when the read had already finished on the first ask.
- GUI: under the provider's account list, once an account has a cap (or
either is on), two ticks for the above, and a note naming the accounts
in use with no cap ("used to 100% of each window"). Accounts, order and
caps stay where they were in that list. zh, zh-TW, ja, de added.
app.js 1,309,658 within its 1,310,460 budget, unraised: addRow and a
per-row forgetOf replace 3 add-button and 5 Remove-button builds.
- CLI: magpie provider pool <id> [--accounts a,b,…] [--cap percent|off]
[--stop on|off] [--careful on|off] shows and sets the whole pool.
- docs: gateway-routing.md and providers-accounts.md.
Run (mote, before the rebase at
|
||
|
|
1885c607e2 |
gateway: Antigravity answers Codex's switched threads and Hermes' old persona with no setup
Antigravity answers some agents' system prompts with a fake 429 "Resource
has been exhausted", whatever quota is left. Jodiezzzzzz on X (10-27): a
Codex thread begun on GPT-5.x and switched to an Antigravity model got 429
again and again. zgoodz on X: "antigravity在Hermes里一样429". v0.1.1625
told the Codex case as a 400 with "start a new chat", which isn't zero
setup.
What Google matches, each tried on a real Antigravity account on 10-27
(in the system instruction, any case):
- "x-anthropic-billing-header:" (Claude Code)
- "built on Anthropic's Claude Agent SDK" ("running within the Claude
Agent SDK" goes through)
- "You are Codex, an agent based on GPT-5" / "..., a coding agent based
on GPT-5"
- new: "Hermes Agent, an intelligent AI assistant created by Nous
Research", Hermes' earlier default SOUL.md, kept by anyone who edited
their SOUL.md. Hermes' current default ("You are Hermes Agent, built by
Nous Research") goes through.
Each goes through with a zero-width space after its first letter.
"You are Hermes Agent, an intelligent..." still fails, so the
break goes inside the matched phrase itself.
Now codeAssistBody puts that zero-width space into each matched line
(antigravityCloak), in the system instruction only, and only for an
Antigravity account. Gemini CLI's account on the same envelope, and
every other provider and protocol, get the prompt as the agent wrote
it. The text added names nothing; it is one U+200B per line.
`magpie provider set antigravity prompt=as-written` (PromptAsWritten,
kept through Save/withPicks and the GUI's save) turns it off. Then the
v0.1.1625/#2156 fallback stands: a 400 with a hint (now one for Hermes
too, in the Routing page's five languages) and Antigravity skipped for
6h in a group.
Default-on, as the community antigravity-cloak middleware's README
says, changes what Google is sent so a request it means to refuse goes
through. That may be against Antigravity's terms. The owner asked for
it ("破解过 antigravity 提示词让其可以在别的 agent 中使用"), and it is
scoped to Antigravity accounts with an off switch.
Run at this tree (rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/provider/
./internal/cli/ ./internal/gui/: gateway, cli and gui ok; provider
died in TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest
channel from outside bubble" in filememo.Forget), #3632, red on main
since 091153bf; with -skip of that test, provider ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: ok. go build: ok.
- GUI (node --test, Playwright 1.62, chromium and webkit):
routing-ag-turned-away, i18n-keys, gui-ja, gui-de, gui-zh-tw,
routing-js, panel-routing: 45 pass, 0 fail.
- Broken by hand: with the cloak skipped, TestAntigravityAnswersHermes
AndCodexByDefault and TestOnlyAntigravityIsSentThePromptBrokenUp go
red; without withPicks' line, "prompt=as-written isn't kept".
- Real account, sandbox HOME with only the Antigravity login copied,
this build on 127.0.0.1:3496:
- real Hermes Agent (AIAgent, sandbox SOUL.md = the old persona plus
one line): "OK", 200. With prompt=as-written: 400 with the Hermes
hint. Back on default: 200.
- real Codex 0.162.1: a thread begun on gpt-5.5 (against a local
fake Responses server), then `codex exec resume <id> -m
antigravity/gemini-3-flash` through this build: "OK". With
prompt=as-written: 400 with the Codex hint.
- a synthetic switched Codex Responses thread, with and without
web_search: 200.
- opencode, droid, kimi, pi, gemini-cli, qwen, crush, goose, amp and
openclaw identity sentences: never refused, as written.
Not tried: Claude models on Antigravity (the sandbox account's Claude
quota is spent, so the Claude Code lines were checked on Gemini 3
Flash only); other agents' whole prompts, only their identity lines;
the Windows box; the whole GUI suite.
The plugins repo's antigravity-cloak 0.1.2 adds the Hermes line for
magpies before this one.
|
||
|
|
d56c14e953 |
gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)
zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.
A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
Patience, set with `magpie provider set <id> patience=2m|off|default`
(at most 4m). The provider editor has no row for it (no new UI), and its
save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
401/403, refusals, response protection, didNotStream, and an agent
that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
"tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
relayed outside the candidate loop, and its backend 429 is always the
plan's usage limit (codexBusy never retries one), so the short rate
limit this waits out doesn't arise there. Its overloads keep
lastRetries and then fallbacks.
longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay
New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)
Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
"patience 0 … want -1 kept".
Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
with "close of synctest channel from outside bubble", the known #3632,
in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.
Run again after rebasing on origin/main
|
||
|
|
d9a8148d7c |
routing: Speed first sends a request to the provider or key that answered the model fastest lately
joeliu96872540 on X: when one model is reachable through several API
channels, they want an option that sends each request to whichever has
been answering fastest, because they compare channel speeds by hand
today. Speed first (`fast`; `fastest` and `speed` also work) is a new
routing beside Free first. It applies to a provider's keys and accounts
(provider editor › Routing) and to a group of one model on several
providers (Routing page › group › Routing).
How it decides. When a streamed answer ends, gateway/speed.go records two
numbers for that account or key and model (restID): the time to first
token and the output tokens per second, as usage.DecodeOf computes them
for the Requests page. Each is a decayed average with a 20m half-life.
After an hour with no answer the record goes stale, and the store holds
at most 4096 records. This is O(1) at the answer choke point, beside
servedCandidate. For a pool routed by BySpeed, weighRouted reads one map
entry per candidate, and only for that pool. The usage history is never
read on a request.
routes.Fastest ranks each awake seat by its estimated time to a
200-token reply: TTFT + 200/TPS. A seat that reported no TPS gets the
median TPS of the others. Seats within 10% of the fastest in their band
keep their listed order, so near-ties don't swap on every request.
Seats with no recent measurement go after the measured ones. One request
in five, counted per pool, goes first to an unmeasured seat, rotating
among them, so each gets measured again. Resting seats go behind the
awake ones, and used-up seats behind those. Rests and failover are the
same as for every other routing.
The request trace gets lateTtft and lateTps, and the row-story sentence
says "answered m fastest lately: first token in 0.8s, 60 tokens a
second". It has a variant for a probe turn and one for when no seat has
been measured yet. i18n covers zh, zh-TW, ja and de. Also updated: the
CLI (`magpie group|provider set <id> routing=fast`, plus a new
`routing=` pair on provider set that refuses manual), the TUI name, the
rotation plugin's Sub, docs/subsystems/gateway-routing.md,
plugin-runtime.md, docs/reference.md and site start.html (en, zh, ja).
There is no new layout: it is one more item in the existing pickers.
app.js stays under its budget with no raise.
Tests:
- routes/fastest_test.go:
- ordering: fastest first, slow writer loses, alike keep order,
resting and used-up, median pace, none measured;
- the probe turn at 5, 10, 15 and 20, rotating between seats;
- a resting seat never gets a probe turn.
- gateway/speed_test.go:
- decay, staleness and per-model records, with an injected clock;
- a group of slowv and fastv routed fast: after the speeds are
measured and seeded, the request goes to fastv with lateTtft set;
- the same group routed in order still goes to slowv.
- cli: parseRouting and the provider routing= pair.
- GUI routing-speed-first.test.cjs: the row story for measured,
no-pace, probe and none, in en, zh, zh-TW, ja and de, in chromium and
webkit: 40/40.
Broken by hand:
- Fastest returning the listed order: the routes tests and the gateway
group test go red.
- noteTrySpeed removed: "the streamed answer wasn't measured".
- The client.js case renamed: routing-speed-first 0/20 in chromium.
Run at b5a5caff2 (base
|
||
|
|
41b0445ccf |
provider: a local server's address is a field shown first, and address= on the command line (LM Studio on another computer)
mengxiangziyou on X: "供应商里的LM Studio只能用本地的,怎么用局域网里其他机器 上的LM Studio, baseUrl 不能改". Moving a local preset (Ollama, LM Studio, oMLX, MLX-Serve) to another host has worked since #1165, but the window put the Address in a "Server address" fold under the key, while the Endpoints row showed http://localhost:1234/v1 as plain text. Reproduced in a sandbox: Add > LM Studio shows the URL and nothing to change it with unless the small fold is found. - GUI: the Server address field is shown first, above the key, never folded, for a new provider and a saved one alike (its label and hint are the strings the fold used, so no new i18n keys). Saving still sends the URLs moved only when the address was changed. - CLI: `magpie provider add|set <id> address=<host:port>` moves every URL the provider has (chat, Anthropic, Responses, decision), each keeping its path; from the preset's when it was saved with none, and `address=` alone puts a local server back at its preset's. A provider of the user's own moves its own URLs. Vertex refuses it as it does url=. Before, Ollama on another computer needed url= and anthropic=. - TUI: unchanged (asked on adding, `w` after). - docs/subsystems/providers-accounts.md: Local servers row. Security: only upstream URLs move. The gateway's own loopback/origin guards are about inbound requests and don't read them; the one rule that looks at an upstream being on the LAN (Unredacted) stays the user's own switch. Run at this tree (origin/main |
||
|
|
0152f66966 |
provider: a Remote magpie's model list follows the other magpie's, fetched every 10m (6igsteven on Discord)
6igsteven (Discord, 10-24/10-25): GLM-5.3-Trial and GLM-5.3-Flash-Trial are listed on the magpie that runs the ZCode plugin, and not on the magpie that uses it as a Remote magpie. The trial entries come from the ZCode plugin once it reads the account's gift (zcode 0.1.26), and the other magpie's /v1/models lists them as it lists every catalog entry. But a Remote magpie is a provider of keys: its list was fetched when it was added and then only when Fetch models was pressed in its editor (KeepListsFresh asks only providers with a RefreshEvery, FetchNew only accounts). So anything listed there later (the trial models, a new provider, plugin or routing group) never reached this magpie. A Remote magpie with no RefreshEvery now has a 10m schedule (RemoteMagpieEvery, RefreshSchedule), so KeepListsFresh refetches it through the same Refetch as Fetch models. `magpie provider refresh-every <id> off` on a Remote magpie is kept as "off" rather than "" so the user's off isn't read as unset. CLI show/refresh-every print the schedule in force. Other providers are unchanged: no schedule means only when asked. Run: TestRemoteMagpieListFollowsTheOtherMagpie (new) with TestKeepListsFreshFetchesWhatIsDue, TestParseRefreshEvery, TestSaveKeepsTheListsScheduleAndRules: ok, sandbox HOME, Go caches pinned. Broken by hand: RefreshSchedule returning RefreshEvery alone (the old behaviour) fails the new test with "asked [], want [office]"; restored, ok. gofmt -l clean. Then, at this commit: go test ./internal/provider ./internal/cli ok (140s, 58s); go vet ./... on darwin, GOOS=linux -tags nogui and GOOS=windows ok; darwin, linux (nogui) and windows builds ok. Not run: go test ./... - the machine's disk had under 1GB free (other sessions' work) and load ~200, so a full suite would not fit. Not tried: a real two-computer setup with a live ZCode gift. A Remote magpie whose user curated its picks (left a listed model unpicked) still doesn't take new models by itself (withNewlyListed, by design). |
||
|
|
5b2b3d3f50 |
providers: a switched-off provider says how to turn it on, after a sign-in too
Atlas (Discord) signed in to WorkBuddy AI with `magpie plugin login
workbuddy-ai`, and `magpie providers` then showed "○ switched off" with
nothing saying why or how to undo it. magpie never sets Provider.Off by
itself; only the user's own switch does, and a sign-in rightly keeps it.
So the setting stays as the user left it, and magpie now says how to
change it:
- `magpie plugin login <id>` and `magpie accounts add <id>` (plugin and
built-in paths), finishing for a provider that is switched off, print
"! <Name> is switched off in magpie, so agents aren't given its models
· turn it on: magpie provider on <id>". One that can't be found says
nothing (not known to be off).
- `magpie providers` puts "magpie provider on <id>" in the switched-off
row's last, unpadded column, so the key column keeps its width.
- The TUI's Providers row notes "o switches it on" (its `o` key).
- The GUI row already shows a "Switched off" badge and its own switch,
and the editor says how to switch it on: left alone.
Run, at this tree (base
|
||
|
|
a3b45eb91e |
provider: a re: pattern matches in any case, as a glob does (usrname1833 on Discord)
A routing group's patterns (Group.Match) and a provider's auto-include rules both compile through compilePattern. A glob compiled with (?i) and a re: pattern without it, so re:gpt-.* missed GPT-5.5 while gpt-* took it. A re: pattern now compiles as (?i)^(?:…)$; (?-i) inside it makes case matter again from there on (re:(?-i)gpt-.*). The Routing page's editor works out a pattern's models in JS (patternRe in plugins/routing/client.js) and refused what JS can't read. It now reads re: with the i flag too, and takes Go's leading flag group ((?-i), (?s), ...) as JS flags, so re:(?-i)OR/B is taken and matches as the gateway will. A flag group further in is still refused there (JS has no bare (?-i)); the CLI takes it. Said in groupmatch.go's comments, magpie group's and magpie provider auto-include's help, and providers-accounts.md (Routing groups, List schedule and rules). No GUI hint said a pattern's case, so none changed and no string was added. Run: - TestRegexpPatternIgnoresCase (new): ok. With compilePattern's (?i) taken off by hand: FAIL, "re:GPT-.* ~ gpt-5.5: false, want true" and three more cases. - group-patterns.test.cjs, chromium and webkit, en and zh: 4 of 4 ok. With patternRe put back to the old re: line by hand: 4 of 4 red, "(?-i) keeps case 0 !== 1" (old JS refused re:(?-i)OR/B). - gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. - go test -tags nogui -timeout 45m ./internal/provider ./internal/cli ./internal/gateway under a sandbox HOME at 1a956129c's tree: ok, ok, ok (380s). go build for darwin, linux (nogui) and windows: ok. - A full ./... run was started and stopped: the machine's disk was full (1GB free), and internal/agent's tests failed on "no space left on device" in TempDir, not on this change. No full suite ran. Not tried: the full suite (above); a real provider's auto-include fetch with mixed-case ids; the Linux app's WebKitGTK; a (?-i) further into a re: in the GUI. |
||
|
|
f5b0157420 |
gateway: a tool Claude Code's tool search loads goes to OpenAI's Responses API where it was loaded (#2660)
Through /v1/messages translated to a Responses provider, every deferred
tool ToolSearch loaded joined the top-level tools on the next request, so
the prompt changed from its first bytes and the cache missed on each load
(maximia's probe: cached tokens dropped on every request after a load).
Now, where Request.LoadedInPlace is set, a deferred tool (defer_loading,
Tool.Deferred) that a tool_result's tool_reference names (toolRefs,
Part.Loads) goes in an {"type":"additional_tools","role":"developer",
"tools":[...]} item right after the run of tool outputs that loaded it,
once, and not in tools (buildResponses). Parallel results and one result
naming several share one item; a tool named again isn't repeated; the
output's text is as before. A history whose loading result is gone
(compaction, edits) puts the tool back in tools: a new prefix, expected.
Scope (loadsInPlace): OpenAI's own API with a key (api.openai.com,
*.api.openai.com), whose tool search guide documents the item and says
its tools load at the end of the context so the cache is kept; and a
provider the user sets with `magpie provider set <id> additional-tools=on`
(Provider.AdditionalTools, kept by the GUI's save like codexAsSent).
Nothing else: xAI answers the item 422 (#350), the ChatGPT backend has
been seen taking it only for Codex's Responses Lite, Azure, plugins and
relays are untried. An upstream that refuses a request holding the item
with a 400/422 naming additional_tools is asked again with every tool in
tools, logged ("turned away additional_tools ... loaded tools go in tools
from now on") and not sent the item again while magpie runs.
Not handled: a tool a tool_addition block in a system message loads (MCP
late tools, the advisor) stays in tools. Not tried against a real
upstream: no OpenAI key or custom Responses relay was used; the item's
shape and position follow OpenAI's docs, and the fixtures follow
maximia's three-request probe (Claude Code 2.1.302) and the
tool_reference shape Claude Code 2.1.306's binary writes.
Tests: TestLoadedToolsKeepThePrefix (top-level tools and instructions
identical across the three requests, each input a prefix of the next),
TestLoadedToolsInOneItem (parallel, batch, repeat), TestLoadedToolsWhereNotTaken
(unsupported upstream unchanged; compacted; non-deferred),
TestLoadsInPlaceScope, TestLoadedToolsThroughTheGateway (off by default on
a relay, on with the flag, refusal retried without the item and not sent
again), TestAdditionalToolsPair (CLI). Broken by hand: with the
buildResponses placement disabled, the first two and the gateway test go
red; with the refusal retry disabled, TestLoadedToolsThroughTheGateway
goes red.
Run at cff7dc67d (this change on
|
||
|
|
1bd99194ea |
provider: Claude Code stays listed, signed out, when every saved account's sign-in is gone
LeeHom on Discord: two Claude Pro accounts vanished from Providers, and
signing one in again showed the other as "needs sign in again". While
Claude Code is signed out, the claude provider is built on
claudeStandIn's account. claudeStandIn skips an account whose sign-in
Claude Code let go of (claudeLoggedOut's claudeLogoutLapse) or that is
still Held. With every saved account like that, it returned "", no claude
provider was made, and the subscription and both accounts left the GUI,
the TUI and `magpie providers` at once.
claudeStandInAccount and Logins now ask claudeListed: the stand-in, else
the signed-out account seen last. A Held account is never listed this way,
because the sign-in Claude Code left on disk would then be served
(TestClaudeSignedOut still holds). The listed account's token still fails
with the lapse reason (claudeSavedDir), so nothing is served on it.
claudeStandIn itself is unchanged, since addLogin and logins_on rely on
it.
The app's row already said "{user} is signed out" when every login in use
had lapsed. Provider.SignedOut is that rule in Go. With it, `magpie
providers` says "○ <user> is signed out · sign in again" and the TUI says
"○ <user> is signed out", instead of a green "signed in". The CLI's key
column moved into keyColumn so it can be tested. The providers-accounts
doc row says this.
Tests:
- TestClaudeAllSignedOutStaysListed: signed in, a second account
logout-lapsed, then Claude Code signed out. It fails on the old code
("Claude Code left the Providers list with every account signed out:
false") and with SignedOut returning false (both broken by hand).
- TestProvidersSaySignedOut, in cli and tui: a signed-out account reads
as signed out and a signed-in one still reads as signed in.
Run: gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./...; go build for all three.
Then go test -timeout 45m ./... under a sandbox HOME at base
|
||
|
|
4896fc3ba1 |
codex: a thread magpie compacted goes on after magpie is quit or disconnected (LukeMa on X)
When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).
Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.
- Only magpie's compaction items change; other lines keep their bytes,
the file its line count, mode and time. An unreadable one is left out
of a list with its replacement_history_metadata entry, as Codex's own
ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
rename, under thread-writer-locks/.coordination.lock and only with the
thread's lock free. A thread a Codex has open is left for a later pass.
A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
pass reads rollouts written since 2026-09-24; later ones only what
changed since the last whole pass, plus what was left held
(codex-portable.json in magpie's folder).
Run at this series' head (on origin/main
|
||
|
|
81a24cf8fe |
groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.
What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
public one). Every old form is still accepted as input forever:
provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
gateway (validateModel), keys, stats, affinity and usage, so both ids
route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
(allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
exists, found groups are listed by their old id (AutoRefsOn) and
auto/<x> means that provider's model. Documented in
docs/subsystems/gateway-routing.md.
Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).
Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.
Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
gateway, whose failures were the tests' expected ids (updated here)
and two regressions now fixed (bare ids; desktop models hiding groups
by prefix). Every failing test passes on rerun. Load average was
~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
10.19s), and it fails the same in a git-archive export of
|
||
|
|
0f1666b387 |
provider: a built-in can be retired, its plugin serving it moved or not, and its unmoved accounts get a Move line
The owner (10-16) wants every deprecated built-in taken out of magpie,
one at a time. This is the ground for that; it retires nothing yet.
- retiredBuiltins / BuiltinRetired(id) in migrate.go name a built-in
whose code is gone. Only an id with a mover can be retired.
- PluginServes(id) is Moved(id) or retired. Every gate that asked
Moved(id) asks it now: sign-in, Factory keys, usage, logins, cards,
forget, accounts, check-ins, plugin sign-in, the CLI's accounts and
providers, the GUI's account label.
- A retired row's move.state is plugin, and its id is in onPlugins
once the plugin is installed.
- /api/providers lists a retired subscription's built-in accounts that
haven't moved in `unmoved` (MoveCandidate, now with the failed move's
error and why). The GUI shows a quiet line over the Providers list
for each, with Move / Try again (unmovedLine), in en, zh, zh-TW, ja
and de.
- AGENTS.md and docs/subsystems/provider-plugins.md say what a retired
built-in is.
Run at 270aa1c9c with this change:
- go test -tags nogui ./... -count=1 -timeout 90m: 66 packages ok.
- gofmt -l internal: nothing. GOOS=linux and GOOS=windows
go vet -tags nogui ./...: clean.
- GUI, both engines, en and zh: retired-move (new, 4/4), plugin-move,
deprecation-notice, deprecated-subscriptions, plugin-move-unserved,
plugin-movable-review, i18n-keys: 39 pass.
- TestRetiredBuiltinIsThePlugins -count=20 (it picks a mover at random).
The Move line is the Providers list's own, not a page that could be a
plugin. It took the core's scripts to 1,427,218 bytes, which the budget
main raised in
|
||
|
|
dc8dcc85d1 |
provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.
- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
the user's own Balance URL only; a vendor magpie knows is asked as
before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
other value is refused and the saved one kept); `magpie provider <id>`
shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.
Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
a POST-only httptest server, POST (any case) reads $0.94 from a string
usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
("asked GET, want POST"); balanceMethodOf passing any method turns it red
(PUT and DELETE sent); the CLI taking any value turns
TestProviderSetBalanceMethod red; the Check balance body without
balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
named and titled in the language, fits beside the URL with no page
scroll, the other pick goes in the check and save bodies). Siblings:
balance-parts, balance-field-default, balance-fix, catalog-hint,
duplicate-pause, key-balance-card, local-address, provider-base-api,
provider-auth-header, provider-gemini, provider-search,
provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
Default: "unavailable 405 Method Not Allowed"; balance.method=post:
"$0.94 from POST …/api/check-balance $usd_balance", the server saw one
POST with Content-Length 0 and the Bearer key; balance.method=PATCH
refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.
Full suite: SUITE_LINE
|
||
|
|
82f48f0935 |
gateway, provider, gui: a provider set to compact natively is asked Codex's compaction_trigger as sent and its sealed compaction goes back unchanged; a checkpoint stays with its writer (#1099)
A new per-provider option, off by default. With it on, Codex's compaction_trigger reaches the provider as Codex sent it, and the provider's encrypted compaction item goes back to Codex unchanged instead of magpie's magpie1: summary. Off, nothing changes. Where it can be on (provider.CarriesCompaction): a provider with a Responses API (Sub2API and other OpenAI relays, a remote magpie), a ChatGPT (codex) account, and the built-in GitHub Copilot on its GPT Responses path. Copilot's Claude models are asked on chat completions, so they still get magpie's summary (CompactsOn). A group compacts natively only when every member does. No silent downgrade: - A turn carrying a sealed compaction goes only to the key or account that wrote it (compactions.json beside affinity.json, 0600, 1024 entries / 30 days). With none left, Codex gets a 400 saying the conversation was compacted natively on <who>, not a summarised or dropped context. - A provider whose request would have to be translated (not relayed) is refused with a 400 instead of losing the item. - The upstream's own refusal goes back to Codex as it came, one call. - base_instructions and Codex's identity are untouched. Turning it on: - GUI: the provider editor's Compaction row, "Codex compacts on this provider" (shown only where the wire can carry it; zh, zh-TW, ja, de). - CLI: magpie provider set <id> compaction=native|magpie. A provider that can't carry it is refused. Run on origin/main |
||
|
|
22512cde53 |
provider, gateway: rest-cap off never rests a provider's keys after an unknown failure (Kismet Alan on Discord)
A relay or account pool fails now and then with errors that say nothing
of why (a 5xx, a dropped connection), and the next request often goes
through. Every such failure rested the key or account a minute, doubling
up to 10, and `rest-cap` could only move that cap (1 minute at least;
`off` read as `default`).
`magpie provider rest-cap <id> off` (provider.RestCapOff, restCap: -1 in
providers.json) now has a failure that says nothing of why (failOther)
rest nobody and not count toward the backoff: restAfterMarked returns a
Rest by "off" with no time left. What says why still rests as before: a
401 or 403, a model not served (restID), an account's window full, a
rate limit (magpie's own 30-minute cap; RestCapOr treats off as unset),
quota, credit, a restriction. `rest-cap <id> 30s` is turned away and names
1m and off (the first rest is a minute already). The Routing page tells a
try rested by "off" as not resting (one new string, zh/zh-TW/ja/de).
No "fail N times before switching" counter: a failed try already moves
the same request on to the next key or member, so a count would only
keep requests on a failing upstream longer.
Run:
- TestRestCapOff (gateway), TestRestCapCmd (cli), TestOwnRestCap: pass;
each goes red with the change taken out by hand (the early return
disabled: "#1 500: rests 59.99s by backoff"; restMinutes in place of
restCapMinutes: "off: <nil> 0").
- routing-rest-off.test.cjs: 20/20 (chromium, webkit; 1100, 420; en zh
zh-TW ja de); red 10/10 with the "off" case renamed.
routing-wb-restricted 20/20. rest-try-now and routing-model-rest fail
a varying few under load average 200-420 here, and fail more on
origin/main
|
||
|
|
ef0c515eb0 |
provider: a sub2api or new-api account query left without its token asks the key's query instead (lx_78654 on Discord)
The editor's "Use …/api/v1/user/profile" sets the Balance URL to the sub2api panel's account query, which only the login JWT can ask. Its Remove button clears the token but not the URL, so the profile query was then asked with the key, refused with 401, and the Usage card said "Allowance unavailable" for good. keyQueryOf now asks the same panel's key query when the Balance URL is an account query (sub2api /api/v1/user/profile, new-api /api/user/self) and no token is set: /v1/usage and /api/usage/token, with the key, their own default field unless the user wrote another. The saved URL is left as set, so pasting a token again asks the account query again. A provider whose Headers carry its own Authorization or Cookie is asked as set. It covers every reader: the Usage page and `magpie quota` (KeyBalances), the editor's Check balance, routing's key windows (sub2APIKeyLimits), and `magpie provider <id>`, whose "from" line now says the query actually asked (BalanceQuery). Run: - TestAccountQueryWithoutTokenAsksTheKey (httptest sub2api + new-api): JWT, removed, JWT again; new-api without token; custom field kept; account query never asked with the key; own Authorization kept. With keyQueryOf a no-op it fails with the reporter's 401 card. - Sandbox CLI (scratch HOME, fake sub2api on 127.0.0.1): old binary, after `provider set sub2 balance.token=`, `magpie quota` shows "401 Unauthorized…"; new binary shows "$7.25 left", from /v1/usage. - go test -tags nogui ./internal/provider/ ./internal/cli/ ./internal/tui/, and internal/gateway's balance, allowance, quota and key-limit tests. The full `go test -tags nogui ./...` passed every other package; internal/gateway and internal/agent ran out of time (10m, then 40m) with the machine at a load average of ~300-370, the tests running at the deadline seconds old, so not a hang; neither run finished. - gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows. Not tried: a real sub2api or new-api account; the GUI not clicked through (no asset changed, it reads the same KeyBalances). |
||
|
|
1a5128747b |
cli: magpie provider refresh-every and auto-include set a list's schedule and rules (#2135)
`magpie provider refresh-every <id> 6h|1d|off` and `magpie provider auto-include <id> 'gpt-*' 're:claude-.*'|none` set the fields the previous commit added; `magpie provider <id>` shows them, and `magpie provider refresh` prints the models its rules took. TestRefreshEveryAndAutoIncludeCmds: a too-short or unreadable time and a plain id as a rule are refused, the rule takes the current matches, and none/off clear both while keeping the picks. Run with the go test in the previous commit's body. |
||
|
|
d9ca84a2f4 |
gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file> --tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the web UI on its listener then serve HTTPS to other computers. Without them nothing changes. - Half a pair, a file that doesn't parse, or a flag with no value is refused at start with a message naming the missing flag. - The pair is re-read when either file's mtime or size changes (certbot renewal), with no restart. A renewal that doesn't parse keeps the certificate already served and is logged once. - Other computers get HTTPS only. Plain HTTP from them gets net/http's 400 "Client sent an HTTP request to an HTTPS server". - This computer (loopback, or a peer address equal to the local one) may still use plain http on the same port. Its connections are sniffed on their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a silent client holds nobody else up. gateway.URL() stays http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the healthcheck and daemon status all use, and no certificate covers loopback. - WSL NAT and containers count as other computers. - ALPN is http/1.1 only (hijacked connections and websockets need it), with TLS 1.2 as the minimum. - Printed links, LAN addresses, publicURL, the serve/web banners and daemon install show https:// for other computers' addresses. - The DNS-rebinding Host checks (foreignPage, rebound, the MCP loopbackHost) don't depend on the scheme and are unchanged. - daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall or `daemon web on` that names no certificate keeps the installed pair, and --no-tls removes it. - Docs: reference.md gets an HTTPS section that names Caddy as the alternative, gateway-routing.md gets a TLS row, and docker.html (en, zh, ja) gets the env rows. What was run: - New tests: internal/gateway/tls_test.go (others HTTPS-only, this computer both, a silent local client holds no other, renewed certificate served, CheckTLS, addresses, Relisten keeps TLS), internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux and darwin, paths with space, %, & and "). - Each was broken by hand and went red: no wrap in listen, no reload, a synchronous sniff, a bad renewal dropping the certificate, http in publicURL or the pinned LANURLs, the carried entries removed, and keepTLS as a no-op. - Real use under a sandbox HOME, with a self-signed pair, on 0.0.0.0:3461: - Half a pair, a garbage certificate, a flag with no value, and the env set to half a pair each exit 1 with the message. - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key: 200. Plain http on loopback: 200. - The cert files were swapped for a second pair while it ran. openssl s_client then showed the new CN and serial, and curl --cacert with the new pair got 200. A junk key file then kept the second pair, logged once. - From the Windows box over the LAN: plain http got 400; https with the key got 200, and without it 401. - magpie web --addr 0.0.0.0:3462: https network links. From Windows, http got 400 and https with the key got 303. - gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and GOOS=windows. - go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS tests of ./internal/gateway and ./internal/gui: all pass at the rebased head. - Two reds in the full suite (`go test -tags nogui ./...`) are the same on origin/main f074996d9; both are filed: - TestGatewayHeldByAContainer failed 2 of 5 there (#2107). - The gateway package runs past go test's default 10m under load: 1208s on main and 1221s here, both passing with -timeout 40m (#2108). |