611ce90d15bbbb2db2edcfc181da4f75ada3cccd
79
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
276c806db2 |
plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.
- host.js gives plugins input.magpie.usage(provider, call) and
input.magpie.account(provider). usage validates the call (kind
[a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
most 999, error clipped to 500) and sends an unasked "usage" event;
host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
magpie on the plugin's provider (provider.PluginID) and account
(provider.PluginAccountUser), with its kind. It is counted, priced
and in every total, not a probe. Kind cache_keepalive is in the
purpose catalog as "Cache keep-alive" (five languages), so the
request log names and filters it. The ping itself still goes straight
to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
middleware's or request hook's, and the Installed row offers the same
Options JSON editor for a provider or agent plugin that suggests or
has options (not while it is off). Clear's confirm no longer calls
them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
(published 10:03Z); the plugins publish run is red only for
think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
gateway-sessions.md (the counted row beside probes).
Run at this tree (rebased on origin/main
|
||
|
|
7503beee72 |
plugin, settings: a model's load goes past 100% for a vendor that queues (axelburks on Discord)
axelburks, on v0.1.2547: their vendor queues, so a model's load can be
past 100%, even 200%. magpie clamped every load to 100, and Busy models
last allowed 1-99 only.
- host.js reportLoad and plugin.noteLoads keep a load from 0 up. The
floor is still 0, null still clears it, and a sanity cap of 10000
(LOAD_MOST, plugin.LoadMost) keeps an absurd value from reaching the
UI or the trace.
- settings.BusyLoad takes 1 to 9999 (BusyLoadMost-1). The segment
choices stay Off/50/70/80/90, and a value set in settings.json (150)
shows as its own choice, as before.
- The editor's badge reads "180%". It is a badge, not a bar, so nothing
assumed 100 wide; the test checks it stays on one line.
- Docs: site plugins page (en, zh, ja) Values and Routing bullets, and
provider-plugins.md and gateway-routing.md.
Run on mote via mote-run, on origin/main 8d8df0639+ rebased:
- go test ./internal/plugin ./internal/gateway ./internal/settings -run
'ModelLoad|TestBusy' -v: all pass. TestPluginReportsModelLoad has
over:250 kept and huge:1e9 at 10000. TestBusyModelGoesBehind has 180
behind 120 at a threshold of 150, and 10000 refused.
- Broken by hand in a copy, with the old 100 clamps and the 99 limit:
TestPluginReportsModelLoad red ("ModelLoad(over) = 100; want 250"),
TestBusyModelGoesBehind red (150 refused).
- node --test model-load (with Queued 180% in every language, Chromium
and WebKit, 420 and 900, plus Over 150% picked at 420) and i18n-keys:
46/46 pass. go test ./internal/gui -run Budget: ok.
- gofmt -l: empty. GOOS=linux go vet -tags nogui and GOOS=windows go
vet on plugin, settings and gateway: ok.
Not run before the push (owner: push and tag first): go test ./... and
the whole GUI suite. They are queued on mote behind another session's
suite.
|
||
|
|
8d8df06399 |
plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.
- A provider plugin calls input.magpie.load(provider, {"<model id>":
0-100 | null}) whenever it likes, from its own timer. host.js
(reportLoad) clamps each number to 0-100, null clears a model, every
other value is dropped, at most 1000 a call, and it returns the count
taken. A provider that isn't a string or loads that isn't an object
throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
id. ModelLoad answers unknown once a load is older than LoadFresh
(5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
1-99 by hand): restLast puts a model reported over it behind the
ready candidates, ahead of the resting. The trace row has busy:<load>.
At a new turn affine moves a conversation off it (Why "busy",
busyBehind); within a turn it stays. after, readyForNew and leastHeld
skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
table; docs/subsystems provider-plugins.md and gateway-routing.md.
Run, all on mote via mote-run at a42736807's tree rebased on
origin/main
|
||
|
|
e84870f173 |
plugins: an option's words in the window's language, and a filtered model list says so (plugins#590)
anewuser6937 (Discord, plugins#590) saw one model in WorkBuddy's editor
and took the plugin for broken. They had turned on "Free models only"
themselves, but its label and description read in English in the Chinese
window, and nothing by the models said the list was filtered.
A plugin option (auth.options, magpie's own field; OpenCode's AuthHook is
provider/loader/methods and never reads it) may now give `labels`,
`descriptions` and `confirms`, each keyed by the window's language
("zh", "zh-TW", "ja", "de"), beside the plain strings, as a page's
`titles` do. The host keeps only non-empty strings under language names
of 16 or less, 16 languages at most, each capped as the plain one is
(60/300/300). The editor shows the exact language, then its first part
(zh-TW reads zh), else the plain words, in the row, the hint, and the
confirm dialog and its title. `filtersModels: true` says the plugin's
model list leaves models out while the switch is on; while one is on, as
saved, the Models field says under the chips "Only some models are
listed: the plugin option “…” is on." (zh 只列出部分模型:插件选项「…」已开启。,
zh-TW, ja, de too). An older plugin shows what it showed before, and an
older magpie shows a new plugin's plain words with no note.
WorkBuddy 0.2.10 gives "Free models only" in all four languages with
filtersModels (magpie-community/plugins aec58ae, on npm: `npm view
@magpie-community/opencode-workbuddy-auth@0.2.10 --prefer-online` on mote
says 0.2.10, latest), and the mover's min is raised to it so every moved
user gets it. The CLI's `magpie plugin options` stays English, as the CLI is.
The core scripts would have gone 608 bytes over their budget; three of the
provider editor's comments in app.js are cut down instead, no raise
(1,532,865 of 1,533,105).
Run, on mote (mote-run), at this tree:
- node --test plugin-option-words.test.cjs (new): Chromium and WebKit,
1100 and 420 wide, en/zh/zh-TW/ja/de, switch on and off: each
language's label and description, zh-TW falling back to zh and ja/de to
the plain words for a zh-only option, the note exactly once under the
chips in a .hint inside the editor with no sideways scroll, none while
off, the confirm in the language. With app.js put back: 19 of 21 red
in Chromium (only "en off" passes, both widths).
- With plugin-options.test.cjs and i18n-keys.test.cjs, both engines:
68 pass, 0 fail.
- go test ./internal/plugin ./internal/provider ./internal/cli: ok.
TestPluginOptions with host.js put back: red (empty maps, FiltersModels
false). The real WorkBuddy 0.2.10 index.mjs loaded into this host
(a temporary test, not kept): plugin.Providers lists free_only for
workbuddy and workbuddy-ai with all four languages and filtersModels true.
- go test ./internal/gui: TestCoreScriptBudget ok after the cut. Red,
and red the same at origin/main
|
||
|
|
2c6b7c0632 |
gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.
A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.
Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.
Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).
Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).
Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.
Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main
|
||
|
|
c26d16018f |
gateway: a plugin model that refuses temperature is asked without it, relayed or translated (#2492)
What changed: the plugin host carries a model's temperature where it is said - the config model's temperature (Factory 0.1.31's configModels, plugins#154), models.dev's own, or a models hook's model field - into plugin.Model and pluginCatalog's catalog model, where RejectsTemperature reads it as it reads a built-in's. A Chat or Responses request relayed as it came to a model whose list refuses temperature and top_p now leaves them out (passthrough), as the translation of one (build) already did. A model nothing says so of keeps what the client sent. OpenCode's capabilities.temperature is not read: its false is what it reads a models.dev silence as, not a refusal said. Docs: the sampling row of gateway-routing, and provider-plugins' new "A plugin model's sampling". Run at |
||
|
|
7da972969b |
provider, gui: a listing's budgets add up, and one provider's fetch models no longer re-lists past them (#4065)
What changed
The budgets a listing of the plugins' providers is made of added up past
the budgets its callers set: the host let one provider spend listWait
(20s) on its models hook plus the wait for a due renewal (RENEW_WAIT,
15s) before it, and a provider with two accounts spent them back to
back. One provider could be allowed 35s (40s with a second account) —
past the 30s refreshDeadline the background refresh asks under and past
the editor's own 20s — so pressing Fetch models, or a refresh, died with
a bare "context deadline exceeded" while no vendor had failed: every
provider is asked side by side, and the sum of the budgets was the only
thing over.
Now the host's own bounds hold by construction:
- host.js info(): the wait for a due renewal (fresh) spends the models
hook's own budget — the hook is given what is left of listWait, and
the renewal wait can no longer be added on top of it.
- host.js providers(): a provider's accounts are listed side by side
(the first no longer waited for before the rest), so one provider
costs one listWait, not one per account.
- gui/providers.go, case "models": the editor's budget is 30s, the same
the host bounds one providers RPC with, instead of 20s — shorter than
even one provider's worst case under the old arithmetic.
A provider whose renewal is slow then lists late (its hook given up on
alone, said so in listError as any other stuck listing) instead of
taking the whole listing past the caller's deadline (#4065).
Run
- TestProviderListCoversAccountsSideBySide, two accounts whose hooks
each take 3s under a 4.5s caller budget: with the product files at
the base (
|
||
|
|
261117363e |
plugin host: a sign-in again joins its account when an older plugin named it another way (#4473)
officeace-auth 0.1.14 to 0.1.17 kept an account as accountId = the masked
phone ("189****8051") and uid = the Huawei domain id. The CodeArts
plugin's OfficeAce card (plugins#522) names a new sign-in by the domain
id, uid the same. settle joined a new sign-in to an old record only on an
equal account id, so signing in again added a second row (fakeco#xxxxxx)
and left the old one "Sign-in required", holding the user's name, proxy
and gateway keys.
settle now also joins two records with the same uid when one of them is
named by that uid (renamedBy): then the uid is the account's own id. The
joined record keeps the old record's accountId, since the user's name,
proxy and gateway keys are kept by it (#4416), as the CodeArts plugin's
renewals already keep a stored accountId.
The issue suggested joining on any equal uid. That is not safe: Kiro
keeps how an account was signed in to as its uid ("google"), so two
different Google sign-ins share one. The test signs in two such accounts
and checks they stay apart; with a uid-only rule they were joined.
Not covered: a re-sign-in where neither record is named by its uid (a
WorkBuddy nickname changed at the vendor) still adds a row; nothing in
the records proves those are one account.
Run:
- Reproduced first on origin/main's host.js: TestPluginReSignInJoinsAnOldIDShape,
with the old record as officeace-auth 0.1.14's callback and
credential.mjs write it (read from the npm tarball), was red: the
sign-in again went to "fakeco#9oncv2" beside the old record.
- Broken by hand: renamedBy on uid alone -> red (two Google accounts of
uid "google" joined); joined without keeping the old accountId -> red
(accountId became the domain id). Green with the fix, and
TestPluginSameNameOtherUID (#413) still green.
- Full go test ./... -timeout 45m on mote was still running at push
(pushed without waiting, per the owner's rule); a red it shows that
isn't on origin/main gets its own issue.
Not tried: a real Huawei Cloud sign-in in a running magpie; the CodeArts
plugin with the OfficeAce card is not on npm yet (plugins#522 is open).
|
||
|
|
8c63c5b787 |
provider, plugin: a plugin model that says it gives no text leaves the chat lists (#3279)
A plugin provider's list counted every model it named as a chat model.
XYenon's Google AI Studio plugin put gemini-embedding-001 and its TTS
models in the chat chips, the agents' lists and /v1/models. The plugin
does declare them: the embedding's capabilities.output is
{"text": false} and the TTS's says audio only. But the host's kinds()
kept only the true keys. That made "said it gives nothing" look the same
as "said nothing", and pluginCatalog never read Outputs.
- host.js passes outputsSaid, which is whether capabilities.output says
yes or no to any kind (kindsSaid). It goes into plugin.Model.OutputsSaid.
- pluginCatalog leaves out a model whose outputs were declared and name
no text, image or video (pluginTalks). Every chat list is built from
that list: /v1/models, provider.Catalog (the agents' lists and routing),
and Available (the editor's chips).
- A plugin that says nothing about outputs keeps every model, whatever
the id. Image-only and video-only models stay where they are; #2792
decides where they go.
Ported from ggbdpq's hunt65-c-3279-kinds (7391b0df2), with changes
after review. That patch found the right place (pluginCatalog) and
wrote the provider tests kept here. It judged an embedding by "embed" in
its id, because the host drops the declaration. So an embedding named
otherwise (bge-m3, text:false) stayed in the list. A plugin that says
nothing about outputs lost any model whose id held "embed" or "-tts",
which changes today's behaviour. An image-only model (outputs ["image"])
was dropped, though the patch said it left #2792's models alone. This
version fixes the declaration in the host instead and guesses nothing
from ids. catalog.textModel is unchanged.
Docs: docs/subsystems/provider-plugins.md, "A model that gives no text".
Run (mote, at base 96a703a59; then rebased onto
|
||
|
|
d4f1d6480c |
plugin: a program a plugin starts with no folder runs in plugin-work, not beside magpie's settings
jiakun_zhao on X asked whose page_<hash>.html, magpie_home.html,
magpie_install.sh and magpie_*.md files they had found after using the
chat page plugin (Magiczerowxy/magpie-chat). That plugin starts the
user's MCP servers from the plugin host with node:child_process spawn
and no cwd, and runs their tools for a model. The host runs in magpie's
config folder (~/.config/magpie), so every file such a tool saved by a
relative name went beside settings.json and providers.json, and a tool
told to write "providers.json" would have written over magpie's.
host.js's spawn wrapper (which already hands on the proxy and keeps
programs off the host's stdio) now starts a program that names no
folder of its own in <config>/plugin-work, created on first use, with
PWD to match outside Windows. A folder the plugin gives is kept.
Not the cause of files in the user's home folder: magpie's host never
runs in ~, and no magpie code names a file page_<hash>.html or calls a
user's MCP tool itself. Files in ~ come from a process whose folder was
~: the chat's server started by hand (node serve.mjs) from ~, or
another agent run there. Filed on magpie-chat for the plugin to give
its MCP servers a workspace of its own and tell the model where it is.
Run (mote, macOS):
- TestPluginProgramsRunInTheirOwnFolder (new; testdata/clicwd checks
child_process spawn, spawn with env, execSync and Bun.spawn, plus an
own cwd kept): ok. Red with origin/main's host.js put back by hand
(plugin-work not made; programs ran in the config folder).
- go test ./internal/plugin ./internal/agentplug ./internal/pluginrt
-count=1: ok (plugin 261s).
- go test ./internal/gateway -run Plugin -count=1 at
|
||
|
|
ba37e78b4c |
provider: a plugin model's test is told a queue at once and warms its host first
mingxia_16024 on Discord (v0.1.1862): testing models on Qoder (CN and
international) and WorkBuddy always failed with "qfmodel: context deadline
exceeded", even though agents got answers from the same models.
Cause, checked with the owner's real Qoder account in a sandbox HOME:
- The test already takes the gateway's route: p.Do, then the plugin's
fetch in the host.
- The Qoder plugin waits out Qoder's free-plan queue (plan queue p3) for
up to 4 minutes, unless X-Magpie-Fallback is "1". magpie never sent
that header.
- The probe gives up after 20s. A raw request with no deadline got its
head after 3m49s.
- The probe's 20s also had to cover the plugin host's cold start and the
account loader's first run, which can renew the sign-in. A first
WorkBuddy AI test took 8.4s.
Changes:
- For a plugin provider, probe sends X-Magpie-Fallback: 1, so a queued
model answers at once with the plugin's queue message.
- It starts the host and runs the account's loader (warmPlugin, through
the account's proxy) under the caller's deadline, not the probe's.
- A plugin probe waits up to pluginTestWait (60s). The GUI gives a model
test 3 minutes.
- host.js lists x-magpie-fallback in MAGPIE_ONLY, so no vendor receives
it.
"Recent calls" lists only the gateway's own calls, for every provider. A
test is written to the Requests page as magpie's own test, timed-out
tries included, so that is unchanged.
The gateway still never sends the header when another candidate follows,
which Qoder 0.2.40 and CodeArts 0.2.3 expect: #4049.
Run (mote-run):
- New tests TestPluginModelTestSaysQueued and TestPluginModelTestColdHost.
They use the fake plugin's new $FAKE_QUEUE and $FAKE_LOAD_WAIT, with a
cold host from plugin.Restart.
- go test -tags nogui -timeout 45m ./... at
|
||
|
|
a05b373538 |
checkin: a plugin's until is when its answer stops holding (Qoder's 10:00 UTC+8)
sdytman on Discord: Qoder's daily credits start at 10:00, can the plugin's check-in follow it? Qoder's /me/campaigns opens each day's CLAIM_BENEFIT campaign at 10:00 and closes it at 09:59 the next day, UTC+8 (startAt and endAt, read with a real account on 10-28; Qoder.app polls the list every 5 minutes). A check-in before 10:00 meets the day before's campaign. Since #2696 the Qoder plugins are asked again every 30 minutes, so today's was claimed somewhere between 10:00 and 10:30; a plain plugin was settled for the Beijing day. auth.checkin may now answer until (RFC 3339 or epoch ms); host.js passes it as RFC 3339 (plugin.Checkin.Until), kept as ValidUntil. settled holds an answer only until then, whatever its outcome; the loop wakes at it instead of its next 30-minute look; an early done that carries it is not provisional (#3326), as the vendor said when its day turns. Instants throughout, so the machine's zone doesn't matter. The Qoder plugins send until from 0.2.43 (plugins fd40b20): the check-in now lands at 10:01. Run (mote): TestPluginCheckinAsksAgainAtUntil, minute by minute from 09:27 Beijing to the next day's 10:30, with time.Local UTC, UTC-8 and Beijing: asks at 09:27, 10:01, 00:00 (the Beijing day), 10:01; a failure in the 09:59 gap asked at 10:01:00 only. GOOS=linux and windows go vet; go test -tags nogui -timeout 45m ./... all ok (76 packages). gofmt -l clean. Broken by hand, each red: settled ignoring ValidUntil (no 10:01 asks); tick not waking at it (10:27 instead); provisional ignoring it (asked every 30 minutes from 00:00 to 10:00); host.js dropping until (ValidUntil zero). Not tried: the Qoder plugin's recheck path with until (the fake plugin is fakeco; the tick and settled it goes through are the same); a GUI change (none: until isn't shown). |
||
|
|
8bade6c5e2 |
provider: a plugin's usage window can be a prepaid wallet's balance (#3950)
SuperMagic's accounts (mycf_711's magicrew plugin) are prepaid wallets of
points with no total. A plugin can now send a usage window as
{name, balance: 6291, unit: "积分"} with no used or limit.
- host.js passes a finite balance on (at least 0), anything else as null.
plugin.UsageWindow.Balance and provider.QuotaWindow.Balance are *float64.
- quotaOfPlugin keeps the figure and does not make the window Text or
Aside, so routing knows the account with no Used invented. allowanceOf
copies it into Limit.Balance; an empty wallet counts as used up.
Allowance.Left(model) is the least balance of the windows that count
the model.
- weighRouted fills routes.Seat.Left and Seat.LeftIn (the account's
provider and unit). Smart, pace and usage (least used) put the seat
with more left first where they would otherwise tie (byLeft), only
when every seat with a balance shares one LeftIn: balances in two
units or two providers are never compared. Tiers still come first.
- The Usage card, the Routing page (Weighed.Balance: the small row's
text, no bar, a why sentence, the account list), magpie accounts and
the status line show the figure, "6,291 积分 left", never a share.
- Docs: provider-plugins (new section), gateway-routing,
providers-accounts, plugin-runtime, host.js typings and the site's
plugins page (en, zh, ja).
Run, at base
|
||
|
|
9bfe680481 |
plugin: a changed plugin option lists the providers again (plugins#430)
WorkBuddy's plugin 0.1.38 adds a "Free models only" switch (a plugin option) that lists only WorkBuddy's free models and refuses any other before it is sent. Its list goes by the switch, but SetProviderOptions only handed the values over: the host cleared its infos while Go kept provCache, so the Providers page and /v1/models showed the old list until something else re-read it. SetProviderOptions now forgets the kept providers (whether the host runs or not), so the next Cached() lists them again. Nothing else runs on a change. The workbuddy mover's min is 0.1.38 (npm view --prefer-online at landing: 0.1.38). Run: - go test ./internal/plugin ./internal/provider -count=1 -timeout 45m at this head ( |
||
|
|
51202cd431 |
plugin: a check-in outcome magpie doesn't know names what the plugin said
A plugin check-in that answered an outcome not in the list, with a message, became failed with the plugin's message alone, so "the daily credits were refreshed" read as magpie's own failure reason. The reason now names the answer first: the plugin answered "yes": <message>. With no message it stays "the plugin answered no outcome" or the answer. Split out of skygunner's fix/usage-absent-used branch (#3650), which carried it beside the usage fix. Run: go test ./internal/provider -run TestPluginCheckinRunsAsTheBuiltinsDo ok. Broken by hand: host.js's old line makes it red (Msg was the message alone). Not tried: a real plugin answering an unknown outcome. Co-authored-by: skygunner <skygunner@users.noreply.github.com> |
||
|
|
9733ed1b4a |
usage: a plugin window that doesn't say used is no reading (#3650)
A plugin usage window that leaves out `used` was read as 0 in host.js
usageOf. The card then showed "100% left" (or NaN% once the GUI saw a
missing value), and allowanceOf ranked the account as the one with all
of its allowance left, so smart routing put spent accounts first.
Now a left-out used is null from the host, plugin.UsageWindow.Used is a
*float64, and quotaOfPlugin makes such a window Text and Aside: the card
shows its display (else "No allowance reported"), with no percentage and
no meter, and routing leaves it out. An account whose windows all tell no
share has no allowance and is not known to routing (routedAllowance), as
one never read: not preferred and not rested. A window that says used:0
is a reading at 0, as before.
Ported from skygunner's fix/usage-absent-used (6791aa99). Changed from
the branch:
- lastAllowances (the reading kept on disk) built an empty allowance for
such an account, which routing read as known with all of it left. Both
it and Allowances now go through routedAllowance.
- quotaText shows "No allowance reported" for a no-share window with no
display, rather than a blank.
- A host-level test (the bun host with the fake plugin) and the GUI test
widened to both engines, every language, 900 and 390px, used and left.
- The branch's check-in wording change is its own commit.
Note: an account whose windows are all aside or text was known with 0%
used before; it is now not known, so loginRoom won't pick it as the
next account with room.
Run at this tree (base
|
||
|
|
fed0055da8 |
plugin: a plugin stuck on its vendor no longer holds up the plugins loaded or listed with it
shualaitianduai on Discord: a plugin whose sign-in kept failing (401)
held up the plugins behind it. host.js loaded the plugins one after
another and answered init only when all were in, so a plugin function
that never returned held every other plugin until init's two-minute
deadline failed the whole host. providers() listed the providers one
after another too, so one stuck models hook held the whole list past
refreshDeadline (30s), and every provider's list went stale.
Now loadPlugins loads every plugin side by side, each given
pluginLoadWait (20s) for its import and plugin function, and each
config hook as long; one still loading is told as not loaded ("the
plugin's load didn't finish in 20s") and init answers with the rest.
Hooks are kept in the list's order, as before. providers() lists every
provider side by side and gives each models hook pluginListWait (20s,
inside refreshDeadline): 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). Documented in
docs/subsystems/provider-plugins.md.
Run at this head (base origin/main
|
||
|
|
bac5be0677 |
plugin: one renewal of a sign-in at a time across magpie processes (plugins #331)
Cause: every magpie process that loads plugins runs a plugin host of its own (the gateway, a CLI quota or usage command, a host restarting while the old one finishes), and host.js's renew() kept a sign-in's renewal to one at a time only inside one host (the in-memory renewing map). Two hosts that found the same sign-in due each called the plugin's auth.refresh with the same refresh token. A vendor that spends a refresh token once (MiniMax, and about ten plugins' vendors: cline, codearts, qoder, trae, workbuddy, raccoon, nous, kiro, factory) turned the second away with invalid_grant, the plugin threw signIn "expired", renew() sent it on without looking at the store again, and host.go -> provider's notePluginLapse marked the account signed out, though the first host had already saved a good token. What changed, in internal/plugin/host.js only, for every plugin: - renew() takes a lock file of the account's beside the store, plugin-auth.json.renew-<sha256(key)[:16]>.lock, holding the holder's pid and start time, across the plugin's auth.refresh, and lets it go in finally. It is separate from plugin-auth.json.lock, which changeAuth holds only for a write and never across an await. A lock whose pid is gone (process.kill(pid, 0), EPERM counted alive) is taken over at once, one older than 60s by anyone; a live holder is waited for with an async backoff (10ms to 500ms), never blocking the host's loop, and never past 120s. A lock is removed only while it holds the bytes read. - Under the lock the sign-in is read again from the file (past readAuth's stat cache). Changed since the renewal began (another host renewed it, or it was signed out or in again), the renewal ends without calling the plugin; no longer due, likewise. - A refresh that throws while the stored sign-in changed meanwhile (a magpie from before this lock spent the token and saved the new one) is logged, not reported expired. Tests (internal/plugin/plugin_renew_race_test.go, fixture testdata/renewrace): a fake vendor on loopback whose refresh tokens are single-use. - TestRenewOnceAcrossHosts: two hosts in two processes (this test binary and a child running TestRenewOtherHost) on one sandbox store. The first host's exchange is held until the second host is renewing too, waited on as state. One exchange, neither host says expired, both requests go with the new token, the store has it. - TestRenewLockOfDeadHostAndRefusal: a lock naming a pid that has ended is taken over inside the request's wait and removed; a token the vendor never gave still says expired and leaves the account as it was; one refused after another magpie saved a new token says nothing and the next request goes with that token. Broken by hand, each red: - no lock (lockRenew returns at once): TestRenewOnceAcrossHosts red with exchanges [r1 r1], the other host said [expired], a request sent a-old - the issue's symptom; the dead-pid test red (lock left). - no re-read under the lock (now = was): exchanges [r1 r1]. - the catch's check removed: "a token another magpie renewed meanwhile said expired". - a dead pid counted alive: the dead-pid test red after its wait. (Removing only the re-read's "changed" branch stays green: the "no longer due" check under the lock catches the same case.) Run at c909ca5e4 (on origin/main |
||
|
|
5871f02dd6 |
plugins, provider, gui: a keyless plugin sign-in needs no key, and a single-identity plugin has one account (#2695, LoKi)
LoKi's patch (lokic7123-star), picked onto origin/main |
||
|
|
9b0f48612b |
gateway: a plugin's model that searches by itself can be the web searcher
01huadalang (Discord #feedback, 10-20): Settings › Web search offered only Antigravity; Trae's search model couldn't be picked, "可能也有别的模型能搜索 但是识别不到". partSearcher and modelSearches answer false for every provider with an account behind it, so no plugin-served provider was ever offered, and a plugin had no way to say which of its models searches. A plugin now marks such a model with `searches: true` (in its config models or the list its models hook gives). host.js passes it on, plugin.Model carries it, and pluginCatalog makes it WebSearch "native". partSearcher offers a plugin provider with such a model, with those models only, at rank 4 (as Command Code's search models); remoteSearch asks it in plain words, the way it asks Command Code's. A client's own web_search sent to that model still goes to magpie's searcher (searchesModel is unchanged): the plugin's upstream takes no web_search tool. Behaviour change: a marked plugin model ranks ahead of Antigravity and Google (rank 5) when magpie picks the searcher itself. Run: - TestPluginSearchModelIsASearcher (new; a fake plugin's model marked searches answers a weather question with a URL): red on the old code (the picker offers [], want the plugin's fake-search alone), green now. - Broken by hand: host.js without the `searches` passthrough; the test goes red at the picker. - gofmt -l clean; go vet darwin, linux -tags nogui, windows on gateway, plugin, provider, catalog. - set -o pipefail; go test -timeout 45m ./... at this tree: 68 ok, no FAIL. Not tried: the Trae plugin itself. It declares nothing about search yet; marking Trae CN's search_agent there needs a Trae account to try it with, which this machine doesn't have. No GUI files changed. |
||
|
|
f76201a84a |
plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里". Grok's plugin signs in through `grok login --device-auth`, and Grok Build (1.0.50, the webbrowser crate) opens the device page itself, through NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER; the macOS binary has no "BROWSER" string. magpie then opened the same URL from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a browser tab) or `magpie plugin login`. Reproduced in a sandbox HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not involved, with and without SSH_CONNECTION. Built-in grok is retired ( |
||
|
|
ef75a9a2b5 |
plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.
Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)
Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".
Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
|
||
|
|
8f37ed57d2 |
plugin: plugin-auth.json is parsed once per version of the file, not on every request
Every request read and parsed plugin-auth.json in the host two or three
times: accountKey (when no account is named), fresh (is a renewal due),
and the plugin's getAuth from its loader's fetch. Reading and parsing a
20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine.
readAuth now keeps what it parsed while the file has the same mtime,
size and inode, as Go's filememo does. While the file's time is within
2 s of now it also keeps the bytes and compares them, so two same-size
writes inside one tick of a coarse clock (Linux) still read as two. A
file that doesn't parse is never kept, so the .bak recovery path is
unchanged. changeAuth still reads afresh under the lock. The kept
object is shared, so what a plugin is handed (getAuth for loader, usage
and check-in, the models hook's auth, pi.js's readAuth) is a copy of its
own (authCopy).
Measured (load average 360-460, so absolute times are inflated):
- readAuth on a settled 20 KB file, old and new interleaved in one bun
process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read
per call. New median 23 us (min 2.3), a stat, and 0 file reads.
- whole fetch (TestPerfScratch, not committed, {} body, 400 fetches):
host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise.
A control run without the big file read 875 us at the same load. Host
RSS 53 MB -> 42 MB.
Test: TestAuthReadOncePerVersion runs host.js's own auth section in node
with readFileSync counted. It checks:
- 100 reads of a settled file read it once;
- a rewrite is read;
- a same-size rewrite with the same mtime is read;
- authCopy's copies are the caller's own.
Broken by hand twice, red both times:
- readAuth made the old uncached read: "a settled file is read once for
100 reads, read 100 times".
- bytes of a just-written file not kept: "a same-size rewrite in one
tick is read".
Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with
TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s
(pinned pi install under load); in a full package run it hit its 4-minute
start deadline ("starting plugins: context deadline exceeded").
|
||
|
|
e3c09f4f36 |
plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.
infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.
Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.
Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).
Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
|
||
|
|
9b04c4e20f |
plugin: async gateway request hooks, run in Bun before routing and after the reply (#2118)
A package's magpie.hooks entry (or a *.hooks.{js,mjs,ts,mts} file) exports
`async onRequest(body, ctx)` and an optional `onResponse(reply, ctx)`. They
run in the Bun plugin host, so a hook can await I/O, for example a context
service like PowerContext, which the sync moejs middleware can't. The
gateway still makes one model request per client request. A hook adds
context to the body; it doesn't register tools or run a loop, so magpie
doesn't become an agent runtime.
Ported from Tsukikage7/magpie#1. Changes from the fork:
- The entry name is magpie.hooks / *.hooks.*. The fork's magpie.gateway /
*.gateway.mjs is already the middleware's alias, so a hook importing
node:fs was also loaded as moejs middleware and failed there.
TestGatewayHookNamesApartFromMiddleware fails if the two sets overlap.
- onRequest is rolled back, and counts as failed with no onResponse, when
it throws, times out, returns non-JSON, or changes tools, tool_choice,
function_call, functions, toolConfig, model or stream.
- onResponse gets the client-facing reply, merged through the gateway's own
stream decoder, collector and renderer (no second merger).
- Codex's native passthrough (/backend-api/codex) runs the hooks too,
without the sync middleware.
- The run ends with the request handler, not the client connection. Codex
hangs up on response.completed, and the reply it got is still captured
as a success. TestGatewayHookSeesReplyAfterClientHangsUp is red on the
old `r.Context().Err()` check and green with -count=3.
- ctx.origin is host-derived (local / gateway-key / remote). Headers, keys
and peer addresses never reach the hook.
- Plugins page: a hook package shows a "Request hook" chip, a diagnostics
line (outcome code, calls, avg ms, bytes, failures; no content), and
Options. Strings are in en, zh, zh-TW, ja and de.
Docs: docs/subsystems/gateway-request-hooks.md (new), provider-plugins.md,
gateway-middleware.md, and site docs plugins.html in en, zh and ja.
Real use, sandbox HOME on 127.0.0.1:3486 with the owner's real Codex Pro
sign-in. The probe hook adds a codename note and logs both callbacks:
- /v1/responses, /v1/messages, Gemini generateContent: stream and
non-stream. onRequest's note reached the model (the answer had the
codename), and onResponse got success=true and the whole reply.
- /v1/chat/completions: with the probe also changing `model`, the change
was rolled back (the reply came from the asked model) and no onResponse
ran. Without that change, earlier: stream and non-stream success.
- The real Codex CLI 0.162.1 `codex exec` through openai_base_url ->
/backend-api/codex: the hook saw origin=local, agent=codex and the
query; the answer had the codename; onResponse success=true (before the
hang-up fix it never ran: the context was already cancelled).
- `magpie plugin list` shows only "async gateway hook onRequest" for the
hook package, no failed middleware.
Tests (base origin/main
|
||
|
|
7ba1b49846 |
plugin: a plugin's usage resets carry the team's and each window's
ZCode's built-in showed the personal plan's and the team's resets with each
reset's end; a plugin's usage could carry only one. host.js now passes a
plugin's resets.team and resets.each through, and movedCards shows them as
the built-in did. zcode 0.1.19 sends them.
TestPluginUsage's team and each check (plugin_usage_test.go) goes red without it.
Run at
|
||
|
|
e733b0722e |
plugins: a provider plugin says which service tiers a model serves, and Codex offers them (#2514)
Lovest on Discord (#general, v0.1.1267): a provider plugin had no way to
say a model is served at Fast or Ultrafast, so Codex never offered them for
plugin models, and the host dropped the field anyway.
- host.js keeps m.serviceTiers (tiersOf: string ids or {id} objects,
trimmed, de-duplicated, anything else dropped) as plugin.Model.ServiceTiers.
- pluginCatalog puts them on catalog.Model.Tiers; CodexTiers offers a
plugin's tiers when it declares any, so codexcat writes service_tiers
(priority named Fast) into Codex's catalog and /v1/models.
- forwardTranslated keeps service_tier (OwnTier) for a plugin provider only
when the request is translated to its Chat or Responses and the tier is
one the model declares (provider.PluginTiers). A request relayed in its
own protocol was already sent as the client wrote it; unchanged. Cursor's
fast flag and #1954's ChatGPT tiers are untouched (#1954 not on main yet).
- Docs: serviceTiers in site/public/docs plugins (en, zh, ja) and a
"service tiers" section in docs/subsystems/provider-plugins.md.
Tests (internal/gateway/plugin_tiers_test.go, fake plugin FAKE_TIERS):
TestPluginModelServiceTiersListed (fake-1 priority=Fast + ultrafast,
fake-resp ultrafast, fake-claude none) and TestPluginServiceTierReachesFetch
(Responses→plugin Chat and Chat→plugin Responses send a declared tier,
drop an undeclared one; same-protocol relays as before).
Broken by hand: OwnTier branch forced false → 3 translated cases red;
CodexTiers without IsPlugin → listed test red; host.js serviceTiers: [] →
listed test red. Restored → green.
gofmt -l clean; go vet -tags nogui with GOOS=darwin, linux, windows clean.
Not tried with a real vendor plugin that serves ultrafast.
Full suite: go test -timeout 45m ./... at af9e0d6b2 (sandbox HOME, load
average ~408 from other sessions): every package ok except agent and
gateway, which timed out at 45m with no failed test (rerun whole: timed
out again, 0 failures), gui (TestMainWindowCorners killed, #1936),
TestVendorThatStopsMidAnswerIsSaid (filed #2535) and
TestSetAnswersWhileDevinAndProvidersHang (#1375). The reds and the tests
running at each timeout (TestCodexKeptOnChatGPT, TestReplyNamesMember)
pass rerun alone, except TestMainWindowCorners (#1936). CI is the gate.
|
||
|
|
6ac7032b4b |
plugins: a community plugin's tools reach every agent through magpie's MCP server /mcp/magpie/tools (P4 tool point)
A plugin's OpenCode `tool` hook ({tool: {name: tool({description, args,
execute})}}) used to reach no agent. Now the plugin host collects each
loaded plugin's tools, turns their zod args (v3/v4 shape or object; a
raw JSON Schema is kept) into JSON Schema, and runs one on a `tool`
call: arguments checked against the tool's own zod first (defaults
filled, a wrong one named), execute raced against ToolTimeout (55s,
ctx.abort fires), the answer as text.
The gateway serves them as an MCP server at /mcp/magpie/tools
(tools_mcp.go, guarded by serveMCP as the search one, 4 MiB body):
tools/list names each <plugin short name>_<tool>, at most 64 chars,
a shared name numbered _2; tools/call holds the call to the calling
key's limit through reserveFor and runs it with the calling agent.
The built-in plugin `tools` ("Plugin tools", Essential) serves
gwtool.PluginTools; off, nothing is listed, a call says the plugin is
off and the host isn't asked. InUse counts plugins that are on and
gave tools, from plugin-tools.json, which the host writes after each
load (whole, only on change), so it never starts Bun; the gateway's
KeepFresh watches that note too. Tool answers go to the calling
agent only, so masking doesn't apply (said in the docs).
The Plugins page lists an on plugin's tools by their MCP names, with
descriptions on hover and a button copying the server's address; a
plugin of tools alone has no Provider chip and isn't said to sign in
to nothing. Not done: a Library featured opt-in entry; wiring is the
copied address.
Docs: docs/subsystems/plugin-tools.md (new), plugin-runtime.md's new
"P4: community plugins at every point" section with the tool row, the
README index, usemagpie.ai/docs/plugins#tools in en, zh, ja with an
example. Strings in zh, zh-TW, ja, de. Example plugin:
internal/plugin/testdata/tools.
Run at this commit's tree (base 4df1ba0c6), each package alone, -p 2:
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
over internal/plugin, gwtool, gateway, plugins/..., gui, pluginrt: ok
- go test ./internal/plugin -run Tool; ./plugins/...; ./internal/pluginrt;
./internal/gui -run 'Builtin|Plugins'; ./internal/gateway -timeout 45m
-run 'ToolsMCP|ServingGates|OwnMCPRejects|SearchOnAndOff|KeyLimitsOnAndOff':
all ok
- GUI, Chromium and WebKit: every plugin-*.test.cjs, i18n-keys,
builtins: 461/461 pass; plugin-tools.test.cjs (new) covers en, zh,
zh-TW, ja, de at 980 and 420 px
Broken by hand, each red, then restored:
- tools/list ignoring the gwtool gate -> TestToolsMCPOff
- tools/call ignoring the gate -> TestToolsMCPOff
- reserveFor removed -> TestToolsMCPHeldToKeyLimit (tool ran)
- collision suffix dropped -> TestToolsMCPServesPluginTools
- ToolsOn ignoring Off -> TestPluginTools
- host arg check removed -> TestPluginTools
- host timeout race not listening -> TestPluginTools (answered at
5.3s by Go's backstop; the test now bounds it at 4s, and the first
try at this break was a syntax error that proved nothing)
- GUI listing an off plugin's tools -> plugin-tools.test.cjs
Real use: a built magpie in a sandbox HOME (MAGPIE_ADDR 127.0.0.1:3491,
real Bun), the example plugin added with `magpie plugin add`. curl over
MCP: initialize, tools/list (4 tools, schemas), shout "HI HI (for
curl)", a missing argument as isError naming it, add {"sum":6.5}, fail
"it broke", a foreign Origin 403; plugin-tools.json written. Claude
Code (sandbox CLAUDE_CONFIG_DIR) `claude mcp add --transport http` +
`mcp list`: Connected. Not tried: a model calling a tool through a
real agent turn (no model in the sandbox). Binary and HOME removed.
|
||
|
|
8947ee7a10 |
plugin: a plugin's usage window keeps runsOutAt and runsOut through the host, so its credits' expiry reaches /v1/magpie/quotas, the Usage page and Smart routing (#2265, zhenghaowen0967)
usageOf() in host.js rebuilt each window from a list of fields that never had runsOutAt/runsOut. |
||
|
|
194b2fd3c5 |
plugin: the host keeps models.dev's catalog through a half-written refresh, and #1928's start test leaves a loaded runner room (#1928 review)
Review of Totopo27's bfd56fab (the commit before this one), which makes the
plugin host start without waiting on models.dev and read the catalog again
once it is written.
What this changes on top of it:
- host.js mdev(): catalog.Sync writes models.json in place, so a host
listing providers during a refresh could read it half written. That
read replaced the catalog it had with {}, and the Go side kept that
list until its next refresh. A read that fails now keeps what was read
before (a failed read means unknown) and is tried again next time.
TestHostKeepsTheCatalogThroughAHalfWrite: red with bfd56fab's mdev()
("a catalog read half written dropped the catalog read before"), green
with this.
- TestHostStartDoesNotWaitOnHangingModelsDev bounded a real bun host start
by 3s, which a loaded runner can exceed. It now allows 15s within a 25s
context: the old blocking start still fails it (the hanging sync holds
the start until the context ends).
What was run at this head (Go 1.26.8, worktree of origin/main
|
||
|
|
78e337a20e |
plugin: sync models.dev in background and reload in host when available (#1928)
What: - In internal/catalog, serialize Sync using a buffered channel (syncCh) so lock acquisition honours ctx.Done(), and add SyncIfMissing to avoid redundant downloads if a catalog appears while waiting for the lock. - In internal/plugin/host.go, run catalog.SyncIfMissing in the background when starting without a cache, tracked by a WaitGroup and cancellable context so startOn never blocks on models.dev network I/O. - Always pass catalog.CachePath() to host.js via modelsDevPath when Source() is empty. - In internal/plugin/host.js, reload models.json in mdev() when the file appears or its modification time (mtimeMs) changes. - In internal/plugin/providers.go, cancel and wait for in-flight background syncs in Settle() to guarantee clean test teardown. - In internal/plugin/modelsdev_wait_test.go, install dial hook with sync.Once and an atomic stop channel to eliminate races and goroutine leaks, and add TestHostBackgroundSyncForgetsProviders to verify Cached() reloads upon background sync completion. - In internal/catalog/sync_ctx_test.go, add TestSyncIfMissingSkipsFetchWhenCacheAppearsWhileLocked. Why: - In #1928, startOn blocked up to 30s when models.dev hung. - Making Sync non-blocking during startup while allowing host.js to hot-reload once background sync completes gives fast startup on offline/slow networks without sacrificing catalog data. - Context-aware lock acquisition prevents calls from stalling behind an active sync when their deadline expires. What was run: - go test -count=1 -tags nogui -v ./internal/catalog/... (PASS) - go test -count=5 -tags nogui -v ./internal/catalog/ -run "TestSync.*" (PASS) - go test -count=5 -tags nogui -v ./internal/plugin/ -run "TestHostStartDoesNotWaitOnHangingModelsDev|TestHostReloadsCatalogWhenFileAppears|TestHostBackgroundSyncForgetsProviders" (PASS) - go vet -tags nogui on windows, linux and darwin (clean) - gofmt -l (clean) |
||
|
|
2076943915 |
plugin: a plugin declares its own switches, shown in its provider's editor and read by the plugin (#2038, Vocllum)
Vocllum asked that a plugin can offer the user generic on/off options
without magpie knowing what each one is for. A plugin now declares them
on its auth hook, beside checkin:
auth.options: [{ key, label, description?, default?, confirm? }]
and reads the user's values through input.magpie.option(provider, key)
or input.magpie.options(provider). Each call reads the current values,
so a change reaches the plugin without a restart. magpie only keeps the
value and hands it over: nothing is scheduled or run when an option
changes. The check-in switch (settings.pluginCheckins) and the check-in
plugins are unchanged.
- host.js: optionsOf keeps a key matching [a-z0-9_-]{1,40} with a
non-empty label, drops repeats, caps the label at 60 characters and
the description and confirm at 300, takes default only when it is
true, and keeps at most 16. The values come at init and through
setProviderOptions.
- Go: plugin.Option, Provider.Options, OptionOn and SetProviderOptions
(sent only to a host that is running). settings.PluginOptions is kept
by the plugin's provider id, then the key. POST
/api/settings/plugin-option {provider, key, on} checks the key the same
way and hands the values to the host. The generic settings save keeps
them, as it keeps PluginCheckins. /api/providers' plugins[].options
carry each option's resolved `on`.
- GUI: a "Plugin options" field in a plugin provider's editor. Each
option is a segs Off/On beside the plugin's label and description, put
in with textContent. A confirm text is asked through confirmAction
before turning an option on. Changes wait for Save, which posts each
one before the provider. Strings are added for zh, zh-TW, ja and de.
- Docs: provider-plugins.md (a new section), reference.md, gui-shell.md
and the tests README.
Run:
- TestPluginOptions (a real host with testdata/options). Red with the
old host.js (no options listed) and red with setProviderOptions turned
into a no-op (the plugin still reads the old value).
- TestPluginOptionSetting and TestSettingsSaveKeepsWhatItDoesNotSend.
Both red with the generic save's PluginOptions line removed.
- plugin-options.test.cjs: 22/22 in Chromium and WebKit, at 1100 and 420
wide, in en, zh, zh-TW, ja and de. Red on the old app.js (no field).
The screenshots were looked at: long text wraps and the page has no
sideways scroll at 420.
- provider-concurrency, plugin-signin, plugin-checkin, provider-price-rate
and plugin-move-unserved: 68/68.
- go test ./internal/plugin/... ./internal/settings/... ./internal/gui/...
./internal/provider/..., gofmt -l, and go vet on darwin, linux
(-tags nogui) and windows.
Not tried with a real community plugin, since none declares options yet.
The check-in row doesn't take a plugin-declared label or hint; it is
left as it was.
|
||
|
|
77f90fd84f |
gateway: a plugin whose config hook says searches: true is sent the client's web_search as sent (#2027, yudaleng)
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay whose quota the plugin reads) had no way to say its upstream runs the hosted web search tool: searchesItself returned at once for any signed-in account, letting only Codex and Grok through, so Claude Code's WebSearch and Codex's web_search always went through magpie's own search. Now a plugin's config hook can set `searches: true` on its provider, as it sets `decide` (#1514). The host passes it through (plugin.Provider.Searches), pluginProvider sets the provider's Searches, and searchesItself honours it for a plugin's provider only, on Anthropic or Responses and only where the plugin has a model on that API, the same rule a custom provider's "Searches the web by itself" has (#359). Another sign-in's Searches is never read; Codex and Grok are unchanged. As with a relay, searchRank leaves it out, so magpie never picks it to search for other models; Settings can name it by hand. Documented in docs/subsystems/provider-plugins.md and the plugin guide (site/public/docs plugins.html, en/zh/ja). Verified: - TestPluginSaidToSearch (new, gateway, through the real fake plugin on bun and New().Handler()): with FAKE_SEARCHES the plugin's upstream gets web_search_20250305; without it, it gets no search tool; Chat doesn't search and searchRank is -1 either way. - Broken by hand, each red: search.go reverted, plugins.go reverted, host.js reverted (each "searches by itself on Anthropic: false"); with the searchesItself assertion disabled and search.go reverted, the wire check fails "said to search true, the plugin was sent []". - TestMovedGrokSearchesItself, TestGrokPluginSearchesItself, TestWebSearch* pass. - go test -tags nogui ./internal/plugin ./internal/provider ok, and ./internal/gateway (see the run noted on #2027) under a sandbox HOME with pinned caches; gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on the three packages clean. - Not tried with a real CPA/sub2api plugin. |
||
|
|
3a53d06d99 |
provider, plugin: a subscription's sign-in goes through the proxy its account's requests use, not always the global one (#1663, demystify0137)
What changed: every sign-in started in magpie now leaves through the
account's own proxy (ProxyOfLogin: the account's, else the
subscription's, else the global one). Before, the sign-in's token
exchange and checks went through the global proxy while the account's
later refresh and usage calls went through its own (ViaLogin), so the
vendor saw one account come from two exits.
- signin.go: SignInOptions{Site, Proxy, User}, StartSignInWith; the flow
picks its proxy (pickProxy, validated with settings.CheckProxy) and
every request goes through s.via. Each built-in sign-in (Claude,
Codex/ChatGPT, Grok, Zed, WorkBuddy, Copilot, ZCode, Factory, MiMo,
Qoder, Command Code, Kiro) uses s.via; Claude Code's own login gets the
proxy as *_PROXY (netproxy.EnvWith).
- proxy.go keepSignInProxy: a proxy picked for the sign-in is kept as
the subscription's when the account is its only one, else as that
account's own entry. "" (global) is refused while the subscription has
a proxy and other accounts, since nothing could keep it.
- plugin host: authorize and callback run under via.run(proxy), so a
plugin's sign-in fetches go through the same proxy; plugins_cli.go
does the same for `magpie plugins login`. PluginAPIKey goes through Via.
- gui: POST /api/signin and /api/plugin-signin take proxy and user.
What was run:
- go test -tags nogui ./... (sandbox HOME), all packages ok.
- gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on the
touched packages.
- Red without the change (each broken by hand, then restored):
TestSignInGoesThroughItsProxy, TestDeviceSignInGoesThroughItsProxy,
TestPluginSignInGoesThroughItsProxy, TestClaudeSignInGoesThroughItsProxy
(internal/provider) and TestPluginSignInProxy (internal/plugin) each
fail with the s.via / EnvWith / via.run / keepSignInProxy removed.
Not tried: a real vendor account through a real proxy. The browser's own
leg of an OAuth sign-in goes through the browser's network, not magpie's.
Devin's CLI probes still use the global proxy.
|
||
|
|
1075991f90 |
gateway: a plugin's fetch is told the folder the agent works in and whether it is a git repository, never seeing magpie's own (plugins #86, Hipple)
A plugin runs in magpie's plugin host, so its process.cwd() is magpie's folder. The ZCode plugin's Start Plan request said that folder (C:\Users\<user>\.config\magpie) as the agent's "Primary working directory", with "Is a git repository: no", and the model looked there. forwardOnce now calls tellWorkPlace on every request to a plugin's provider. It reads the request as sent to the plugin with workPlace (the same reading rules by folder use) and sets two headers on the plugin's fetch: - x-magpie-work-dir (provider.WorkDirHeader): the folder, percent-encoded (url.PathEscape; decodeURIComponent reads it); - x-magpie-work-git (provider.WorkGitHeader): yes/no. The agent's own word beside the folder (Claude Code's "Is a git repository: true/false", OpenCode's "Is directory a git repo: yes/no") wins. Otherwise it is a .git in the folder or above it, when the folder is on this computer (provider.GitSaid, provider.GitOnDisk in the new workplace.go). Each is left off when unknown; a folder that isn't on this computer and that the agent didn't call a repository has no git value, never "no". host.js's fetch (unsaid) takes both headers off every request a plugin sends, so a plugin that forwards the headers it was given sends them to no vendor. Documented in docs/subsystems/provider-plugins.md. Run: TestPluginToldWhereTheAgentWorks (new) sends the captured Claude Code and Codex requests, and Pi-style ones from a temp repo subfolder and a plain folder, through the fake plugin to fake-claude and fake-1. It checks what the plugin read and that the vendor got neither header. Broken by hand: without the tellWorkPlace call every case fails; without unsaid in host.js it fails with "the vendor got X-Magpie-Work-Dir". go test internal/gateway (-timeout 40m), internal/provider, internal/plugin; gofmt -l; go vet on darwin, GOOS=linux and GOOS=windows for the three packages. |
||
|
|
2df2e0886d |
plugin, provider, gateway: a plugin's model is listed with every kind it takes and gives (audio, video, pdf), not image alone (#1595, tkhs101)
The plugin host read a model's capabilities.input only for "image", and
fromModelsDev hard-coded output to text, so /v1/models listed
opencode-zen-free's muse-spark-1.3-contributor-free (models.opencode.ai:
input text/image/audio/video/pdf) as ["text","image"] with no output.
- host.js: fromModelsDev and the config merge keep modalities.input and
.output whole; the listing sends inputs/outputs, the kinds the
capabilities object marks true, in OpenCode's order.
- plugin.Model gets Inputs/Outputs; pluginCatalog puts them on
catalog.Model's new InputModalities/OutputModalities (input only where
the plugin said what it takes, as ImageInput already is).
- catalog: models.dev entries and a vendor's live list (now reading
modalities.output) fill the same fields; Decorate carries the catalog's
when the live list says nothing, beside ImageInput.
- provider.Entry.Modalities() is what the gateway lists: the source's
kinds, with "image" still decided by Images, so the user's own
"takes images" override still wins and the other kinds stay.
Not changed: the 7 models the report lists as having lost their levels
have reasoning_options [] upstream (models.opencode.ai), so "reasoning,
no levels" is what they are; mimo-v2.6-flash turns away levels (#214).
DSH's model kinds and Muse's list still say text/image only.
Tests: TestPluginModelModalities (gateway) with the reporter's literal
metadata: muse-spark's config as opencode-zen-free 0.1.3's configModels
writes it, and mimo-v2.6-flash-free's capabilities as its models hook
lists them; a model said nothing of stays unlisted, and the image
override drops image only. TestFetchedModalitiesKeepEveryKind (catalog).
Broken by hand: host.js without inputs gives the report's [text image]
(red); Entry.Modalities without the Inputs branch (red); Decorate
without the fill (red). Run: go test catalog, plugin, provider, gateway;
gofmt -l; GOOS=linux and windows go vet on the four; go test ./...
green on 76db4c6c2+this; after rebasing on
|
||
|
|
93c5d846ca |
plugin: a plugin's requests to a host on the user's own network go direct, as magpie's own do (#1572, ggbdpq)
What changed: with a proxy set (magpie's, the environment's or the system's), the plugin host sent a plugin's requests for a host on the user's own network - a Remote magpie, an LLM relay on the NAS - through that proxy, which can't reach it (502 Bad Gateway) or resolve its name. Go's netproxy.Func leaves such a host direct since #982 (lan.go onLAN); host.js's proxyFor and its node:http2 sessions (#1035) were that rule's siblings without it. - host.js ports lan.go's rule: onLAN takes a private (10/8, 172.16/12, 192.168/16, fc00::/7), link-local, loopback or CGNAT (100.64/10) address, a .local name, or a name every address of which is one of those; looked up for 400 ms at most, kept a minute (256 names), a failed or slow lookup is "not on the network". It is asked only when the global proxy would be taken (after loopback, a provider's own proxy or "direct", and NO_PROXY), as Func asks it, so a user without a proxy pays no lookup and a provider's own proxy is still taken as is. IPv6 is compared on its bytes, so a v4-mapped address in hex form (::ffff:a00:1, how URL writes it) is judged as its IPv4 address. - http2.connect returns its session at once, so tunnel() now takes a promise of the proxy and connects when onLAN has answered: straight to the host for one on the user's network, through the CONNECT otherwise. Unlike the issue's patch, a LAN name that needs a lookup is covered on this path too. - The issue's patch was reviewed, not applied: its lanIP missed loopback and hex v4-mapped IPv6, it didn't strip a trailing dot, it never cleared its lookup timer, and it left HTTP/2 to LAN names proxied. New TestPluginLeavesTheUserNetworkDirect (real Bun, a proxy that keeps every target it is asked): a fetch to this computer's private address over http:// (absolute form) and https:// (CONNECT; a certificate for that address via NODE_EXTRA_CA_CERTS), to "localhost." (a name decided by what it resolves to), and an HTTP/2 session to the private address all reach the server directly; a public address (203.0.113.5) and a name that resolves nowhere (vendor.invalid) still go through the proxy. Run: the new test against the old host.js fails on all three fetches (proxy asked for each); with only the HTTP/2 check removed it fails on the session ("h2: proxyconnect tcp: 502 Bad Gateway"); with every host taken as LAN it fails on the public address and the vendor name. A bun check of lanIP over 24 addresses (both sides of every range) matched lan.go. go test ./internal/plugin ./internal/netproxy ok; full go test -tags nogui ./... ok in every package (the five whose build hit another session's go-build cache prune were rerun, all ok: ., agent, gateway, gui, library); gofmt -l clean; go vet -tags nogui internal/plugin on darwin, GOOS=linux and GOOS=windows clean. Not tried with a real NAS or Remote magpie behind a real proxy. |
||
|
|
4b2f2ec31e |
provider, plugin: a plugin can serve System One for its provider, and the models it marks are a routing group's classifier (#1514, FourLeafTec)
A plugin had no way to say its provider answers TypeSafe's System One,
so a free decision model a plugin reaches (mu-zi-lee/magpie-our-free-model)
could only be listed as a chat model.
Now the plugin's config hook sets `decide: true` on the provider, and
`decides: true` on a model, in the config hook or on the models hook's
list. host.js passes both through (plugin.Provider.Decide,
plugin.Model.Decides). pluginProvider sets the provider's Decide to its
own base, plugin://<id>/v1, so System One is asked at {baseURL}/systemone
through the loader's fetch with the account's sign-in: pluginFetch sends
nowhere but the loader's host, so an address the plugin named itself
couldn't be reached. AskSystemOne now sends with Provider.Do, as the
gateway's classifier already did, so the editor's test goes through the
fetch too (Do is client.Do for every provider without an account).
decide.go treats a plugin provider's decision models as the ones it marks
plus Jev's by name (jev-*): kept from agents, refused for chat ("only
decides"), refused as a group member, offered as a group's classifier
(Deciders, DecisionModels, Jev). A mark without `decide` on the provider
changes nothing. Docs: site plugins page (en, zh, ja) and
docs/subsystems/provider-plugins.md.
Thanks to FourLeafTec, whose reference commit (bc0b3fee in their fork)
proposed the two fields and the plugin base; this is written afresh.
Run:
- internal/gateway TestPluginServesSystemOne and
TestPluginMarksWithoutDecide, through the real bun plugin host with the
fake plugin (FAKE_DECIDE). Red with host.js, plugins.go and decide.go
reverted ("Decide = \"\""), with only host.js reverted, and with only
decide.go reverted (no classifiers, offered to agents, chat to one 200).
- go test -tags nogui ./... (temp HOME): every package ok; internal/gateway
hit the 10m default at load ~140 in TestLargeRequestEndpoints, then
passed alone with -timeout 40m (548s).
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on
internal/plugin, internal/provider, internal/gateway.
- Real use: a nogui build in a sandbox HOME on 127.0.0.1:3612, a local
plugin declaring decide with judge-x marked, a fake vendor on 3613.
`magpie group rule add ... classifier=dec1514/judge-x` saved; judge-x
was not in /v1/models and not accepted as a member; a turn to the group
asked /v1/systemone judge-x (levels, then intent) with the plugin's key
and its fetch's own header, then went to chat-b; chat to judge-x
answered 400 "only decides".
- No GUI change: a plugin's editor is the account editor, which has no
address fields.
Co-authored-by: FourLeafTec <5875432+FourLeafTec@users.noreply.github.com>
|
||
|
|
89271cd4e8 |
provider, plugin, settings: accounts left all zero by a crash are read from their last good copy, and every state file is flushed before it is renamed in (#1505, Zhangwier)
Zhangwier's Windows machine went down hard, and logins.json (10783 bytes)
and plugin-auth.json (29926 bytes) came back at full length with every byte
0x00. Every account was gone. The rename had reached the disk before the
data. magpie then read "no accounts", and its next write would have made
that final.
What changed:
- Flushed before rename: steady.WriteFile writes a temp file, fsyncs it,
then renames it in. A failed write or flush removes the temp file and
leaves the old file as it was. edit.WriteAtomic, Kiro's writer, the
Codex session rewrite and the plugin host's writeDurable (host.js)
flush the same way. So do writePrivate (providers, logins, migrations),
settings, profiles, plugins.json, plugin-auth.json and mcp-signins.json.
- A last good generation: before each write, lastgood.Keep keeps the
valid file there as <file>.bak. A file that isn't valid is copied aside
as <file>.bad-<time>, with -2, -3 when two land in one second (O_EXCL),
and is never overwritten before that copy exists. The .bak lags one
write behind on purpose, since a crash zeroes the latest write.
- A failed read is unknown, never empty. On a cold start, logins.json,
providers.json, migrations.json, settings.json, profiles.json,
plugins.json, plugin-auth.json (Go and the host) and mcp-signins.json
are read from their .bak when they don't read. The recovery is logged
and listed in /api/state's recovered, and the window says it once in
every language. With no good .bak, a sign-out leaves plugin-auth.json
and mcp-signins.json as they are (the host's changeAuth no longer
writes {} over them). magpie's own sign-out returns the error, and a
sign-in copies the bad file aside before writing.
- caller-keys.json is flushed but never read from a .bak. A key revoked
in the last write would come back, so a store that doesn't read still
refuses every key, as its tests require.
ggbdpq's patch (f230bcae) is where the fsync-before-rename in
writePrivate, writeWhole and writeAuth came from. This change puts it in
one shared helper and reaches every other writer of magpie's state. The
JS write cleans up its temp file. The .bak recovery, the .bad copies and
the GUI notice are added here.
What was run:
- New tests, built from the literal case (10783 and 29926 zero bytes):
- internal/lastgood
- provider: TestZeroedLogins*, TestZeroedMigrations*,
TestZeroedProviders*, TestWritePrivateSyncsBeforeRename
- plugin: TestZeroedPluginAuth* against the real bun host,
TestPluginAuthSyncedBeforeRename with a plugin that makes fsync fail,
TestZeroedPluginList*
- TestZeroedSettings*, TestZeroedProfiles*, TestZeroedMCPSignIns*
- steady TestWriteFileSyncsBeforeRename, edit
TestWriteAtomicSyncsBeforeRename
- gui recovered-file.test.cjs (en/zh/zh-TW/ja/de, Chromium and WebKit)
- Broken by hand, each going red:
- Without the sync: the steady, edit, writePrivate and host fsync tests.
- Without the .bak fallback: every TestZeroed* test.
- The old changeAuth writes "{}\n" over the zeros.
- The old readLogins default.
- KeepBad without suffixes fails the one-second test.
- Without recoveredOnce, the GUI test fails 5/5.
- macOS: go test -tags nogui ./... in a sandbox HOME. The only failures
were the two access tests (then fixed by not recovering caller keys) and
TestProvidersCmdSaysUnreadable, which now removes the .bak to test the
no-backup case. Both packages were rerun and pass. gofmt -l prints
nothing. go vet, and GOOS=linux and GOOS=windows go vet -tags nogui, are
clean on the touched packages.
- GUI: recovered-file, whats-new, click-scroll, gui-de, gui-ja,
gui-zh-tw and i18n-keys pass.
- Windows box (cross-compiled test exes, sandboxed USERPROFILE/APPDATA):
lastgood, steady, provider, plugin (real bun host), settings, mcpauth,
edit and access pass. In profile, TestProfileSwitchesModelList and
TestOldProfileKeepsModelList fail the same on origin/main (filed as
#1517).
Reported-by: Zhangwier
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
|
||
|
|
f0c63264e5 |
plugin: a Node program a plugin starts takes magpie's proxy, as Node's fetch skips HTTPS_PROXY without NODE_USE_ENV_PROXY=1
larchsis on X (Windows 11, a proxy set in magpie, none in the system): the "our free model" plugin's sign-in said 原渠道包下载失败. The plugin downloads its channel pack in a Node program it starts. The host hands such a program magpie's proxy as HTTPS_PROXY/HTTP_PROXY (since the grok login fix), but Node's built-in fetch ignores those unless NODE_USE_ENV_PROXY=1, so the download went direct and failed behind the wall. host.js's proxied() now also sets NODE_USE_ENV_PROXY=1 whenever it hands the program a proxy, unless the plugin's env already names it (a plugin's own value, 0 included, is kept). It is not lowercased. Not changed: the Go side's netproxy.Env, which starts npm, Claude Code, grok and devin. Those read *_PROXY themselves, and the proxy there may be socks5://, which Node's env proxy does not take. Run: - TestPluginNodeTakesTheProxy (new) fails on the old host.js and passes now, on macOS and on the Windows box. - go test ./internal/plugin/... passes. - GOOS=windows and GOOS=linux go vet pass; gofmt is clean. - End to end through the real host, on the Mac (Node 22.22) and on the Windows box (Node 22.22.2), with a throwaway plugin (not committed) that starts `node` to fetch https://raw.githubusercontent.com/ while magpie's proxy points at a fake 502 proxy: - old host.js: direct200, so it went past the proxy; - fixed: fetch failed at the proxy. |
||
|
|
99009b9333 |
provider: a plugin's model pool counts a bare id with its @sizes, so a routing group's cursor/grok-4.7 is weighed on Cursor Models, not a used-up Other Models (Will on Discord)
Will's routing group keeps cursor/grok-4.7. Cursor's plugin (0.2.2/0.2.3) lists Grok 4.7 only at its context sizes, grok-4.7@256k and grok-4.7@500k, and its usage() builds the Cursor Models window's models and Other Models' notModels from those ids. quotaOfPlugin matched a model against those lists by the whole string, so bare grok-4.7 (which the plugin still runs, at its default size) fell into Other Models: used up, so the Routing page showed it 0% left and weighRouted ranked it last, while composer-2.5 showed ~84%. The window's lists are now an idSet: a bare id is in it when one of its id@size is, and an id@size when its bare id is. Only the trailing @size is taken off, so distinct models stay apart: another @size of a model, another family member (grok-4), and other suffixes (ZCode's -Trial) still match by the whole id. Every route that asks a plugin window whether it counts a model goes through w.matches -> Limit.applies (routing's For, Pace, Count, Renewal, fallback's Pooled, CapHeld, QuotaWindow.Counts for the usage page's holds), so the one change reaches them all. host.js's contract comment says so for plugin authors. The plugin's own lists are also fixed in magpie-community/plugins (cursor 0.2.4 adds each listed id's bare name to its pool), for magpie versions before this one. Verified: - TestPluginPoolCountsBareIDOfSizes (the reporter's literal ids) fails on the old code: "grok-4.7: used 100, want 16", "the usage page's holds count grok-4.7 in Other Models", "grok-4.8@1m: used 100, want 16"; passes with the change. - gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui on internal/provider and internal/plugin; go build for darwin, linux, windows. - go test -tags nogui ./... green but TestNoCommandBypassesProc, red on main since |
||
|
|
7d0e415e62 |
plugins: two plugins that sign in to one provider are both listed, each row says which serves it, and Use for picks the other (neiko on Discord)
neiko on Discord installed a third-party plugin beside a plugin of their
own, added by its folder. Only the third-party one could be seen. Both
plugins' auth hooks name the same provider id. The host's auths() keeps
the last plugin in plugins.json for an id, as OpenCode does, so the
user's own plugin silently lost it:
- its row read "Signs in to nothing magpie can use";
- its provider was gone from the Add sheet;
- keepUnloaded could list the id a second time, from the
plugin-providers.json kept before.
A package-name clash and a display-name clash were tried as well. Both
plugins stay visible in those cases, because a folder plugin's name is
its path.
What changed:
- host.js:
- init gives each loaded plugin the ids it signs in to (provides) and,
for each id another plugin serves, that plugin's spec (servedBy).
- auths() honours plugins.json's new prefer map (id -> spec).
- Only the serving plugin's provider.models hook runs for the id.
- plugin:
- Clashes() turns provides and servedBy into {id, by, with} per spec.
- Prefer() records a pick and restarts the host.
- Remove drops the removed plugin's picks.
- Re-adding a plugin under a new spec carries its picks over.
- remove, off, options and prefer find a plugin by its exact spec
before its package name (indexOf), so acting on one plugin never
reaches another of the same package.
- keepUnloaded no longer re-adds a provider from before when another
plugin serves its id now.
- GUI:
- /api/plugins rows carry clashes, with the provider's listed name.
- POST /api/plugins/prefer {spec, provider}.
- 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", with a "Use for {name}" button.
- New strings in zh, zh-TW, ja and de.
- CLI: `magpie plugin` prints the same lines, with the command that
fixes it, and `magpie plugin use <name> <provider>` makes the pick.
- Docs: docs/subsystems/provider-plugins.md, docs/reference.md and
site/public/docs/{,zh/,ja/}plugins.html.
What was run:
- Reproduced under a sandbox HOME with magpie web on 3562: a fake npm
plugin and a folder plugin, both on id "acme".
- Old binary: the local row had providers [] and /api/providers
listed acme twice.
- New binary: both rows carry the clash; prefer moves acme to the
folder plugin; remove clears the pick and leaves the other plugin
serving acme.
- New Go tests:
- TestTwoPluginsOneProvider, a real Bun host: Prefer, restart,
off/on and Remove.
- TestClashes, TestPluginNamedExactlyFirst and
TestKeepUnloadedLeavesAServedID.
- TestPluginsClashRows (gui) and TestPluginListSaysClash (CLI).
- Each fails when its piece is broken by hand: prefer ignored in
host.js, the keepUnloaded id check removed, name before exact spec,
Remove keeping picks, no provides, no clashes in the rows, no
prefer route.
- plugin-clash.test.cjs, in Chromium and WebKit, in en, zh, zh-TW, ja
and de, at 1100 and 560px: 22/22 pass. It times out on the old
plugins.js.
- gui-de, gui-ja, gui-zh-tw, i18n-keys and every plugin-*.test.cjs:
248 tests.
- 245 passed in the 4-wide run.
- plugin-moved-signin (webkit) failed once in that run, then passed
3/3 alone and 26/26 in a smaller 4-wide rerun.
- gofmt -l; go vet ./...; GOOS=linux and GOOS=windows go vet -tags
nogui ./...; go build ./...
- The full go test -tags nogui ./... under a temp HOME with the caches
pinned: 44 packages ok, none failed.
- After rebasing onto
|
||
|
|
baecbb1be0 |
provider, gateway: Cursor moved onto its 0.2.x plugin gets Fast back, in the agent picker (#954) and for a Routing group's member, on the models Cursor has a fast variant of (#1360, loosheng: 插件 0.2.x 后 Cursor 的快速模式不见了,保存 cursor/<model>:fast 报 "has no fast mode magpie can ask for")
Plugin 0.2.x lists Cursor's picker once per context size (claude-opus-5-5@300k, @1m) and no -fast model, so CanFast, which looked for a -fast sibling, said no for every model: FastFor in route.go, canFast in the group editor, SetFastPick and cleanFast all go through it. The plugin itself still ran service_tier priority as the fast variant. opencode-cursor-auth 0.2.2 (magpie-community/plugins fb253f9) now says fast on a model listed at a size Cursor has a fast variant at; host.js passes it on as plugin.Model.Fast, CanFast takes it, and a plugin before 0.2.2 is still read by its -fast sibling. The Cursor mover asks for 0.2.2. On the way a fast request translated for a moved Cursor (Anthropic, Responses, chat not streamed) lost its service_tier: buildChat sets it only for host "cursor", and a moved provider's host is empty; buildHost names it. Tested: the fake plugin lists sized models with fast on one (FAKE_FAST=tier); TestCursorPluginGroupFast (CanFast per size, @1m:fast refused, a group's @300k:fast sends priority), TestCursorPluginGroupFastSibling (the old -fast list), TestCursorPluginFastPick (moved: picker fast on chat, chat streamed, Responses and Anthropic sends priority, codex's doesn't). Without groupfast.go, host.js's fast or buildHost they fail. go test -race -tags nogui on gateway, provider, plugin, agent, gui; go vet, GOOS=linux/windows vet and build. With the built binary under a temp HOME, the real npm 0.2.2 plugin and Cursor's API answered by a preload (a picker fixture, the agent API's Run caught): /api/state offers fastFor on @300k and composer-2.5, not @1m or grok; /api/groups canFast the same; saving @1m:fast is refused, @300k:fast saved; opencode's picked @300k reaches Cursor's Run with fast=true on chat, Anthropic and Responses, codex's with fast=false. origin/main's binary in the same HOME offers none and refuses @300k. Not tried with a real Cursor account. |
||
|
|
cdf325f178 |
plugins: a package that is only a command (an MCP server like magpie-x-search) isn't listed under Unreviewed, isn't added as a plugin, and one added before says what it is instead of a host stack (#1327, congee949)
A repository tagged magpie-plugin whose npm copy (from that repository) names no file to load (no main, no exports) was listed and installed from npm without the entry check the GitHub route has; it then failed every host start with "has no entry" and a stack. Now: - the Unreviewed list checks npm's copy the same way: one that names no file needs the index.js the repository's own route needs (askTagged); - `magpie plugin add` / the Plugins page refuse a package that names no file, has no index file and is neither pi's nor a middleware, take the package just installed for it out again, and say it isn't an OpenCode or magpie plugin, and, for one with a bin, to add an MCP server under Library → MCP servers (notPlugin); - the host says the same, without a stack, for one already on the list. Run: TestCommandOnlyPackageIsNoPlugin (magpie-x-search 1.2.0's real package.json) fails without the change (Add = <nil>; with only host.js reverted, the stack message), TestTaggedRepos with the real GitHub package.json and npm latest of cyberElar/magpie-x-search fails without it (listed), both pass with it; TestNotPluginKeepsPlugins (index.mjs, main, exports, middleware, pi, a file stay plugins). go test -tags nogui ./internal/plugin under a temp HOME ok; go vet -tags nogui for darwin, linux, windows. The built binary in a sandbox HOME: `magpie plugin add magpie-x-search@latest` from real npm prints the new error, and plugins/package.json no longer lists it. Co-Authored-By: Claude <noreply@anthropic.com> |
||
|
|
51d2cf88ea | plugin host: a plugin's node:http2 connection goes through magpie's proxy like its fetch does (#1035, cataglyphis: Cursor opus-5-5 high ends after ~148s with "Cursor: 502 Bad Gateway" cursor_error) — the Cursor plugin runs agent.v1.AgentService/Run over node:http2, which Bun connects directly and ignores the proxy that host.js gives every fetch; the built-in sent the same request through s.client, so a user who needs magpie's proxy (setting, env or the system's) to reach Cursor had their sign-in, models and usage proxied but every Run went out directly. host.js now wraps http2.connect: for a URL proxyFor gives a proxy to (provider/account via, global, SOCKS bridged), it opens an HTTP CONNECT tunnel (Proxy-Authorization from the URL) and runs TLS with ALPN h2 over it; "direct", a caller's own createConnection and unproxied URLs keep Bun's connect; a tunnel that fails ends the session with "proxyconnect tcp: …". TestPluginHTTP2TakesTheProxy (an HTTP/2 vendor at an unresolvable host reached only through a CONNECT proxy; direct and a dead proxy fail with the reason) fails without the change ("h2: getaddrinfo ENOTFOUND h2vendor.invalid"; it carried 0) and passes -race -count=10. With the owner's Cursor account in a sandbox HOME and a logging proxy set, Claude Code's captured request on cursor/claude-opus-5-5 high: before, the proxy saw api2.cursor.sh only; after, it also sees agentn.global.api5.cursor.sh and the reply streams. The reporter's 502 wasn't reproduced here (direct runs answer in 4–20s). go test -race ./internal/plugin, the gateway/provider Plugin|Proxy|Cursor tests, gofmt and vet pass. | ||
|
|
87487c5ef0 | plugin, provider: a plugin can press its vendor's daily check-in itself (auth.checkin), and magpie runs it as its own check-ins (Lemon on Discord #feedback: provider 每日签到的方法能放到插件里面去做吗; ARNO earlier asked for Qoder's) — the check-ins magpie had (WorkBuddy, Trae CN, MiniMax Code, Qoder) are each written in magpie against the vendor's endpoint, even for a subscription that moved to its plugin, so a plugin author had no way to give their provider one. A plugin's auth hook may now have checkin(getAuth, provider) beside usage: the host lists the provider with checkin: true (plugin.Provider.Checkin) and answers checkin({provider, account}) (plugin.AccountCheckin), refreshing the account as usage does, with {outcome, credit, streak, message}; outcome is claimed, done, ineligible, inactive, captcha or failed, and a throw or an outcome outside these is failed with the reason. internal/provider/plugin_checkin.go runs these through checkin.go's checkiner, as the built-ins are: each signed-in account in use once a Beijing day (first look 2 minutes after start, then every 30), a failure asked again after wbCheckinRetry, every other outcome settled for the day, results kept in plugin-checkin.json by provider|account; a failure is recorded as failed and resets nothing. captcha is new (CheckinCaptcha): the vendor wants a captcha, which magpie never solves, so it is said as "check in in its own app", not as a failure, and not asked again that day. The results mark the account's Usage card (checkinBy "plugin:<provider>", WithCheckins), so the card's check-in row, its Auto check-in and Check in now work for it (POST /api/settings/plugin-checkin {provider, on}, POST /api/usage/plugin-checkin {provider}); Settings → Usage gains a Plugins tab, shown while such a plugin is signed in, a Daily check-in row per provider with Off/On and how each account went; magpie accounts checkin and c on the TUI's Usage page include them (the TUI's "no account" line names check-in plugins). The switch (settings.PluginCheckins, by provider) is off by default; for WorkBuddy, Trae CN, MiniMax Code and Qoder it follows that vendor's existing switch until set on its own, and magpie's own check-in through the plugin's fetch leaves a provider whose plugin checks in to it (pluginChecksIn), so no account is checked in twice. The Settings page's save carries PluginCheckins over (TestSettingsSaveKeepsWhatItDoesNotSend's fixture names it). No plugin declares the hook yet; Qoder's check-in stays magpie's own here. TestPluginCheckinRunsAsTheBuiltinsDo (the fake plugin with FAKE_CHECKIN, five accounts answering claimed, done, captcha, a throw and an unknown outcome: off presses nothing; on, each outcome kept with its vendor; a minute on nothing pressed again; past the retry only the two failures; the next day all five; PluginCheckins and the cards marked; another provider's press asks none) and TestPluginCheckinTakesOverTheVendors (a qoder plugin without the hook leaves magpie's Qoder check-in its account, with it none; PluginCheckinOn's fallbacks) pass -race -count=10, and the latter fails with pluginChecksIn stubbed false; TestTUIChecksPluginsIn passes -race -count=20. plugin-checkin.test.cjs (the card's row with the captcha said, Auto check-in posting {provider, on}, no page move; the Settings Plugins tab at 440px with the row fitting, no sideways scroll, On posting) passes on Chromium and WebKit in en, zh, ja and de; usage-checkin, i18n-keys, gui-ja, gui-de and settings-* pass. go test -tags nogui ./internal/..., go vet, gofmt -l, linux (nogui) and windows builds pass. Not tried with a real plugin or account: no published plugin has the hook yet. docs/subsystems/provider-plugins.md (the hook's contract) and docs/reference.md say it. | ||
|
|
bc00ee1df2 |
plugin, provider: a program a plugin starts has magpie's proxy, and a CLI login with no link says why (𝕏 on Discord)
The Grok plugin's sign-in said only "grok login gave no link to open". The plugin host has magpie's proxy only as MAGPIE_*_PROXY, so the `grok login` the plugin runs went out with none, where the built-in's had it (netproxy.Env); where x.ai is reached only through a proxy, it failed. host.js's spawn wrapper now gives a started program HTTPS_PROXY and HTTP_PROXY (the account's own proxy, none for direct, else magpie's) when the plugin set none. grok 1.0.46, unable to reach x.ai, prints "Error: error sending request for url (https://auth.x.ai/oauth2/device/code): …", whose URL the built-in's runCLISignIn took for the page to open; a line saying error gives no link, and a login with none ends with the CLI's last line. The plugin does the same from 0.1.8, which the grok mover now asks for. plugin_cliproxy_test.go and TestCLISignInSaysWhyNoLink fail before this. Checked with grok 1.0.46 itself through the plugin host and the published plugin's code, given a proxy that refuses: the CLI goes through it and the error names what it said. |
||
|
|
4788cf2bbd | plugin, gui: a plugin's account whose model list failed says why, rather than listing Auto alone (gnayiab on X) — with magpie in WSL, Cursor's plugin account offered only Auto: the plugin's models hook couldn't get the account's list and magpie, with no list kept from before, showed the plugin's defaults with nothing saying so, its editor even calling them "vendor list", and Refresh answered "1 models". The host now keeps why a models hook fell back (what it threw, else how its last fetch failed) for the provider and each account; plugin.Cached carries it with the accounts it reads again from the sign-ins; provider.ListError gives it for a plugin's account. The editor says "<provider> couldn't list its models: <why>" under the models (amber, no left border) and no longer calls the defaults the vendor's list, and Refresh fails with it. A list kept from before, or one that comes in, says nothing. en/zh/ja/de. Tried with the real Cursor plugin (0.1.9) in a sandbox: a key Cursor refuses shows "Cursor couldn't list its models: Cursor didn't take this API key" and Refresh says it; the owner's real account lists 72 models with nothing said, and Claude Code -p through the gateway ran a Bash tool on cursor/auto, composer-2.5 and claude-opus-5-thinking. The plugin itself, in WSL (magpie-desktop), listed 254 models and streamed chats with tools. TestFallenBackListSaysWhy (hook returns its defaults, throws, or hands back its own) fails without the change; plugin-list-error.test.cjs (Chromium and WebKit, en and zh) too; TestFallenBackListKeepsTheLastOne, account-models, plugin-signin and click-scroll pass. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. | ||
|
|
c38728145b |
plugin: a slow reader pauses its stream instead of racing a watchdog (#812)
* plugin: a slow reader pauses its stream instead of racing a watchdog #664 gave a plugin reply a soft watermark (softQueuedBytes 4 MiB, softQueuedEvents 4096) and a 10-second idle watchdog: past the watermark, a reader that made no progress for stallIdle had its call failed with errStalledReader, and hardQueuedBytes/hardQueuedEvents (64 MiB / 65536) cut the reply outright. Both are guesses at how long a reader may take, and both end a reply that reader was still consuming. The host now hands each fetch a credit window instead. Go grants streamWindow (512 KiB) up front and returns credit as the reader takes bytes, so the child stops producing at the window instead of being timed out; the window is charged per delivered byte plus frameOverhead (2048), so a run of tiny frames cannot fill it with metadata. streamBudget (64 MiB) and maxFrame (64 KiB) bound a whole reply and a single frame, and a child that sends past its window is a protocol violation (errProtocolOverrun) rather than a slow reader. The plugin side grew the matching gate (makeGate, gate.take/spend/add, waitDrain): a fetch holds at the window until Go credits it, and its pending writes are cancellable. Cancellation and shutdown now have one owner per call - a five-state lifecycle (sending, active, draining, aborting, released) whose single transition helper disposes the queue, detaches the watcher, commits the terminal answer, creates the abort and returns capacity exactly once - so a host failure, a Close, a cancelled context and an already-delivered reply can no longer race each other over who cleans up. A reply the host already delivered keeps its bytes and its vendor outcome when the host dies. Tests: the JS cancellation cases run the production sections with controlled stdout backpressure (stopped gate, split chunk, terminal suppression, acquired-body cancel, 30,000 cancelled bootstrap waits with no retained waiter or ready reaction); the Go cases drive lifecycle orderings directly (terminal-before-failure, failure-before-terminal, abort acknowledged before capacity returns, blocked enqueue), and the shutdown, body-close and mid-setup-cancel cases block on explicit channels instead of sleeping. TestFlowBigReplyProd reads 100 MiB non-SSE and SSE through the real host and checks lengths and SHA-256, including a 12 s reader pause. CI installs Bun 1.4.2 on Linux and runs that case in its own step, since the plugin sandbox skips when bun is not on PATH. * plugin: the stream-head credit test waits for the credits before the reply ends (CI, macos-latest: TestHostStreamHeadChunksFinal failed on the macOS runner with "the credits were given back didn't happen", while the same package passed on ubuntu-latest and locally) — the test sent the child's final answer together with its 50 chunks, so the call could be marked stopped and its pending credits dropped before waitFor saw them; a completed fetch needs no credit, so waiting longer could not recover them and the expectation was a race, not a real accounting bug. The final answer is now withheld until io.ReadFull has taken the 140 payload bytes in order and exactly 140 + 49*frameOverhead credits have been observed with frameOverhead still owed, and only then does the child answer and the test assert a zero-byte EOF read. No production code changed. Tests: go test -run '^TestHostStreamHeadChunksFinal$' -count=500 ./internal/plugin/ and -count=200 -race pass; go test -count=1 and -race -count=1 ./internal/plugin/... pass; gofmt -l and git diff --check clean. |
||
|
|
67092380fb |
plugin: pi packages run as pi runs them — a program a login starts can't take the host's stdin, a select is answered with its option's id, and the extensions get pi's runner, pi's auth.json and session_start (owner: 都补上,用真实账号测) — tried with real accounts, five pi packages had problems that the fake one didn't show. pi-devin-plus runs devin auth login with stdio "inherit" when it finds no Devin sign-in, and the program read magpie's next requests from the host's stdin as its answer ("Login canceled") while writing over its answers; host.js now gives every program started through Bun.spawn and Bun.spawnSync (all of node:child_process goes through them) nothing to read and stderr to write. pi-zcode asks its region with onSelect and options { id, label }, pi's own shape, and checks the id ("bigmodel"); pi.js answered with the label, so the login said "Login cancelled". Packages read their sign-in back from pi's auth.json (readStoredCredential: pi-zcode for its plans, pi-cursor for its token, pi-provider-qoder through the registry, pi-antigravity syncs its accounts through it) and register what they find on session_start (pi-zcode its plans' models, pi-devin-plus and pi-xai-oauth refresh their catalogs), and a provider registered after loading went into a queue nothing read. Now each package is bound with pi's ExtensionRunner as pi's session binds it (bindCore: no UI, tools or session of magpie's), so a later registerProvider reaches the runtime; each pi provider's first account is kept in $PI_CODING_AGENT_DIR/auth.json as pi keeps it, written when it changes; and a provider newly signed in, and each one signed in when the host starts, is sent session_start, after which magpie lists its models again if they changed. A runner that can't be made leaves the packages registered as before. TestPiPackage now has a select answered with an id, a login that starts a program on the terminal, and a session_start that reads the sign-in from pi's auth.json and adds a model; it fails on the old code (the label answered; the model never listed, auth.json empty) and passes. With real accounts in a sandbox HOME: pi-zcode signed in through Z.ai and lists 11 models (none before); its requests reach ZCode but the account's Start Plan answers 200 {"code":1005,"msg":"exceed quota limit"}, which pi-zcode reads as an empty answer (its bug). pi-provider-qoder signed in through Google, 16 models, tool round trips on Kimi-K3 and Efficient. pi-devin-plus signed in, its catalog refreshed on session_start (53 models), tool round trips on swe-2 and claude-opus-5.5; pi-xai-oauth (grok-4.7) and pi-antigravity (gemini-3.8-flash) tool round trips; @rahularya01/pi-cursor answers text (its agent doesn't call a client's tools, upstream). pi-provider-kiro wasn't signed in: it needs pi's terminal, a Builder ID or an IdC login. go vet, builds (darwin, GOOS=linux -tags nogui, GOOS=windows) pass.
|