ac4af582301a4e8a29245dbba767eba31334ddf9
88
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
92e8edd7fc |
windows: magpie is listed in Installed apps, and its Uninstall puts every agent back
Jevik_AI on X uninstalled magpie and rebooted, and Codex's config.toml still had openai_base_url = "http://127.0.0.1:3425/backend-api/codex"; Rk1ngggg asked whether an update cleans it. magpie's own uninstall (Settings › About › Uninstall magpie, `magpie uninstall`) already disconnects every agent and takes Codex's leftovers (#3866), but on Windows magpie wasn't in Settings › Apps › Installed apps, so it was removed the way Windows offers for a program it doesn't list: by deleting the exe and folders, which runs no code. shortcut.Ensure now writes HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie (DisplayName, DisplayIcon, Publisher, InstallLocation, UninstallString, URLInfoAbout, NoModify, NoRepair) at every installed start, beside App Paths, and Remove (uninstall's System step) takes it out the same way: only while it names this exe, or an exe that is gone. Its Uninstall runs `magpie.exe uninstall --window` (shortcut.UninstallArgs). magpie.exe has no console, where the terminal's `magpie uninstall` would refuse for want of one to ask on, so those exact args open the app's window (or forward to the running app, OnSecondInstanceLaunch) on Settings › About with Uninstall magpie's question asked (uninstallView, ?uninstall=1). It asks once: a redraw of Settings doesn't ask again, and Cancel removes nothing. magpie web opened at that link asks nothing. Deleting the app by hand still runs no code (macOS drag-to-Trash included); agent-wiring.md says so. Run on mote at the pushed head (rebased onto |
||
|
|
39569d5604 |
claude desktop: an optional Claude Magpie app beside your own Claude (#5671)
baranwang on X asked to keep Claude Desktop's own (1P, Anthropic) sign-in while using magpie. Turning on "Separate app" in Claude Desktop's row on the Agents page (or `magpie claude-desktop launcher add`) moves magpie's 3P wiring into ~/Library/Application Support/Claude-Magpie-3p and adds ~/Applications/Claude Magpie.app. That launcher opens Claude.app with --user-data-dir on that folder, so it runs side by side with the user's own Claude.app. Its icon is Claude's icon with a magpie badge. Off is the default, and turning it off (`launcher remove`) moves the wiring back and removes the app. It is macOS only: Desktop's packaged app strips CLAUDE_USER_DATA_DIR, and on Windows it hardcodes LOCALAPPDATA\Claude-3p. The folder ends in -3p because Desktop adds -3p to any other name. Restarting the isolated app ends only its own process (pkill on its --user-data-dir) and opens the launcher again. Run at 1b25cda26 (this change on origin/main |
||
|
|
608c1543e8 |
gateway: a bare model name goes to the asking agent's own subscription first
freefcw on X: Codex, started by Mirasim, asked for gpt-6-astra by its bare
name. Its own ChatGPT subscription serves it, but magpie sent it to Devin
through the group it found (auto-gpt-6-astra, soonest renewal first).
With found groups off it still went to another vendor: Resolve takes the
first provider in the Providers order, AutoStandIn and agent.Reseat did
the same.
Now:
- A bare model id the asking agent's own subscription in magpie serves (a
provider whose Account.Agent is the agent: Codex's ChatGPT accounts,
Claude's for Claude Code, Copilot's) goes there, found groups on or off
(gateway ownFirst, provider.OwnRoute). count_tokens counts it there too.
- Kept as they were: a group the user made or changed by that name; a found
group magpie set one of the agent's fields to (agent.SetToGroup over the
applied record, #750's bare spelling included, wired as
gateway.SetToGroup); a gateway key held to some models; ids with a
provider in them and group refs; clients magpie doesn't know as an agent.
- Found groups off: a bare id several providers serve, none of them the
agent's own, is refused for an agent that has a subscription of its own
in magpie, with a 400 naming the provider/model ids and
"magpie group auto on" (provider.OffSpread). Off, magpie picks no vendor.
- AutoStandInFor and Reseat's sameModel prefer the agent's own
subscription for a found group that is gone.
Docs: gateway-routing.md's Model resolution row and the bare-ids section.
Run (mote, at this tree on
|
||
|
|
e215d335a6 |
gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.
- access: Key and Change get MaxConcurrency, and Identity carries it, the
issuer's cap included. The concurrency-key action refuses a value
below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
key's cap, however the request came (loopback, LAN, a Remote magpie, a
Responses socket's turn). One request too many waits in the key's
queue in arrival order. It shows as "slot" in Active, and its wait goes
into the try's Queued. A request whose agent goes away while it waits
leaves the queue and sends nothing. A stream holds its slot until it
ends. serve's routes (chat, responses, messages, ollama, gemini, the
Codex backend) wait inside the try, after keepQueued, so a streaming
agent gets keepalives while it waits. The other model routes (images,
embeddings, rerank, audio, videos, search, decisions, native) wait
before their handler runs. forward and codexUpstreamOn take the slot
too, so nothing reaches a vendor without one. A key issued under
another waits for its own slot, then for its issuer's.
/v1/magpie/concurrency lists each capped key under "keys", and counts
its waiters in "waiting". A key's limit (key_limit) reports the cap.
Not held, as a provider's MaxConcurrency doesn't hold them: GET,
HEAD, OPTIONS, count_tokens, :countTokens and MCP.
TestKeySlotEveryRoute fails when a route is judged neither held nor
free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
negative, over 1000, a fraction, a word, --help or an extra argument
with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
and Other… takes a number typed in place. A value that isn't a whole
number up to 1000 is refused and nothing is sent. Browser and
read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
de. An unset badge, which a hover shows, gives way before the masked
key (flex-shrink 8). Without that, at 420px in en and de, the extra
badge squeezed the key until its copy button slid under the pointer
that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.
Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto
|
||
|
|
cdf734757a |
agent: OpenMausBot gets magpie's models back, and a Restart for a list it hasn't read
maxleebeta (Discord #feedback, 11-08) picked Antigravity's models in
magpie, and OpenMausBot's model search didn't find them. magpie wrote them
correctly: a sandbox with an Antigravity sign-in lists
antigravity/gemini-3.8-flash[1m] and the others in config.json. OpenMausBot
loses them in three ways, each reproduced on the real app:
- it reads config.json once, at start, so a list magpie writes while it
runs never reaches its picker;
- a change to any engine in its Settings writes back every engine as it
held them since it started, so magpie's newer list is replaced by the
old one;
- an edit of magpie's engine there (updateClaudeEndpoint) keeps only the
model picked.
Nothing in magpie wrote the list again: a sync runs on a catalog change,
or when magpie starts.
- KeepOpenMausBotListed (gateway.WhileServing, every 30s) writes magpie's
list again when the file lists other models (ombListStale). The model
picked in OpenMausBot (ANTHROPIC_MODEL) and its other engines stay. It
isn't a Check drift: that reads as unwired, and a port change rewires
only agents without one.
- OpenMausBot gets a Restart on its Agents row (restartApps: OpenMausBot.app,
OpenMausBot.exe; appReads: ombPart = gateway, first model, list, not the
key), so one running on an older list is offered a reopen. Its own save
of the same engine after it starts doesn't count.
The same gap in NewMax, LiveAgent, OpenPencil, OpenBot, Pencil and ZCode
is #5662.
Run (mote, at this tree rebased on origin/main 00198b26e;
|
||
|
|
d55881730d |
gateway: a key can be held to some MCP servers and tools
wakaka on Discord (#help, 11-06) asked for gateway keys limited to some MCP servers and tools, as keys already are to models (#882). A key's MCP list (caller-keys.json "mcp") holds entries "server" (every tool of it) or "server/tool"; "-" alone is no MCP server; an empty list is every server, as before. A key issued under another is held to its issuer's list too. Every MCP route checks it: - magpie's own servers (web search, vision, image, Magpie Browser, plugin tools) through serveMCP: initialize/tools/list/tools/call are refused or filtered per server and tool, and /v1/magpie/key-limits names "mcp"; - the Library hub ("magpie"): only the backing servers and tools the key may use are listed, and a call by name or by fallback is refused; - /mcp/<name> and /mcp/run/<name>: the server is refused, tools/list is filtered in JSON and SSE replies, tools/call refused; a reply the filter can't read (an encoded body) is a 502, never passed through. GUI: "MCP servers" in the key row's menu opens the app's own picker (no native select) with All, No MCP server, each server and its tools (GET /api/caller-keys/mcp lists magpie's own servers and the Library's). A key held to some shows a badge saying which, that opens the same list; a free key shows nothing more in its row, on hover either. A hover badge was tried first: it pushed the row past 560px (gateway-caller-keys) and squeezed the masked key under a drag at 420px (gateway-key-arrange). CLI: magpie gateway-key mcp <id> github fs/read_file | none | all. zh, zh-TW, ja, de strings; docs/reference.md and the gateway-routing and library subsystem pages. Not covered: a model's own built-in web search (a vendor tool, not MCP). GET /api/caller-keys/mcp is named in the CLI parity test's notYet (its list is what `magpie gateway-key mcp` takes; TestEveryRouteHasACommandOrIsNamed caught it at the rebased head). Run on mote (mote-run), at the pushed head: - go test ./internal/access ./internal/cli ./internal/gui ./internal/library ./internal/gateway at a9c40186d (this change on |
||
|
|
1f439ecc5e |
gateway keys: a limit can count only some models or providers (zola_xynb)
zola_xynb on X asked for a cap per model or per provider under one gateway key. A key limit can now name models (access.Limit.Models, "<provider>/<model>" or "<provider>/*"), so one key can have, for example, a month of $20 on openai/* next to a month for the whole key. Limits without models still cover the whole key, as before. - budget: sums are kept per window and scope, and count a ledger row only when its provider/model matches (any of the model's ids). reserve holds a request to a scoped limit only when the model it names is served there. windowsOf keeps every scope's sums, so the ledger is not read again on each request. - gateway: keyLimited puts the key's spent scopes on the caller (withSpent), count_tokens included. A direct request for a spent model gets a 429 with Retry-After and no X-Magpie-Limit-Reset, so a remote magpie rests only that model. A routing group, a provider's fallback and embedding/image/video/decision groups skip spent members (groupKeeps, allowedCandidates) and get a 429 only when none is left. System One, count_tokens and magpie's own calls for the key are held too. Model lists are unchanged. A refusal turned away before routing now records its ErrType in the ledger. - CLI: magpie gateway-key limit <id> add month --cost 20 --model openai/* (--model repeatable, --models a,b). - GUI: the key limit editor has a Models field that opens the app menu (multi-pick: All models, every model of a provider, each model). It has no <select> and no new screen. The badge, line and tabs name the models. Strings are in every language. - docs: reference.md and subsystems/gateway-routing.md. Run at d52725d32 (this change on |
||
|
|
f9e6061b85 |
claude: claude-magpie runs Claude Code through magpie, a plain claude left on the user's account
baranwang on X (11-06): `claude` stays on the user's own Claude account, `claude-magpie` goes through magpie, and nothing is switched back and forth. `claude-magpie` runs `magpie claude run [args…]`. That writes a settings file of magpie's own, <config>/claude-launch/settings.json, connected as Connect connects Claude Code (the gateway, its key, the shared LAN key when sharing is on, the model, the tiers) and starts `claude --settings <file> args…`. Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell's variables (tried on 2.1.318), so ~/.claude/settings.json is never rewritten. ANTHROPIC_API_KEY and the cloud switches (Bedrock, Vertex…) are blanked in the file, so neither the user's file nor the shell can take a request past magpie. The file is the agent `claude#launch`, listed nowhere: the Agents page, Check and Notice see only the user's file. It is set again when the gateway moved or its key changed. - /model in a claude-magpie session saves to the user's settings.json (Claude Code never writes a --settings file). After the session a magpie model picked there moves into the launch file, for the next claude-magpie, and the user's file gets its model back. A Claude alias (sonnet) stays. - Claude Code's own one-time `opus` -> `opus[1m]` rewrite of the user's file (migration_opus_to_opus1m), which the launch file's 1M opus tier sets off, is undone the same way. Found in the end-to-end run below. - claude runs as a child so that can happen: on Unix a stopped child stops magpie too (^Z, fg; proc.WaitFollowingStops reaps it with WUNTRACED, as cmd.Wait can't see a stop), and claude's exit code is magpie's. On Windows magpie ignores Ctrl+C while claude has it. - The command: a launcher beside the `magpie` command. Settings › Command line (AddCLI) writes it; `magpie claude launcher [add|remove]` adds it for a command put there before. It is a `#!/bin/sh` exec of magpie's stable path, or on Windows a .cmd running "%~dp0magpie". A file by that name without "written by magpie" is never written over. - Docs: agent-wiring.md, and the start page in en/zh/ja. Run at this commit (rebased on origin/main |
||
|
|
9d143eacab |
uninstall: install.sh --uninstall disconnects every agent first, a deleted magpie too
whimsical_wolf_15477 (Discord): after uninstalling magpie, Codex didn't go back to its own config. `install.sh --uninstall` deleted the magpie command and app and left every agent wired to a gateway that no longer runs: Codex kept openai_base_url (or model_provider = "magpie" and model_catalog_json) pointing at 127.0.0.1. A magpie deleted by hand undid nothing either, and `--purge` refused with no magpie left to run. - `magpie uninstall --keep-data` (uninstall.KeepData): every agent disconnected and its own values put back from stash.json, the service, autostart, shortcut, scheme and helpers removed, magpie's settings, providers and usage kept. - install.sh --uninstall runs `magpie uninstall --yes --keep-data` (--purge: `--yes`) before deleting anything, and stops if it fails. With no magpie of its own (deleted by hand) but magpie's config left, it fetches the newest release into a temporary folder, checks its sha256, runs that, and deletes it after. An older magpie without --keep-data gets the newest one for this too. A magpie on PATH that the script didn't install is left to its own `magpie uninstall`, and said so. - MAGPIE_UNINSTALL_SCRIPT=1: under the script magpie doesn't ask to delete a path that the script deletes next. - docs (en/zh/ja start.html #uninstall) and READMEs: what the line does, that it works for a magpie already deleted, and Codex's lines by hand. Run (WSL magpie-desktop; mote's disk is full, nothing run or deleted there): - go test -tags nogui -run "Uninstall|Help|TestKeepData" ./internal/cli/ ./internal/uninstall/: ok. node --test site/install.test.mjs: all pass. - The new install tests against the old install.sh: 5 red. Broken by hand (--keep-data case removed, Data() back in KeepData): TestUninstallKeepData and TestKeepData red. - Real e2e: magpie built from this tree, Codex wired in a sandbox HOME (not signed in, and ChatGPT signed in), magpie installed and deleted by hand; install.sh --uninstall with a local feed. config.toml's diff before wiring vs after is the [model_providers.magpie] table only (kept on purpose for threads started on magpie); model, effort, openai_base_url, model_provider and model_catalog_json are the user's again; settings kept. - gofmt -l clean; go vet GOOS=windows/darwin/linux (nogui) for the two packages; sh -n and dash -n install.sh. Not tried: macOS's zip path for a deleted magpie run for real (tests cover it with fakes), Termux, Windows (no install.sh there; docs say download magpie again and use Settings › Uninstall). The full internal/cli package timed out at 10m under WSL load in providers_unreadable_cli_test (not touched here); see the full suite record. |
||
|
|
234903cb23 |
cli: magpie model api sets the API a model is asked on, as the editor's picker does (yew_fence_931206)
A relay with many models behind one key can now have each model's API
set from a script, not only in the provider editor's Names, prices &
levels ("API this model is asked on"):
magpie model api <provider/model>... chat|responses|anthropic|gemini|auto
magpie model api <provider/model>... --reset (auto)
magpie model api <provider/model> what it is asked on
magpie model apis [<provider>] the settings; with a
provider, every model
It saves through provider.SetModelPrefs, the editor's Save, into
settings' modelAPIs, so a running gateway reads it on the next request
and the agents' model lists are told once. Choices are those the editor
offers (modelAPIs in app.js): the APIs the provider has a URL for, when
it has two or more; Vertex AI none. --help anywhere prints the usage. A
flag in place of a model, an unknown API, a model the provider doesn't
list, or an API it has no URL for is refused; several models are all
checked before any is written. A saved setting for a model the vendor
no longer lists can still be reset. Documented in docs/reference.md
("The API a model is asked on") and the gateway-routing page.
Run (mote, via mote-run, at this tree on
|
||
|
|
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
|
||
|
|
75e30625f5 |
plugin: a command that serves no pages moves a page's service off the app's port (#5187)
MYCF711 (#5187, Windows, 0.1.2901): magpie plugin update run while the
app runs hung with no output. Its host loads every plugin, and
page-chat's service waits for port 3477, which the app's host holds:
each CLI command that starts a host waited ~6s on it, then kept trying
the port every second in the background, so it could take 3477 from
the app's host when that restarted after the update.
Now magpie run with a command that serves no pages (anything but the
app, tray, tui, web, serve, a bare magpie or a magpie: link opened in
the app; servesPages) sets plugin.ServePages(false), and its host hands
a plugin whose magpie.page.service names an option a free port of its
own in that option (hostOptions). The plugin's other parts load at once
and the app's port is left alone. plugins.json is not changed, and a
service no option moves is started as before. The class, not
page-chat: any plugin page service declared with an option.
Run, at base
|
||
|
|
d136d0fe98 |
gateway-key: rotating a key can give it a value of the user's own (isaac_bai)
isaac_bai on Discord: a gateway key's value is random, and only rotate changes it, to another random one; they want to set one easy to pass on. Adding a key could take an own value since 6b6113aa; an existing key couldn't. - access: rotate-key takes Change.Secret. Given, it is checked as an added key's own value (ownSecret: 8-256 printable ASCII, no space, not sk-magpie-, no other key's value; its own current value is allowed); empty, magpie makes one as before. The key keeps its id, name, limits, models and accounts, and Named counts a request from this computer with it as that key. - ownSecret now refuses a value that is one of the user's provider keys (a provider's Key or any of its Keys, constant-time), for add-key too: a client sending it would spend that provider directly. - CLI: `magpie gateway-key rotate <id> --key <value|->`; docs/reference.md. - GUI (plugins/gateway/keys.js, outside the core budget): the Rotate key dialog has a hidden "Your own key (optional)" field; Enter rotates, Escape cancels; an own value says "Gateway key changed. Clients that send this key reach magpie now." Strings in zh, zh-TW, ja, de. Tests: TestRotateToOwnValue (bad values refused, old value still works after a refusal, trimmed own value authenticates as the same key, is Named, listed masked; empty makes a new key; add-key refuses a provider key). TestRotatedOwnValueKeepsTheKeysLimit: after rotating to an own value the old one is 401 from another computer, the own one 200 from another computer and from 127.0.0.1, and a 700-token day limit stops the third request from either (429), every record under the key. gateway-key-own-rotate.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de, 1000 and 400px. Run (mote): at the pushed head: TestCoreScriptBudget ok, ./internal/access ok, the own-key/caller-key gateway tests ok. At |
||
|
|
900ae0fa51 |
backup, sync: sign-ins go too when picked, sealed, never over a later renewal
qianxunji (#feedback) and curtinp118 on Discord: a VPS restored from a backup, or a new computer joining sync, had to sign in to every subscription again. Sign-ins (subscription accounts in logins.json, Codex's auth.json, plugins' sign-ins in plugin-auth.json) can now go too, in each place only when picked; all are off by default, so an upgrade carries nothing new. - Sync (WebDAV, S3, GitHub): a "Sign-ins" tick in the form, with a line saying anyone with the passphrase and the server's file can use the accounts, and that an account on two computers can be signed out on one when the other renews it. CLI: `magpie webdav|s3|github set sign-ins=yes`. - Export: "With the sign-ins", off; ticked, the passphrase hint says the file holds them. CLI: `magpie backup --sign-ins`. - Import: "Bring in the sign-ins too, when the file has them", on. CLI: `magpie restore --no-sign-ins` leaves them out. - Back up by itself: "Sign-ins in backups", Off/On. On asks for a passphrase (twice) that seals the sign-ins alone (the rest of an automatic backup stays unsealed, as before); it is kept in autobackup.json (0600), never sent in the view. A backup whose sign-ins another passphrase sealed restores without them and says so. What goes (provider.CollectSignIns, plugin.CarriedAuth): magpie's own copies only, not an agent's own account, an agent-home row, a hidden or plugin: row, or a retired built-in. Each record is keyed by agent + email + org (or the account key); ids two rows share go on neither side. Restore/import (RestoreSignIns) adds what is missing and updates only when the incoming copy was renewed later; nothing here is removed. Before writing over a row it counts every row that could be the same account (same login, same refresh token, same id): none adds, several keeps all, one is kept when it isn't magpie's own copy, is held, or is the agent's live account. Codex's auth.json is written temp-and-rename, 0600, only where Codex is signed out. Sync merges per record against the last sync's hashes (MergeSignIns): the later renewal wins; a removal crosses only when the other side still had it as of the last sync; ApplySignIns re-checks each row's hash before writing so a renewal in between is kept. A computer with the tick off sends none, so others remove nothing for it; turning it off, a Restore, or a replaced server file clears the last-sync record. Export's and Import's forms moved out of app.js into syncfiles.js, imported when one opens (as autobackup.js is), so the core is 3.2KB under its budget with no raise (app.js 3.2KB smaller than before). docs/subsystems/sync-backup.md has a "Sign-ins, when picked" section; subscription_signin_test.go's header now says it pins the default. Run at the pushed head (678d28cba on origin/main |
||
|
|
b295d11965 |
serve, update: one magpie works the gateway; the service waits, the copy an update left stops (#4938)
ox01024's #4938, Bug 2. Two magpies did the gateway's work at once on a Mac: - launchd's com.yetone.magpie.serve ran `magpie serve` beside the app. It ran startUp (plugin Settle/Refresh, FoldCopies, Hold, the agent moves), the plugin host and every account's model fetch, then failed to bind, exited 1 and was started again 5s later: 6,035 times in two days, a 279MB serve.log, and logins.json.lock held against the app's requests until they went 504. - The copy an update left (.magpie-update/old) handed the socket over, hid, and lived on ~3h, its loops writing beside the new one. What changed: - cli: `magpie serve` (no --web) checks codexrelay.Leave, gateway.ServedBy and gateway.Taken before startUp, as the app's serveGatewayLocked does. While the port is held it prints one line and looks again every 15s, doing nothing else. Once the port is free it serves (serve_wait.go). It waits rather than exiting 0: under KeepAlive SuccessfulExit:false a clean exit would leave no service after the app quits. - gui: after a handover the old magpie's loops end with backendCtx: - library.KeepLinked (now takes a ctx), - provider.WatchQuotas, - the menu bar usage loop, - the updater's check/auto-restart loop. lighten lets its hidden webviews go as lightweight mode does, so their polls stop. quitBy exits it at handedOffDrain + 3m whatever holds its quit up (gateway.HandedOffDrain getter; exitNow stubbable). - docs/subsystems/gui-shell.md says both. Run at the pushed head on mote (mote-run): - gofmt -l internal/: nothing. go vet ./internal/{cli,gui,library,gateway}; GOOS=linux go vet -tags nogui and GOOS=windows go vet of the same: ok. - go test -count=1 -timeout 45m ./internal/cli ./internal/library ./internal/gui ./internal/gateway at |
||
|
|
1cb4d43013 |
profiles: a saved profile renames, in its details, the TUI and magpie rename (#2721, erlinerd)
erlinerd's patch on #2721 (profile.Rename, /api/state profile/rename, a Rename button in the details), reviewed against main and adapted: - profile.Rename trims both names, refuses an empty, taken or missing name and leaves profiles.json as it was, renames by case only (home -> Home), and keeps what the profile holds. - GUI: Rename turns the details' name into a field. Enter renames through profileAction, so the chip is renamed at once, pending, and rolled back with the error if magpie refuses; the details stay open under the new name, with In use kept. Escape or a click away puts the name back. The field lives in profilerename.js, imported on press, so the core script stays under its budget (no raise; 50 bytes under after comments in app.js were cut). While the field is open In use, Apply and Rename hide so a 360px panel's field has room. - TUI: ctrl+e on a profile renames it on the name line. - CLI: `magpie rename <old> <new>`; a flag is never taken for a name. - WebDAV: a rename syncs as the old name gone and the new one in (davsync test). Run on mote at 47672f11c (on |
||
|
|
52195b6b07 |
backup: the setup is backed up into a folder by itself, and any version put back (jwaitq)
jwaitq (Discord) nearly lost their setup on Windows and got it back only
from a Downloads\data folder they happened to have. They asked for
backups made on a schedule into a folder, with a version to go back to.
What changed
- internal/backup/auto.go: Settings › Sync › "Back up by itself". On by
default: once every 24 hours, the last 7 kept, into
<config dir>/auto-backups. Interval (1 hour, 6 hours, 1 day, 1 week, or Off), keep (3,
7, 14, 30) and the folder are the user's to change. autobackup.json holds
only what the user set; a field they never touched follows the default,
so a later default never overrides their own value. An unreadable
autobackup.json makes no backup and says so, never "off" or a default.
- What goes in is the export without API keys (backup.Collect(false)),
the same bundle and the same handling of secrets as the manual no-keys
export, with the proxy URL blanked as well (it can carry a password).
Not sealed, so it opens without a passphrase. Files are 0600 in a 0700
folder, written to a temp file, fsynced and renamed, and listed only
when they parse and their sha256 matches, so a half-written file is
never a version. A temp file over an hour old is removed.
- A backup is made only when the setup changed since the newest one, so
a quiet week keeps a week of versions, not seven copies of one day.
The loop runs inside the gateway (WhileServing), first 2 minutes after
launch, then every 10 minutes it checks whether one is due by the
newest file's time, so a restart doesn't make an extra one.
- Restore puts a version back the way Import does (additive), after
first writing the current setup as a "-restore" backup. If that
backup can't be written, nothing is put back. The row says when the
undo copy was made, and restoring it undoes the restore. "-restore"
backups are pruned past Keep like the rest.
- internal/gui/backup.go: GET /api/autobackup and POST
/api/autobackup/{set,choose,now,reveal,restore}. internal/cli
settings_parity_test names the two routes in notYet (S2).
- GUI: autobackup.js, imported lazily when Sync is drawn, so app.js and
the core budget are not raised. The app's own segmented controls and
menus (no <select>), the folder row with Change…/Show/Default, Back up
now, and the versions list with Restore behind a confirm. Strings in
en, zh, zh-TW, ja, de (22 keys each).
- docs/subsystems/sync-backup.md: "Backups by themselves".
- Tests touched beside it: sync-sign-in's "last row" is now the last of
Sync's own rows (the new rows come after Import); usage-computers
scrolls its tick to the middle, since in WebKit the sticky Settings
tabs covered it at the page's end; agent-prefs waits for Settings'
first draw instead of reading the static index.html's rows.
Tests
- internal/backup/auto_test.go: TestAutoBackupOnSchedule (injected
clock, no sleeps), TestAutoBackupAfterRestartWaits,
TestAutoBackupOffOrUnreadable, TestAutoBackupPrunes,
TestAutoBackupHoldsNoSecrets, TestAutoRestoreRoundTripAndUndo,
TestAutoRestoreNeedsTheBackupFirst, TestAutoHalfWrittenNeverListed.
- internal/gui/backup_test.go: TestAutoBackupRoutes.
- internal/gui/tests/auto-backup.test.cjs: chromium and webkit, 1100px
and 420px, en/zh/zh-TW/ja/de; plus "Sync redrawn while the backups are
being read still shows them", which found a real bug (the rows were
dropped when Sync redrew during the first read) and is red on the old
code.
Broken by hand, each test red, then put back: dedup off (OnSchedule),
interval check off (OnSchedule, AfterRestartWaits), keep+1
(Prunes), proxy left in (HoldsNoSecrets), no backup before a restore
(RoundTripAndUndo), restore going on after a failed backup
(NeedsTheBackupFirst), unreadable config read as default
(OffOrUnreadable), checksum not checked (HalfWrittenNeverListed),
os.Rename without the temp step (HalfWrittenNeverListed). And the
redraw fix, reverted: the redraw GUI test red in both engines.
Run on mote (macOS 27) at this change on c9af34446; rebased then onto
|
||
|
|
7d1f2ecba3 |
claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from `magpie claude-code install`, and asked whether a magpie update touches it and how it updates. The download lives in <cache>/claude-code (/config/cache, on the volume), so a new image keeps it. But nothing ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it stayed at the version first installed until the user ran install again. claudecode.KeepCurrent now runs while magpie serves (a WhileServing loop): a minute after start and every six hours it asks downloads.claude.ai for the latest release and downloads a newer one, checked against the manifest's SHA-256 and size as install does. The version it replaced is removed on the next look rather than at once, since a run being started may hold its path (Install, the CLI's, still removes it at once; a folder with a .part download in it is left alone). It does nothing when magpie downloaded none, when the machine has its own `claude` (that one is run and updates itself), or when DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a version. A failed look keeps the download and is logged. It never downgrades. The status line of `magpie claude-code`, the Docker docs (en, zh, ja) and the bridge's subsystem page say so. Run: - wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v ./internal/claudecode/ -run 'Keep|Install|Find': all pass. - Broken by hand on WSL, each red: no newer() check (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own() check (the_machine's_own), pruning at install (UpdatesMagpiesDownload), no prune on the next look (UpdatesMagpiesDownload). - Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program with a fake 2.1.1 download ran KeepCurrent against the real downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to 2.1.316", the kept binary's --version said "2.1.316 (Claude Code)", 2.1.1 was still there for the next look, and the loop ended with its context. - mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of both packages, go vet ./internal/claudecode/, go build ., then go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m: VET-OK; claudecode ok 0.680s, cli ok 56.673s. - gofmt -l clean. Not tried: the Docker image itself (no docker on the test boxes), and a Windows run whose replaced binary is still in use (prune leaves what it can't remove for the next look). Full suite not run: the change is the claudecode package, one WhileServing line and one CLI status line. A WSL run of ./internal/cli/ at the default 10m timeout timed out while the box ran other sessions' full suites; the 45m run above replaces it. |
||
|
|
5dfbca6274 |
cli: magpie settings list|get|set|reset, through the window's own save (#4745)
Stage 1 of #4745 (StringKe): every setting POST /api/settings saves can be read and set from the terminal. - internal/settingsapi holds the save the handler made: Merge (the carry of keys a page leaves out, moved verbatim from api.go, plus upstream's RouterNote line), the vision/imageGen/searcher checks, settings.Save's own checks, catalog.Touched. POST /api/settings and `magpie settings` both call settingsapi.Apply, so a value is checked and saved one way. It sits outside internal/gui so the nogui build has it. - `magpie settings` (list, the default, with value, default and choices; get; set; reset to settings.Defaults()), --json on list and get. Body sends the whole file with one key changed, so a key the save keeps when absent (noBird, refusalRetries, ...) is set even to off. A flag where a key or value goes, an unknown key (with near matches named) or a refused value writes nothing and exits 1; --help prints usage. - Parity guards: TestKeysAreWhatTheSaveWrites (each Settings field sent changed on its own; what the save takes must equal Keys), TestSettingsCLISetsWhatTheWindowSaves (every key the page's prefsKeep and savePrefs send is a key), TestEveryRouteHasACommandOrIsNamed (each /api route has a command or a reason in notYet, which later stages shrink; 36 have one now). - Item 3 of the stage (per-provider CLI-only fields in the window) is left for stage 2. - The open app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update re-check) run only from the window's save: #4752. Run (mote, at the pushed head |
||
|
|
788057340b |
library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP servers, image recognition, image generation and search, in the Library's Discover. Image generation and search were there; image recognition was an address to copy in Settings only (#4653). - `magpie mcp vision` (browsermcp.RunVision) relays stdio to the gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's relative image path is made one in the agent's folder on the way (imageFrom), since the gateway can't know where the agent runs; an absolute path, ~, a URL or a drive goes as written. - library: magpie-vision is a featured, opt-in server (no agents until picked), any binary's `mcp vision` is one server (serverKey), and it gets the 120s tool timeout (selfTimeout). - Settings › Models › Images: the Image recognition row has Give agents Magpie Image Recognition… / Turn on the Library, none with recognition off or in gateway mode. The three links are one helper, libWay, used by Image generation and Web search too (no budget raised: core 1,533,011 of 1,533,105). - Never a dead tool: Discover lists all three whatever is set up, and one that can't answer yet says why (gateway.OwnUnready, set by /api/library/market/servers as `unready`): a "Not set up yet" badge on its card with the reason as its title, and the reason in its sheet (nothing set up, or turned off in Settings / Plugins). It can still be added; its tools already answer with the same reason until then. - Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md. Run, all on mote (macOS 27) through mote-run, at this head's tree (rebased on |
||
|
|
b1fc435407 |
library: Magpie Web Search, magpie's search MCP server in Library › MCP (lutra_fs)
lutra_fs on Discord: magpie's search MCP shows in Settings › Models but not in Library › MCP servers. They were right. The gateway's web search MCP (/mcp/magpie/web-search) was only an address to copy in Settings › Models › Web search. It was never a Library server, so no agent could be given it from the Library, and the Library didn't list it. Change: - `magpie mcp search`: a stdio relay to the gateway's search MCP, made by widening browsermcp's Magpie Browser relay into a bridge with its own path, title and an optional session (search sends none, and has a 5 minute client). It takes no arguments. When magpie isn't running, it says "Magpie Web Search can't be reached: start magpie". - library: Magpie Web Search (magpie-web-search) is a featured, opt-in server beside Magpie Image and Magpie Browser. It is installed with no agents, so the user picks them in its sheet, and it switches per agent like any other row. Its command is the full binary path, and serverKey treats any binary's `mcp search` as the same server. Each agent's tool timeout is at least 120s. - Settings › Models › Web search › MCP server: under the address there is a "Give agents Magpie Web Search…" link that opens its Library sheet, or "Turn on the Library" while the Library is off, as Images does for Magpie Image. Gateway mode has no link. - The sheet's hint says where each search goes and what it costs. All strings are in en, zh, zh-TW, ja and de. - docs/subsystems/library.md names magpie's own servers and the new one. - An agent in WSL gets it through the MCP router, as Magpie Browser does. The image-only WSL side() is unchanged. - The sibling, Image recognition's MCP server, is still in Settings only. That is filed as #4653. Run, at this head (rebased on origin/main |
||
|
|
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
|
||
|
|
5a56bc7d73 |
gateway: a CI job trades its OIDC token for a short-lived key (#4531)
xazaj on X asked for GitHub OIDC: a GitHub Actions job should get a
gateway key without a long-lived magpie key in the repository's secrets.
A rule (magpie gateway-key oidc add --key <id> --repo owner/name
[--ref …] [--environment …] [--claim k=v] [--ttl 1h] [--issuer URL]
[--audience a]; oidc list, oidc remove) names an issuer (GitHub Actions'
by default, any https issuer), an audience (magpie-<rule id> by default,
so a token asked for one rule opens no other, and the workflow needn't
know the gateway's address), claims (exact or path.Match globs) and the
gateway key the keys are issued under, which must be let issue. A GitHub
rule names the repository or its owner with no wildcard, or every
repository on GitHub could get in. No rule, no exchange.
POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an
optional {"ttl","models"} verifies the token (RS256 only, keys from the
issuer's discovery document's https jwks_uri, exp required, nbf/iat with
a minute's leeway, the rule's aud and claims, a jti traded once) and
issues a key through access.IssueKey under the rule's key, named
repo@ref (run N), living no longer than the rule. Everything issued keys
guarantee holds: bounded by the issuer's models and accounts, its spend
counted against the issuer, stopped when the issuer is turned off.
- A token is judged only against rules naming its iss, so it can't make
magpie fetch from a URL of its choosing.
- Keys are cached an hour per issuer, read by one request at a time with
no lock held across the fetch, asked again for an unknown kid at most
every 10s, and kept while the issuer is down; with none ever read,
nothing is let in.
- The route is lanGuard's one exemption from remoteKeyed (that exact
path, POST, no gateway key): only while shared, past the allow list,
and a refused token counts against tooManyAuthFails (429 past the
burst). A read-only key is refused it.
The issue's open questions, decided: rules are generic from the start
(the GitHub repository rule applies to GitHub's issuer); rules are CLI
and file only for now (oidc-rules.json), no GUI.
Docs: docs/subsystems/gateway-routing.md (Trading an OIDC token for a
key, routes table) and site/public/docs remote in en, zh and ja, with
the workflow snippet.
Tests: TestOIDCTokenTradedForKey (no rule, a traded key that works on
chat with its TTL capped and its name, a model past the issuer, another
branch, no token, 51 bad tokens -> 429, issuer turned off, a token on a
model route, loopback, not shared -> 403); TestMatchEachCheck (14 bad
tokens, list aud, replay, the refusal naming the claims);
TestKeysCachedAndKept (8 concurrent tokens one fetch, rotation, a made-up
kid inside and past the gap, the issuer down 2h later, an unnamed issuer
never fetched); TestUnreadKeysLetNothingIn; TestAddRefuses;
TestGatewayKeyOIDCCLI; TestReadOnlyKeyEveryRoute with the new route.
A JWKS from an httptest TLS server, never the network.
Broken by hand, each red then restored: the signature check, the claims
match, the jti check, the exp check, the refetch gap, the GitHub scope
rule, the lanGuard exemption, the throttle and the TTL cap.
Run at this head (rebased on
|
||
|
|
0e90572274 |
browser: Magpie Browser, agents use the user's own browser and its sign-ins
The owner asked for a browser-use MCP of magpie's own, so an agent's browser keeps working when Claude Code switches accounts, and asked that it act in the browser the user uses every day: a fresh Playwright profile is signed in to nothing. Magpie Browser is an MV3 extension (internal/browserext, ID dmlhojidlfnkgamkekjhacgkpanbkeko, pinned by its key) that the user loads once in Chrome, Edge, Arc, Brave or another Chromium browser. It holds a WebSocket to the gateway's /v1/magpie/browser/extension and carries out each tool call with chrome.debugger (the DevTools protocol) in the user's own tabs. The socket is taken only from this computer, with a loopback Host (no DNS rebinding) and the extension's own Origin; a page or another extension that connected in its place would be handed every call. Agents reach it at /mcp/magpie/browser (Streamable HTTP) or through `magpie mcp browser` (stdio), and the Library's MCP market lists it as Magpie Browser, opt-in. Like the image server it is magpie's own, but it is never served to another computer, shared and with a key or not, and never to a web page, since it acts as the user wherever they are signed in. 17 tools: navigate (url, back, forward, reload), snapshot (an accessibility tree with refs, interactive-only on ask), click, type, press, select, hover, drag, upload, scroll, wait (text, gone, seconds), dialog, evaluate, text, screenshot (page, full page, element; JPEG or PNG), console and tabs (list, new, select, close). Each agent session goes on in its own tab; a link that opens a tab is followed, and a dialog a click opens is said in the reply. The Library's sheet for it has Set up the extension…, which writes the extension to ~/.config/magpie/browser-extension pointed at this gateway and shows the folder, the three steps to load it, and whether the browser is connected, polled while the sheet is open. Run: - TestBrowserToolsInARealBrowser: the extension magpie writes, loaded in a real Chrome for Testing 141 (Playwright's chromium-1234, headless=new) with --load-extension, connects, and all 17 tools act in a real tab of a fixture site. Green on mote (macOS 27), on xiaomi-gpu (Windows 11, win-run) and in magpie-desktop (Ubuntu 24.04, wsl-run). Under a test HOME Chrome needs --use-mock-keychain / --password-store=basic, or the extension's storage waits on a keychain and it never connects. - go test ./internal/gateway -run 'Browser|ReadOnly|Image', ./internal/ browserext, ./internal/browsermcp, ./internal/library, ./internal/gui -run 'Library|Browser', ./internal/cli on mote. - GUI: library-browser-setup.test.cjs (new) in Chromium and WebKit, en, zh, zh-TW, ja, de, at 1100 and 420 wide: 22/22. With i18n-keys and every library*.test.cjs: 915 pass, 1 fail, i18n-keys' "Unmarked", red on main since |
||
|
|
64cdb68035 |
accounts: import claude reads claude-swap's export (#4532)
StringKe (#4532) is moving from claude-swap (cswap 0.29.0) to magpie, and `magpie accounts import claude` didn't read cswap's export. It does now: parseLoginImport takes cswap's format-1 envelope ({version: 1, swapVersion, encrypted, accounts: [...]}, read from cswap 0.29.0's transfer.py) and cswapEntry reads each account's credentials.claudeAiOauth and config.oauthAccount: email, account and organization uuid, and the organization's name. The tokens are kept as the file has them; magpie asks Anthropic nothing. Refused, each with what to do: an encrypted export (decrypt with gpg -d first), another format version, a Codex entry, and an API-key entry (added as a key instead). An entry with no refresh token is accessOnly, as for every other file. cswap's alias becomes the account's name in magpie (importNames) when the account was added or updated, has no name yet, and no other account is called that or signed in as it, so the name stays a selector for one account (the previous commit's rule). testdata/cswap_0.29.0_export.json is claude-swap 0.29.0's own `cswap export` output, made from its source in a sandbox HOME in WSL with two accounts and fake tokens (cswap's add step asked Anthropic once with the fake refresh token, which it called dead; no real account was involved). Run (mote unless said): - At this commit's tree (on origin/main |
||
|
|
149e763e9e |
accounts: a name you gave an account picks it wherever an email does (#4532)
StringKe (#4532): `magpie accounts switch claude work` failed when "work" was the alias; accountNamed matched the email only. provider.AccountByName resolves a name (magpie accounts alias) among an agent's accounts. It refuses a name two accounts share, and a name that is another account's email or email part, so a name never picks the wrong account. It is used by: - accountNamed: accounts switch/on/off/remove/alias/cap and the rest that take <email>; - provider pool --accounts; - accountRef (GUI and account-cap): the exact email first, then a name, so another account's alias never shadows an email; - account-cap's display, through AccountRefOf (it filtered by email). Run (mote, at this commit): - go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok (104.9s, 33.2s). - TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts and account-cap by name; a shared name and another account's email refused. Red with each part removed by hand: the accountNamed call, pool's resolution, the clash check, the shared-name check, accountRef's name step. Not run: the GUI suite (no GUI file changed); real accounts. |
||
|
|
15b83901ac |
accounts: switch to the next account with room, or the one with the most left (#4532)
StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch to the next account", and when every account was past its line the automatic switch stayed on the spent one, where cswap moves to the account with the most room left. - `magpie accounts switch <claude|codex> next` (provider.NextInOrder) takes the other accounts that are on in magpie, from the one after the account the agent is on, wrapping round: the first whose allowance is known and has room, else the one with the most room left, and says it is past its line. A saved Claude account not read yet is read first (readSpare), as the automatic switch's spares are. With no reading of any it refuses rather than guess; for any other agent it asks for the account by name. - NextLogin (shared by Codex and Claude Code): when the account the agent is on is spent and every spare is past its line too, it moves to the spare with the most room left (roomLeft: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has at least roomMargin (1 point) more than the one it is on, so two all but even accounts don't trade the agent each look. A held, failed or unknown reading is never moved to. One model's own window still counts for nothing, as before. - docs: reference.md (the automatic switch and `next`; its "a Claude account magpie knows nothing of is not moved to" was stale since readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja start pages' command table, `magpie help`. Run (on mote, sandbox HOME through the packages' TestMain): - go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok (144s, 44s), at this change's tree before the next commit's edits. - TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each over codex and claude with three accounts: green; red with the fallback taken out of NextLogin (the two "most room" cases, both agents) and with NextInOrder not starting after the signed-in account ("the one after it", both agents). The "none has more by the margin" case fails without roomMargin. - Built the nogui binary and ran in a fresh sandbox HOME on mote: `accounts switch claude next --help` (prints the accounts help), `switch claude next` and `switch codex next` with no accounts ("has no other account that is on"), `switch gemini next` (asks for a name), `switch claude nxt` (no such account), `switch claude` (usage). - gofmt -l clean. Cross-OS vet: run at the head of this stack. Not tried: a real switch between real Claude or Codex accounts; the CLI `next` with real saved accounts (the provider tests cover the choice). |
||
|
|
ceeb73a0f1 |
app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log while chasing a Codex "hit a snag" through the gateway, and had no such folder. Only the launch agent (magpie daemon install, written by launchd) and a gateway magpie tui left running wrote a log; the app opened from the Finder, the Dock or the Start menu logged to a stderr nobody reads, on every system. Now runGUI and runPanel (magpie, app, tray, panel, a window view, a magpie: link) call applog.Start before gui.Run. It sends the standard logger (the gateway, the plugin host, providers and Wails' error handler all log through it) to app.log as well as stderr, and points debug.SetCrashOutput at it so a panic's trace is there too: macOS ~/Library/Logs/magpie/app.log Windows %LOCALAPPDATA%\magpie\logs\app.log Linux $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log portable data/logs/app.log app.log, not serve.log: on a Mac launchd writes serve.log for the service, another process. The file is 0600. At 5 MiB it becomes app.old.log (two files at most); when another magpie (an update's new process) rotated it already, it is only opened again; when it can't be moved it is emptied. stderr goes first, through a writer that never fails, since io.MultiWriter stops at a failed writer and an app opened from Explorer has no stderr. Secrets: the log calls name header names and paths without queries; no key or token was found logged (grep of log.Print* in gateway, provider, plugin, gui, agent). scrub masks bearer/basic credentials, key/token query parameters and sk-, AIza, gh?_ and JWT shapes anyway. How a user finds it: Settings › About › Log, with the path, Copy and an Open that shows its folder (POST /api/settings/log/reveal; the row is hidden in magpie web, which writes no file). magpie log prints where every log is (the app's, app.old.log, the service's, the tui's background serve.log); --path the app's alone, -n N its last lines, -f follows it across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where is magpie's log?" and the CLI table) and privacy (files on your computer), en/zh/ja. Run: At 227ce6074 on origin/main |
||
|
|
fbb1b36d1f |
provider: the Claude keep-alive keeps off accounts, its reading, and its turn (#4532)
stringke read |
||
|
|
b48881f507 |
provider: keep idle saved Claude accounts signed in, by Claude Code itself (#4532)
#4532: a saved Claude account switched on but not needed for weeks (switch-only) had nothing run on it, its refresh token sat idle, and it was found signed out when the switch wanted it. Codex's saved sign-ins already had a keep-alive (RenewLogins, every 8 days, one account an hourly look). The same loop now takes saved Claude accounts that are on, not Claude Code's own, not added by setup-token and not already signed out (claudeKeptAlive). For one that is due it has real Claude Code run /usage in the account's own CLAUDE_CONFIG_DIR, the path a card's refresh takes (readSavedClaudeUsage, inSavedClaudeDir), and syncSavedClaude keeps whatever sign-in Claude Code refreshed. magpie asks Anthropic nothing itself: no OAuth or usage endpoint, as removed in |
||
|
|
2eac916170 |
gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.
A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.
- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
cost, readOnly} answers 201 with the secret once, no-store. GET lists
the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
[--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
until/expired/issued by.
Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
Such a request can already use every model with no key and run the CLI,
so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).
An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.
An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.
Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.
Run at base
|
||
|
|
fdf5e2c65f |
cli: claude-tui-helper ends on a signal its own way, not of magpie's handler
magpie's process-wide handler (endProbesOnSignal) re-raises SIGTERM. In claude-tui-helper it killed the helper (exit -15) before the shim's own handler could stop its Claude Code and remove what it wrote, so a run the gateway aborted left them behind. The helper's command now lets go of those signals (leaveSignals) before claudetui.Run. Run: go test ./internal/claudetui ./internal/cli on mote (macOS) and in WSL magpie-desktop (-tags nogui), ok; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build on mote, ok. Broken by hand: without leaveSignals, SIGTERM to a real helper in the sandbox gateway exited -15 and left its temp folder; with it, exit 1 and the folder removed (termimg.py). Not tried: SIGHUP from a closed terminal. |
||
|
|
333e7f573b |
gateway: gateway keys are dragged into the order you want, kept with the keys (alextjy on Discord)
alextjy asked on Discord whether gateway keys can be reordered. They could not: the Gateway page listed them in the order caller-keys.json held them, and nothing changed that order. - access: a "move-key" action puts one key at a place in the list, under the same file lock as every other key change. Nothing else about the key changes, and the sharing key's mirror in settings is left alone (its pointer would otherwise land on another key). - GUI: the Gateway page's key rows are dragged the way search APIs' rows are (shared dragRows, a grip shown on hover only, Alt+Up/Down, the existing "Drag to reorder" title). A refused move puts the list back from the server. New strings in zh, zh-TW, ja and de. - CLI: `magpie gateway-key move <id> <place>` (from 1); list already prints the stored order. - Usage > Requests: the key filter lists keys in the user's order, removed keys after. The Overview stays a ranking by use. Run (worktree at |
||
|
|
43966a53fb |
claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.
`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).
A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.
claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.
The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.
Run (rebased on
|
||
|
|
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 |
||
|
|
0804f2d97d |
search: Tencent Cloud's Yuanbao Search (wsa) is a built-in search API (plugins#509)
chenjiangzi asked for Tencent Cloud's WSA SearchPro (元宝搜索). It is added
as vendor "wsa", following Doubao Search (
|
||
|
|
f2c6831a31 |
gateway: a read-only gateway key reads quotas and usage and uses nothing (Steven on Discord)
Steven's ESP32 desk display polls magpie (Docker, on his LAN) every 15s on GET /v1/magpie/quotas and /v1/magpie/usage and never sends a model request. Only a key held to nothing was told the usage summary, so the key kept in the device's flash had to be one that could spend every account. A gateway key can now be read-only (access.Key.ReadOnly): - `magpie gateway-key add <name> --read-only`, `magpie gateway-key access <id> [read-only|full]` (`gateway-key --help` lists it; `list` has an ACCESS column), and "Make read-only" / "Give full access" in the key's menu in Gateway -> Gateway keys, with a "Read only" tag on its row. - readOnlyGuard (internal/gateway/readonly.go), after callerGuard and before withCaller/keyLimited, judges the pattern ServeMux.Handler routes the request to. A read-only key is answered GET /, /v1, the quotas, their history and cards, the usage summary and its requests, its limit and the concurrency. Every other route is refused with 403 gateway_key_read_only: every model route, count_tokens, the Responses WebSocket's upgrade, every MCP server, Codex's and Gemini's backends, /v1/models and the Ollama routes, the catch-all, the trace and route, debug profiles, and every write (usage ingest, quotas refresh). It is default deny, so a route added later is refused until it is classified. - The key is held to nothing else, so heldKey leaves it alone: it reads the usage summary and every account's quotas, as a key held to nothing does. None of those routes holds a key's secret. - The sharing key can't be made read-only, since magpie gives it to its own agents (LANSecret). Update refuses it, and the GUI item is off with why. Older versions: a magpie from before this commit doesn't know `readOnly` and treats such a key as a full one, so downgrading magpie widens the key. Tests: - TestReadOnlyKeyEveryRoute (internal/gateway/readonly_test.go) takes the patterns from the router itself (routes() records each HandleFunc). It fails when a pattern is in neither readOnlyRoutes nor its refused list. It sends every refused pattern, by each method it takes, from 192.168.1.9 and from loopback, plus a WebSocket upgrade and an unclean chat path, and expects 403 gateway_key_read_only with the upstream never reached. It checks that every allowed route answers, that no body holds any key's secret or the upstream key, that the usage summary names the other key's use, and that a full key and a key made full again still reach the model. - TestReadOnlyKey (access) covers add-key and access-key on and off, Authenticate, List, and the sharing key refused. - TestGatewayKeyCLIReadOnly covers --read-only before and after the name and beside --key, access, the list column, bad values, and --help. - gateway-key-readonly.test.cjs runs Chromium and WebKit, 1100 and 420px, in en/zh/zh-TW/ja/de. It covers the tag, both menu items and what they post, the status line, the sharing key's item off with its why, no scroll on click, no sideways scroll, no select, and no left stripe. gateway-card.test.cjs now expects the menu's 4th item. - TestClientPathCoversHandler takes the patterns from routes() instead of parsing Handler's source, which moved into routes(). Broken by hand: - readOnlyGuard passing everything: TestReadOnlyKeyEveryRoute red (103 lines, /v1/models 200 onward). - A new `POST /v1/new-thing` route in routes(): red, "in neither readOnlyRoutes nor readOnlyRefused". - The GUI item not off for the sharing key: gateway-key-readonly red 10 of 10 in Chromium. Run at the pushed head (on origin/main |
||
|
|
dca3e2d716 |
search: Doubao Search (Volcengine) as a search API (CyberCaius on Discord)
CyberCaius asked on Discord #help (10-30) for Volcengine's Doubao search under Settings › Models › Search APIs, or a custom API address. Volcengine's Doubao Search Custom (豆包搜索 Custom版, once 联网搜索 / 融合信息搜索, docs.volcengine.com/docs/networked-search/networked-search, the same page as volcengine.com/docs/87772/2272953) can now be added with its API key: - provider.SearchVendors: volcengine, "Doubao Search (Volcengine)", at https://open.feedcoopapi.com, keys at console.volcengine.com/search-infinity/api-key, after DeepSeek. The GUI takes its vendors from SearchVendors, so it shows in the Search API picker with its Get a key link and base URL field; no GUI file changes. - askSearchAPI: POST /search_api/web_search, Bearer key (the default, as the docs and volcengine/mcp-server's askecho_search_infinity send it), body {Query, SearchType: "web", Count: searchHits, Filter: {NeedUrl: true}}. The query is cut to the 100 characters the docs allow. NeedUrl leaves out its 火山如意 cards, which have no URL to cite. - readVolcSearch reads Result.WebResults: Summary as the page's text (the docs recommend it for models; Content is the whole page, Snippet ~200 chars "only for list display"), Snippet when there is no Summary, PublishTime as the page's age, a 1970-01-01 time (its image example's stand-in) as none, and a result with no Url left out. - volcSearchError: its errors are in ResponseMetadata.Error, a code the docs list, and the docs don't say the HTTP status, so the code decides: 10401/10403/10409 rest the key as turned away (403), 10406/10408/ 10410/10412 (free searches spent with none paid, no plan, plan spent) as out of credit (402), 700429 as rate limited (429). Any other code is a plain error, a 200 carrying one included. The key is masked in the error as for every vendor. - A custom address: every search API already takes a base URL (#1580, the field under the key in Settings, url= in the CLI), so an endpoint that answers as Tavily, SearXNG, Brave, Exa, Firecrawl, You.com, DeepSeek or now Doubao Search does can be set there. There is no common format across the vendors (each has its own path, body and reply), so no separate "custom" vendor was added. - Siblings: CLI usage (main.go, search_cli.go's api list and empty-state hint), README.md, README.zh-CN.md, gateway-routing.md's path list and refusal paragraph. The test's reply is the docs' own web-search response example, byte for byte (testdata/volcengine_web_search.json); its error replies are the docs' error example with its "// 该字段为错误码" note taken out (not JSON). Not tried against the real API: no Volcengine search key in this run. Run (worktree on origin/main |
||
|
|
af8f3a9399 |
sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.
- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
the aggregators (allFiles, callFilesWith, callSourcesWith,
traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
readers of an already-listed session (TranscriptOf, ContentOf,
SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
ErrNotRead, so a cache from before a switch was turned off goes no
further. The Sessions list, stats, /api/sessions/overview, the call and
trace indexes, Usage's agent-file calls and the Codex/Pi title readers
all pass it.
- SettleReads decides once and saves: an install with sessions.json or
a calls-v* cache read sessions before and keeps all on; a fresh one
reads none, not asked. A saved value is never replaced; save, sync and
restore keep it (KeepOwn); only SetSessionReads writes it. An
unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
shows a consent card: each agent found (by a stat of its folder only)
with a switch, Allow selected and Allow all. Settings > Privacy >
Agents' session history has "Agents found later" and a row per agent.
Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
says on stderr when nothing is allowed yet; the TUI's empty Sessions
page says how.
Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).
Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).
Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
change on
|
||
|
|
96a703a591 |
uninstall: magpie uninstall and Settings › Uninstall magpie put every agent back before magpie's files go
Jevik_AI on X (Windows, portable magpie) deleted magpie's folders by hand. ~/.codex/config.toml kept openai_base_url on 127.0.0.1:3425, and every Codex turn then failed with a 502, with nothing left that knew why. Deleting magpie's files never puts an agent back, so there is now an uninstall that does. - internal/uninstall: Run goes in this order. System removes the background service, opening at login, the Start menu shortcut (shortcut.Remove, with its App Paths key), the magpie:// links and the privacy model's helper. Agents ends Codex's account failover, then runs each connected agent's own Disconnect, or its offline disconnect for an app that is closed. That is the same code as the Agents page, so a value the user changed by hand since Connect stays theirs ( |
||
|
|
0c4e3455ee |
agents: a line magpie writes into a TOML, YAML or env config has a note above it saying so
Jevik_AI on X deleted magpie's folders by hand. Codex's config.toml kept openai_base_url = "http://127.0.0.1:3425/backend-api/codex", with nothing in the file naming magpie, and every Codex turn failed with a 502. Each line magpie writes that points at the gateway, or at magpie's model list, now gets a comment line of its own just above it: # magpie: Codex on magpie's local gateway; Disconnect in magpie or # `magpie uninstall` undoes it, or delete this line and the model line model_provider = "magpie" - Only a line the write adds or changes, or one that had a note, gets one. A line of the user's own that magpie leaves alone gets none. - The note is never on the value's line. Grok App's providers.rs reads the rest of a line as the value, and an end-of-line comment broke TestGrokApp in a first try. - Every write takes the notes out and puts back the ones still needed, so a note goes with its line and Disconnect leaves none. - No note in JSON. A YAML note that would change what the file reads as isn't added. - Wired in run (agent.MarkWritten); tests leave edit.Mark nil so their exact bytes stay. Run at this commit's tree (worktree, sandbox HOME, private GOCACHE): - gofmt -l clean; go vet darwin, GOOS=windows, GOOS=linux -tags nogui ok. - go test -tags nogui -run Mark ./internal/edit ./internal/agent: ok. - ./internal/agent and ./internal/edit whole with edit.Mark forced on for every test (a snapshot with lineNote set in agent's TestMain): edit ok; agent fails only TestDshRouteKeepsTheAPIPickedInDsh and TestDshSearchThroughGateway, which compare exact bytes and see the note line. With Mark unset (as shipped) they pass. - Real Codex: built magpie from this tree, `magpie codex fakeai/fake-1` in a sandbox HOME. config.toml got the three notes above model_provider, model_catalog_json and openai_base_url; `codex mcp list` and `codex features list` (codex-cli 0.162.1) read it, rc 0, and Python's tomllib reads the same values. `magpie codex default` took them out. - Broken by hand: a note on every line, not only changed ones -> TestMarkTOML and TestMarkOnlyWhatMagpieWrites red. - The notes' line filter is withoutNotes, unexported: an exported Unmarked put a word the routing plugin translates into a Go file, and i18n-keys' "a plugin's words are its own" went red on it. It passes now. Full suite: run with the uninstall commit that follows, recorded there. |
||
|
|
4534561f6b |
codex: a thread open when magpie quits goes on through a relay, not a 503
idkatbro on X: a Codex session started while magpie was open keeps failing after magpie quits with "unexpected status 503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses", until magpie is opened again. Cause: Codex signed in to ChatGPT, with more of its accounts on in magpie, gets openai_base_url = the gateway's /backend-api/codex (failover). At quit EndCodexFailover takes it out of config.toml, but a thread already open, in the Codex app and its app-server above all, keeps the base URL it started with. Every turn after went to a closed port. With a system or env proxy in between, the proxy answers 503 with an empty body, which Codex shows as "Unknown error"; without one Codex says "Connection refused" and reconnects. Reproduced on mote with codex 0.162.1 and a proxy answering 503 for the closed port. Masking plays no part: it runs only in the gateway, is opt-in, and its own 503 carries a readable message. Fix: when quit really ends failover (EndCodexFailover now says so), the gateway is on loopback, and Codex processes run (provider.CodexPIDs), magpie starts a detached `magpie codex-relay` (internal/codexrelay). It waits up to 60s for the gateway's port, then passes /backend-api/codex/* on to the ChatGPT backend with the same transforms the gateway applies to Codex's own turns, signed by the caller's own Authorization; it adds no credential (gateway.CodexRelay). - Refused with a readable 400 (Codex retries a 5xx five times over): a magpie model, a turn naming one of magpie's Codex accounts, and a turn masking would have masked, which is never sent unmasked. - 403 for any Origin (null too) or a non-loopback Host, as corsGuard. - Any other path gets 503 "magpie isn't running", never readable as magpie by ServedBy. - It ends once every Codex process it was left for is gone and nothing is in flight. - The next magpie (GUI or `magpie serve`) calls codexrelay.Leave first: a POST with the token from a 0600 state file. The relay closes its listener at once, so the port is free when Leave returns, and finishes its streams (up to 30 minutes). No running turn is cut. Run (at 6df7dc287 on origin/main |
||
|
|
628ac36fc9 |
agents: Add magpie says when nothing here opens the app's import link (sungt)
sungt (Discord #feedback, Windows, magpie 0.1.1976, Cindy 0.1.119, Cindy
open): on the Agents page Cindy's 添加 magpie "spins, no response".
What magpie got wrong: Cindy, AionUi and Lody take magpie only through
their import link, which magpie hands to rundll32 / open / xdg-open and
never waits on. A link nothing opens did nothing, the button never awaited
/api/open nor caught its error, and `magpie cindy add` printed "opened"
whatever happened.
- agent.OpenAppLink asks the system, without opening anything, whether
something opens the link's scheme: Windows' HKCR\<scheme> (what
Electron's setAsDefaultProtocolClient writes) and then the user's
UrlAssociations UserChoice; macOS Launch Services (cgo builds); Linux
`xdg-mime query default`. Only "none", or a registered program whose
full path is gone, refuses the link (NoLinkHandlerError); anything
unknown hands it over as before.
- /api/open (Cindy, AionUi, Lody after OpenLody) answers
code no_link_handler with app, exe and said, an i18n.js key from
linkSaid that api() puts through t() as it does bunSaid's.
- The import button now waits for /api/open and shows the result: "Sent
to {name}: confirm adding magpie there", or the reason in the
reader's language.
- The CLI's add returns the same error.
This is not verified as sungt's cause. Cindy was open, and Cindy
registers cindy:// at every start, so the check most likely passes on
their machine. If so, the spinner is Cindy's own import dialog
(previewProviderImport / fetching magpie's /v1/models). Cindy 0.1.119
wasn't available here. We still need Cindy's log around "received deep
link" from sungt.
Run (worktree at origin/main
|
||
|
|
ec3dad75ae |
provider, gateway, gui, cli: Claude's accounts can be kept to Claude Code's own sign-in, magpie serving nothing on them (myduso)
myduso on Discord asked for an exclusive mode on Claude's subscription: switch the credentials locally and proxy no traffic, since Claude Code is used on its own and the SDK run magpie's bridge makes spends more of the allowance than the interactive client. The switch-only setting Codex has (#1907) now also takes claude. On it, Provider.KeptToAgent is true and On() false, so the gateway, catalog, groups, fallbacks, search, draw and embeddings serve nothing on the Claude accounts, and a request naming them is refused 404 saying they are kept to Claude Code's own sign-in and how to undo it (switchedOff). Switching Claude Code's sign-in when an account is used up, and reading usage, go on: both are gated by leftAlone on the raw Off, which this doesn't set. Groups magpie found keep their Claude members (heldOffEntries). Nothing is sent as Claude Code: magpie only writes and restores Claude Code's own credentials as it already did. GUI: the tick under Claude's accounts, shown with one account too, drawn by the block Codex's tick had (one block now, its strings picked by agent). app.js stays under its budget with no raise (1,311,711 of 1,311,735). CLI: magpie accounts switch-only <codex|claude> [on|off]. Docs: reference.md, subsystems/providers-accounts.md. Run on mote at this tree on 06950fbbb; then rebased on |
||
|
|
e8c7dddcb4 |
notices: the release carries the third-party licence notices
The owner asked for the licence notices in the release package (moejs alpha.11 compiles Intl's data in, which carries its own notices). THIRD_PARTY_NOTICES is embedded in the binary (main.go, //go:embed) and handed to internal/notices; `magpie licenses` prints it, GET /api/notices serves it, and Settings › About has an Open-source licenses row that opens it in a dialog, in every language. `make app` copies the file into the .app's Resources too. The core's scripts are 1,527,245 bytes, their budget raised to it with no room added; app.js stays under its own. Run at this head (rebased on origin/main): - win-run (Windows 11): go vet -tags nogui . ./internal/notices ./internal/cli; go test TestNoticesFollowMoejs (.), ./internal/cli, TestCoreScriptBudget (./internal/gui): ok. - wsl-run (Ubuntu 24.04): go vet -tags nogui ./..., go build -tags nogui: ok. Run at the pre-rebase head 14e2d13fb, on mote (macOS): - gofmt; make app's copy byte-identical to the file; `magpie licenses` output equal to the file; GOOS=linux/windows vet and build; go test . ./internal/cli: ok. ./internal/gui: only TestMainWindowCorners red, the same on origin/main (#3949). - about-notices.test.cjs: chromium and webkit, en zh zh-TW ja de, 1100 and 420px: all ok. Broken by hand: TestNoticesFollowMoejs red with the embedded file cut. Not run: the GUI suite at this head. The rebase met main's cancelAsk helper where showNotices sat, and the dialog's Done now uses it (the same stopPropagation + closeConfirmAsk). The whole GUI suite at 14e2d13fb was cut off when mote went down at load ~50: the files it reached outside About had reds, most of them 180s browser-launch timeouts, the rest passing in other languages or the other engine; they are run again once mote is back, and any that stay red are filed. |
||
|
|
add927e604 |
codex: the Codex app beside the ChatGPT sign-in lists magpie's models too
laddieyao (Discord #general, 10-27): with Codex joined to magpie beside its ChatGPT sign-in, the Codex desktop app's model picker showed OpenAI's GPT models alone, while the Codex CLI listed magpie's. The /models request does reach magpie's gateway and its answer holds magpie's models. ChatGPT.app 26.1013's picker then narrows app-server model/list to the models a Statsig config (107580212, use_hidden_models / available_models) names, while Codex is on its built-in provider, unless Codex reads its list from a file (model_catalog_json, hasConfiguredModelCatalog) or names a provider of its own. The CLI has no such filter. Where the Codex app is installed (codexReaders has an "app"), and only joined/beside the sign-in (not magpie as Codex's provider, not account failover alone), magpie writes the list it hands Codex at /backend-api/codex/models to ~/.codex/magpie-desktop-models.json and names it with model_catalog_json. Codex is still on its built-in provider. With a catalog named Codex asks for no list, so magpie asks the backend itself, with Codex's live sign-in (provider.CodexLiveList): its entries go in verbatim, base_instructions and all, merged as the gateway merges them (codexMerged, factored out of codexModels: picked, hidden, window, V1, AutoReview edits), magpie's models after them. - A list not known (not asked yet, or the backend failing) is unknown: the file as it was stays, never an empty list; a key naming a file that is gone goes, as Codex loads no config then. - Written via temp+rename at Join, set, settle and every Sync (so a change of magpie's models, picks or hidden models rewrites it, as SyncCatalog runs on them); the backend list is asked again hourly (5 min after a failure) and a change syncs again. - A model_catalog_json of the user's own stands; none is written beside. - magpie API, the app gone, or unwire take the key and the file out; unroute never restores the desk file as the user's catalog. - connectinfo counts the file, so a running app on an old list reads as needing a restart. - CLI-only machines: unchanged, the live /models path as before. Run: - Real account, sandbox HOME (copy of auth.json, chatgpt Pro; live ~/.codex untouched): Join wrote model_catalog_json and the file with the real backend's 10 entries (gpt-6.1-sol ... codex-auto-review, each with base_instructions) plus relay/claude-opus-5.5 and relay/claude-sonnet-4-5. Then the real app-server bundled in ChatGPT.app (codex 0.163.0-alpha.10.2, CODEX_HOME sandbox, base URL pointed at a dead port) model/list returned all 12, relay models visible, and config/read showed model_catalog_json set, which is what the app's picker checks to skip its filter. - New tests: TestCodexDesktopListBesideSignIn, ...CLIOnly, ...KeepsTheirs (internal/agent), TestCodexDesktopCatalog (internal/gateway). - Broken by hand, each went red: deskList a no-op (all three agent tests), the user's-own branch removed (KeepsTheirs), the gone-file branch removed (KeepsTheirs), the keep-last-good rule broken in codexDeskRefresh (TestCodexDesktopCatalog). - go test -tags nogui -timeout 45m ./internal/agent ./internal/gateway ./internal/provider ./internal/cli at bc0a99bb6 (on |
||
|
|
3ec3cb704b |
plugin: turning an agent plugin off or removing it puts the agent's config back first (#3810)
An agent a plugin adds is known only while the plugin is on. Turning the plugin off or removing it (CLI `magpie plugin off/rm`, or the Plugins page) left the agent's config on magpie, and `magpie <agent> default` then said `unknown agent`, with nothing to put it back. - provider.SetPluginOff (off) and provider.RemovePlugin first call provider.PluginAgentGoing, set by internal/agent to UnwirePlugin: the agent is disconnected as `magpie <agent> default` does (Disconnect), while the plugin still loads. A plugin off already is read from its module as it is; one whose module is gone puts back each file whose stash names its spec. If that fails, the plugin is left as it was and the error says why. - The stash now records the plugin's spec and the file's format, so `magpie <id> default` for the agent of a plugin deleted on disk puts the file back from the stash alone (agent.RestoreGone; an older stash's format comes from its file's name, agentplug.FormatOf). A file that no longer holds magpie's gateway key is the user's and is left alone; one that can't be read is unknown: nothing is written, the stash is kept. With the plugin only switched off, `default` says the agent is off magpie already instead of "unknown agent". - Turning the plugin back on (or installing it again) does not rewire the agent by itself: its config stays as the user had it. Connecting it (its switch on the Agents page) puts back the model it was on, through Disconnect's `.reconnect`. The CLI says so when it turns off or removes a plugin whose agent was on magpie. Run (this change on origin/main |
||
|
|
9ae7912210 |
agent: plain agy starts Antigravity CLI on magpie in a new terminal
agy takes magpie's gateway, key (GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL)
and --model only from how it is started, so a user on magpie had to copy
the launch command at every start (bestony on Discord). Now:
- magpie agy run [args…] execs the real agy with the env and --model when
agy's settings.json is on magpie's model (a --model/-model the user
gives wins), and runs agy untouched otherwise. On Windows agy is a child
through proc and its exit code is passed through. It refuses when "agy"
on PATH resolves to magpie itself. magpie agy env prints what run adds
(PowerShell's function reads it, since the desktop exe has no console).
- update.ShellFunction puts a function named agy in a marked block
(# >>> magpie agy >>> … # <<< magpie agy <<<) of each shell profile
cliShells finds: .zshrc (ZDOTDIR), the bash profile a terminal reads
(.bash_profile, or .bash_login/.profile on macOS when that is missing),
config.fish once its folder exists, and the PowerShell 7 / Windows
PowerShell profiles where the execution policy runs them. Only the block
is written, in place, temp-and-rename, CRLF and BOM kept; a profile that
can't be read is not written; only files inside the home are. The
function falls back to `command agy` when the magpie it names is gone.
- Set to a magpie model writes the block, stepping out takes it out (the
file comes back byte for byte), and Sync at start writes it for users
already wired.
- Notice, Launch tooltip and the connect panel say plain agy works in a
new terminal, with the command for a terminal open now. Strings in
i18n.js for zh, zh-TW, ja, de. docs/reference.md and
docs/subsystems/agent-wiring.md updated.
Run at this head (base
|
||
|
|
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
|
||
|
|
5b4dec58e4 |
providers: a vendor's keys saved a provider each are one provider with those keys
yuluo_yx on X: "NVIDIA #595"…"#600" at integrate.api.nvidia.com and "Mistral #0001"… at api.mistral.ai were a provider each on the Providers page and a row each on Routing, and with thousands of keys magpie started slowly. They came from an app that keeps an entry a key (CC Switch) imported in one batch: ImportFromApps only offered "add as another key" against providers that existed before the batch, so each entry became a provider of its own (nvidia, nvidia-2…). Fold (internal/provider/fold.go): - FoldCopies runs in startUp, before anything lists the providers, so every user who has such copies already finds them folded. Automatic, not a one-click offer: they are the same account's keys at the same address, what the user wanted is one provider (zero-config rule), and nothing is lost: each copy's id goes in the provider's Was, so its calls count with it by key (ProviderKeyID is the key's fingerprint, unchanged) and a model picked by the old id still resolves. - Only copies by name fold at start-up: a base name and that name with a number after it (" #12", or freeName's " 2"), at least one numbered. They must also be alike in all but the key: the provider with id, name, keys and on/off left out, their per-model settings, and every place that names them (Visible, picked/hidden/ordered models, groups, fallbacks). A copy shown to one agent alone, given its own models or settings, or named by the user ("Home relay" / "Work relay") stays apart. Subscriptions, hidden ones, Vertex and StepFun-signed ones are never folded. - The first copy that is on takes the rest; it is named the base name ("NVIDIA") and its key keeps its old name. Others become keys in the providers' order, named as they were, off if they were off. - Group members, weights, rules, classifier, pick and fallbacks name the provider once; per-model settings and fetched lists of the folded ids go; balance and window history kept by their id moves to their key's name, where a provider with several keys reads it. - A providers.json that doesn't parse is left alone (read() would have given its .bak, and a fold would write that over it). - ImportFromApps folds what one import added by shape alone, whatever the entries are called. Routing needed no change: a provider's keys for one model already fold into one row ("2400 keys"), opened on click (FOLD_AT, #1319). Numbers, sandbox HOME with 2400 NVIDIA + 600 Mistral copies (gen.py, NVIDIA preset + 2 models, Mistral 15 models), `magpie web`, every outgoing request through a dead proxy: - before (origin/main |