dccfefdf722ea25f5cf2be1798d5686e43b89fbd
158
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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
|
||
|
|
f54e76dbdd |
gateway: a request builds the providers once, and plugin-auth.json and the discovery setting are parsed once a version (#2502)
XcodeFish (#2502): with several agents at once the gateway sat at 100-350% CPU. Counting provider.AllBuilt around one streamed chat request gave 3 full catalogue builds per request, and each build re-read and re-parsed plugin-auth.json and settings.json (AccountDiscoveryOff called Load() on every provider list). - holdCatalog wraps the gateway's handler in provider.Hold() and filememo.Hold(), so one request builds the providers once and stats each file at most once a second. Hold already drops the cache on provider.Changed and on magpie's own writes; another program's write is seen within the second. - plugin-auth.json is read through filememo (mtime, size, and the raw bytes while the file is under 2s old), so it is parsed once per version. A file that doesn't parse falls back to the last good .bak through lastgood, as settings does. Auths still hands each caller its own decoded map. The host looks at the file again before it reports a sign-in it just saved. - AccountDiscoveryOff reads the setting through filememo with the same parse settings.Load uses (now settings.parse), under fileMu. What was run: - TestRequestBuildsProvidersOnce: two streamed requests, one build each (3 each before). Red with holdCatalog taken out. - TestAuthParsedOncePerVersion: 100 rounds of Auths, SignedIn and the listing proxies parse plugin-auth.json zero more times; a caller's edit doesn't leak; a same-size rewrite is read; a zeroed file reads the .bak and stays signed in. Red with authRaw reading past filememo. - TestAccountDiscoveryOffParsedOnce: 100 calls, no parse; a Save is read. Red with AccountDiscoveryOff back on Load(). - gofmt -l clean; go vet -tags nogui on darwin, linux and windows ok. - Full suite, set -o pipefail; go test -p 4 -timeout 45m ./... at this pair rebased on |
||
|
|
ba132d68b6 |
plugin: the GitHub plugin list reads every page of the search, not the top 50 (@HoGee_xxl on X)
@HoGee_xxl on X: the Plugins page's GitHub list showed 50 repositories
while the opencode-plugin topic held 59. askTagged asked GitHub's search
for one page of 50 and stopped, so every repository past the 50th by
stars never showed. It now reads pages of 100 until a short page or
total_count, up to the 1000 GitHub's search answers, and a repository
that moves between two pages (starred in between) is listed once.
Run:
- TestTaggedReposEveryPage (new): a fake search of 7 repositories served
2 a page; all 7 listed, in order, once. Red with the page loop broken by
hand (stop after page 1): only the first 2 listed.
- Full suite at
|
||
|
|
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.
|
||
|
|
008571462b |
plugin: Settle starts no refresh while it settles (#2449)
Settle's own Restart tells the OnChange hooks, and one that calls
Cached() started refreshProvidersInBackground after Settle's last
refreshing.Wait. callWithTimeout starts the host under WithoutCancel, so
it went on once Settle returned and spawned a host in the test's removed
HOME ("Module not found host-....js", uv_cwd) or in the next test's,
while that one signed in. provSettling keeps Cached and the loop's
continue branch from starting one while Settle runs.
TestSettleStartsNoRefresh: red without the fix ("Settle started 3
refreshes"), green with it, also -race -count=20. In go test -v
./internal/cli the stray host lines went from 7 to 0.
Run: internal/cli, internal/plugin, internal/provider whole ok; gofmt -l
clean; go vet -tags nogui for darwin, linux, windows ok.
Full suite: go test -tags nogui -timeout 45m ./... at
|
||
|
|
6641e1b0ac |
provider: a plugin sign-in drops what a request holds at once (#2449)
TestPluginLoginInstallsItsCLIFirst went red on macOS CI (run
38798393584) with "not signed in after the install: []". cli's run()
sets catalog.Changed = agent.SyncCatalog, and a sync left going from an
earlier step holds the catalog (provider.Hold), plugins and their
sign-ins among it, for up to a second. The host's "auth" event dropped
that only through catalog.Touched, told in the background, so on a busy
runner provider.Logins right after the sign-in read the snapshot taken
before it.
plugin.OnChangeNow registers hooks run before changed() or listed()
returns, i.e. before the host's reply after the event is read; provider
registers dropHeld there. Changed() is filememo.Forget + dropHeld.
Reproduced by injecting a pause where SyncCatalog holds (patch kept
outside the tree): without the fix red 3/3 with the CI message; with it
ok -count=5. TestHeldGoesWithAPluginChange: red without the fix ("held
from before the change: built 1 times, want 2"), green with it, also
-race -count=20.
Run: -count=20 -run TestPluginLoginInstallsItsCLIFirst ./internal/cli
ok; internal/cli, internal/plugin, internal/provider whole ok; gofmt -l
clean; go vet -tags nogui for darwin, linux, windows on the three ok.
Full suite: go test -tags nogui -timeout 45m ./... at
|
||
|
|
db8b791797 |
plugin: tools-, page- and agent- packages take their short name without the prefix
@magpie-community/tools-calc served its tools as tools-calc_eval and its
page under "tools-calc" because ShortName only dropped middleware- and
opencode-. It now drops tools-, page- and agent- too, so the calc example
serves calc_eval/calc_convert/calc_date as its README and the docs say.
`magpie plugin options` / SetOptions find a plugin by its short name or by
its bare package name (plugin.Called), so "agent-aider" keeps working
beside "aider".
Run at
|
||
|
|
b6533893a7 |
plugins: Discover lists tools and page plugins, and the intro links to the plugin docs
Every kind of plugin magpie runs now has its place on the Plugins page, so
someone looking to extend magpie finds what exists and how to write one:
- Discover has "Tools for agents" (market kind "tools") and "Pages" (kind
"page") sections beside Subscriptions, Gateway middleware and Agents,
each card with its own chip (a new Tools chip, the Page chip). Before,
both kinds fell under Subscriptions as Providers.
- A GitHub repository tagged magpie-plugin whose package.json has
magpie.page.file is a Page, and that file must be committed, as a
provider's entry must (TaggedRepos).
- An installed plugin that only gives tools wears the Tools chip.
- The intro says what a plugin can be (provider, gateway middleware,
routing strategy, tools, an agent, a page) and its "Write a plugin" link
opens usemagpie.ai/docs/plugins in the window's language (zh and zh-TW
to zh/, ja to ja/), outside the window.
- The docs' Publishing section lists the "tools", "page" and "agent"
registry kinds and the community package names for each, in en, zh, ja.
Run at the reviewed head (on origin/main
|
||
|
|
4c07442d29 |
provider: a model no catalog prices is at the price its plugin lists, or $0 when the plugin says it is free; devin's mover needs 0.1.18 (太陽と向日葵 on Discord)
太陽と向日葵 on Discord: Usage no longer showed what calls through Devin cost. Devin's own models (SWE-2, SWE-1.7 Lightning) are in no catalog, and ListPrice read only catalogs. In the owner's ledger on origin/main, devin claude-opus-5-5 and deepseek-v4-1-flash rows are priced and the swe-1.7-lightning row is blank. Devin lists its own price for each paid model in GetCliModelConfigs, and devin 0.1.18 (plugins 43d93b0) now gives it as the model's cost. 0.1.18 also makes swe-2 free again: Devin's new -lightning variants under SWE-2 had taken that away on 0.1.17. After every catalog, ListPrice now takes the plugin's price (pluginListPrice, an input or output above 0, read with plugin.Cost, which now carries cache read and write). If there is none, a model the plugin marks free (plugin.Model.Free) costs $0 (pluginFree). A catalog's price is still kept over the plugin's, and a plugin model with neither stays unpriced. The devin mover's min is raised to 0.1.18 (npm view --prefer-online on registry.npmjs.org: 0.1.18). A row is added to providers-accounts.md. Run: TestPluginFreeModelCostsNothing (new) and TestPluginCatalogPriceAndImages, -p 1: ok. Broke it by hand: pluginListPrice off turns swe-1.7-lightning red; pluginFree off turns swe-2 red. gofmt -l clean. go vet -tags nogui ./... for darwin, linux and windows: ok. Real use: a sandbox HOME with only the owner's Devin key, plugin 0.1.18 and this build. - `magpie plugin list --json` on Devin's live answer: swe-2 free; swe-1.7-lightning 2.5/12.5 (cache 1); swe-2-high-lightning 1/5; claude-opus-5-5 4/20. - `magpie usage --csv`: the 10-03 swe-1.7-lightning row is $0.000819, where origin/main gave none. Not done: Cursor auto, Qoder's and WorkBuddy's own models have no USD price from their plugins (they list credit multipliers), so they stay unpriced unless marked free. Full suite: SUITE_LINE |
||
|
|
49639cd162 |
agents: a plugin signed in to, out of, or listing new models updates the agents' model files (#2373, 18565882223-beep)
After signing in to Trae CN (a plugin's subscription), Pi's models.json
kept the list it had before the sign-in, so Pi's picker had no trae-cn/*
model while settings.json named one. A plugin's sign-in change
(plugin.OnChange) only dropped what the gateway held; catalog.Changed
(SyncCatalog), which a provider saved runs, never ran for a plugin. Now
plugin.OnChange and a new plugin.OnListed (told when the host lists
providers/models other than the list kept, also across a restart) call
catalog.Touched, so every connected agent's own model list follows, Pi's
models.json among them, and a sign-out takes the models out again.
Not reproduced: the report's GUI pick leaving models.json's mtime
unchanged. GUI and CLI picks go through the same Agent.Pick, which writes
models.json in-process here. With this change the file is rewritten when
the plugin lists its models, not only on a pick. PiCode's providers.json
isn't wired by magpie at all; unchanged.
Tests:
- TestPluginSignInReachesPiModels (internal/agent): pick a model, sign
Trae CN in, models.json lists trae-cn/kimi-k3-max; sign out, gone.
Broken by hand (hold.go back to plugin.OnChange(Changed)): FAIL
"models.json hasn't Trae CN's models after its sign-in".
- TestNewListIsTold (internal/plugin): a new list is told once, the same
list or the one kept on disk is not. Broken by hand (listed() not
called): FAIL "the first list: told 0 times, want 1".
Run at origin/main
|
||
|
|
3f913b3de6 |
plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:
- strategies: {name: (pool, seats, options) => order}. Each is a routing
"<short name>/<name>", registered with routes.Register while the plugin is
on and loaded and removed when it goes off or reloads. Seats are
routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
or a result that isn't an order of the seats means the listed order. The
failure is counted and logged, rate-limited. A file's name is made into a
routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
error text, sessions or request ids). The rows come from a bounded queue
(1024) with one worker, off the request path; a full queue drops the row
and counts it, and a request never waits. 250ms each.
plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.
providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.
GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".
Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.
What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
plugins/middleware ok, internal/provider ok (210s), internal/cli ok
(203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
plugins/... run printed a bare FAIL line that `tail` cut off before its
cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
plugin-middleware): 1220 tests, 1204 pass, 16 fail.
- routing-manual (4): mine. A group's own "manual" was offered a second
time as a routing no plugin serves. Fixed in client.js withJS. The
coordinator is rerunning routing-manual, keys-fold, group-fold,
intent-entry and routing-js alone in both engines, so that rerun is
not recorded here.
- routing-model-rest: red alone too, and red on untouched 4df1ba0c6
(3/20). It is #2115; I commented there with the webkit cases.
- group-member-weight webkit de 420 is #2387.
- group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
waits a fixed 2s for the save post. Filed as #2388.
- routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
and routing-intent-entry (browser launch timeout 180s) are load
timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.
Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.
Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
"usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
should.
- Not tried: the GUI against that gateway, or a real vendor account.
|
||
|
|
64b0f3a201 |
plugins: a community plugin's own page in magpie's window, shut in a sandboxed frame (P4)
A plugin's package.json may declare magpie.page {title, file, icon} and
magpie.permissions.reads. While the plugin is on, its page gets a tab in a
"Plugins" group after the built-in pages, drawn in an iframe sandboxed to
allow-scripts only (an opaque origin: no cookie, no storage, no parent).
Its files come from /_magpie/plugin/<token>/ (HMAC of the spec with a
per-process secret) under a CSP with connect-src 'none' and
frame-ancestors 'self'; a path that leaves the page's folder, a symlink
out, or an off plugin's token is refused. The window's postMessage bridge
answers only that frame (event.source checked) with theme and language,
the plugin's own options.get/set (throttled), and the reads it declared;
any other read is refused in the window and again by the server, and no
read carries a secret. /api refuses Origin: null and frame/iframe
fetch-dest requests (noFramedAPI), so the frame never reaches the GUI's
API even with the cookie. A page that throws or never says hello shows
the kernel's broken-page state with Try again. The Plugins page shows the
page and what it reads before the plugin is turned on.
Docs: gui-shell.md, plugin-runtime.md (P4 section), site docs en/zh/ja
with an example plugin; i18n zh, zh-TW, ja, de; fixture in
internal/gui/testdata/page-plugin.
Run (worktree at base 4df1ba0c6, -p 2, one package at a time):
- go test -count=1 -timeout 45m: internal/gui ok, internal/plugin ok,
internal/pluginrt ok, plugins/... (budget groups middleware otel redact
rotation search) ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean.
- Playwright (chromium + webkit, 5 languages, narrow widths): plugin-page 4/4,
plugin-kernel 4/4, builtins 4/4, i18n-keys, gui-de, gui-ja, gui-zh-tw 3/3,
plugin-middleware 24/24, plugin-own-icon 22/22, plugin-options 22/22,
plugin-local 8/8, plugin-agent 22/22, click-scroll 22/22.
Broken by hand, each went red: CSP without connect-src; apiFramed always
false; the server's read check removed; the noFramedAPI wrap removed from
api.go (red through the real Handler); inside() letting every path
through; CORP same-origin re-added; in JS the client read check removed,
the ev.source check removed, and allow-same-origin added to the sandbox.
Without the Array.isArray guard on /api/plugin-pages, plugin-kernel,
builtins and plugin-middleware/own-icon/options went red (their mocks
answer a non-list) - that was found by the run, then fixed.
Real use: built magpie, `magpie web` on 127.0.0.1:3472 (gateway 3471) in a
sandbox HOME with the example plugin added. curl: the page file loads
with the CSP and no cookie, traversal and a bad token are 404, /api with
Origin: null or Sec-Fetch-Dest: iframe is 403 even with the cookie, an
undeclared read 403, a declared one 200. Chromium and WebKit at 1100 and
420: the page draws its declared read, the probe's fetch/absolute
fetch/top access/undeclared read are all refused, an <img> of /api is
refused, no page errors. Real use found that a
Cross-Origin-Resource-Policy: same-origin header blocked the frame's own
files (its origin is opaque); it is gone and a test guards it.
Not tried: the desktop (Wails) window. Market cards of plugins not yet
installed don't show a page's reads. The Playwright suite mirrors the
CSP in a mock route rather than the Go server (the Go tests and real use
cover the server).
|
||
|
|
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.
|
||
|
|
4ac4d9ba99 |
plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:
- Agent: a middleware on an agent's request in its own API and on its reply.
serveAgent runs each registered one. The JS gateway middleware is the one
there (middleware.Chain), registered by the new built-in plugin
`middleware`. Its place, API, limits and fail-open are unchanged. InUse is
middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
back. The new built-in plugin `redact` serves masking.Masker (in
internal/masking, since settings imports redact). InUse is masking.Wanted.
It fails closed: masking asked for with no masker serving, or a masker that
panics, is a 503 "nothing was sent" at every call site that masked before
(serve, count_tokens, embeddings and audio, transcriptions, images, video,
search stand-ins and their queries, the Codex backend).
With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.
Run (on origin/main
|
||
|
|
58651568b3 |
agent, sessions, provider: a state file that doesn't parse is kept aside, not written over as empty (#2263, ggbdpq)
applied.json, wsl.json and sessions-wsl.json were read as empty when they didn't parse, and the next save wrote that emptiness over them. What magpie had applied to each agent, the WSL distros and the WSL session listing were lost with no copy. stash.json already kept a bad file aside as .bad-<time>. Each of these now does the same through one helper, lastgood.KeepUnparsed, instead of a copy per file: - It does nothing when the file is missing or empty. - When the file doesn't unmarshal into the reader's own type (lastgood.Into[T]), it copies the file aside (KeepBad). - It stops the write when the copy can't be kept. This also fixes the issue's claim about stash.json. Stash judged a file with json.Valid, so `[]`, which a map reader takes as empty, was written over unkept. Its failed copy was only logged, and the write went ahead anyway. Both are fixed (TestUnreadStashArrayKeptAside), and gateway-hidden.json uses the same helper. Siblings found by going through every single-file JSON reader that takes a bad file as empty and then writes it whole: - stepfun-auth - login-returns - quota-history - balance-history - credits-daily - Claude Desktop tiers - plugin updates - usage's computer id - davsync's sync state Each now keeps a bad copy. Caches that are rebuilt from the vendor are left alone; docs/subsystems/providers-accounts.md lists them. Run: - gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui, GOOS=windows): clean. - go test -tags nogui -p 4 -timeout 40m ./... with the other three commits of this push: see the last one's body. Broken by hand: on the code before this, these fail: - the issue's applied_keep_test.go and wsl_keep_test.go - TestUnreadStashArrayKeptAside - TestUnreadStateKeptAside (10 subtests) - the gateway, usage, davsync and plugin _keep tests TestKeepUnparsed and TestKeepUnparsedFailsWhenItCantBeKept cover the helper. I dropped a test, "not written when it can't be kept", for stash. It passed on the old code too, because a read-only folder also stops the atomic write. Not tried: a real WSL distro. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
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. |
||
|
|
118f4f28bf |
plugin: a community plugin npm doesn't have installs from the plugins repo's dist branch, so a reviewed plugin no longer waits unmerged for an owner's npm 2FA (magpie-community/plugins#84)
npm's Trusted Publishing can't create a package, so a new plugin's first
version needs an owner's 2FA, and reviewed PRs sat unmerged for it. A
trust made after 2026-09-03 also allows stage publish only, which is why
npm refused zed 0.1.7 and zen-free 0.1.7.
The plugins repo now packs every merged version onto its `dist` branch
(scripts/dist.mjs, magpie-community/plugins f5308cd): tgz/<file> and an
index.json with each version's sha512, manifest and README, with no
credentials. magpie still asks npm first. Only when `bun add` fails for a
@magpie-community package at latest or an exact version, and not because
of the user's minimumReleaseAge (that hold is kept), does installDist
fetch the tarball. It refuses the tarball unless its sha512 is the index's,
keeps it in plugins/dist and runs `bun add ./dist/<file>`. A later npm
install replaces it, and pruneDist removes tarballs package.json no longer
names. npmAsk (market version, Update, the hourly check) takes dist's
latest when npm errors or is behind, and Readme falls back to dist's. The
branch is read through jsDelivr when the China mirror switch is on, else
raw.githubusercontent.com. installMu is now held for the whole install,
fallback included.
Run at this head (on origin/main
|
||
|
|
8bf98110b8 |
plugin: a folder plugin's path written on macOS or Linux is a path on Windows too, so a backup or a sync leaves it out (#2229, JasonBuildAI)
plugin.IsPath read a spec as a path when filepath.IsAbs said so on the host. On Windows "/Users/me/plugin" is not absolute, so a folder plugin added on a Mac was carried into a backup and a WebDAV sync as if it were an npm package, and the Windows machine restoring it asked bun to install "/Users/me/plugin". A spec starting with / or \ (a UNC path among them) now counts as a path on every system, as a drive-rooted one already did off Windows. Run: - TestIsPathWhicheverSystemWroteIt (new). On the Windows box at the old code it fails for "/Users/me/plugin", "/home/me/plugin/index.js" and `\Users\me\plugin`; on macOS for the two backslash forms. Passes on both with the change. - On the Windows box, the three reds the issue names, old code then new: TestPluginsCarried (provider), TestRestorePluginsAndSignIn (backup), TestSyncPluginsAndSignIn (davsync) FAIL then PASS. - go test -tags nogui ./... on macOS with this and the next four commits: every package ok. - gofmt -l, go vet ./... on darwin, linux (nogui) and windows, and the three builds: clean. - Windows internal/plugin as a whole: TestTaggedRepos, TestTaggedReposSlowRead, TestReadmeOfTaggedRepo, TestGitPluginUpdateOnlyWhenItsRepositoryMoved, TestMarketIconsAreBundled, TestEnsurePi and TestGitPlugin fail there with and without the change (Windows-only, CI compiles them only). TestLoadConcurrentWithSavesAndEdits failed once in the full package run with the change; alone it passed 6 of 6 at the old code and 6 of 6 with it. Noted on #1827, the open issue for Windows-only reds. |
||
|
|
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) |
||
|
|
4e9335c96c |
plugin: Windows on ARM downloads Bun's native windows-aarch64 build and runs plugins, not "Bun has no build for windows/arm64" (#2183, EdwinDigital)
bunTargetFor turned windows/arm64 away, so magpie-windows-arm64.exe listed a plugin as on while its host never started, and its providers never showed. Bun publishes bun-windows-aarch64.zip (1.4.2 and later), so windows/arm64 now maps to it, with no baseline suffix (arm64 has no baseline build). Its SHA-256 a7a16b87…0cfd is added to bunSums, taken from Bun 1.4.2's SHASUMS256.txt, so the download is still checked and can come through a mirror. The provider-plugins page says so. What was run (macOS arm64, sandbox HOME, private GOCACHE): - TestWindowsOnArmGetsNativeBun (new): with windows/arm64 stubbed, Bun() downloads bun-windows-aarch64.zip from an httptest release and runs it; the checksum is the official one. Old bun.go: FAIL "bunTarget = "", Bun has no build for windows/arm64". - TestBunTargetForMusl gains windows/arm64 and now checks every target has a checksum; TestBunDefaultSums and TestBunTarget list bun-windows-aarch64. Both FAIL on the old code. - go test ./internal/plugin/ ok; gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean; GOOS=windows GOARCH=arm64 go build ok. - Downloaded the real bun-v1.4.2/bun-windows-aarch64.zip: SHA-256 matches, it holds bun-windows-aarch64/bun.exe, a PE32+ Aarch64 binary. Not tried: a real Windows ARM64 machine (the Windows box is x64), so the plugin host starting on that bun is not verified. |
||
|
|
9bc9a6e5e1 |
tests: TestRefreshInvalidationCancelsStaleCall gives the second ask 10s, not 1s, so a loaded runner doesn't read it as a stale listing left running
Seen red during a full run at load average 200-360 ("stale listing was not
cancelled and followed by the new state", 1.73s). The test's fake first ask
waits on its context alone, so a listing that invalidation fails to cancel
never ends; a 1s bound only measured how fast the second ask and the commit
ran. 10s keeps that apart with room on both sides.
Run: a 1.5s sleep injected into the second ask fails the old 1s bound with
the same message and passes the 10s one; with provCancel() taken out of
forgetProviders the test still fails (Fatal at 10s, then the package times
out on Settle, as before). go test -race -count=20 -run the test, go test
-tags nogui ./internal/plugin (179s), gofmt -l, go vet darwin, GOOS=linux
-tags nogui and GOOS=windows on ./internal/plugin pass. Test-only change;
./... not run. TestRefreshDeadlineBoundsRealProviderCall in the same file
still bounds a 100ms deadline against a 1.5s plugin call with a 1s wait
(900ms/500ms of room); not changed here.
|
||
|
|
33da86c71a |
provider: removing a plugin sets its providers' model picks in providers.json aside, and adding it again puts them back (#2057, dawn1095)
A plugin's provider leaves a record in providers.json once the user picks its models: its id and nothing of its own (OnlyPicks). Removing the plugin left those records behind. Nothing listed them, `magpie provider rm` couldn't reach them, and a sync or backup asked for a sign-in to them on every run. RemovePlugin now finds the ids the plugin's providers are stored under (PluginID of each provider plugin.Listed gives for its spec), and moves the records with those ids that hold only picks into providers.json's new pluginLeft, under the plugin's package name. Left alone: - any record with an endpoint or a key (the user's own provider, whatever its id); - a built-in's ids (accountIDs) and "magpie"; - an id another installed plugin serves too; - everything, when the plugins' listing isn't known (no cache and no plugin-providers.json): unknown is not "none is the user's". provider.AddPlugin (CLI, GUI, backup restore) puts the set-aside records back, each one whose id has no record now; one the user has given to a provider since stays aside. plugin.Listed is new: the cached listing, or plugin-providers.json. Run: - plugin_left_test.go, four tests with user-owned records beside the plugin's (a user "zap" with an endpoint next to the plugin's zap-plugin, a hand-made "mine", a built-in's picks, another plugin's and a shared id). Each guarantee broken by hand turned its test red: no set-aside, no OnlyPicks check, no other-plugin exclusion, no unknown-listing guard, take-back over the user's record, no take-back. - go test ./... in a sandbox HOME; gofmt -l; go vet darwin, linux (-tags nogui), windows. Not done: records left by plugins removed before this change stay where they are; turning a plugin off (not removing it) sets nothing aside; `magpie provider rm` still can't name such a leftover. The move flow (installPlugin) still adds through plugin.Add, since its own migration owns those records. Not tried with a real plugin removal in the GUI. |
||
|
|
a0ebe0032d |
plugin: a listed plugin whose package is gone is installed again, and bun's installs run one at a time (#2002)
anganing (Windows 11, v0.1.1229): after an auto-update, every switched-on plugin said "no such plugin: …\node_modules\@magpie-community\opencode-grok-auth" at each start. For the github: plugins the path was the spec itself (node_modules\github:owner\repo), so package.json no longer listed them. Removing a plugin and adding it again was the only way out. - InstallMissing installs again each listed plugin (switched off or not) whose package isn't in plugins/, from its own spec. KeepUpdated runs it 30s after start and then hourly, before CheckUpdates. Nothing did this before: CheckUpdates skips a plugin with no installed version. - installMu serialises every bun command that changes plugins/: install (including the first package.json it writes), reinstall's bun update, and Remove's and add's bun remove. At start KeepUpdated (30s) and keepMovedCurrent (20s) each run bun add with no lock. On the Windows box, three concurrent bun add runs (Bun 1.4.3) in one folder kept only one writer's package.json change. A git plugin's dependency dropped that way leaves Name() unresolved, which is the reporter's github rows. The exact sequence that emptied the reporter's node_modules wasn't reproduced. Bun 1.4.2 -> 1.4.3, magpie v0.1.1205 -> v0.1.1227 with the same plugins, and a package.json reset all left the folders in place. So this repairs the state and closes the one race found. It isn't proven to be the trigger. Run: - go test ./internal/plugin ./internal/provider -count=1: ok. - The new tests -count=3 on macOS, and on the Windows box as a cross-built test binary: ok. - Broke each fix by hand (lock a no-op; InstallMissing returns early): TestBunCommandsOneAtATime fails with "another bun is running here", and TestMissingPluginsInstalledAgain gets 0, want 2. - Real use on the Windows box, sandbox HOME, port 3561, real Bun 1.4.3: deleted opencode-grok-auth and opencode-qoder-auth from node_modules and started serve built from this commit. The host logged the reporter's exact "no such plugin" for both. At +30s it logged "installed 1 missing plugins again" and both folders were back. After the restart, no plugin failed to load. - gofmt -l internal/: clean. go vet for darwin, linux -tags nogui and windows (plugin, provider, gateway), and GOOS=windows go build ./...: ok. |
||
|
|
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.
|
||
|
|
3857376a2f |
tests: the slow-read list's immediate re-ask is asked within its own retry window (#1889)
TestTaggedReposSlowRead 在负载下(load ~28)误报一次:晚到读取的轮询上限 10s 与 taggedRetry=1s 重叠,轮询加首次调用超过 retry 窗口后,被截断的列表 被(正确地)再问,测试把它当成 bug。按 LESSONS 注入 1.2s 延迟复现 ("asked again at once: 3"),随后修复并保持延迟下通过。 修法:把「不重问」断言放在它自己的 retry 窗口内——断言前将 taggedAt 移到 now,断言后(含 Fatal 分支)还原。窗口与轮询耗时不重叠,测试两边留余量 (code standards: a timing test leaves room on both sides)。「past taggedRetry」步骤仍用还原后的真实窗口,sleep 与断言语义不变。 验证:注入延迟下旧代码 FAIL(asked again at once: 3)、新代码 PASS; -count=3 通过;TestTaggedRepos 不受影响。 Changed on review: moving taggedAt to now made the step ask about a whole list (held ten minutes), so a cut-short list no longer held for taggedRetry passed the test. The step now marks the list cut short now, as TaggedRepos does, and the hold itself is checked right after the cut-short ask: held till between ask-start+taggedRetry and ask-end+taggedRetry, bounds from the clock with no slack to outgrow. Run: old test + 1.2s injected before the step: FAIL "asked again at once: 3"; new test + the same delay: ok. Hold broken by hand (-taggedTTL) and doubled (2*taggedRetry): both FAIL at the new bound. -count=5 TestTaggedRepos*: ok. Full internal/plugin (-tags nogui): ok, 649s under load. |
||
|
|
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. |
||
|
|
9e76fcdc68 |
plugin, cli, gui: a plugin's "password" question is typed unseen, as an API key is (#1982)
A sign-in method's prompts could only be "text" or "select", so a token a plugin asks for (the Qoder plugin's PAT sign-in, magpie-community/plugins#103) showed on screen as it was typed, in the app and in `magpie plugin login`. What changed: - internal/gui/assets/app.js renderPluginAsk: a prompt of type "password" gets a password field (masked), the same field an "api" method's key gets. A "text" prompt is unchanged. - internal/cli/plugins_cli.go askPrompt: on a terminal a "password" prompt is read with term.ReadPassword (no echo); piped in it is read as a line, as a script answers it, and an empty answer still goes to the plugin's validate, as a text one does. - internal/plugin/providers.go: the Prompt type lists "password". host.js passes the type through untouched, so nothing there changes. The TUI has no plugin sign-in. - Docs: docs/reference.md and site/public/docs (en, zh, ja) plugins.html say what "password" does and that it is magpie's own (OpenCode has text and select). The answer is only sent to /api/plugin-signin/prompt and the sign-in, as a text answer is; nothing logs or shows it. What was run: - TestAskPromptPasswordIsUnseen (internal/cli): with the password branch disabled by hand it fails with `password on a terminal = "typed-in-the-open", <nil>, hidden reads 0; want pt-secret read unseen`; restored it passes. - plugin-password-prompt.test.cjs: Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and 420 wide, 11/11 each. With app.js put back it fails with expected 'password', actual 'text'. plugin-signin and plugin-signed-out-account 16/16 in both engines; i18n-keys passes in both. - gofmt -l clean; go vet for darwin, GOOS=linux -tags nogui and GOOS=windows on internal/cli, internal/plugin, internal/gui; go test -tags nogui of those three packages in a sandbox HOME: ok. Not tried: a real Qoder PAT through the community plugin (its PR isn't merged), and the CLI on a real Windows console (term.ReadPassword is the same call `magpie plugin login` already uses for an API key). |
||
|
|
b790594074 |
plugin: Settle waits for the sign-in hook, so TestPluginModelsSayExpired no longer writes into its removed folder (#1935, Nxir; #1543)
The cause: a host's "signIn" event (a models hook saying an account's sign-in expired) ran provider's OnSignIn hook with a bare go f(...). That hook writes the account's lapse into logins.json (lastgood.Keep, then the file, then Changed) under .config/magpie. TestPluginModelsSayExpired returns as soon as the lapse reads back, and Settle, its cleanup, waited for refreshes and the change hooks (Told) but not this one, so the rest of its write could land while TempDir removed the folder: "unlinkat .config/magpie: directory not empty", seen under load on #1543 and on Nxir's CI run. The fix: the sign-in hook runs through the same counted tell() as the change hooks, so Told, and so Settle, waits for it. Settle then waits for refreshes and restarts once more, since a hook told before the providers were read reads them, which can start a host again. Reproduced by injecting a writer into the hook (300 files in .config/magpie, 1ms apart, after notePluginSaid): on the old code TestPluginModelsSayExpired -count=3 failed with the reported "directory not empty"; with the fix it passed 3 of 3. The injection was removed. New TestSettleWaitsForTheSignInHook (synctest, as its sibling for change hooks) goes red with the bare go f(...) put back. Run: go test -tags nogui ./internal/plugin/ ./internal/provider/ -count=1 in a sandbox HOME (both ok), TestSettle* -race -count=3, gofmt -l, GOOS=linux and windows go vet ./internal/plugin/. |
||
|
|
334bb182e9 |
plugin: Bun's release check asks GitHub's API with the GitHub token from Settings too (#1942, bingqilinweimaotai)
What changed: an audit of every request magpie makes to GitHub's API after the git-plugin fix. The library's skill checks, private-repo probes and RTK's release check already carried the token; the Plugins page's git-plugin check and topic search got it in the previous commit. The one left was Bun's newest-release check (bunLatest), asked of api.github.com/repos/oven-sh/bun/releases/latest anonymously through getURL. getURLFrom now has a request to GitHub's API's host carry the token (ghtoken.Authorize), and bunLatest asks githubAPI so tests can move it. Bun's zips (github.com, npmmirror) are other hosts and never get it. With a token set, that one request isn't sent to the MAGPIE_MIRRORS fallback (source.Do sends nothing with Authorization to a mirror), the same as the library's API requests. Left as they are: Copilot's api.github.com requests carry the user's Copilot sign-in, not this token; raw.githubusercontent.com and codeload aren't the rate-limited REST API; site/worker.js is the website's. What was run: - TestBunReleaseCheckCarriesGitHubToken (new): bunLatest is asked with "Bearer github-env", a download from another host with none. With the Authorize call removed it fails: "Bun's release was asked of GitHub's API with Authorization """. - go test -tags nogui -run 'Bun' ./internal/plugin: ok. - gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows on internal/plugin: clean. |
||
|
|
431707944e |
plugin, library: Check for updates asks GitHub with the GitHub token from Settings, and says when GitHub's rate limit is used up (#1942, bingqilinweimaotai)
What changed: a plugin installed from GitHub (github:owner/repo) is
checked by asking GitHub's API for its branch's commit (githubHead,
through fetchJSON). That request went without a token, so a token saved
in Settings → Network and sharing did nothing for it: the check stayed
at GitHub's 60 requests an hour for the whole address, which a shared
proxy exit uses up, and the row said only "<url>: 403 Forbidden".
- The token lookup, where a token may go and how a rate limit is told
move from internal/library into a new internal/ghtoken, shared by the
library and the plugin package (plugin can't import library).
The order is unchanged: Settings, then GITHUB_TOKEN, then GH_TOKEN.
- plugin's fetchJSON has a request to GitHub's API's host (githubAPI)
carry it, which covers the git plugins' check and the Plugins page's
topic search. Raw files, npm and every other host never get it, and
source.Do already sends nothing with Authorization to a mirror.
- An answer from GitHub's API that is a rate limit (429, or 403 with
X-RateLimit-Remaining 0, Retry-After or a rate-limit message) is a
ghtoken.Limited: the check's row has Why "limited" and Limited {until,
token} for the page, as the library's skill check already had. A 401
to a request with a token names which token was refused, never the
token.
What was run:
- TestGitPluginCheckCarriesGitHubToken (new, internal/plugin): asks with
no token / GH_TOKEN / GITHUB_TOKEN / Settings in that order of
precedence, a 403 rate limit with and without a token, a 429 with
Retry-After, a refused GH_TOKEN, and a raw-file host that must get no
Authorization. Broken by hand twice: with fetchJSON's Authorize removed
it fails "GH_TOKEN: GitHub's API was asked with Authorization "", want
"Bearer gh-env"" (and the other two sources); with the limit check
removed it fails with Why "registry", Limited nil, "403 Forbidden".
- go test -tags nogui -count=1 ./internal/library ./internal/plugin
(temp HOME, pinned caches): ok, the library's TestGitHubToken*,
TestGitHubRateLimitSaid among them.
- gofmt -l clean; go vet -tags nogui on darwin, GOOS=linux and
GOOS=windows for internal/plugin, library, ghtoken, gui: clean.
- Not tried against the real api.github.com (tests stay off the network).
|
||
|
|
e0a3b8c60a |
library, plugins: the RTK page and the Installed plugin list open without waiting on the package manager or the plugins' vendors (#1178)
The Library's RTK page took ~3.9s to open and the Plugins page's Installed list ~2.2s, every time. - Installed named each plugin's subscriptions from plugin.Providers, the whole providers RPC: each plugin in turn fetching its vendor's model list. The page uses only the names, which plugin.Cached keeps without starting the host (refreshed in the background when a sign-in or the plugins change). It now reads those: 2.2s to 13ms with seven plugins. A plugin added a moment ago has no names yet, so its row no longer claims it "signs in to nothing magpie can use" until the plugins have answered (plugin.Answered, the row's named). - ReadRTK waited up to 3s for GitHub and the package manager; winget show refreshes its sources and takes ~7.7s, so every open waited the full 3s and #1025's "waiting for winget" tag never came from it. GitHub stays on the first read; the package manager is asked in the background, its answer kept 6 hours as before. 3.9s to 1.6s. - ReadRTK and SetRTK detected the agents twice per call; once now. wizzy-yang's PR head 12342aa3, which conflicted with main: plugins.go keeps main's clash rows (plugin.Clashes) with the names from Cached, idName filled from Cached too; plugins.js keeps main's middleware/agent and clash branches ahead of the PR's named one; providers.go keeps main's Told and Settle beside the PR's Answered. Run: see the next commit. |
||
|
|
bde11c7780 |
plugin, cli tests: stay off the network, so a host start never waits 30s on the real models.dev (#1922)
What: internal/plugin's and internal/cli's TestMain now call testenv.Offline, as gateway's and provider's already do, and each package has TestStaysOffTheNetwork. TestPluginListSaysMiddleware runs on testenv.Bun via MAGPIE_BUN like its siblings, instead of downloading Bun 1.4.2 from GitHub on every run (the guard turned that up). Why: every plugin test's sandbox is a new home with no models.dev catalog, so startOn fetched the real https://models.dev/api.json, with a 30s cap, on each host start until one succeeded. When models.dev didn't answer the macOS runner, a test that starts two hosts (Add, then Restart or a list changed elsewhere) spent 30s + 30s; the second start reached its init call with the test's one-minute ctx already gone: "starting plugins: context deadline exceeded" at 60s, TestPluginsChangedElsewhere at 90s. Ubuntu's runner got models.dev's answer in time. What was run: - Injected the delay on the old code: a DialContext that holds every non-loopback dial. TestFallenBackListKeepsTheLastOne/throws=,=1,=own 60.1-60.4s, TestUnloadedPluginKeepsProviders 60.32s, TestPluginsChangedElsewhere 90.36s, each "starting plugins: context deadline exceeded" - CI's signature. With Offline on top of the same slow dial: all pass in 0.4-1.0s. - TestStaysOffTheNetwork fails on the old TestMain ("models.dev answered 200 OK"), passes with the change. - 8 parallel -race processes x -count=6 of the three tests on the old code: all passed (models.dev answering here), so the delay, not load, is the cause. - go test -tags nogui ./internal/plugin/... ./internal/cli/... pass; go vet (darwin, linux, windows), gofmt -l clean. Not tried: on a macOS CI runner itself (the push's run is the check). The product path is unchanged: a magpie whose models.dev fetch hangs still waits up to 30s on each host start until one succeeds. |
||
|
|
a64b3a8d46 |
plugin: a pi provider's message_start tells the prompt's usage pi's start named, so Claude Code's context meter isn't 0 until the turn ends (#1887)
What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.
Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
chunk, but KStart was emitted before reading it. KStart now carries the
prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
nothing to tell; a stream that counts on its first chunk now has its
prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
Command Code send KStart before any usage is known.
Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.
Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
partial.usage input 11, cache 3/2, output 0, text, done with output 7):
message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
("late": start with zero usage, then the shared message counted):
message_start 11/3/2/0. Red with message_start back on usageOf(), and
the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
the default 10m timed out under load average ~20). The disk filled
during the run (3.7G free, not this change's): every failure was
ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.
Reported-by: guoqchen1001
|
||
|
|
920d96af55 |
tests: provider, plugin, gateway, codexcat, gui and tui tests pass in any order and on any -count (#1146)
Squashed from wei's #1146, onto main. Each test now starts from state of its own instead of what an earlier test (or an earlier -count run) left: - plugin: changed() counts the OnChange hooks still running; Told waits for them, and Settle ends with Told and UseCached(nil), so a change one test made isn't told in the next and the next test's plugin list isn't read as changed. Only tests call Settle/Told; in production changed() only counts. New TestSettleWaitsForTheHooksItTold and TestSettleForgetsTheFoldersPlugins. - provider: isolate forgets Copilot's state, the plans' quota cards and balances; the warm-up, Cursor sign-in, hold and moved-plugin tests wait for what they started. - gateway: fresh() forgets refused seals, and TestRouting, TestSmartRouting and TestQuotaRestsUntilItsReset start from forgetRouting; codexSignedIn and TestForeignReasoningIsLeftOut start from fresh. - codexcat: XDG_CONFIG_HOME under the test's home. tui: costAt reset. gui: the fake Cursor account no longer outlives its test. cli: Settle. Left out as already on main: the cli_identity keepIdentities switch ( |
||
|
|
1d8134605a |
plugin: a plugin pinned to a version, or turned off, keeps both throu… (#1076)
* plugin: a mover installs the version its user pinned, not @latest
plugin.Add installs the spec it is given and appends @latest to a bare
package name, so installPlugin — the mover's installer, for
keepMovedCurrent, Move and HandOver — handing it a bare name quietly
replaced <pkg>@1.2.3 with <pkg>@latest in plugins.json. The pin was the
user's choice, and it was destroyed behind their back every time the
mover's min was raised.
installPlugin now hands Add the entry's own spec when the user has one.
A pin older than the move needs is left pinned and reported by the check
that was already there below it ("%s %s is installed; moving needs %s
or newer"), whose remedy is to unpin it; a pin that satisfies min still
returns early and is not reinstalled. A user with no entry for the
package keeps the bare name, which is a first install and there is no
pin to keep. A plugin the user turned off is still refused before any of
this, as it was.
TestInstallPluginKeepsTheUsersPin pins fake@0.1.5 with the move needing
0.2.0 and writes the version plugin.Version reads into the plugins folder
it is read from. It asks Add for fake@0.1.5 — against installPlugin as it
handed over the bare name it fails with "asked Add for [fake], want the
pinned fake@0.1.5" — and gets "needs 0.2.0 or newer" back rather than a
silent install of @latest. It also checks that a plugin the user turned
off is refused and not asked for at all. addPlugin is a var beside
pluginProviders and removePlugin so the test can read the spec handed
over without the Bun that Add runs.
Rebased on main as of
|
||
|
|
c162a98a11 |
plugin tests: TestHostJSCancellation and TestFlowAbortDuringSetupStaysHealthy stop node at the run's deadline, catch ready-wait and held-window leaks by name, and fail a case that never finishes (#1120)
* plugin tests: TestHostJSCancellation's ready-wait counts every listener on its fake stdin and stdout, so a cancelled bootstrap wait that leaves one there fails by name ready-wait counted stdout's drain listeners only. A listener that a cancelled wait left for any other event, on stdout or on stdin's readline, went through every cycle. A fetch that adds a stdout 'close' listener and removes it only once it starts (a request cancelled while it waits for init never starts) passed with nothing but a MaxListenersExceededWarning, which the Go test only logs. A stdin 'line' listener per fetch was caught at 30,000 cycles only by the 10s deadline, since every line walks every listener; at 1,000 ( |
||
|
|
f230fa23b0 |
plugin tests: TestPiPackage runs on a pi pinned by a bun.lock, not npm's latest that minute (#1879)
TestPiPackage installed pi the way ensurePi does, `bun add @earendil-works/pi-coding-agent` at npm's latest, so it ran on whatever pi's packages were that minute. pi-codemode 1.2.0 (2026-10-12 23:00:01Z) dropped MCP_TYPESCRIPT_PREAMBLE and mcpStructuredContentSchema, which pi-coding-agent 1.0.x and 1.1.0 import from it; their ^1.x range takes 1.2.0. pi-coding-agent 1.2.0 (no longer importing them) came out at 23:03:25Z. A full run that reached TestPiPackage in between got pi-coding-agent 1.1.0 + pi-codemode 1.2.0 and pi didn't load; the run alone came after. Nothing is shared between tests here (each has its own plugins folder, and bunCommand puts Bun's cache under the test's HOME), so "only in the full run" was the clock, not the suite. The test now writes testdata/pi-lock's package.json and bun.lock (pi 1.2.0, every package at its npm integrity) into the plugins folder and runs `bun install --frozen-lockfile`; Add then finds pi there. The "pi is installed with a pi package" half moves to TestEnsurePi, with bun stubbed: installed once for a pi package, not again with pi there, not for an OpenCode plugin. The BUN_INSTALL_CACHE_DIR the test set did nothing (bunCommand sets its own after it) and is gone. Users: magpie installs pi at latest (1.2.0 with 1.2.0 now), and bun keeps a plugins folder's lock when other plugins are added, so a folder installed before the 1.2.0 release keeps 1.1.0 with 1.1.0. Only a pi install that resolved in those ~3-8 minutes (CDN metadata cache) got the broken pair. No magpie change. Run: - with the lock swapped for pi-coding-agent 1.1.0 (codemode resolved to 1.2.0): TestPiPackage fails with the issue's exact "Export named 'MCP_TYPESCRIPT_PREAMBLE' not found"; with 1.1.0 + codemode 1.1.0 and with the 1.2.0 lock committed it passes - TestEnsurePi fails with ensurePi's "pi is there" check removed - go test ./internal/plugin/ -count=1 three times: ok (140s, 121s, 112s) - go test ./internal/plugin/ -run 'TestPiPackage|TestEnsurePi' -count=5: ok - go test -tags nogui ./internal/...: ok - gofmt -l; go vet darwin, linux -tags nogui, windows: clean |
||
|
|
23c6e865a7 |
plugin: a musl Linux (Alpine) runs plugins on Bun's musl build, kept apart from the glibc one (#1877)
emptyteeth found it: bunTarget picked Bun's build from GOOS/GOARCH alone, so Alpine got bun-linux-x64-baseline, a glibc build whose interpreter (/lib64/ld-linux-x86-64.so.2) Alpine lacks. exec then said "fork/exec …/bun/1.4.2/magpie-bun: no such file or directory", which reads as a missing file, and no plugin could be added or run. - bunTarget: a musl Linux gets bun-linux-x64-musl-baseline or bun-linux-aarch64-musl. The musl check moves out of internal/claudecode into internal/libc (libc.Musl, unchanged rule: Anthropic's installer's /lib/libc.musl-*.so.1), which claudecode, the plugin host and the CLI test that skipped on musl now share. - bunSums: the two musl builds' checksums, checked against Bun v1.4.2's own SHASUMS256.txt (downloaded from the GitHub release; they match the issue's numbers). - Cache: a musl Linux keeps its Buns and state.json under bun/musl, so a machine whose C library changed never runs the other build, nor takes its state, whose Bad may list versions only the glibc build failed (CheckBun on Alpine set aside every newer Bun). glibc, macOS and Windows stay in bun/<v>, so a Bun downloaded before is used as it is, with no new download. - A bun on disk that exec can't start with ENOENT says it is a build for another C library and names MAGPIE_BUN (cantStart), for the host's start and for bun add/bun update. The same for a $MAGPIE_BUN. - Bun's musl build needs libstdc++ and libgcc, which a bare Alpine lacks: the loader then prints "Error loading shared library libstdc++.so.6" above ~40 "Error relocating" lines, and bun add cut it off. bun add, bun update and a host that died starting now say which library is missing and `apk add libstdc++ libgcc` (missingLibs, whyDied). Decided: a Bun that can't be started at all is not counted as crashed. The fallback goes to the version before, which is the same build for this system and fails the same way, and setting the current one aside would mark a good version bad for good. The libc check happens before the download instead (the target), so Alpine never fetches the glibc build. Run: - docker alpine:3.20 (arm64, and amd64 under emulation), sandbox HOME in the container, linux nogui builds. origin/main's binary reproduces the report: "bun add …: fork/exec /sbx/.cache/magpie/bun/1.4.2/magpie-bun: no such file or directory". This one on bare Alpine downloads bun/musl/1.4.2 and says "this system lacks libstdc++.so.6 … apk add libstdc++ libgcc"; after apk add, `magpie plugin add @magpie-community/opencode-cursor-auth` adds it and `plugin list` starts the host and lists cursor (arm64 and amd64), with the old glibc bun/1.4.2 left beside it unused. With libstdc++ removed again, plugin list says the library; MAGPIE_BUN pointed at the glibc build gives the C library message. - New tests (bunmusl_test.go, libc_test.go), each broken by hand and seen red: no musl branch (TestBunTargetForMusl, TestMuslBunKeptApartFromGlibc), no bun/musl root (TestMuslBunKeptApartFromGlibc), cantStart returning the error as is (TestCantStartSaysCLibrary, TestHostOnUnstartableBunSaysCLibrary, which fails with the reporter's exact message), host.go without it, no musl sum (TestBunDefaultSums), no hint in bun add (TestMissingLibsNamesThem) or in the host's start (TestHostOnBunLackingLibsSaysWhich), muslAt always false (TestMuslAt). -race -count=20 on them: green. - gofmt -l; go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows; go build for darwin, linux nogui, windows; go test -tags nogui for internal/plugin, libc, claudecode, cli in a sandbox HOME, and go test -tags nogui ./... (all green). One earlier run of internal/plugin with the other three packages went red, and its output was lost to a tail; four reruns of it, alone and together, were green, and the new tests were green under -race -count=20, so which test it was isn't known. Not tried: a glibc Linux end to end after the change (the unit test covers that its Bun stays at bun/<v>); a musl Linux other than Alpine (the detection is unchanged and looks for Alpine's libc.musl-*.so.1). The old glibc bun/<v> on an Alpine machine stays on disk (~90 MB); it isn't removed, as a volume shared with a glibc container could be using it. |
||
|
|
49b6e87b41 |
plugin, cli: on Windows, a plugin added from a folder is found by its short name too (magpie plugin off/on/rm/options zz-tags) (#1827)
ShortName cut a plugin's name at its last "/". A plugin added from a
folder is named by its path, and on Windows that path has only
backslashes, so its short name was the whole path: `magpie plugin off
zz-tags` said there was no plugin "zz-tags", and so did on, rm, options
and plugin.SetOptions. It now cuts at the last "/" or "\". npm names
have no backslash, so they are unchanged.
TestPluginOnOffRmShortName was one of the 26 Windows failures listed in
#1827 (CaramelizedCUDA). TestSetOptionsShortName now also checks a
Windows path, so the case fails on every OS without the fix.
Run:
- without the fix, macOS: TestSetOptionsShortName fails, ShortName
("C:\\Users\\me\\plugins\\middleware-zz-tags") = the whole path, want
"zz-tags"; with it, passes.
- Windows 11 box (windows/amd64 test binaries, sandbox USERPROFILE and
APPDATA): at
|
||
|
|
3f5c3b0553 |
plugin: the host keeps reading a plugin's stderr after a line over 4 MiB, so the plugin host no longer hangs (Windows) or keeps the unread output in memory (Linux)
The host logged the plugin child's stderr with a bufio.Scanner capped at 4 MiB. On the first longer line Scan stopped with ErrTooLong, the goroutine returned, and nothing read the pipe again. host.js sends console.log and process.stdout.write to stderr, so one long line from any plugin was enough. Now the reader drains the pipe past an overlong line and logs what it can, so the output stops being dropped silently. Measured on Bun 1.4.2 (Windows and Linux, official binaries, sha256 checked): on Windows the plugin host stopped answering init when a plugin wrote one long line while loading; on Linux a script writing 200 MiB to stderr with no reader went from 18 MiB to 412 MiB RSS. Each of those reproduced at HEAD and is gone with this change; the Linux memory number comes from that Bun-only measurement, since magpie's own RSS did not differ at this scale. Run before this commit: go test -tags nogui ./internal/gui ./internal/plugin is ok on Linux (WSL2 Ubuntu 24.04, go1.26.8) both on HEAD and on this change. On Windows, go test -tags nogui ./... (49 packages): every failing test also fails at |
||
|
|
3a4df527f5 |
plugin, provider, gateway, upstream: a test whose check fails while its fake vendor holds a reply ends with a FAIL, not a package hung until -timeout (#1808)
TestNPMInfoDeadline's fake npm held slow-one's reply on <-release, closed only
on the happy path. A check firing first under load (on the issue's machine,
the quick ones missing at npmAll = 300ms) left the handler held, and
httptest.Server.Close, run in the test's cleanup, waited for it forever:
the whole internal/plugin package hung to -timeout and lost every result.
- TestNPMInfoDeadline: a t.Cleanup registered after fakeNPM (so it runs
before the fake's Close) lets the handler go once (sync.OnceFunc). Its
timing assumptions, all listed: the 2s wall-clock bound on Info is gone
(slow-one is held and npmEach is an hour, so Info coming back at all is
npmAll at work; a minute only turns a wait into a FAIL); npmAll is 5s,
the quick ones' time to answer on a loaded machine, not 300ms; the slow
one's kept answer is polled for 30s, not 3s.
- The same pattern in its siblings, each fake handler blocked on a channel
only the happy path closed, now let go by a cleanup/defer that runs
before the server's Close: TestRestartFinishesTheReply (plugin),
TestPastedAddressAndCallbackFinishOnce, TestPartnersFetchedLastIsHeld
(provider), TestBusy (before gw.Close too, whose request waits on it),
TestLaneReleasedOnFailure (gateway), TestReadOnceInFresh (upstream; its
100ms bound on Of goes the same way as the 2s one: the page is held, so
Of coming back is its not waiting, 10s being short of the read's 15s).
- Audited, already right: grok_accounts, quota_refresh_order,
quota_history_waiter, subscription_usage, sub2api_usage, qoder, routing,
github_test, session_route, request_encoding, key_limits, vertex (quit),
plugin_usage (r.Context).
Run, in a sandbox HOME with pinned caches:
- Old TestNPMInfoDeadline with its check forced (took > 0): "httptest.Server
blocked in Close", panic at -timeout 30s. With a 500ms delay injected into
the fake's answers (a loaded machine): FAIL at the quick-ones check, then
the same hang. New test: with the delay injected, PASS (5.55s); with the
check forced, FAIL in 5.5s and the package's other tests run; with
npmAll an hour (the deadline broken), "Info waited for the slow package"
and the package ends.
- Each sibling with t.Fatal injected while its handler is held: old code,
all five httptest siblings hang to -timeout 90s ("blocked in Close"),
upstream's stalls ~56s; new code, each ends at once with FAIL.
- go test -race -count=5 of every touched test: pass.
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: clean, before and after rebasing onto
|
||
|
|
0738154520 |
plugin, gui: an installed plugin's row and page show its own magpie.icon, not its first provider's (#1775)
peterroe's plugin signs in to several providers. Each provider gets its own picture from the auth hook, and package.json's magpie.icon is the picture for the plugin itself. Settings → Plugins → Installed only took a plugin picture from the market listing. A plugin that isn't listed (installed from a path, git or an unlisted npm package) had none, so its row and its page showed its first provider's picture. - plugin.InstalledIcon reads magpie.icon from the installed package.json. It goes through the same ownIcon check as a listing's icon (data: or https only). - pluginsState stores the picture through provider.RepoIcons, as listed plugins' pictures are, and returns it as `icon` on each plugin entry. - plugins.js: the installed row and the detail page use the listing's icon, then the plugin's own, then its first provider's, as before. - Docs (en, zh, ja): magpie.icon is the plugin's picture (Discover card and Installed row) and the fallback for providers without their own. A plugin of several providers gives each provider auth.icon. Run: - go test ./internal/plugin ./internal/gui: ok. TestPluginsStateGivesThePluginsOwnIcon covers a data: icon (kept), no icon and a plain-http icon (both ""). - internal/gui/tests/plugin-own-icon.test.cjs: Chromium and WebKit, en, zh, zh-TW, ja, de, at 980 and 420 wide. It fails on the old plugins.js (the row shows pa.png). - The plugins GUI tests: 34/34 in each engine. - gofmt; go vet darwin, windows, and linux -tags nogui. - Full go test ./...: the only red is gateway OTel timing under load ~79. That's #1794, commented there; alone it passes 3/3. Not tried with peterroe's real package; the fixture follows the layout the issue describes. |
||
|
|
48e59c5b89 |
plugin: the unofficial plugins on GitHub aren't cut short through a slow proxy, and a list cut short is asked again in 20s, not kept ten minutes (larchsis on X)
larchsis (Windows, no system proxy, magpie's own proxy on) saw no
unofficial plugins on the Plugins page, and saw them with the system
proxy on and magpie's set to automatic.
No request bypasses magpie's proxy. Every listing and install read
(market.json, npm info and search, GitHub's search, package.json and
README, Bun's download, plugin icons) goes through http.DefaultClient or
DefaultTransport, which netproxy.Install routes through settings.Proxy,
else the environment, else the system proxy (HKCU Internet Settings on
Windows). Checked with a counting CONNECT proxy in a sandbox magpie on
macOS and on the Windows box: every connection to api.github.com,
raw.githubusercontent.com and registry.npmjs.org went through it, and
lsof / Get-NetTCPConnection showed none going direct.
The cause is timing. askTagged gave the whole listing 8s, six package.json
reads at once, each bounded by that same 8s, and a repository whose read
hadn't finished was left out. The cut list was then kept ten minutes, and
on disk for a restart. Through a sandbox proxy that adds latency per
chunk: no delay 29 repos, 150ms 21, 300ms 6. A slow proxy loses most of
"Unofficial, on GitHub", and when it loses all of them the section is gone.
The two setups differ in latency and in what was cached, not in proxy
handling.
Now:
- Reads go on past the page's wait (taggedEach 20s each, 12 at once), on a
context detached from the request. They are kept by repository and push,
as before, so the next ask has them.
- A repository whose read didn't come in time is as the last list had it
(in memory, else on disk), with the search's current stars and
description.
- A list that left one out is asked again after 20s, not ten minutes. Its
copy on disk is dated so that a restarted magpie asks again too.
Run:
- TestTaggedReposSlowRead (new) holds word-guard's package.json past a
300ms wait. It fails on the old code (5 repos, word-guard missing). It
also fails with each part broken by hand: no fallback to the last list,
a partial list kept 10 minutes, reads cancelled at the wait, and the disk
copy not aged back.
- Sandbox magpie web (own HOME, own ports, proxy 127.0.0.1:3481 with
injected latency), no cache: at 300ms 11 repos at 8s, then all 29 25s
later (the old code kept 6 for ten minutes). At 1s none at first, all 29
25s later.
- go test ./... on
|
||
|
|
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
|
||
|
|
93e118a578 |
testenv: a test that runs plugins on a bun older than 1.4.2 is skipped, saying which bun and to install 1.4.2 or newer, not failed on Bun's own differences (#1600, justrun1983)
justrun1983 saw TestPluginModelListThroughAccountProxy fail on main with "fake-not the list: http://models.invalid:80/list" among the models. The plugin tests run the bun on PATH (testenv.Bun), and Bun 1.3 names the default port in a proxy's request line: GET http://models.invalid:80/list, which Go reads as r.URL.Host "models.invalid:80", so the test's proxy answered 400 and the fake plugin took the error text as a model. Bun 1.4 sends GET http://models.invalid/list. It wasn't the offline environment: the test already clears every *_PROXY variable and reaches nothing real. magpie itself never runs plugins on a Bun older than plugin.BunVersion (1.4.2, the one it downloads and the floor CheckBun keeps), and CI pins 1.4.2, so an older bun on a developer's PATH tests something no user runs. On Bun 1.3.0 internal/plugin's TestPluginSOCKSProxy ("vendor vendor.invalid:80"), TestPluginProxy (the proxy saw http://vendor.invalid:80/...) and TestPluginHTTP2TakesTheProxy (Bun 1.3's node:http2 answers status 0, and the host quits) failed the same way. testenv.Bun now runs `bun --version` once (it already ran it to warm the binary) and skips with a message naming the bun when it is older than testenv.MinBun. testenv can't import internal/plugin (whose own tests use it), so MinBun is a copy, and TestMinBunIsBunVersion fails when it and plugin.BunVersion differ; BunVersion's comment names it and test.yml's bun-version. Run (bun 1.3.0 from npm's @oven/bun-darwin-aarch64 first on PATH, temp HOME): - before: gateway TestPluginModelListThroughAccountProxy FAIL with the reporter's exact text; plugin TestPluginSOCKSProxy, TestPluginProxy, TestPluginHTTP2TakesTheProxy FAIL. - after: all skipped, packages ok. A probe of the request line a proxy receives: 1.3.0 sends http://models.invalid:80/list, 1.4.2 and 1.4.3 http://models.invalid/list. TestBunOlderThanMinSkips (fake bun printing 1.3.0, 1.4.1, 0.9.9, 1.4.2, 1.4.3-canary, 1.10.0, 2.0.0, nothing) goes red with the skip removed by hand. With bun 1.4.2: go test -tags nogui ./internal/testenv, ./internal/plugin, ./internal/gateway pass; gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui on testenv and plugin pass. Not run: the full ./... suite, nor the fake-bun test on Windows (it skips there: the fake is a shell script). |
||
|
|
6f1b432759 |
provider, gui: smart routing spends WorkBuddy credits that expire soonest first (cdredfox on X)
WorkBuddy's Credits window had no reset, so in a Smart group every WorkBuddy account ranked alike. workbuddy plugin 0.1.14 (plugins f0274d6) reads WorkBuddy's own package lists (billing/meter/get-user-resource-paid- packages and -free-packages, the calls WorkBuddy's client makes) and reports on the Credits window when the soonest-ending package that still has credits ends (runsOutAt) and how many credits it holds (runsOut). The daily Free Plan slice (CapacityType 4) and code 001 aren't counted: they renew daily. magpie carries runsOutAt from the plugin's usage window into QuotaWindow and the routing Limit. Allowance.Renewal, which only Smart ranks on, treats it as the window's reset when it is sooner than the real one. Pace, the tiers, For, Full and resting are unchanged. The mover's min is raised to 0.1.14 so moved users get the plugin. The usage card and account meter say "232.4 expire in 5h" in every language. Run: - plugin: bun test, 63 pass; 2 of the 3 new tests fail on 0.1.13's index.mjs. Verified live on a workbuddy-ai account in a sandbox HOME: Bonus Pack 232.4 left ending 10-12T16:39Z ranked before Pro (10-28). - TestWorkBuddyCreditsRunOutForRouting and TestSmartSpendsWorkBuddyCreditsRunningOutFirst: both fail with the Renewal change removed by hand. - GUI: credits-run-out.test.cjs in webkit and chromium, 5 languages, at 360/440/1000px, red on the old app.js; with i18n-keys, quota-*, panel-usage, reset-each-title, usage-fold: 117 pass. - go test ./... green (agent and gateway rerun with -timeout 30m after the default 10m ran out under load from other sessions; 378s and 492s). - gofmt -l clean; GOOS=linux and windows go vet of provider, plugin, gateway clean. Not tried: the CN workbuddy site (its token was stale, 401), so the CN package list is assumed to have the same shape. The built-in WorkBuddy (not moved users) doesn't get this. The account-line tooltip has no GUI test of its own. |