Files
magpie/docs/subsystems/provider-plugins.md
T
ggbdpq 3da58c3dfc fix(plugin): end ordinary RPCs' plugin work when their caller leaves (#4678)
A plugin model list's deadline and an ordinary RPC's cancellation released
only the caller. inTime raced the hook without stopping it, and host.go
marked only gatewayRequest cancellable, so a cancelled usage or providers
call never told the host: the plugin's task kept running, the host's
pending count kept it, and repeated reads left task after task alive past
their callers. Reported with an offline host-script reproduction that
shows abort reaching none of three pending usage tasks and five model
tasks outliving their deadlines.

The cancellation path a fetch and a gateway request already take now
carries ordinary RPCs too:

- host.go marks every call but init cancellable, so a caller whose
  context ends has the host told (the existing callAborting write), the
  way it already tells it of a stopped fetch. init is left alone: a start
  that overruns is stopped whole.
- host.js registers each ordinary RPC's AbortController; an aborted
  RPC's answer, nobody's then, is not sent.
- the handler is handed the signal: usage passes it to the plugin's
  auth.usage hook as its own options, and a model list's hook options
  carry it, with the listWait deadline aborting the same controller, so
  vendor I/O that supports stopping stops at the deadline or when the
  caller leaves, whichever comes first.

Sign-in renewal and its persistence are untouched: fresh() runs before
the hooks, and an aborted RPC's handler still finishes what it saves.

Refs #4678

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: an aborted ordinary RPC is no longer
answered "Aborted" at once and dropped from pending. It stays pending
until its handler ends, as on main. host.go's stop() closes the host's
stdin and then gives a renewing host up to stopRenewing to save the
rotated token; with the early done(), host.js's own `pending === 0 &&
closed` exit ended the process at once under a cancelled call whose
handler was still renewing or saving (keepSignedIn, set, signOut, a
usage hook mid-refresh). The Go side needs no answer: an aborted call
is released once its abort is written. The signal to the usage and
models hooks, and the listWait deadline aborting the models hook, are
kept as the patch had them.
TestCancelledCallKeepsTheHostTillItsHookEnds is new: a usage hook that
ends 600ms after its abort, then Settle() closing the host's stdin; the
hook's end must reach its trace.

Run on mote (darwin arm64, Go 1.26.8, Bun via testenv): go test -tags
nogui -count=1 ./internal/plugin/... ok 102.8s; -run Plugin
./internal/gateway/ ok 52.1s and ./internal/provider/ ok 13.3s.
Broken by hand: host.js and host.go at main, tests kept:
TestOrdinaryCallCancelTellsTheHost FAIL "the host was told of the
cancellation didn't happen", TestCancelledUsageReachesThePlugin FAIL
"the plugin's usage hook was handed a signal didn't happen",
TestModelListDeadlineTellsTheHook FAIL "the models hook was handed a
signal didn't happen". host.js as the patch had it (early answer):
TestCancelledCallKeepsTheHostTillItsHookEnds FAIL "the host left
before the hook ended; trace: {"signal":"live"}...".
Not tried: the reporter's replay.py against the built host, and a real
plugin's usage hook that passes the signal to its fetch. The reporter's
"host lives on after stdin closes with a task pending" row is unchanged
by design: that is the renewal safeguard.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:53:23 +08:00

105 KiB
Raw Blame History

Provider and plugin ownership

Some built-in subscriptions are deprecated and have community plugins that provide the same service. A subscription can still use its built-in implementation or move to its plugin. That ownership determines where sign-in, refresh, model discovery, requests, usage, and errors are handled.

Responsibilities and sources of truth

Part Responsibility Source
Provider migration Match subscriptions to plugins, record ownership, transfer accounts, and maintain required plugin versions migrate.go and migrate_*.go in the same directory
Provider integration Expose plugin-backed provider cards, usage, sign-in, and the plugin's own daily check-in plugins.go, plugin_usage.go, pluginsignin.go, plugin_checkin.go
Plugin host Load plugins and execute their code internal/plugin, host.js
Gateway Dispatch requests through the implementation that owns the subscription internal/gateway
GUI Present available subscriptions, migration state, and plugin sign-in app.js
Community plugin Implement the moved subscription's upstream behavior magpie-community/plugins, packages/<name>

The movers map assembled in internal/provider/migrate*.go is the authoritative subscription-to-plugin mapping. Each mover's min is the minimum plugin version required by magpie. The list of moved subscriptions in AGENTS.md is a contributor lookup; confirm the mapping in source when changing it.

Ownership and runtime paths

provider.Moved(id) identifies a subscription whose migration state in migrations.json is plugin. In /api/providers, its row exposes move.state == "plugin"; the GUI also receives its id in onPlugins.

A retired built-in (retiredBuiltins in migrate.go, provider.BuiltinRetired(id)) has no built-in code left: the plugin serves it whether or not a move has run, and its row's move.state is plugin. Gates that once asked Moved(id) ask provider.PluginServes(id), which is moved or retired. Built-in accounts of a retired subscription that haven't moved yet are served by nothing; /api/providers lists them in unmoved (each a MoveCandidate, with the failed move's error and why), and the GUI shows a line over the Providers list with a Move button (unmovedLine in app.js). Built-ins are retired one at a time, each in the commit that removes its code.

Operation Built-in owns the subscription Plugin owns the subscription
Sign-in, refresh, and models Built-in provider implementation Community plugin through magpie's plugin integration
Upstream requests and translation Built-in gateway adapter Plugin fetch through the plugin host
Usage and upstream errors Built-in implementation Plugin, exposed through magpie's provider integration
Migration state and required version Magpie Magpie

For a moved subscription, its built-in upstream implementation does not run. Plugin accounts use Account.Agent == "plugin"; requests reach plugin.Fetch through Provider.Do and bypass the built-in subscription adapter. Magpie still handles routing, protocol conversion, quota handling, and compatibility adjustments, as well as the plugin host, provider integration, migration code, and GUI plugin paths.

Quota aggregation in quotas.go suppresses a key's GLM Coding Plan card only when its comparable reset windows match a ZCode subscription card: built-in or moved zcode, or independently installed zcode-plugin. PlanQuotas identifies GLM plans by their quota endpoint, including custom provider ids. Matching reset schedules from unrelated vendors do not hide cards. Within this pair, resets remain a heuristic for the shared account; a plan's User is a key label or mask, not a login identity. Errors, conflicting resets, or no comparable resets keep the plan visible. This applies to the Usage page, tray, quota reports, alerts, and quota waits; it does not change plugin ownership or upstream requests.

Usage a plugin collects late

A plugin that learns a step's usage only after the step has ended reports it with a later step, in usage.magpie_deferred (prompt_tokens, completion_tokens, cached_tokens, cache_write_tokens) beside that step's own usage fields. The Cursor plugin does this: a tool step's usage event shows seconds after the step, so the step says 0 and the conversation's next step collects the event (#1053).

The gateway parses the field into Usage.Deferred (cUsage) and adds it only where it bills: the usage records, the OTel attempt spans and route pricing, which prices it as a tier before the request's own (routeUsage, Usage.billed). What a client is told stays the request's own, because agents read prompt_tokens as how full their context is: the passthrough forwards the plugin's bytes as they are, whose standard fields are the step's own, and a translated reply is encoded from the own count alone. promptCounted also reads the request's own. A reply without the field is handled as before. With an older magpie the field is ignored and the owed step goes unbilled in the ledger. deferred_usage_test.go covers the passthrough, the translated reply, the ledger, the OTel span and the pricing tiers.

A usage window that says no share

A usage window's used (percent) may be left out when the plugin can't tell it: the Loomy plugins send only display (#3650). Left out is not 0. The host passes it on as null (usageOf in host.js), plugin.UsageWindow.Used is a *float64, and quotaOfPlugin makes such a window Text and Aside: the card shows its display (else "No allowance reported"), never a percentage or a meter (quotaNoShare in app.js), and allowanceOf leaves it out. An account whose windows all tell no share has no allowance, so routing counts it not known (routedAllowance in routing.go, for a fresh reading and the one kept on disk alike), as one never read, rather than as the one with all of it left. A window that says used: 0 is a reading at 0, as before. plugin_usage_absent_test.go and usage-no-reading.test.cjs cover both.

A window that leaves out used but tells its count, amount of limit with both above 0, has the count's share (370 of 1000 is 37 used): quotaOfPlugin fills Used from it, so the window is neither Text nor, unless the plugin set it, Aside, and routing reads it (magpie-community/plugins#468). Before, such a window was text alone, and an account whose windows all told counts so was unknown to routing. An amount of 0 is what a left-out amount reads as, so a limit alone still says nothing. aside: true keeps a window out of routing (allowanceOf) whatever its count; the card and /v1/magpie/quotas still show it. TestAWindowsCountIsItsShare in plugin_usage_absent_test.go covers it.

A wallet's balance

A prepaid wallet (SuperMagic's points, #3950) has a balance and nothing it is a share of. A usage window may send balance (a number, in unit) and leave out used, limit and aside: {name: "积分", balance: 6291, unit: "积分"}. The host passes a finite number on, at least 0, and anything else as null (usageOf in host.js); plugin.UsageWindow.Balance and provider.QuotaWindow.Balance are *float64. quotaOfPlugin keeps the figure and does not make the window Text or Aside, so the account is known to routing with no Used invented. allowanceOf copies it into Limit.Balance, and an empty wallet (0) counts as used up. Allowance.Left(model) is the least balance of the windows that count the model, with its unit. weighRouted sets routes.Seat.Left to it and Seat.LeftIn to the account's provider and unit; Smart, pace and usage put the seat with more left first where they would otherwise tie (byLeft in strategies.go), and only among seats that share one LeftIn, so balances in two units or two providers are never weighed against each other: each kind is put in the places its own seats take (the pool's order, or what magpie sent each lately for pace and usage), and the other kinds keep theirs. Before, a pool with two kinds was weighed by no balance, so a group of SuperMagic's and WorkBuddy's accounts spent SuperMagic's smallest balances first (#4095). The card, the Routing page (Weighed.Balance) and the CLI show the figure ("6,291 积分 left", provider.BalanceText) and no meter. A wallet window's runsOutAt/runsOut (its soonest batch to lapse) and the rows set aside after it (aside text: SuperMagic's day's, timed and permanent points) are display only: the card says them, and the Routing page reads them from the same card (cardOf in the routing plugin's client.js, live requests only), its row saying the lapse after the figure ("6,291 积分 left · 185 积分 expire 23:59", runsOutText, #3964) and its tooltip, and the account list's figure on hover, each window (winsOf). Routing goes by the balance alone. Tests: TestPluginWalletBalanceIsAReading, TestPluginHostPassesABalanceOn, TestWalletsGoByWhatTheyHaveLeft, TestWalletsOfSeveralProvidersEachGoByWhatTheyHaveLeft, TestWalletWithMoreLeftGoesFirst, TestGroupWalletsGoByWhatTheyHaveLeft, usage-wallet-balance.test.cjs, routing-wallet-balance.test.cjs, routing-wallet-lapse.test.cjs.

Cache a vendor doesn't count

A plugin whose vendor counts no cache tokens says so with usage.magpie_cache_unknown: true in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in aUsage into Usage.cacheUnknown, ORed across a reply's usage events. routeUsage then sets RouteUsage.CacheUnknown on a try that counted no cache read or write. The Routing page's promptOf (plugins/routing/client.js) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: Usage.anthropic() leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger carries it too (#3464): the gateway records usage.Record.CacheUnknown on a call that counted no cache (Usage.cacheNotCounted), the ledger keeps it as row flag 8192 (rowCacheUnknown), and usage.Totals sums such calls' prompt into cache_unknown and their count into cache_unknown_calls. Every hit rate leaves that prompt out of its denominator: Totals.HitRate, and cacheHitOf in app.js, used by the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card (which says how many it left out, cacheLeftOut) and each ranking row. One of only such calls shows no rate. A request row's cache cells show "—" and its details say the vendor doesn't count the cache. Calls kept before Kiro's plugin said so carry no flag, so a Kiro call (kiro or kiro-plugin) with no cache counted is read as one (usage.CountsNoCache): in the ledger's rowChunk.row, in Totals.countCache, and for Routing's history in pricedRoutes (cacheCounted, internal/gui/trace.go). The context view (internal/gui/context.go, context.js) shows no cache for such a call and doesn't score it as a miss. Not covered: hit rates read from agents' own session files (sessions.Tokens: the TUI and CLI session lists, the Sessions tab's totals), which carry Kiro's 0 as a miss. cache_unknown_test.go covers the passthrough and translated replies, both whole and streamed.

A plugin's daily check-in

A plugin can press its vendor's daily check-in (签到) itself: its auth hook gains checkin(getAuth, provider), beside usage. The host lists the provider with checkin: true (plugin.Provider.Checkin) and answers checkin({provider, account}) (plugin.AccountCheckin) by refreshing the account as usage does and calling the hook with the account's auth.

The hook returns {outcome, credit?, streak?, message?, until?}. outcome is one of claimed (checked in now), done (already in today), ineligible, inactive (no check-in event now), captcha or failed. A throw, or an outcome not in that list, is failed with the reason; for an outcome not in the list the reason names what the plugin answered, before its own message (the plugin answered "yes": …), so a plugin's wording isn't read as magpie's. captcha means the vendor wants a captcha: magpie never solves one, and says "check in in its own app" instead. A plugin must not solve captchas either. An inactive or ineligible result with a message shows it beside the fixed label ("No check-in event now · ") on the card, where it wraps rather than ends in "…", in Settings' check-in line and in magpie accounts checkin; the TUI's narrow cell says c says why, and c's flash carries it (plugins#304). Without a message the label reads alone.

plugin_checkin.go runs these through the same checkiner as the built-in check-ins (checkin.go): each signed-in, in-use account once a Beijing day, the first look 2 minutes after start and then every 30 minutes, a failed asked again after 30 minutes, every other outcome settled for the day. A done, inactive or ineligible answered before noon Beijing (checkinSureHour) for an account magpie hasn't seen claim that Beijing day is provisional (provisional, #3326): a vendor whose day turns at UTC midnight (08:00 Beijing) or later still answers yesterday's "already" at 00:00, and magpie took it for today's and never asked again. The loop asks it again 30 minutes after the answer, until a claim or an answer from noon on, so at most 24 more asks a day and none once magpie claims; a press (soon) asks it again at once, whatever the hour, since the vendor's answer is what the press is for. A claim stamps Claimed, carried over while later answers that day say done, so a done after magpie's own claim is settled. Such a record is sent with again: true (shown, never kept), and the card, Settings, TUI and CLI say the vendor said already checked in and magpie asks again later, not "Checked in today", and the card keeps Check in now. A vendor whose day turns after noon Beijing (a US day) is not covered. The Qoder, Qoder CN and ZCode plugins are the exception, as magpie's own Qoder check-in is (recheck, pluginRechecks, #2696, plugins#503): a campaign or gift plan can open mid-day (Qoder CN's ran 10:00 to 09:59 the next day), so the loop asks again 30 minutes after the last answer, whatever it was but a captcha or own-app, which waits on the user in the vendor's app and stands for the day (asked again, ZCode's claim only answered 3007 again, plugins#503), and Check in now asks at once, and their card keeps Check in now for an inactive result. Every other plugin keeps the day's result. A plugin whose vendor's day turns at another hour says when in until (an RFC 3339 time or epoch milliseconds; host.js passes it on as RFC 3339, plugin.Checkin.Until), kept as the record's ValidUntil: the answer is settled only until then, whatever its outcome (settled), the loop wakes then rather than at its next 30-minute look (wbCheckinLoop.tick), and an early done that says it isn't provisional, since the vendor said when its day turns. Qoder's daily credits open at 10:00 UTC+8 and close at 09:59 the next day (its /me/campaigns startAt/endAt); the Qoder plugins from 0.2.43 answer until a minute past the next opening, so a check-in before 10:00, which claims or meets the day before's campaign, is asked again at 10:01, not up to half an hour later (sdytman on Discord). Times are compared as instants, so the machine's zone doesn't matter. Results are kept in plugin-checkin.json by provider|<sign-in key> (pluginCheckinKey: the key plugin-auth.json keeps the sign-in under, autoclaw or autoclaw#x1y2z3), never by the display name: two sign-ins can share a name (AutoClaw's default can't be changed), and keyed by it only the first of them was ever checked in, by the loop or Check in now (plugins#254). The sign-in key holds over a refresh and over signing in to the same account again (settle in host.js puts it back under its key); a sign-in made after one was signed out the same day may take the freed key, and with it that day's result. An entry kept by provider|<display name> before then is carried over once the plugin's accounts are listed (adoptLegacyPluginCheckins): a check-in goes to the first sign-in in use of that name, the one the old key asked, and only to it, so its namesakes are asked and none twice; an Off in settings.CheckinOff goes to every sign-in of that name, since none of them was checked in while it was off. A plugin-checkin.json that can't be read or parsed is left as it is and carried over once it reads; until then no plugin account is checked in, and each says why (readCheckins, as for every vendor's check-in file). A failure is recorded as failed and never resets an account, a key or a previous day's result. Each account's Usage card has the check-in row (checkinBy: "plugin:<provider>"), and Settings → Usage has a Plugins tab with a Daily check-in switch per provider (settings.PluginCheckins, POST /api/settings/plugin-checkin {provider, on}; Check in now is POST /api/usage/plugin-checkin {provider}). The press says what it came to, a count per kind (checkinPressSaid, #3326): claimed now with the credits, already checked in today, not available yet (inactive, ineligible, or an again answer), to check in in the vendor's own app, failed; a result is claimed now only when it carries asked (Asked, sent but never kept), so an account claimed earlier today counts as already. magpie accounts checkin and c on the TUI's Usage page include them. Every check-in, built-in or a plugin's, also skips an account listed in settings.CheckinOff by its file key (#1902): checkinNow asks nothing for it, by the loop or a press, CheckinAccounts() lists each account with its own on for Settings (checkinAccounts, a row each under the vendor's switch when it has two or more, POST /api/settings/checkin-account {key, on}), and its card carries checkinOff. Under each vendor's switch in Settings, a Check in now row checks one account in once (checkinNowRow, drawn by checkinnow.js, loaded when Settings draws a vendor's check-in so it weighs nothing on the core; POST /api/usage/checkin-account {by, key}, provider.CheckInAccount; xiaowu_95660 on Discord): the same checkinNow press, with only set to that account's key, so no other account is asked or reported, and the account is asked even while its switch is off, which the press leaves as it is. With two or more accounts the button opens the app menu to pick one. The row says what came of it: checked in with the credit and streak, already checked in today, not eligible or no check-in event with the vendor's message, check in in the vendor's own app, or the failure. It reads the Usage cards again but doesn't draw Settings again under the button.

The switch is off by default. For a provider whose vendor magpie checked in through the plugin's fetch before (WorkBuddy, Trae CN, MiniMax Code, Qoder), it follows that vendor's existing switch until set on its own, and magpie's own check-in leaves that provider's accounts to the plugin (pluginChecksIn), so an account is never checked in twice.

Trae CN plugins without auth.checkin use trae_checkin.go through the plugin's fetch: /status, then /claim while the check-in is on and today's isn't in. A claim answered 9074 (当前参与用户太多,请稍后再试) is saved as own-app, settled for the Beijing day like any answer other than failed: no retry ever got past it (#808), so neither the loop nor Check in now claims again that day, and the card, Settings, TUI and CLI say Trae CN refused the check-in (9074) and to check in in the Trae CN app, not that Trae pays only its own app, which Buddy Switch disproves (#1920). Since plugin 0.2.14 the account this machine's Trae CN desktop client is signed in as sends the client's own device id (the iCubeAuthInfo://icube-dc:<id> key of its storage.json, read only) with its check-in; every other account keeps its own device, and none is made up or rotated (#1705). 9074 on /status, and every other code, keep their previous handling. own-app is not a plugin hook outcome.

WorkBuddy's check-in (workbuddy_checkin.go, built-in or through the plugin's fetch) tells a 401 apart. WorkBuddy's gateway answers a token it refuses with a bare HTML 401, which the card said only as "Unauthorized" and retried every 30 minutes. On a 401 from /v2/billing/meter/checkin-activity-status or /daily-checkin, the account's credits (/billing/meter/get-user-resource-summary) are read with the same headers: when they read, the sign-in is good and the check-in alone refuses magpie (WorkBuddy's own app sends its check-in, and only that, with an X-Device-Token from its security SDK), so it is saved as own-app for the day; when they don't, it is failed with "sign in to it again".

Qoder plugins without auth.checkin still use qoder_checkin.go through the plugin's fetch. The server's CLAIMABLE status decides whether to claim; the local [startAt, endAt) check only recognizes an already-claimed campaign and its expiry, including one that crosses Beijing midnight. Successful results keep the active campaign's end in the optional until field of qoder-checkin.json. Scheduled checks reuse results from the same Beijing day for at most 30 minutes and never past that end, so a long campaign cannot hide new or reset campaigns indefinitely. The existing loop looks every 30 minutes and on a Beijing day change; a midnight refresh saves today's result for the Usage card and TUI. An inactive result is now asked again after 30 minutes rather than settled for the day; failures retain their existing retry schedule. A manual check-in always asks immediately. Saved results without until remain readable and use the same 30-minute refresh, with no migration needed. Other vendors and plugins with their own check-in retain their daily settlement.

A plugin's own options

A plugin can declare switches for its provider (#2038): its auth hook gains options: [{key, label, description?, default?, confirm?}]. The host (host.js optionsOf) keeps an option whose key matches [a-z0-9_-]{1,40} and whose label isn't empty, drops a key seen before, caps the label at 60 characters and the description and confirm at 300, takes default only when it is true, and keeps the first 16. The provider is listed with them (plugin.Provider.Options). An option may give its words in the window's other languages, as a page's titles do (plugins#590): labels, descriptions and confirms, each {"zh": "…", "zh-TW": "…", "ja": "…", "de": "…"}, kept without what isn't a string or is empty, a language name over 16, or past 16 languages, each capped as the plain one is. label stays a string beside them, so an older magpie, which copies only the plain fields, shows the plain words, and OpenCode, whose AuthHook is provider, loader and methods, never reads options at all. filtersModels: true (anything else is false) says the plugin's model list leaves models out while the switch is on, as WorkBuddy's "Free models only" does. placement: "top" says the switch is about the whole plugin, not its requests (#5269), and has the editor draw it under the accounts, above Routing; any other value is left out, and the switch goes under the models.

The user's values are kept in settings.PluginOptions by the plugin's own provider id and the option's key, and set with POST /api/settings/plugin-option {provider, key, on}, which checks the key the same way. The host is handed them at init (options) and again after each change (setProviderOptions, plugin.SetProviderOptions, sent only to a host already running). A plugin reads them through input.magpie.option(provider, key) (the user's value, else the default; false for a key it didn't declare) or input.magpie.options(provider) (every declared key). Both read the current values each time, so a change reaches the plugin without a restart. A plugin written for older hosts checks input.magpie?.option first. When an option changes magpie keeps and hands over the value, and forgets the providers it keeps, so they are listed again: a models hook may list by an option (WorkBuddy's "Free models only", plugins#430). Nothing else runs. The check-in switch is separate and unchanged.

The provider's editor lists them under Plugin options (pluginOptionsField in app.js, the values from /api/providers' plugins[].options[].on): those with placement: "top" in a block right under the accounts, above Routing, the rest in one under the models, each in the order the plugin declares them, and the note that the plugin reads them under the first block drawn. A plugin that says no placement is drawn as before, and an older magpie, which copies only the fields it knows, draws every option under the models. Each is an Off/On beside the plugin's label and description, put in as text, in the window's language (optionWords: its labels/descriptions/confirms by the language, then by its first part, so zh-TW reads zh, else the plain one). One with confirm asks it before it is turned on. Changes wait for Save, which posts each changed one before the provider. While an option that says filtersModels is on, as saved (the list was read with it), the Models field says so under the chips (pluginFilterNote): "Only some models are listed: the plugin option “…” is on.", with the option's label in the window's language. Off, or with no such option, nothing is said.

A plugin's package options, the second argument its function is called with (options in plugins.json), are a separate thing: numbers and words, not switches. The Plugins page's Installed row has the same Options JSON editor for them that a middleware or gateway plugin has (optionsEditor in plugins.js, POST /api/plugins/options, which restarts the host), shown for a plugin that is neither (a provider's, an agent's) when its package suggests options (package.json magpie.options, /api/plugins' optionsExample, now read for every plugin, not only a middleware's) or it has some set; never while it is off (plugins#592: Devin's cacheKeepaliveInterval and cacheKeepaliveMaxPings, beside its Cache keep-alive switch). Its Clear asks "Saved options will be removed…", for every plugin now, not a middleware's words. The Off/On switches above don't get number fields: that would be a new option type across the host, settings and the provider editor. TestProviderPluginOptionsExample, plugin-provider-options.test.cjs.

A request a plugin sends by itself

A plugin can tell magpie of a request it sent its vendor on its own, outside any request the gateway handed its fetch (plugins#592: Devin's cache keep-alive pings, which re-send the last turn on a timer and were invisible). It calls input.magpie.usage(provider, {kind, model, input?, output?, cacheRead?, cacheWrite?, status?, ms?, error?, account?}). The host (host.js reportUsage) throws a TypeError for a provider that isn't a string of 1–200 characters, a call that isn't a plain object, a kind that doesn't match [a-z0-9_-]{1,40} or an empty model; it makes each count a whole number from 0 (what isn't a finite number is 0; status at most 999), caps error at 500 characters, and takes account only when it is the provider's (devin or devin#…), else the account of the request in hand (input.magpie.account(provider), keyFor), else the provider's id. A plugin reads input.magpie.account(provider) while its fetch runs to name, later, the account a timer's request belongs to. It is sent as an unasked {event:"usage", provider, account, usage} (dispatch in host.go, plugin.OnUsage).

plugin_calls.go registers the one listener and appends a row: agent magpie, the provider as magpie names it (provider.PluginID), the account's display name (provider.PluginAccountUser), the model as both asked and served, its kind, tokens, status, time and error. It is a counted row, as the routing classifier's are, not a probe's: it is priced and in the totals, since the user who turned the keep-alive on is to see what it costs. Its kind cache_keepalive is in the purpose catalog as Cache keep-alive (purposeKinds, purposes.js), so the request log names it and can filter by it. It carries no session, so the session views don't count it as a turn. A plugin written for an older host calls input.magpie?.usage?.(…); an older plugin reports nothing, as before. The ping is never routed back through the gateway, which would re-shape the body and break the cache it keeps warm. TestPluginReportsOwnUsage, TestPluginKeepaliveIsCounted.

A model's load

A plugin can say how busy each model is (axelburks on Discord: an in-house vendor queues requests to its busy models, and a load put in the model's name changed only when the list did). It calls input.magpie.load(provider, {"<model id>": 0 and up | null}) whenever it likes, from its own timer, as usage data refreshes; magpie never asks. The host (host.js reportLoad) throws a TypeError for a provider that isn't a string of 1–200 characters or a loads that isn't a plain object, clamps each finite number to 0–10000 (LOAD_MOST, plugin.LoadMost: past 100 is a vendor that queues, 200 twice what it serves at once, axelburks again; 10000 is a sanity cap), sends null as -1 (cleared), drops every other value and an id over 200 characters, takes at most 1000, and sends what is left as an unasked {event:"load", provider, loads} (dispatch in host.go). It returns how many it took.

load.go keeps each by the plugin's provider id and the model id lowercased, with when it came (noteLoads, at most 1000 a provider). ModelLoad(provider, model, now) answers it by the plugin's own id of the model (its callers, the provider editor and busyOf, map a model the user lists by another id back through OwnModelID first), a model@size falling back to its model, and unknown once it is older than LoadFresh (5 minutes): a plugin that stops reporting leaves its models unknown, never idle. Nothing is saved; a restart starts with none known.

The provider editor shows it by the model as a grey badge (/api/providers' models[].load, loadTag in app.js). Routing reads it only when the user sets Busy models last (settings.BusyLoad, POST /api/settings/busy-load {at}, off by default): see restLast and busyBehind in gateway routing.

A search API that uses a plugin's sign-in

A plugin's search entry can name one of its own sign-ins with auth: "<provider>" (axelburks on Discord: a search plugin reusing a vendor's sign-in had to read plugin-auth.json itself). The provider is one the plugin's auth hook signs in to, with models or an auth hook with none. magpie then manages the accounts as it does for that provider's models: it asks the accounts that are on, in the order its model requests take them (a search-rested one last), and the hook's ctx.getAuth() returns a copy of the one account chosen, renewed first under fresh (the shared de-dup), with the wait counted within the search's time. An account signed out while it is renewed stays signed out, and the search does not go out as it. The hook runs in inScope, so a token it saves with client.auth.set goes to the account it searched as. A refusal rests that account for search only; the provider's model routing never sees it. Not signed in, or none on, is an error in the request log and in the row in Settings, and the next search API is asked. A plugin with several providers adds an entry per provider. An entry with no auth, or one naming a provider the plugin doesn't sign in to, is a keyed search API as before. The search side is in plugin tools ("Sign in"); TestPluginSearchSignsIn covers it in search_test.go and search_signin_test.go.

A plugin whose upstream searches

A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, say) can say its upstream answers a web search tool by itself (#2027). Its config hook sets searches: true on the provider; the host passes it through (plugin.Provider.Searches), and pluginProvider sets the provider's Searches, as a custom provider's "Searches the web by itself" does (#359). searchesItself honours it for a plugin's provider only, on Anthropic's or Responses' API, and only for one the plugin has a model on: a client's web_search then goes to the plugin's fetch as sent, not through magpie's search. Another sign-in's Searches is never read, and Codex's and Grok's stay as they were. As with a relay, searchRank leaves it out, so magpie never picks it to search for other models; Settings can name it by hand (namedSearcherRank).

A plugin in front of an OpenAI-compatible API draws with the image models its list names (01huadalang on Discord: the SenseNova plugin, aqiu817/magpie-sensenova, lists sensenova-u1.5-lite from token.sensenova.cn/v1/models). Drawers lists a plugin provider's model for Settings' image generation picker when its id is an images-API model (catalog.DrawsID and catalog.ImagesAPI) and the plugin speaks it on @ai-sdk/openai-compatible (Provider.PluginOpenAICompatible); drawImages sends it to /v1/images/generations or /v1/images/edits under the plugin's base, through its fetch, which signs it as a chat. A model on another package (Anthropic's, a vendor's own API such as Cursor's) isn't listed, as no images API sits under that base. Grok's and WorkBuddy's plugins keep their own drawers. TestSenseNovaPluginDraws.

A plugin's model on Gemini's API (@ai-sdk/google, so Provider.APIs is Code Assist alone) draws as a Google sign-in's image models do (XYenon's Google AI Studio plugin, XYenon/magpie-google-ai-studio). Drawers lists it when its id names an image model (catalog.DrawsID) or the plugin says it gives images (capabilities.output.image, or models.dev's modalities.output, read into OutputModalities), and it isn't an Imagen (catalog.ImagesAPI, which draws on :predict, not served). draw sends it to drawCodeAssist (pluginDrawsGemini): one generateContent per image through the plugin's fetch, with responseModalities ["TEXT","IMAGE"] (Request.draws asks for it of a model not named for images), and an edit's pictures as the prompt's inlineData; the pictures come back from the answer's inlineData. The images routes' key holds and usage apply as for any drawer. TestGeminiPluginDraws.

A request pluginFetch sends goes under the loader's baseURL, else the model's own api.url, the provider's api, its npm's default (pluginRequestBase in plugins.go); magpie's /v1 is taken off the path, as the AI SDK's base ends where magpie's /v1 does. The loader's base is one for all the provider's models, so an Anthropic model whose own URL ends in /v1 goes under the loader's base + /v1 when that base doesn't end in it: Copilot's loader says https://api.githubcopilot.com (or its enterprise host), its Claude models are on /v1/messages (models.dev's api.url, and OpenCode's own Copilot provider adds /v1 for them), and sent to /messages they were answered 404 (cyoking1 on X). A model whose own URL has no /v1 (Kiro's) and a base that ends in it go as before. TestPluginAnthropicBaseKeepsV1.

Embeddings, rerank, speech and transcriptions reach a plugin provider whatever API its chat models are spoken on: serveRetrieval sends them under Provider.OpenAIBase, which is plugin://<id>/v1 for a plugin (its Chat base for any other provider), so they arrive OpenAI-shaped at the plugin's fetch, at <base>/embeddings, /rerank, /audio/speech or /audio/transcriptions under the base pluginFetch picks for the body's model, with the model's own id. The plugin answers them or puts them in its vendor's shape (XYenon's Google AI Studio plugin: Gemini's embedContent, a TTS model's generateContent); magpie converts none of them to Gemini's API. Before, a plugin with no @ai-sdk/openai-compatible model was turned away 400 "has no OpenAI-style API". The model is named provider/model; the retrieval routes' key holds, account holds, masking and usage apply. TestGooglePluginTakesEmbeddingsAndSpeech.

A plugin's model that says it gives video (capabilities.output.video, or modalities.output: ["video"]) makes videos (customVideomakers; the Grok plugin keeps its own). Start, poll and content go OpenAI-shaped through the plugin's fetch on the account, to <base>/videos, /videos/{id} and /videos/{id}/content (videoBase, Provider.OpenAIBase): a POST of OpenAI's video body (remoteVideoBody: model as the plugin's id for it, prompt, seconds, size, input_reference as a data URL), answered {id, object: "video", status, progress, model}; the id is the vendor's, path-escaped in the GET. The poll and content GETs carry no model, so pluginFetch sends them under the loader's base (else the provider's api, else its npm's). The video's id names the account that started it (keyMark: a + signer), and markedKey asks after it on that account of the plugin's (AlsoOn) while it is signed in. Key account and model holds apply to all three routes (videoAsker, videoModelHeld, which needs the answer's model), and the start is in the usage ledger. TestPluginMakesVideos.

A plugin can instead mark single models of its list with searches: true (on the config hook's model or the models hook's list): a model that searches the web by itself when asked in plain words, such as Trae's search model. The host passes it through (plugin.Model.Searches), pluginCatalog makes it the catalog model's WebSearch "native", and the gateway offers the provider in Settings › Web search's picker and its own pick with those models alone (pluginSearches, partSearcher).

A plugin's service tiers

A plugin says which service tiers its vendor serves a model at with serviceTiers on the model (#2514): ids such as "priority" and "ultrafast", or objects with an id. The host keeps the ids (tiersOf in host.js, into plugin.Model.ServiceTiers), pluginCatalog puts them on the catalog model's Tiers, and CodexTiers offers them to Codex, as codexcat names them (priority is Fast). In forwardTranslated a request translated to the plugin's Chat or Responses keeps its service_tier (Request.OwnTier) only when it is among the model's tiers (provider.PluginTiers); a request relayed in its own protocol was sent as the client wrote it before, and still is. A model served at priority on its Chat or Responses API has fast mode (CanFast, via pluginTierOn), whichever plugin it is: it can be a group's fast member or an agent's fast pick, and it can be picked Ultrafast when it is served at ultrafast too (UltraOn). Fast mode in Claude's words (speed "fast", or a fast pick from an agent on Claude's API) reaches the plugin as tier priority, or as ultrafast for an Ultrafast pick, when the model is served at that tier (Lovest on Discord). Cursor's fast flag and -fast siblings still give Cursor's plugin fast mode as before.

A request translated to the Grok plugin's Responses API that turned tools off with no tools declared (Chat's tool_choice: "none", Anthropic's {"type":"none"}, Gemini's functionCallingConfig.mode NONE) reaches the plugin's fetch with tool_choice: "none" and no tools (#3110). Before, it went without a tool_choice, the same as a request with no preference, so a plugin that adds a server-side tool of its own (Grok's x_search, magpie-community/plugins#263) couldn't respect it. buildResponses keeps the "none", and forwardTranslated leaves a lone tool_choice out for every other upstream (keepsLoneNone): every vendor, xAI and Copilot (refusesLoneToolChoice, #378), and every other plugin, whose vendors haven't been tried with a lone "none". So what a vendor is sent is unchanged. Grok's Responses backend doesn't take it either: the Grok plugin's bodies are shaped by grokPluginBody, which keeps the lone "none" that grokBody drops for the built-in, and the plugin leaves it out before its request goes to Grok (0.1.18, the mover's min). A request the plugin serves in its own Responses protocol goes to its fetch as the client wrote it, and the client's own tool_choice object of a type Grok's backend doesn't take (an allowed_tools naming the client's tools) was dropped the same way (grokShaped), so the plugin couldn't tell it from no choice and added x_search over it: a tool outside the client's allowed list went out. grokPluginBody keeps such an object for the plugin to read now, and the plugin leaves it out before Grok as it does the lone "none" (#3153); the built-in, which is Grok's last stop, still drops it. Chat, Anthropic and Gemini requests still carry no tool choice beside no tools, which OpenAI's Chat refuses ("'tool_choice' is only allowed when 'tools' are specified"). TestToolsOffWithoutToolsReachesPlugin, TestToolsOffWithoutToolsNotSentToOtherPlugins, TestToolsOffWithoutToolsNotSentToVendor, TestToolsOffWithoutToolsLeftOutForXAI and TestToolsOffWithoutToolsPerBuilder in tool_choice_none_test.go, TestGrokPluginBodyKeepsLoneNone, TestGrokPluginBodyKeepsUnsupportedToolChoice and the gateway-to-plugin TestAllowedToolsReachesGrokPlugin, cover it.

A plugin model's sampling

A plugin says whether its vendor takes a model's temperature and top_p with temperature on the config model — Factory's OpenAI route says false of its reasoning models (plugins#154) — as models.dev says it of the built-ins, or on a model the models hook lists. The host carries it (temperature in host.js, into plugin.Model.Temperature), pluginCatalog puts it on the catalog model's Temperature, and RejectsTemperature reads it there as it reads a built-in's: a request translated to the model goes without them (build), and one relayed on Chat or Responses does too (passthrough, gateway-routing). A model nothing says so of keeps what the client sent. OpenCode's capabilities.temperature is not read for this: its false is what it reads a models.dev silence as, not a refusal said.

A plugin's decision API

A plugin can serve TypeSafe's System One for its provider (#1514). Its config hook sets decide: true on the provider, and decides: true on a model that answers questions rather than a conversation, in the config hook or on the models hook's list. The host passes both through (plugin.Provider.Decide, plugin.Model.Decides). pluginProvider then sets the provider's Decide to plugin://<id>/v1, its own base: pluginFetch sends nowhere but the loader's host, so a decision address of the plugin's own couldn't be reached. AskSystemOne and the gateway's classifier post /v1/systemone with Provider.Do, which reaches the loader's fetch as {baseURL}/systemone with the account's sign-in.

In decide.go a plugin provider's decision models are the ones it marks (pluginMarks, read from the plugin's current listing) and Jev's by name (jev-*). They are kept from agents (isDecision in buildEntries), refused for chat ("only decides"), refused as a member of a group beside models that hold a conversation (a group of decision models alone answers /v1/systemone: gateway-routing), and offered as a group's classifier (Deciders, DecisionModels). A mark counts only when the provider says decide; without it every model stays one to chat with. A plugin provider's editor (the account editor) has no address fields, so this address is never typed; the GUI marks the decision models from deciders.

Where the agent works, for a plugin's fetch

A plugin's fetch runs in magpie's plugin host, so its process.cwd() is magpie's own folder, not the folder of the agent that asked. A plugin that tells its vendor the user's environment, as the ZCode plugin's Start Plan request does in its # Environment section, said magpie's ~/.config/magpie as the working directory, and the model went looking there (magpie-community/plugins#86).

The gateway tells the plugin instead. On every request to a plugin's provider, forwardOnce calls tellWorkPlace (workdir.go), which reads the request as sent to the plugin with the same workPlace that rules by folder use (gateway-routing) and sets two headers on the plugin's fetch:

Header Value
x-magpie-work-dir (provider.WorkDirHeader) The folder the agent says it works in, percent-encoded UTF-8 (decodeURIComponent reads it).
x-magpie-work-git (provider.WorkGitHeader) yes or no: whether that folder is in a git repository. The agent's own word beside the folder when it says one (Claude Code's Is a git repository: true/false, OpenCode's Is directory a git repo: yes/no), else, when the folder is on this computer, whether git finds a repository from it: the nearest .git in it or above it that git takes for one, a folder with a HEAD naming a ref or a commit and objects and refs folders (in the one its commondir names, for a linked worktree), or a file gitdir: <folder> naming such a folder (a linked worktree's, a submodule's). A .git folder git doesn't take, an empty one say, is passed over as git passes it over, so an empty /tmp/.git doesn't make every folder under /tmp a repository (#3675); a .git file that names none is no, as git stops there (provider.GitSaid, provider.GitOnDisk and provider.GitAt in workplace.go; the library's skill groups find a skill's checkout with the same GitAt).

Each is left off when it isn't known: no folder said, or a folder the agent didn't say is a repository that isn't on this computer or has a .git on the way up that magpie can't read (another user's, through a shared magpie). A plugin then leaves out what it can't know rather than saying magpie's. The host's fetch (unsaid in host.js) takes both headers off every request a plugin sends, so a plugin that sends on the headers it was given sends them to no vendor.

TestPluginToldWhereTheAgentWorks (plugin_workdir_test.go) sends Claude Code's and Codex's captured requests and Pi-style ones from a folder in a repository, one not and one under an empty .git, through the fake plugin, and checks what the plugin read and that the vendor got neither header. TestGitOnDiskIsWhatGitFinds, TestGitOnDiskAgreesWithGit (each folder asked of git rev-parse --git-common-dir too, beside worktrees and a separate git dir git made itself) and TestGitOnDiskUnreadIsUnknown in workplace_test.go hold GitOnDisk to what git finds, and GitAt to the folder git finds the repository in.

The session the agent named, for a plugin's fetch

The agent's own headers never reach a plugin's fetch: forwardOnce builds the plugin's request afresh. A plugin that keeps state per conversation had only the request's text to go by. Devin's cache keepalive keyed Claude Code Auto's permission check by its first user message, which magpie's translation merges with the transcript, so the history grew in the middle of it and every check looked new; a check left its older pings running beside the new ones (magpie-community/plugins#620, zelong77).

So forwardOnce sets two more headers on every plugin request, each dropped first when the agent sent one and left off when the agent named none:

Header Value
x-magpie-session (provider.SessionToPluginHeader) The session the request names, as sessionOf reads it: the caller's own X-Magpie-Session, else the agent's header (Claude Code's x-claude-code-session-id, OpenCode's x-opencode-session, Codex's session_id and the rest of sessionHeaders).
x-magpie-subagent (provider.SubagentToPluginHeader) The Claude Code subagent the request is of (x-claude-code-agent-id, subOf); never sent for the lead's own turns.

unsaid in host.js takes both off whatever the plugin sends on. Devin 0.1.34 keys its keepalive by them. TestPluginToldTheSession (plugin_session_test.go) sends Claude Code's lead and subagent, a caller's X-Magpie-Session, OpenCode's header and none, to a relayed Anthropic model and a translated Chat one, unstreamed, and checks what the plugin read and that the vendor got neither header.

Whether another candidate follows

A free model's vendor may queue a request for minutes: Qoder answers its code 10605 and its plugin waits in Qoder's queue as Qoder's client does (up to 4 minutes), CodeArts answers a 429 with queue-status: queued and its plugin polls the trace for up to 5 minutes. While another account, provider or routing group member could answer at once, that wait only keeps the agent waiting (axuhere on X: "模型请求正在排队 · 预计等待超过 10 分钟").

So the try loop marks a try that isn't the last candidate (withFallback in continuation.go, from !last in the loop), and forwardOnce sets x-magpie-fallback: 1 (provider.FallbackHeader) on that plugin request; a header the agent sent under that name is dropped first. A plugin told so answers a queued request at once, a 503 with the queue's Retry-After and a message that says the queue (Qoder 0.2.40: "Qoder queued the request for dfmodel (this plan's queue: p3, 3 ahead); try again in 30s"; CodeArts 0.2.3 leaves the queue first). The 503 is busy, so the next candidate is asked, the trace shows the try's reason, and the queued one may be asked again in a replan round after its Retry-After. The last candidate is never told, and its plugin waits in the queue as the vendor's client does. unsaid in host.js takes the header off whatever the plugin sends on. A plugin model's test sends it as well, so a queued model is said at once there too (probe in test.go, TestPluginModelTestSaysQueued).

TestPluginToldAnotherFollows (plugin_fallback_test.go) sends a group of two members through the fake plugin: the first is told, gives way with a 503, and the second answers untold; a lone model is never told, and the vendor never gets the header.

Trae's plugin doesn't give way yet: Trae.app reads a queue_info.position on its own chat stream, but no real queued reply on the llm_utils_chat path the plugin uses has been captured, so its queue events stay ignored.

Two plugins for one provider id

The host runs one plugin per provider id. When two installed plugins have auth hooks for the same id, such as a third-party plugin and the user's own copy added by its folder, auths() in host.js takes the one picked for that id in plugins.json's prefer map (provider id → spec). Without a pick it takes the last one in the list, as OpenCode does. Only the serving plugin's provider.models hook runs for that id. Every plugin's config hook still runs, so another plugin can still add models or a name to config.provider[id].

Before this, the plugin that lost the id disappeared silently: its row read "Signs in to nothing magpie can use", and keepUnloaded could list the id twice, once from the old plugin-providers.json (neiko on Discord). Now:

  • init returns each plugin's provides (the ids its auth hooks name) and servedBy (id → the other spec, for each id it doesn't serve).
  • plugin.Clashes turns these into {id, by, with} per spec.
  • /api/plugins gives each row its clashes, along with the provider's listed name.
  • keepUnloaded doesn't keep a provider from before when another plugin serves its id now.

Both rows stay visible on the Plugins page:

  • The serving row says "{other} signs in to {name} too; this one serves it".
  • The other row says, in amber, "{name} is served by {other}, which signs in to it too". It has a Use for {name} button, which calls POST /api/plugins/prefer {spec, provider} (plugin.Prefer) and restarts the host.

In the CLI, magpie plugin list prints the same two lines, and magpie plugin use <name> <provider> makes the pick.

How the store handles picks and names:

  • Removing a plugin drops its picks.
  • Switching a plugin off hands the id to the other plugin until it is switched on again.
  • Re-adding a plugin under a new version or spec keeps its picks.
  • Remove, off, options and prefer find a plugin by its exact spec first, then by package name (indexOf in store.go). This way, acting on one plugin never reaches another plugin that has the same package name.

A plugin that is slow or stuck

The host loads every plugin side by side (loadPlugins in host.js) and gives each one pluginLoadWait (20s, host.go) for its import and its plugin function, and each config hook as long. A plugin still loading then is told as not loaded ("the plugin's load didn't finish in 20s") and the host answers init with the rest; what it returns later is dropped until the host starts again. Hooks are still kept in the list's order. A listing (providers) asks every provider side by side too, and gives each models hook pluginListWait (20s, inside refreshDeadline's 30s): one that hasn't answered is listed as fallen back with that as its listError, so magpie keeps the list it had, and that answer isn't kept for requests (keepInfo). Before, one plugin whose sign-in kept failing held every plugin after it until init's two-minute deadline failed the whole host, and one stuck models hook failed the whole list (shualaitianduai on Discord). TestStuckPluginLoadHoldsNoOther and TestStuckModelListHoldsNoOther hold both.

A plugin's 401 about the model

A 401 marks the account's sign-in by default (notePluginSignIn in plugins.go), and the gateway fails a 401 over to the provider's next account (retryable in fallback.go), which a model the plan doesn't serve answers the same way. So a plugin that answered "this model isn't available to you" with 401 marked every account of the provider as needing a new sign-in, for credentials that were fine (magpie-community/plugins#468). A 401 without X-Magpie-Sign-In whose body says the model isn't served (provider.ModelUnserved, the gateway's unservedWords, read decoded by catalog.Words) and nothing of a token, key, credential, session or sign-in (signInWords) is now read as kept (modelOnly401). Only the body's first 64KB is read, and the body goes on whole. The gateway still rests the account under its usual failure backoff for that answer; the guide asks for 403 or 404 for a model the account may not use, which modelRefused reads as the model refused. TestPluginModel401KeepsSignIn in plugin_signin_model_test.go covers both kinds of 401.

A 401 on an access token its refresh token renews

An OAuth account keeps a short-lived access token beside its refresh token, and its plugin's loader (or magpie's auth.refresh) renews the access token when its stored expires comes. A vendor can turn an access token away before that: Copilot's API dropped the inference token of a slot that had carried no traffic, while its GitHub OAuth token still traded at /copilot_internal/v2/token, and the bare 401 marked the account "sign-in has expired — sign in again", whose row then offered only a new device flow (magpie-community/plugins#618, jinpy666). The host now judges a 401 its plugin said nothing of (no X-Magpie-Sign-In) against the sign-in as the request found it (staleAccess in host.js): an OAuth sign-in with a refresh token whose access token is still the stored one and not due yet is made due (expires 1, under the auth lock, only while the access token is unchanged) and said kept, so the next request renews it and goes through, and the gateway fails this one over as it fails any 401. The account is still marked when the access token was renewed for this request and turned away, when it was due already and the plugin didn't renew it, when the account has no refresh token, and when the plugin says so (an error with signIn: "expired", a refresh auth.refresh was refused). A sign-in that can't be read when the 401 comes (readAuthState's known false) is unknown: kept, never marked. A marked account is still routed to (pluginAlsoOn leaves no account on out for its mark), so a slot marked before is renewed on its next request and cleared by the success. Copilot's plugin 0.1.1 says expired only for the token exchange's own 401 and renewed for a quota read GitHub answers, which clears a mark left from before. TestPluginStaleAccessRenewsNotLapses in plugin_stale_access_test.go covers the idle account renewed, a renewed token turned away, a refused refresh, an unreadable sign-in and the marked account still routed.

A sign-in nothing uses

A plugin's auth.refresh renews a sign-in only when something uses the account (a request, its models, its usage, its check-in) within its refreshLead of expires. An account left idle past its token's life lapsed, and for a vendor whose session dies with its token the user had to sign in again: OrcaTerm's WeChat token lives two hours, and its refresh after that answers SESSION_EXPIRED for good (#5080, orinsid, magpie-community/plugins#675). So the magpie serving the gateway renews each such sign-in as it comes due (KeepPluginsSignedIn in plugin_keepalive.go, started beside KeepPluginsListed). It reads the due times from plugin-auth.json (plugin.RenewAt: expires less the lead the host reckons, Provider.RenewLead, listed with Renews), asks nothing and starts no host until one is due, and sleeps until the next, at most five minutes. A due sign-in is renewed through the host's own renewal (keepSignedIn → renewal in host.js), the one a request makes: one at a time per account whoever asks, a request arriving meanwhile waiting for the same one, under the lock file every magpie process renews under, through the account's proxy. Only accounts switched on and not marked, of a plugin provider not switched off, hidden (leftAlone) or being moved, are kept. A renewal that fails marks nothing: it is held back a minute, doubled each time to half an hour, for that sign-in only; only the plugin's signIn: "expired" marks the account, as at a request. A plugin whose renewal costs the account something, or whose refresh token another client holds too, says auth.keepAlive: false and is renewed only when used. No plugin in magpie-community/plugins says so as of this change: their refreshes cost no quota, those that rotate a refresh token (Cline, Factory, Nous, SenseNova, CodeArts, Qoder, MiniMax) already rotate it at use, and the ones reading another app's sign-in (kimi-work's reference accounts, Raccoon's desktop) never refresh it. TestKeepSignedInRenewsIdleSignIns in plugin_keepalive_test.go runs the renewal fixture in a real host; TestKeeperAsksOnlyWhatIsDue, TestKeeperBacksOffAFailedRenewal, TestKeeperHoldsWhatTheHostFindsNotDue and TestKeptSignInsAreTheOnesSwitchedOn in plugin_keepalive_test.go cover the loop and which accounts it keeps.

An account signed out while one of its hooks runs stays signed out. A hook that saves a sign-in through client.auth.set (a models list spending a rotating refresh token, as the fake plugin's rot- sign-ins do) saves nothing once the account it was called for is gone from plugin-auth.json: inScope in host.js notes whether the account was signed in when the call began (had), and auth.set checks it under the file's lock, as renewLocked already did for a renewal. A sign-in's own steps (signingIn) are not held to it, since their account is new. Before this, a listing that started before a sign-out, or before a failed move took its accounts back out of the plugin (putBack), wrote the account in again, and the plugin kept an account of a move that failed (#5126, #5119). TestSignOutOutlastsRunningHook in signout_hook_test.go holds the hook (FAKE_MODELS_HOLD) across the sign-out in a real host.

A model's free and rate

magpie never reads free from rate: rate 0 is none given (plugin.Model.Rate in providers.go), and a model is free only by its own free: true, a $0 list price or the user counting its whole provider free (Provider.CountFree) (FreeModel in models.go). A plugin sets free from the vendor's word; the guide says so (magpie-community/plugins#468).

A model that gives no text

A model's capabilities.output says what it gives. The host passes on the kinds marked true (kinds in host.js, plugin.Model.Outputs) and whether the object said yes or no to any kind at all (kindsSaid, plugin.Model.OutputsSaid), so an embedding's {"text": false} is a model said to give nothing, not one said nothing of. pluginCatalog leaves out a model whose outputs were said and name no text, image or video (pluginTalks in plugins.go): an embedding, a TTS that gives audio alone. Every chat list builds on that list (/v1/models, the agents' provider.Catalog, Available and the editor's chips, routing), as the catalog's own lists leave such models out (textModel), #3279. A model whose plugin says nothing of its outputs is kept, whatever its id; an image or video model alone is kept where it is until #2792 places it. Tests: TestPluginModelGivingNoTextLeavesTheChatLists (gateway, a real host), TestPluginModelSayingNoTextLeavesTheChatList, TestPluginAccountListLeavesTheSpeechlessOut.

The npm registry plugins come from

Plugins are installed from, and magpie's own npm questions (a package's newest version for the market, Update and the hourly check, its README, the search) are asked of, one registry (registry.go, timwangdev on X). Registry() takes the first of: the one set in magpie (npmRegistry in settings.json, npm registry on the Plugins page's Discover tab or magpie plugin registry <url>); BUN_CONFIG_REGISTRY, NPM_CONFIG_REGISTRY or npm_config_registry in magpie's environment, then in the login shell's (only the cached probe, proc.LoginEnvKnown, so asking never waits on a shell); install.registry in the plugins folder's or the user's .bunfig.toml; registry= in the plugins folder's or the user's .npmrc; npmmirror when the 「国内镜像」 switch is on; npm's own. The switch never comes before a registry the user named. Only an http(s) address with a host, no user info, query or fragment is taken (CleanRegistry); anything else is refused and not saved, and a bad value written into settings.json by hand is passed over. bun reads the environment, bunfig and .npmrc itself, so registryEnv tells it the registry only where it wouldn't find it: magpie's setting (over the environment's), the login shell's, the switch's mirror. Lookups go to npm's own through the mirror logic as before when the registry is npm's or the switch's; otherwise fetchRegistry asks the user's registry, a package with an @scope:registry= of its own that scope's, with the //host/path/:_authToken= the .npmrc keeps for the longest matching prefix (${VAR} expanded) and no other host's; a redirect to another host drops it. The token is never logged or shown. npm's download counts are still npm's. Not read: bunfig's [install.scopes] for magpie's own lookups (bun reads them for installs), .npmrc's _auth and username/password, NPM_CONFIG_USERCONFIG and npm's global npmrc. /api/plugins says which registry is in use and where it came from (registry). TestRegistryPrecedence, TestSetRegistryRefusesWhatIsntOne, TestBunTakesTheUsersRegistry and TestLookupsAskTheUsersRegistry in registry_test.go and plugin-registry.test.cjs cover these. The row is drawn by registry.js, which plugins.js imports when Discover draws it, so it weighs nothing on the core.

A GitHub listing's licence

A repository tagged magpie-plugin shows the licence GitHub's search reads from its LICENSE file. GitHub gives NOASSERTION for a file it can't match to one (MIT's text with a line of credit added) and nothing for none, and magpie drops NOASSERTION, so such a card had no licence while the same package on npm shows its package.json license. readTagged in github.go now keeps package.json's license (a string) as PkgLicense, and License falls back to it, on a fresh read and on one kept across searches (fresh) (magpie-community/plugins#468). TestTaggedRepos covers both cases and the one with neither.

A tagged repository's kind (Tagged.Kind, the card's chip and the GitHub strip's kind filter) comes from what its package.json declares. magpie.agent makes it an agent whether or not it has a main or exports: an agent that needs a runtime (a poller, a file watched) ships its agent file in moejs and a Bun module as main, and read only by the absence of main it was listed as a provider (miaocell/magpie-agent-deva, magpie-community/plugins#737). Middleware, a page and request hooks are still a kind only when that is all the package is, since a page or a hook beside a provider's module is that provider's accessory. A package with a module of its own has that module checked as committed (its main, the agent's too), else the one file it declares (TestTaggedAgentWithMain). One card has one kind, the declared one winning; an Installed row wears every chip it has, and an agent's wears Provider only when its module serves a provider (plugin-agent.test.cjs).

The same read keeps what the package says of itself: magpie.name (ownName) and magpie.summary (ownSummary in market.go: a language to a one-line sentence of at most 300 bytes, no control or format characters, anything else none) become Tagged.Name and Summary, and npm's copy's say them instead when the card installs from npm. ghListing in plugins.js puts them on the card in place of the repository's name and GitHub's description (which stays the English line when the package gives none), with an "Its own words" chip whose tip says nobody reviewed them; they never get the community badge and never resolve a name. A summary that isn't an object of strings reads as none, never as a package.json that doesn't parse, which would leave the repository out (MYCF711, #3608). TestReadTaggedOwnWords, TestOwnWordsBounds, plugin-own-words.test.cjs.

How ownership changes

Migration records use five states:

State Meaning
moving Migration is in progress or was interrupted. An explicit retry first rolls back the interrupted move.
plugin The plugin owns the built-in provider id. This is the only state recognized by Moved.
back Ownership returned to the built-in by an older magpie. MoveRetiring moves it again.
failed Migration failed and the built-in continues serving. Automatic retry waits six hours.
removed The user removed the plugin of a moved subscription. Its accounts stay with the plugin's sign-ins and the record keeps them. Nothing moves or installs it by itself; the plugin installed again (HandOver) or the editor's Move (Adopt) makes it plugin again, record and all.

The editor's "Move to plugin" action calls provider.Adopt. With accounts, adoption delegates to Move, which installs the plugin, imports every account and commits plugin ownership. Each account is tried through the plugin, and none holds the move back, since the built-in is retired: one the vendor refuses goes along marked lapsed, and one already lapsed or that fails its check otherwise (its vendor unreachable) goes along untried, for the plugin's own reads to judge. No model the built-in served is checked against the plugin's list. Only an install failure, the plugin not serving the id, or a sign-in the plugin won't import fails the move, which then puts everything back (putBack) and is tried again after six hours. A why from an older magpie's failed move (lapsed, unserved, account) is still read and translated by the page. With no accounts, adoption verifies the package and the provider it serves, then records plugin ownership without account checks.

Installing the plugin independently can also hand over ownership through provider.HandOver. The package must be enabled, meet the mover's minimum version, and serve the expected provider. After add, update, or upgrade, the GUI calls HandOver(ctx, false), which can adopt a built-in with no accounts. Existing built-in accounts wait for HandOver(ctx, true) in gateway maintenance.

KeepRetiringMoved first runs after 20 seconds, then hourly, or sooner when a retired built-in's failed move is due (nextRetiringRun). Each cycle maintains moved plugin versions, calls MoveRetiring, then performs automatic handover. MoveRetiring moves every subscription with a mover (retiring, which is MovableIDs) that has built-in accounts. A failed attempt waits six hours (moveRetry), or ten minutes when the built-in is retired (retiredRetry, retryWait), since nothing serves those accounts until they move: a move that failed because npm was out of reach or the plugin wasn't installed yet is tried again soon. The built-ins are being retired (the owner, 10-16: 陆续把内置Provider下线掉), so a back record is moved again too; a removed one is left until the user installs the plugin. Handover turns a removed record whose plugin is installed and current back into plugin, preserves a plugin already signed in under its separate -plugin id and skips existing migration records except a failed record old enough to retry.

There is no move back: provider/moveback and magpie plugins move-back answer that the built-ins are retired, and removing or turning off the plugin doesn't move anything back either. Turned off, the plugin keeps the subscription plugin, off with it. Removed (RemovePlugin), the subscription is recorded removed, its accounts kept in the plugin's auth store, since plugin.Remove leaves sign-ins until the user signs out. The Plugins page and magpie plugins rm/off say the subscription stops working and its accounts are kept. Rolling back a failed move (putBack, through each mover's back and settle) is the only path that writes to the built-in's logins.

Removing a plugin also sets aside the model picks its providers left in providers.json (#2057, plugin_left.go). Before, nothing listed those records and magpie provider rm couldn't find them, so sync and backup asked for a sign-in to them on every run (NotSignedIn).

  • RemovePlugin reads which ids the plugin's providers have (pluginRecordIDs: PluginID of each provider plugin.Listed last gave for its spec, an off plugin's included) while it is still installed. It leaves out:
    • a built-in's id;
    • any id another installed plugin also serves.
  • After plugin.Remove, only records under those ids that hold picks alone (OnlyPicks) move into providers.json's pluginLeft, under the package's name. A record with an endpoint or a key is the user's own provider and stays.
  • With no listing known (no cache and no readable plugin-providers.json), nothing is set aside.
  • provider.AddPlugin is what the GUI, the CLI and AddPlugins (backup and sync) add through. It puts the package's records back, each one whose id has no record now. One the user gave to a provider since stays aside.
  • Switching a plugin off sets nothing aside, since off is undone by switching it back on. Records left behind by removals before this change stay as they are; they can't be told from picks a sync brought for a plugin not installed here yet.

New users do not see an unused deprecated built-in in the Add sheet. unusedSub leaves it out when it has no account. Until an installed replacement takes ownership, replacedSub makes the Add sheet show the plugin tile. The Plugins page is the installation entry point.

keepMovedCurrent maintains the required plugin version for moved subscriptions. Raising the owning mover's min after publishing a plugin fix triggers this update path. Update failures are logged; disabled packages and local-folder installations are not automatically replaced.

The editor's Update button and Update all install npm's newest version; a pin the user set is kept until they update it themselves, and is then unpinned. keepMovedCurrent is the one path that acts without the user pressing anything, so installPlugin leaves what the user chose: a pinned npm version below the move's min is not reinstalled, and the move says it is pinned and which version it needs; a git install is reinstalled from its own spec; an unpinned npm one goes through plugin.Upgrade (npm's newest, which bun says why it won't install under a minimumReleaseAge, where Add's @latest would quietly give an older one); a plugin the user turned off is left alone.

A @magpie-community package npm doesn't give is installed from the community repo's dist branch (dist.go). npm can't take a new package's first version without an owner's 2FA (Trusted Publishing sets up only a package that exists), so reviewed plugins sat unmerged waiting for someone to publish them (magpie-community/plugins#84); a Trusted Publisher made after 2026-09-03 allows stage publish only, and zed 0.1.7 and zen-free 0.1.7 were refused that way. The repo's publish.yml now packs every merged version onto dist (scripts/dist.mjs: tgz/<file> and index.json with each version's sha512, manifest and the README) with nobody's credentials, and npm is published to beside it. install asks npm first, as before; only when bun add fails for a community package at latest or an exact version (distWanted), and not because of the user's minimumReleaseAge (that hold is kept), does installDist fetch the tarball, refuse it unless its sha512 is the index's, keep it in plugins/dist and bun add ./dist/<file>. A later install from npm takes its place and pruneDist removes the tarballs neither package.json names nor bun.lock's packages has a package at: Bun installs from the lock's, which can be behind package.json, and Bun 1.4.0 writes a package it adds from a tarball into package.json a second time, the new tarball first, where encoding/json reads the second. A tarball only the lock's workspaces names (Bun 1.4.2 and 1.4.3 leave the one replaced there) goes. A lock behind package.json put a package's older version back at every bun command, and, once that tarball was gone from plugins/dist, failed every bun add and bun remove, of any plugin, with ENOENT extracting tarball from <that package> (#3622, Windows, Bun 1.4.4), so before each bun command mendDist runs one bun update of every package the lock has at a dist tarball package.json doesn't name, when package.json's is there, which takes the lock back to package.json's without the network (bun add doesn't, on Bun 1.4.2 and 1.4.3), and logs it. Both read the lock's first object alone (lockHead), as Bun does: a shorter lock written over a longer one without truncating, as package.json was (magpie-community/plugins#405), leaves the old lock's packages after it, which would keep their tarballs and send them to bun update at every command. npmAsk (the market's version, Update, the hourly check) takes dist's latest when npm errors or is behind, and Readme falls back to its README. Tarballs are read through the 「国内镜像」 switch's jsDelivr copy when that is on (fetchJSONFaithful), else raw.githubusercontent.com. index.json is read from raw.githubusercontent.com, and with the switch on from jsDelivr beside it (readDistIndex): a jsDelivr edge serves the branch as it was when it cached it, up to 12 hours before (s-maxage=43200), and a Gcore edge served CodeArts' 0.2.3 as latest for hours after 0.2.4 was packed, so for a package npm doesn't have the hourly update, Check for updates and Update all found nothing newer (star21321321124 on Discord). The two copies are merged (mergeDist: every version either names, each package's newer latest), each version keeping the sha512 its own copy names; GitHub is waited for distGrace (5s) past the mirror's answer, and where it can't be reached the mirror's copy is read alone. TestDistOnlyPluginUpdatesPastAStaleMirror, TestDistIndexFromTheMirrorAloneWhenGitHubFails and TestDistIndexDoesntWaitOutAHangingGitHub in dist_updates_test.go, TestDistInstallsAPackageNPMDoesntHave, TestDistServesAVersionNPMRefused, TestDistRefusesATarballNotItsIndexs, TestDistTarballTheLockNamesStays, TestDistLockBehindPackageJSONIsMended, TestDistLockTailIsntRead and TestUpdateBunHoldsBackSaysWhy (with dist holding the held version) in dist_test.go and update_held_test.go cover these.

A plugin on the list whose package isn't in plugins/ is installed again from its own spec, switched off or not, by plugin.InstallMissing. KeepUpdated runs it 30 seconds after start and then hourly, before CheckUpdates. Nothing else did this. An update skips a plugin with no installed version, so the host said no such plugin: …\node_modules\… at every start until the user removed the plugin and added it again (#2002, Windows, after an update). Every bun command that changes plugins/ runs one at a time under installMu: install (with the first package.json it writes, through temp and rename), reinstall's bun update, and Remove's and add's bun remove, each after mendPackageJSON and then mendDist, which reads package.json. At start, KeepUpdated and keepMovedCurrent both run bun add. Two at once each read package.json before either writes it, so one change was lost (reproduced with Bun 1.4.3 on Windows), and a git plugin whose dependency was dropped can't be found. TestMissingPluginsInstalledAgain and TestBunCommandsOneAtATime in plugin_missing_test.go cover both.

A name the user types is resolved before anything is installed (resolve in resolve.go), in plugin.Add, which the CLI's magpie plugin add, the Plugins page's field (/api/plugins/add) and the movers all go through. A bare name that one of the community's listings goes by, case aside, is that package at the version given: its package or that without the scope, its short name (workbuddy, think-tags), its shown name (WorkBuddy, Command Code), a provider id it serves or the subscription it replaces, and a retired subscription's id through its mover (qoder-cn, plugin.SubscriptionPlugin = MovePackage). A name two listings go by, or one no listing goes by that isn't an npm name, is refused with the community plugins named. A name no listing goes by is npm's own package (opencode-gemini-auth) only when the list was fetched within the six hours: when the fetch fails, the copy kept or built in may not name a newer plugin, so the name is refused with why, and npm:<name> installs npm's package as written. Before, WorkBuddy failed as no npm name, and workbuddy installed npm's unscoped workbuddy (Atlas on Discord, 10-25). Scoped names, paths and git specs are kept as written, and a backup's or a sync's plugins are installed by their own spec (plugin.AddExact), never resolved. TestResolveCommunityNames, TestResolveRefusesWhatItCantName, TestResolveListUnread and TestAddByCommunityName in resolve_test.go cover these.

A plugin added from a git repository is reinstalled by reinstall's bun update, which re-resolves its branch or tag where bun add keeps the commit bun.lock has. Bun resolves a git spec through its own bare clone of the repository, kept in the install cache (installCacheDir in installcache.go), and a fetch there moves FETCH_HEAD but not the clone's refs/heads, so every resolve after the first named the first install's commit again: an update of a plugin added as an unfixed git+https://… URL said it had installed while the plugin, bun.lock and the clone all stayed at the old commit, and an uninstall followed by an add again resolved it too (#2954). refreshGitCache (gitrev.go) now fetches the clone's branches and tags before install's bun add (best-effort: a remote that can't be reached leaves the install to what the cache has) and before reinstall's bun update (an error: an update that didn't happen is not reported as done); a spec that names a commit (#<sha>) is left alone, for nothing is resolved for one and its pin stands. When bun update exits 0 but the plugin is still behind the commit the checks saw the repository at, reinstall says so rather than claiming the update. TestGitUpdateInstallsTheBranchsCommitNow and TestGitUpdateKeepsACommitPin (on the bun on PATH, against a local git+file:// repository) and TestGitUpdateSaysWhenItDidnt (with the fake bun keeping the lock's commit, as Bun's stale cache did) in plugin_gitupdate_test.go cover these.

A plugin the user turned off stays off through every install path: add keeps Off when it replaces an existing entry, so Add, Update, Update all and Upgrade all leave it as the user left it.

Constraints for fixes

Determine ownership before choosing the fix location. A bug affecting a moved subscription usually needs a change in the community plugin. A built-in-only fix does not reach moved users.

For a plugin fix, publish the corrected community package and raise the owning mover's min to that version. Change the built-in too when the fix must reach users who have not moved.

Keep the migration, host, and upstream behavior separate when investigating failures. A plugin bug can require a community change; a host, provider-card, sign-in orchestration, or migration bug can require a magpie change even for moved users.

The host gets magpie's proxy only as MAGPIE_*_PROXY and applies it to each fetch itself (proxyFor), and to each HTTP/2 session a plugin opens (http2.connect, tunnel, #1035). A host on the user's own network goes around that proxy as it does for magpie's own requests (onLAN in host.js, a port of internal/netproxy/lan.go's: a private, link-local, loopback or CGNAT address, a .local name, or a name every address of which is one of those, looked up for 400 ms at most and kept a minute; #1572). A provider's own proxy is still taken as it is. The two rules are kept the same: a change to one is made in the other. A program a plugin starts, such as the Grok plugin's grok login, gets it back as HTTPS_PROXY/HTTP_PROXY from the spawn wrapper in host.js, unless the plugin set one. A sign-in that works in the built-in and fails through the plugin may be a host difference like this one, not a plugin bug. The same wrapper starts a program that names no folder of its own in plugin-work under magpie's config folder (with PWD to match), not in the host's own folder beside settings.json: the chat page plugin starts the user's MCP servers this way, and a tool's file saved by a relative name, or one named like magpie's own files, landed among magpie's (TestPluginProgramsRunInTheirOwnFolder). A folder the plugin gives is kept.

magpie downloads the Bun build for this machine (bunTarget in bun.go): the baseline build on x64 Linux and Windows, the native bun-windows-aarch64 on Windows on ARM (it was turned away as having no build until #2183), and on a musl Linux such as Alpine (libc.Musl, the check Claude Code's download uses too) the musl one, bun-linux-x64-musl-baseline or bun-linux-aarch64-musl. A glibc build names glibc's loader, which Alpine lacks, so it couldn't start there and exec said "no such file or directory" (#1877). A musl Linux keeps its Buns and their state.json under bun/musl, so a machine whose C library changed never runs the other one's build or takes its set-aside versions; everywhere else they stay in bun, where a Bun downloaded before is. A bun that is on disk but can't be started says it is a build for another C library and names MAGPIE_BUN (cantStart), and it isn't fallen back from or set aside: the version before is the same build. Bun's musl build needs libstdc++ and libgcc; on an Alpine without them, bun add and the host's start say which library is missing and apk add libstdc++ libgcc (missingLibs). TestBunTargetForMusl, TestMuslBunKeptApartFromGlibc, TestCantStartSaysCLibrary, TestHostOnUnstartableBunSaysCLibrary, TestMissingLibsNamesThem and TestHostOnBunLackingLibsSaysWhich in bunmusl_test.go cover these.

A bun this machine can't run at all says so instead of its exit status (wontLoad, a *BunUnstartableError). Windows refuses to load Bun 1.3.14 and later before Windows 10 1809 and Windows Server 2019: they import kernel32's CreatePseudoConsole, which older Windows lacks, so the process ends with 0xc0000139 (STATUS_ENTRYPOINT_NOT_FOUND) before it runs (zgcwkj on Discord, a Windows service). A processor without an instruction Bun's x64 build uses (it targets SSE4.2) ends it with 0xc000001d on Windows and SIGILL elsewhere. bun add, bun update and the host's start (whyDied, cantStart) each wrap the exit in it. The message says which of the two it is and names MAGPIE_BUN. An install doesn't try the community repo's dist branch after it, because that bun add can't start either. The GUI's fail answers it with code bun_unstartable, bunWhy (windows or cpu) and said, the i18n.js key for it (bunSaid in api.go, kept there so app.js holds one line under its budget), which api() in app.js puts through t() in place of the English. TestBunSaidIsTranslated fails when a language lacks it. There is no fallback to an older Bun: the last one Windows Server 2016 loads, 1.3.13, is below BunVersion, and Bun's baseline assets are now the same binary. TestWontLoadSaysWindowsOrCPU, TestInstallOnUnstartableBunSaysWhyAndSkipsDist and TestHostOnUnstartableBunSaysWhy in bunload_test.go, TestFailSaysBunUnstartable in internal/gui and plugin-bun-unstartable.test.cjs (both engines, every language) cover these.

Bun takes only http:// and https:// proxies. A SOCKS5 one, such as a Mac's system SOCKS proxy, is given to every bun magpie starts as a loopback HTTP proxy in front of it (netproxy.Bridge): to the host through hostEnv, and to bun add, bun update and bun remove through bunCommand (netproxy.EnvForBun). Before, an install with only a SOCKS system proxy failed as UnsupportedProxyProtocol (#1409). An agent CLI that bun installed is updated through the bridge too (updateEnv in internal/agent/cliupdate.go). Claude Code, built with Bun, gets it for the Claude subscription's runs and sign-ins (netproxy.EnvForBunWith, #2651; see Claude subscription bridge).

The host reads its proxy once, when it starts. When the proxy magpie would give a new host differs from the one the running host got (the system proxy set after magpie started, as at login before Clash is up, or Settings changed), the next call to the host replaces it (proxyMoved in host.go, looked at no more than every 15s, or every 2s while the host has no proxy: proxyLookNone, #1518). A call made for a read nobody asked for, while allowances are read only when asked (netproxy.Held), never reaches the host. Before this, a host started without a proxy kept none, so the Grok plugin's grok models couldn't renew its token and the account read as signed out after each restart (#1363).

The host is told where magpie's gateway is as MAGPIE_ADDR (hostAddr in host.go): magpie's own MAGPIE_ADDR when it runs under one, on loopback when that listens on every interface, else Settings' port on loopback. A plugin with a service of its own reaches the gateway there; Magiczerowxy/magpie-chat's chat server asks MAGPIE_ADDR, then 3425, so with the port set in Settings its model list was empty (Magiczerowxy/magpie-chat#1). A port changed in Settings is a new host's at the next call, as a moved proxy is (proxyMoved), and opening a page whose plugin has a host part is such a call (plugin.Warm). Test: TestHostToldTheGatewayAddress.

What a plugin writes with console.log, console.warn and the rest goes to the host's stderr, which magpie logs a line at a time (drainStderr in host.go). A line over 4 MiB ends the logging: magpie logs that it did, and reads and drops the rest, so the host never blocks on a full pipe. Before, nothing read the pipe after such a line: on Windows the host hung on its next write, and on Linux Bun kept everything written after it in memory.

The host is waited for the moment it ends, not when its stdout reaches EOF (reap in host.go, proc.Output in output.go). A program a plugin started that kept a copy of the host's stdout (a Bun.spawn given Bun.stdout, a daemon it left running) held that pipe open past the host's end, so the reader never saw EOF, the only cmd.Wait never ran, and every host stopped (a restart, a moved proxy) stayed a <defunct> magpie-bun under magpie until it quit (acezan on Discord, a Linux systemd service). Once the host has ended, the reader has proc.OutputGrace (2s) to read its last lines; then its stdout and stderr are closed under their readers and the host fails as one that quit. Every command magpie starts elsewhere is waited for too: one it leaves running goes through proc.StartReaped, never Process.Release, which doesn't reap on Unix (TestEveryStartedCommandIsWaited in reap_test.go). TestHostReapedWhileItsChildHoldsStdout (Linux) runs a real host whose plugin holds its stdout that way and counts this process's <defunct> children after each Restart. Before magpie web puts a new version in its own place (Web.Wait, update.Reexec), plugin.EndHosts stops every host, waits until each has been waited for, and starts none after: a host still running at the exec is a child nothing waits for after it, one <defunct> magpie-bun per restart to update (#3285; TestEndHostsLeavesNoChild). The host is started as a proc.Tree (Output.StartTree): a session of its own on Unix, a job on Windows. Every way a host ends (stop after stopWait, a line too long, the host ending by itself) ends what its plugins started with it, at any depth: host.kill kills the tree, and the wait sweeps what a host that ended by itself left. A host killed alone left a plugin's headless Edge processes running with no parent (Bun's own job lets a child's children out of it on Windows), 620 msedge.exe in an hour on one machine (#5402, baijiu666). Nothing outside the host's session or job is reached, magpie's own process group included. TestHostEndedEndsWhatItsPluginStarted runs a real host whose plugin starts a child that starts another, on each of the three ends.

A plugin's account whose sign-in its vendor refused (lapsed, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (signedOut in renderAccounts, app.js).

A plugin sign-in's page is opened once. An authorize result may say opened: true (not OpenCode's field): the plugin's own CLI opened the page already. Grok's grok login --device-auth does this on macOS and Windows, where nothing turns it off, and magpie's opening it too showed two pages (andyfmyth on X; plugin 0.1.17, which on other systems gives grok a BROWSER that opens nothing instead). host.js passes it on as Authorization.Opened, then SignInState.Opened, and the desktop's /api/plugin-signin, magpie plugin login and the window in a browser tab (startPluginSignIn, and followSignIn after an install) then open nothing; the page's link is still shown (TestPluginSignInPageOpensOnce, plugin-signin-opened.test.cjs).

A plugin sign-in magpie gives up on ends in the host too (#5016). The user's Cancel, or the sign-in's timeout (signInTimeout), ends plugin.Finish's context, and authorize, callback and apiKey are cancellable calls (cancellable in host.go), as a gateway request is: magpie writes abort for the call, and host.js (signInSteps) drops whatever the plugin answers after it, so nothing is saved, and counts the call as done at once. The plugin's own wait is told where the host can tell it: every fetch the plugin makes for the sign-in carries the sign-in's signal (whileSigningIn), and magpie's hook hands the signal to the plugin as a second argument, callback(code, { signal }) and authorize(inputs, { signal }) (OpenCode passes none), so a plugin that polls a file or its vendor for minutes (AStudio's waits on its desktop app's session file, plugins#658) can stop. Before, a session file written after Cancel still signed the account in. An oauth method's authorize that can't start says why as an api method's does, { type: "failed", error }; host.js answers it, or a result with no callback, as the sign-in's failure (plugin.Authorize gives ErrFailed with the reason) instead of calling the callback it lacks, which reached the user as "s.a.callback is not a function". TestCancelledSignInSavesNothing, TestCancelledSignInEndsThePluginsWait, TestCancelledSignInEndsItsFetch and TestSignInFailsWithThePluginsReason in plugin_signinend_test.go.

Every other call but init is cancellable too (#4678): a models list, a usage read or a check magpie stops waiting for (its caller left, or listWait ran out) gets an abort, and host.js aborts the call's signal, which the usage hook gets as usage(..., { signal }) and the models hook as signal. The call stays pending in the host until its handler ends, and nothing it answers after the abort is sent, so a hook still saving a refreshed sign-in finishes before the host may exit. TestCancelledCallKeepsTheHostTillItsHookEnds and the other tests in plugin_rpc_cancel_test.go.

The GUI's plugin integration includes subOf, pluginSubs, and startPluginSignIn. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects.

Verification

Plugins may also declare a provider-independent magpie.hooks entry, including pure gateway packages and mixed provider/Pi packages. Its asynchronous request contract and verification are documented in Gateway request hooks. Existing provider hooks still use their normal entry path.

migrate_notice_test.go includes TestMovedBuiltinsSayTheirPlugin, which checks that moved built-ins tell contributors which plugin serves them. Migration tests live beside migrate.go.

Gateway parity tests in plugin_parity_test.go and other plugin_*_test.go files compare or exercise plugin paths. A built-in test alone does not establish moved-user behavior. Inspect each test's fixture to confirm that it covers the provider and operation being changed.

plugin_decide_test.go runs the fake plugin (FAKE_DECIDE) with a decision API: its marked and jev-* models are classifiers and not offered to agents, chat to one is refused, a group saves one as classifier, not beside a chat model, and a group of decision models alone, and each classifier's question reaches the fake vendor at /v1/systemone through the plugin's fetch. With FAKE_DECIDE=models the marks without decide change nothing.

plugin_checkin_test.go runs the fake plugin's auth.checkin (FAKE_CHECKIN) through the schedule: off, each outcome, no second press the same day, failures only after the retry window, the next day, cards and Settings, and the vendor check-in stepping aside; TestPluginCheckinTellsSignInsOfOneNameApart signs in four accounts under two names, two of each (plugins#254), and checks each is checked in, kept, carded and switched off on its own, and TestPluginCheckinCarriesOverDisplayNameEntries upgrades a file and an Off kept by display name. TestPluginCheckinQoderRechecksCampaigns holds the Qoder plugins' recheck, by the loop and a press, after inactive and done, TestPluginCheckinOthersSettledForTheDay every other plugin's day from noon Beijing, and TestPluginCheckinEarlyDoneAskedAgain the reporter's 00:00:28 done asked again by the loop and a press (#3326); TestPluginCheckinAsksAgainAtUntil holds the clock from 09:27 Beijing through the next day's 10:30, with the machine in UTC, UTC-8 and Beijing, and checks the asks land at 09:27, 10:01, the Beijing day's turn and 10:01 again, and a failure in the 09:59 gap at 10:01; checkin-early-done.test.cjs covers that card; qoder-checkin-recheck.test.cjs covers the card's press. plugin-checkin.test.cjs covers the card row and the Settings tab.

plugin_options_test.go loads testdata/options in a real host: which declared options are kept and how they are capped, the user's value over the default at start, a change read by the plugin after SetProviderOptions without a restart, and a models hook's list that goes by an option following it after the change. plugin_option_api_test.go covers the endpoint, a bad key, and a Settings save keeping the values. plugin-options.test.cjs covers the editor in Chromium and WebKit, 1100 and 420 wide, in every language. plugin-option-words.test.cjs covers the words in each language (zh-TW falling back to zh, ja and de to the plain ones when a plugin gives only zh) and the note under the models, on and off, in both engines, 1100 and 420 wide.

plugin_cliproxy_test.go's TestPluginHostTakesANewProxy starts a real host without a proxy, sets one, and checks that a program the plugin starts gets it. plugin_lan_test.go's TestPluginLeavesTheUserNetworkDirect checks with a real host that fetches (http:// and https://) and an HTTP/2 session to this computer's private address reach it directly with a proxy set, and that a public address and an unresolvable name still go through the proxy. plugin-signed-out-account.test.cjs covers a moved Grok account signed out while in use and as the agent's own, in Chromium and WebKit, en and zh, 420 and 1100 wide.

stderr_drain_test.go's TestDrainStderrKeepsTheChildGoing checks that a child writing 8 MiB to stderr with no newline finishes, and that the log says its stderr was dropped. stderr_e2e_test.go's TestHostStartsPastAnOverlongStderrLine starts a real host whose plugin logs one 5 MiB line while it loads, and checks that the host starts; without the fix it fails on Windows only.

These tests cover two plugins on one provider id:

  • plugin_clash_test.go's TestTwoPluginsOneProvider loads two copies of the fake plugin in a real host. It checks provides/servedBy, Clashes, that the id is listed only once, and that the pick survives Prefer, a restart, off/on and Remove.
  • TestPluginNamedExactlyFirst and TestKeepUnloadedLeavesAServedID cover the store and the providers cache.
  • TestPluginsClashRows (internal/gui) and TestPluginListSaysClash (the CLI) check what the user sees.
  • plugin-clash.test.cjs covers both rows and Use for, in Chromium and WebKit, in en, zh, zh-TW, ja and de, at 1100 and 560 wide.

quotas_dedupe_test.go checks unrelated reset collisions and ZCode deduplication, including plugin usage window conversion for both plugin ids. TestPlanQuotas checks the custom GLM endpoint, cached cards, and fallback readings restored from disk. These fixtures do not contact the live vendors or run the community ZCode plugin.

Run the relevant package tests with an isolated home directory. Resolve GOPATH and Go's caches before changing HOME, so repeated runs reuse dependencies and downloaded toolchains. The subshell makes temporary files writable and cleans up its home on exit, including when tests fail, and returns the test command's exit status.

(
	verification_home=$(mktemp -d) || exit
	trap 'chmod -R u+w "$verification_home"; rm -rf "$verification_home"' EXIT
	verification_gopath=$(go env GOPATH) || exit
	verification_modcache=$(go env GOMODCACHE) || exit
	verification_buildcache=$(go env GOCACHE) || exit
	HOME="$verification_home" GOPATH="$verification_gopath" GOMODCACHE="$verification_modcache" GOCACHE="$verification_buildcache" \
		go test -tags nogui ./internal/provider ./internal/gateway ./internal/plugin
)

Some migration and gateway plugin tests require Bun on PATH and use local plugin fixtures; they skip when Bun is unavailable. Report any skipped tests and verify the community package separately when its implementation changes.

Fixed-credential sign-in

An auth.methods API method may declare magpie-only keyless: true when its authorize function supplies the credential. The host carries this boolean only for API methods with an authorize function. GUI and CLI skip personal-key entry for it; ordinary API methods still require a key. auth.single: true declares one provider identity: signing in again reuses its account slot and the account action says Sign in again. Existing records are not deleted. Other plugins keep multiple accounts. OpenCode ignores these optional fields; no provider id is special-cased in magpie.