31da93ccdca03073513d2e1d73efdfd50bd14f6a
189
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f2aa7fe346 |
plugin: HasGateway looks at the plugins once a second, not on every request (#3725)
Every agent request asks plugin.HasGateway (gatewayHooks, and GatewayBegin again when on). It read plugins.json through lastgood and steady, cloned the list, and stat'ed and read every enabled plugin's package.json. With 12 plugins installed and none with hooks: Windows (Ryzen AI MAX+ 395, Defender on): 457µs, 51KB, 360 allocs macOS (M4 Pro): 251-286µs, 36KB, 260 allocs per call. It now keeps its answer for a second, keyed on plugins.json's path and filememo.Gen, as middleware.current does: magpie's own writes (plugin add/remove/on/off all go through save, which calls filememo.Forget) are seen at once, another program's within a second. Now 0.5µs/640B on Windows and 0.3-0.85µs/208B on macOS. Run at |
||
|
|
51202cd431 |
plugin: a check-in outcome magpie doesn't know names what the plugin said
A plugin check-in that answered an outcome not in the list, with a message, became failed with the plugin's message alone, so "the daily credits were refreshed" read as magpie's own failure reason. The reason now names the answer first: the plugin answered "yes": <message>. With no message it stays "the plugin answered no outcome" or the answer. Split out of skygunner's fix/usage-absent-used branch (#3650), which carried it beside the usage fix. Run: go test ./internal/provider -run TestPluginCheckinRunsAsTheBuiltinsDo ok. Broken by hand: host.js's old line makes it red (Msg was the message alone). Not tried: a real plugin answering an unknown outcome. Co-authored-by: skygunner <skygunner@users.noreply.github.com> |
||
|
|
9733ed1b4a |
usage: a plugin window that doesn't say used is no reading (#3650)
A plugin usage window that leaves out `used` was read as 0 in host.js
usageOf. The card then showed "100% left" (or NaN% once the GUI saw a
missing value), and allowanceOf ranked the account as the one with all
of its allowance left, so smart routing put spent accounts first.
Now a left-out used is null from the host, plugin.UsageWindow.Used is a
*float64, and quotaOfPlugin makes such a window Text and Aside: the card
shows its display (else "No allowance reported"), with no percentage and
no meter, and routing leaves it out. An account whose windows all tell no
share has no allowance and is not known to routing (routedAllowance), as
one never read: not preferred and not rested. A window that says used:0
is a reading at 0, as before.
Ported from skygunner's fix/usage-absent-used (6791aa99). Changed from
the branch:
- lastAllowances (the reading kept on disk) built an empty allowance for
such an account, which routing read as known with all of it left. Both
it and Allowances now go through routedAllowance.
- quotaText shows "No allowance reported" for a no-share window with no
display, rather than a blank.
- A host-level test (the bun host with the fake plugin) and the GUI test
widened to both engines, every language, 900 and 390px, used and left.
- The branch's check-in wording change is its own commit.
Note: an account whose windows are all aside or text was known with 0%
used before; it is now not known, so loginRoom won't pick it as the
next account with room.
Run at this tree (base
|
||
|
|
afc99490f2 |
plugin: a fetch's body goes to the host in one line made for it (#3472)
Each plugin request was copied several times before it reached the plugin: - pluginFetch read the body with io.ReadAll, which grows from 512 bytes, so a 1 MB body was some 3 MB read. It now reads into a buffer of the request's Content-Length. - Fetch marshalled a map holding the FetchRequest and the body as []byte, so encoding/json base64'd the body into its own buffer and then copied it into the line, and enqueueOwned appended the newline in another copy. fetchLine now marshals the request without the body (FetchRequest.Body is json:"-") and appends the base64 body and window into one slice sized for the whole line; enqueueLine sends it as is. The frame is byte for byte what it was: TestFetchBodyWireIsUnchanged compares it with the old json.Marshal of the map, field order included (request fields, body, window). BenchmarkFetchBodyProd B/op, before -> after: 1 MiB 1,516,234 -> 1,411,609 8 MiB 14.4 MB -> 11.2 MB 16 MiB 29.7 MB -> 22.4 MB Through the gateway with the previous commit (probe, 60 requests of ~938 KB, per request including the test's client and fake vendor): /v1/chat/completions 21.2 MB -> 17.3 MB (24.4 MB before both, -29%) /v1/messages 33.7 MB -> 29.3 MB (39.8 MB before both, -26%) Server.serve's own share on /v1/messages: 29.1 -> 19.0 MB (-35%). What is left on top is buildChat's json.Marshal of the outgoing body, which the upstream byte fixtures pin; not changed here. Run at this head (base origin/main |
||
|
|
fed0055da8 |
plugin: a plugin stuck on its vendor no longer holds up the plugins loaded or listed with it
shualaitianduai on Discord: a plugin whose sign-in kept failing (401)
held up the plugins behind it. host.js loaded the plugins one after
another and answered init only when all were in, so a plugin function
that never returned held every other plugin until init's two-minute
deadline failed the whole host. providers() listed the providers one
after another too, so one stuck models hook held the whole list past
refreshDeadline (30s), and every provider's list went stale.
Now loadPlugins loads every plugin side by side, each given
pluginLoadWait (20s) for its import and plugin function, and each
config hook as long; one still loading is told as not loaded ("the
plugin's load didn't finish in 20s") and init answers with the rest.
Hooks are kept in the list's order, as before. providers() lists every
provider side by side and gives each models hook pluginListWait (20s,
inside refreshDeadline): one that hasn't answered is listed as fallen
back with that as its listError, so magpie keeps the list it had, and
that answer isn't kept for requests (keepInfo). Documented in
docs/subsystems/provider-plugins.md.
Run at this head (base origin/main
|
||
|
|
a9242eb68b |
plugins: a package.json with bytes after its object is mended around each bun command (plugins#405)
klmno1993 (Windows 11, bun 1.4.4, magpie 0.1.1552): plugins/package.json
kept the old file's last 56 bytes after its closing brace once a shorter
one was written over it (244 bytes before and after; zcode-auth had just
left the list). From then on every bun add in plugins/ failed on
"failed to read/parse package.json for workspace ''", whatever the plugin
or source. magpie itself writes package.json only when it is missing, so
the in-place write is likely bun's remove on Windows; not reproduced here.
Now, under installMu, before and after each bun command (runBun and
install's bun add), a package.json that doesn't parse but starts with a
whole object is cut to that object and written through edit.WriteAtomic;
the file as it was is kept as package.json.broken. A file whose start
isn't an object, or one cut short, is left as it is. Users already stuck
are mended on their next install or update, with nothing to do.
Run:
- TestPackageJSONTailIsCut, with the reporter's bytes: red with the write
pointed elsewhere by hand, green with it.
- go test ./internal/plugin (104s, ok, at
|
||
|
|
091153bf71 |
idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.
Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.
Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (
|
||
|
|
2c7f0ac12c |
plugin: options saved from a hooks package's own page reach its hook
SetPageOptions saved without starting the host again for any package whose
page and panels looked like all it had. Window() only reads main/exports,
so a package with magpie.hooks and a page (magpie-community/plugins#117's
PowerContext) counted as page-only. The host hands each hook the options it
loaded with, so a Service URL or key saved from the page did nothing until
magpie restarted. A gateway hook now goes through SetOptions, as a
middleware and an agent already did.
Run at
|
||
|
|
a2ff7e6cab |
plugin: add takes a community plugin's name (WorkBuddy, think-tags, qoder-cn)
Atlas on Discord (#help, 10-25, Linux): `magpie plugin add WorkBuddy`
said "isn't an npm package name". Worse, a bare `workbuddy` passed the
npm-name check and installed npm's unscoped workbuddy@latest, not
@magpie-community/opencode-workbuddy-auth.
plugin.Add, which the CLI, the Plugins page's field (/api/plugins/add)
and the movers all go through, now resolves a bare name first
(internal/plugin/resolve.go). Case aside, a name one community listing
goes by is its package, at the version given: the package or its bare
name, the short name (workbuddy, think-tags), the shown name (WorkBuddy,
Command Code), a provider id it serves or the subscription it replaces,
and a retired subscription's id through its mover (qoder-cn; provider
sets plugin.SubscriptionPlugin = MovePackage). The CLI says which
package it picked. A name two listings go by, or none that isn't an npm
name, is refused with the community plugins listed. A name no listing
goes by is npm's own package (opencode-gemini-auth keeps working), but
only when the list was fetched within the six hours: when the fetch
fails, the copy kept or built in may not name a newer plugin, so the
name is refused with why, and npm:<name> installs npm's package as
written. market() now says whether its list is a fresh fetch (marketErr).
Scoped names, paths and git specs are unchanged. A backup's or a sync's
plugins go in by their own spec (plugin.AddExact via addPluginExact),
never resolved, so a restore isn't held by GitHub being unreachable.
Update, Upgrade and InstallMissing use add with stored specs, unchanged.
Tests (fake registry over httptest, fake bun; no network):
TestResolveCommunityNames, TestResolveRefusesWhatItCantName,
TestResolveListUnread, TestAddByCommunityName. TestUpdateAllUpdatesAPinnedPlugin
adds an unscoped third-party name, so it now serves a registry.
Broken by hand: Add without resolve -> TestAddByCommunityName red with
the reporter's own error ("WorkBuddy" isn't an npm package name) and
workbuddy -> workbuddy@latest. The unread-list rule turned off (valid
name goes to npm regardless) -> TestResolveListUnread red.
Real use, sandbox HOME, built binary, real npm and GitHub:
`plugin add WorkBuddy` -> installed @magpie-community/opencode-workbuddy-auth@latest,
listed workbuddy and workbuddy-ai; `think-tags` -> middleware-think-tags;
`opencode-gemini-auth` -> npm's, google-plugin listed; `qoder-cn` with
MAGPIE_PLUGIN_MARKET=off -> opencode-qoder-auth; "Work Buddy Pro" ->
refused with the 38 community plugins listed; `twinz` with the list off
or at a dead URL -> refused, saying why and npm:twinz.
Run at this head (rebased on origin/main
|
||
|
|
5b32b7ea80 |
plugins: a Bun Windows can't load (0xc0000139, before 10 1809 / Server 2019) says so and what to do (zgcwkj on Discord)
zgcwkj runs magpie-cli-windows-amd64.exe as a Windows service (nssm) and every plugin install failed with "bun add …: exit status 0xc0000139: (and from the community repo's dist branch: bun add ./dist/….tgz: exit status 0xc0000139: )". Why: 0xc0000139 is STATUS_ENTRYPOINT_NOT_FOUND, the loader refusing the exe before it runs. Reading the PE imports (debug/pe) of Bun's windows-x64(-baseline) zips: 1.3.14 and later, so magpie's floor 1.4.2 and the latest 1.4.4, import kernel32's CreatePseudoConsole, ClosePseudoConsole and ResizePseudoConsole, which Windows has from 10 1809 (build 17763) / Server 2019 on. 1.3.13 doesn't. Bun's docs say "Windows 10 version 1809 or later" (bun.com/docs/installation). So Windows Server 2016 and Windows 10 1507 to 1803 (LTSB 2015/2016) can't run any Bun magpie uses. 1.4.2's pinned SHA-256 matches the asset. What changes: - wontLoad (internal/plugin/bun.go) reads an exit of 0xc0000139 as "this Windows" and 0xc000001d or SIGILL as "this processor" (Bun's x64 build targets SSE4.2), as a *BunUnstartableError whose message says which, the versions Bun needs, and MAGPIE_BUN. - bun add, bun update, cantStart and whyDied (the host's start) wrap it. - An install no longer tries the dist branch after it: that bun add can't start either, and its error read as the dist branch's. - The GUI's fail() answers it with code bun_unstartable, bunWhy and said, an i18n.js key (bunSaid in api.go), which api() in app.js puts through t(): en, zh, zh-TW, ja, de, in the window and in magpie web. The sentences live in Go so app.js grows one line: with both in app.js, TestCoreScriptBudget was 128 bytes over app.js's budget and 487 over the core's, and no budget is raised here. TestBunSaidIsTranslated fails when a language lacks one. The CLI prints the English message. - No fallback to an older Bun: 1.3.13 is below BunVersion and Bun doesn't support that Windows, and the -baseline assets are now the same binary. - docs/subsystems/provider-plugins.md says all this. Run: - New tests: TestWontLoadSaysWindowsOrCPU (injected NTSTATUS exits, a real kill -ILL), TestInstallOnUnstartableBunSaysWhyAndSkipsDist (0 dist requests), TestHostOnUnstartableBunSaysWhy, TestFailSaysBun Unstartable, TestBunSaidIsTranslated, plugin-bun-unstartable.test.cjs (chromium and webkit, every language, window and web). - Real Windows (10.0.26200 box, a sandbox dir of its own): a windows/amd64 nogui magpie-cli.exe with a fake magpie-bun.exe that exits 0xc0000139, `plugin add @magpie-community/opencode-raccoon-auth` printed the new message, and no dist folder was made. - gofmt -l; go vet darwin, linux -tags nogui, windows; builds of all three. - Full suite (go test -tags nogui -timeout 45m ./..., through suite-lock, at |
||
|
|
3b5a2f612d |
dsh: Max reaches GLM-5.3 as max, asked adaptively with its level
01huadalang on Discord (10-24): DSH Desktop on magpie-anthropic, zcode
GLM-5.3 at Max; magpie's Routing log showed 77 of 78 requests at low,
one at high, never max.
What DSH sends, from the real app (DSH Desktop 0.2.1-rc.3's app.asar,
pi-ai 1.1.0 and dsh-llm-pi-ai, run read-only through node with
magpie's GLM-5.3 entry): at Max and at High alike, max_tokens 128000
and thinking enabled, budget_tokens 16384. pi-ai's clampReasoning turns
xhigh and max into high before thinkingBudgetForLevel, so no
thinkingBudgets setting can give Max a budget of its own. At Low it
sends 2048; with reasoning off, no thinking field.
What magpie did with it: 16384 is read as high (effortOfBudget) and
sent as output_config.effort high, so Max could never reach max. The
"low" rows were not reproduced: no request DSH builds at Max reads as
low here, and Z.ai refused none of the shapes (live, below), so no
refusal memory lowered it. A 2048 budget (a session or a subagent DSH
runs at Low; dsh-tool-subagent lets the model pick reasoning_effort)
reads as low, and that is the likeliest source. It is asked of the
reporter.
The fix, zero-config: Z.ai's GLM-5.2 and GLM-5.3 (the GLM half of
effortInOutputConfig) are written into dsh's magpie-anthropic route
with compat.forceAdaptiveThinking (gateway.AdaptiveWithEffort, beside
AdaptiveThinking). MiniMax-M3.1-Flash, the other half, is left on its
budget: adaptive wasn't tried on MiniMax (no key), so it is on #3496. pi-ai then sends thinking adaptive and
output_config.effort from magpie's thinkingLevelMap, max as max
(checked against the real asar: low/high/max each go as themselves).
The gateway already passes adaptive thinking with output_config.effort
through for these models (fitted to their levels, withOutputEffort;
TestGLMEffortInOutputConfig pins it), so the gateway only gains
AdaptiveWithEffort. No client name is keyed on, and a budget alone is
read as before. An adaptive-to-budget rewrite in withOutputEffort was
tried first and dropped: TestGLMEffortInOutputConfig pins adaptive
passing through, and Z.ai takes it.
Live, Z.ai GLM-5.3 with the zcode key (sandbox script, key never
printed): adaptive and enabled+effort both accepted; effort max
thought 1237-1427 chars against 426 at high, so max is a real tier.
Run, at this head rebased on origin/main
|
||
|
|
63c0c354af |
gui: Discover is quieter: one unofficial mark, one button style, a reason in your language
Kiko03O1 on X asked for a better-looking Plugins › Discover page
("ui 设计能不能好看点"). Five things on it said one thing twice or said
it raw:
- A GitHub card had an "Unofficial" chip. A GitHub card is only ever
drawn in the 非官方插件 · GitHub section, so the chip repeated the
section's head on every card. It is gone from the card; the plugin's
page keeps its full warning.
- Sign in on a card and on an Installed row is tinted like Install,
not filled. It stays filled only in the plugin's sheet, so each level
of action has one look.
- The GitHub line said Go's English in the middle of a zh page ("no
answer in 8s"). internal/plugin's GitHub read now wraps its timeout in
ErrNoAnswer; /api/plugins/github passes `why`: "slow" for that or any
timeout, "limited" for GitHub's rate limit (ghtoken.Limited), and the page says "GitHub 响应超时" (zh, zh-TW, ja, de); the raw
error is the line's hover. The line is smaller and muted, and Retry
takes the accent colour.
- The second filter row's All had a count. It always equalled
Installed + Not installed and the first row's picked count, so
"全部 · N" showed twice side by side. It has no count now.
- Found on the way, same page: the filter box's placeholder was cut off
in en at 1280/1100/980 and in de at every width but 420. It fits at
every width now; the filter bar wraps where it did.
Looked at and left alone: the 8px inset on the borderless Signed in,
and the monospace version numbers.
plugins.js nets -25 bytes (the Unofficial chip's code went), so the
core script budget is unchanged: TestCoreScriptBudget passes at the
pushed head with no raise.
What was run, at this change on origin/main
|
||
|
|
7d9165d842 |
gateway: tests for plugin-served Factory with Standard usage only, 99% caps and order routing (plugins#349)
TestPluginFactoryStandardOnlyCaps runs the fake plugin as factory (marked moved, two OAuth accounts A then B, order routing, each capped at 99% with SetAccountCap as `magpie provider account-cap factory <account> 99` does). The windows are those Factory's plugin 0.1.38 reports with standard_only on (limitWindows(l, true)): Standard's 5 hours and 7 days with no model list, Droid Core's and Extra usage aside. The fake plugin gains $FAKE_WINDOWS, a file of each account's windows read at each usage reading, so routing reads them through the host and provider.Allowances, not a stub. What it holds, today's behaviour, no code change: - A's 7 days at 99% (its 5 hours at 40%): A is not sent the request; B serves fake-1, fake-claude and glm-5.3 (a Droid Core model). The trace shows a@fake 99/99 left out with its reset. Core windows at 100% on an account below its Standard caps don't hold it. - Both capped (A's 5 hours 99%, B's week 100%): 429 rate_limit_error, "usage cap reached: every account that serves ... - Factory (a@fake) is at 99% of a usage window, past its 99% cap, until <time>; Factory (b@fake) ...", advice naming magpie provider account-cap, Retry-After at the sooner reset (A's 5 hours), nothing sent to the vendor, logged "every account at its usage cap". - A read again below its cap serves again; a kept reading still at 99% whose reset time has passed serves too. - A conversation on A moves to B when A is capped. Once A is back: auto affinity with no cache worth keeping goes back to A; with B's cache (5000 cached tokens) it stays on B; affinity session stays on B. A new conversation goes to A. Broken by hand, each red at the step it guards: capHeld returning nil (A served while capped), allowanceOf keeping aside windows (glm-5.3 went to B while A's Standard windows were below cap), CapHeld ignoring a passed reset (429 where A should serve). Run: go test -tags nogui ./internal/gateway -run TestPluginFactoryStandardOnlyCaps -count=1 -v, ok; go test -tags nogui ./internal/gateway ./internal/plugin ./internal/provider ./internal/cli -count=1 -timeout 45m at base |
||
|
|
3dc25a6168 |
tests: a plugin fake's vendor counts only its own test's requests (#3357)
Run 39913278700 at |
||
|
|
bac5be0677 |
plugin: one renewal of a sign-in at a time across magpie processes (plugins #331)
Cause: every magpie process that loads plugins runs a plugin host of its own (the gateway, a CLI quota or usage command, a host restarting while the old one finishes), and host.js's renew() kept a sign-in's renewal to one at a time only inside one host (the in-memory renewing map). Two hosts that found the same sign-in due each called the plugin's auth.refresh with the same refresh token. A vendor that spends a refresh token once (MiniMax, and about ten plugins' vendors: cline, codearts, qoder, trae, workbuddy, raccoon, nous, kiro, factory) turned the second away with invalid_grant, the plugin threw signIn "expired", renew() sent it on without looking at the store again, and host.go -> provider's notePluginLapse marked the account signed out, though the first host had already saved a good token. What changed, in internal/plugin/host.js only, for every plugin: - renew() takes a lock file of the account's beside the store, plugin-auth.json.renew-<sha256(key)[:16]>.lock, holding the holder's pid and start time, across the plugin's auth.refresh, and lets it go in finally. It is separate from plugin-auth.json.lock, which changeAuth holds only for a write and never across an await. A lock whose pid is gone (process.kill(pid, 0), EPERM counted alive) is taken over at once, one older than 60s by anyone; a live holder is waited for with an async backoff (10ms to 500ms), never blocking the host's loop, and never past 120s. A lock is removed only while it holds the bytes read. - Under the lock the sign-in is read again from the file (past readAuth's stat cache). Changed since the renewal began (another host renewed it, or it was signed out or in again), the renewal ends without calling the plugin; no longer due, likewise. - A refresh that throws while the stored sign-in changed meanwhile (a magpie from before this lock spent the token and saved the new one) is logged, not reported expired. Tests (internal/plugin/plugin_renew_race_test.go, fixture testdata/renewrace): a fake vendor on loopback whose refresh tokens are single-use. - TestRenewOnceAcrossHosts: two hosts in two processes (this test binary and a child running TestRenewOtherHost) on one sandbox store. The first host's exchange is held until the second host is renewing too, waited on as state. One exchange, neither host says expired, both requests go with the new token, the store has it. - TestRenewLockOfDeadHostAndRefusal: a lock naming a pid that has ended is taken over inside the request's wait and removed; a token the vendor never gave still says expired and leaves the account as it was; one refused after another magpie saved a new token says nothing and the next request goes with that token. Broken by hand, each red: - no lock (lockRenew returns at once): TestRenewOnceAcrossHosts red with exchanges [r1 r1], the other host said [expired], a request sent a-old - the issue's symptom; the dead-pid test red (lock left). - no re-read under the lock (now = was): exchanges [r1 r1]. - the catch's check removed: "a token another magpie renewed meanwhile said expired". - a dead pid counted alive: the dead-pid test red after its wait. (Removing only the re-read's "changed" branch stays green: the "no longer due" check under the lock catches the same case.) Run at c909ca5e4 (on origin/main |
||
|
|
5871f02dd6 |
plugins, provider, gui: a keyless plugin sign-in needs no key, and a single-identity plugin has one account (#2695, LoKi)
LoKi's patch (lokic7123-star), picked onto origin/main |
||
|
|
226551d0d8 |
gateway: MiniMax M3.1-Flash is sent its effort in output_config (shin4 on plugins#316)
An OpenAI client's reasoning effort (Responses' reasoning.effort, Chat's
reasoning_effort) for MiniMax Code's MiniMax-M3.1-Flash or -Preview, built
into an Anthropic body for the minimax plugin, went as a thinking budget
alone. Under the reporter's 8192 cap medium, high, xhigh and max were all
budget_tokens 7168, so the level was lost before the plugin saw it.
The two models join GLM-5.2/5.3 in effortInOutputConfig: buildAnthropic
sends output_config.effort next to the budget, and an Anthropic client's
budget gets its nearest level there too (withOutputEffort, passthrough).
MiniMax Code's catalog marks M3.1-Flash forced_on at low..max. The budget
stays as it was (the owner's plan on plugins#317); dropping thinking for
the managed-login route, as MiniMax Code 3.1.4 does, stays the plugin's
call. Nothing goes into prompt text. Claude, MiniMax-M3 and other vendors'
models keep the budget alone. MiniMax's public Anthropic API doesn't list
M3.1-Flash (platform.minimax.io text-anthropic-api), so the rule reaches
MiniMax Code's subscription and any relay serving those two models.
Tests (internal/gateway/minimax_effort_test.go, fake plugin $FAKE_MINIMAX):
- TestMiniMaxPluginGetsTheNativeEffort: the reporter's Responses request
and its Chat form, low..max, both models, on minimax-code and
minimax-code-global through the plugin host (bun), plus an Anthropic
client's budget 10000 -> medium; MiniMax-M3 keeps no output_config.
- TestNativeEffortLeavesOthersAlone: claude-sonnet-4-5, kimi-k3 and
MiniMax-M3 on an Anthropic relay get budget 7168 and no output_config.
Run at
|
||
|
|
9b0f48612b |
gateway: a plugin's model that searches by itself can be the web searcher
01huadalang (Discord #feedback, 10-20): Settings › Web search offered only Antigravity; Trae's search model couldn't be picked, "可能也有别的模型能搜索 但是识别不到". partSearcher and modelSearches answer false for every provider with an account behind it, so no plugin-served provider was ever offered, and a plugin had no way to say which of its models searches. A plugin now marks such a model with `searches: true` (in its config models or the list its models hook gives). host.js passes it on, plugin.Model carries it, and pluginCatalog makes it WebSearch "native". partSearcher offers a plugin provider with such a model, with those models only, at rank 4 (as Command Code's search models); remoteSearch asks it in plain words, the way it asks Command Code's. A client's own web_search sent to that model still goes to magpie's searcher (searchesModel is unchanged): the plugin's upstream takes no web_search tool. Behaviour change: a marked plugin model ranks ahead of Antigravity and Google (rank 5) when magpie picks the searcher itself. Run: - TestPluginSearchModelIsASearcher (new; a fake plugin's model marked searches answers a weather question with a URL): red on the old code (the picker offers [], want the plugin's fake-search alone), green now. - Broken by hand: host.js without the `searches` passthrough; the test goes red at the picker. - gofmt -l clean; go vet darwin, linux -tags nogui, windows on gateway, plugin, provider, catalog. - set -o pipefail; go test -timeout 45m ./... at this tree: 68 ok, no FAIL. Not tried: the Trae plugin itself. It declares nothing about search yet; marking Trae CN's search_agent there needs a Trae account to try it with, which this machine doesn't have. No GUI files changed. |
||
|
|
62a1df8010 |
provider: a plugin's daily check-in reaches every sign-in, also two that share a display name (plugins#254)
AutoClaw's plugin can hold several sign-ins under one default display name,
which AutoClaw doesn't let the user change. plugin_checkin.go keyed each
account's check-in on "<provider>|<AccountID>", the display name, so
checkinNow's per-key dedupe asked only the first sign-in of each name, by
the loop and by Check in now alike; the others stayed 今日未签 for good,
and Settings showed one row, and one Off switch, per name.
Each sign-in is now keyed on the key plugin-auth.json keeps it under
(pluginCheckinKey: "autoclaw|autoclaw", "autoclaw|autoclaw#x1y2z3").
Two sign-ins never share it; a refresh writes the same key, and signing
in to an account already signed in goes back to its key (host.js
settle). The display name is shown only. Cards, Settings rows,
CheckinOff and Check in now all read the same key, so app.js is
unchanged. An account without an AccountID already had this key.
Upgrade (adoptLegacyPluginCheckins, run when the plugin's accounts are
listed): an entry kept as "<provider>|<display name>" goes
- in plugin-checkin.json, to the first sign-in in use of that name (the
one the old key's check-in asked) and only to it, and the old entry
is dropped: it isn't asked again today, and its namesakes, never asked,
are;
- in settings.CheckinOff, to every sign-in of that name: the user turned
that name off and none of its sign-ins was checked in since, so the
upgrade switches none on (settings.EditCheckinOff edits that field
alone from what the file holds).
A plugin-checkin.json that can't be read or parsed is left as it is and
carried over once it reads; writes go through writePrivate
(temp-and-rename). Known gap: a sign-in made the same day after another
was signed out can take the freed key and that day's result.
The fake plugin's check-in now records a signed-in account as
name@fake/uid so two of one name tell apart in the presses.
Tests:
- TestPluginCheckinTellsSignInsOfOneNameApart: four sign-ins, A/u1, A/u2,
B/u3, B/u4 (the reporter's case). All four pressed once, none again
that day, four entries kept, four Settings rows, every card marked;
with A/u2 off, Check in now the next day presses the other three.
- TestPluginCheckinCarriesOverDisplayNameEntries: a plugin-checkin.json
with fakeco|A@fake and fakeco|B@fake claimed today plus another
plugin's entry, and CheckinOff ["workbuddy|123", "fakeco|B@fake"].
A's check-in goes to its first sign-in only, the old entries go, the
other plugin's stays, both B sign-ins are off and workbuddy|123 is
kept; the loop then presses only A's namesake, and a second look
presses nothing.
- TestPluginCheckinCarriesNothingOverAnUnreadableFile.
Broken by hand, each red:
1. key back on the display name: TellsApart pressed only A@fake/u1 and
B@fake/u3; CarriesOver kept the old entries.
2. adoption not called: CarriesOver ("A's check-in went to ... ok false").
3. record to every heir: CarriesOver ("carried to both") and Unreadable.
4. Off to the first heir only: CarriesOver (CheckinOff lacks one B).
5. old entry kept: CarriesOver and Unreadable.
6. parse error ignored: Unreadable.
Run at
|
||
|
|
0f044e9447 |
plugins: a GITHUB_TOKEN GitHub refuses is dropped for anonymous requests, not shown as an error (till on Discord)
till's Plugins page said "无法连接 GitHub: GitHub refused GITHUB_TOKEN (no GitHub token is set in Settings → Network and sharing)". ghtoken.Token falls back to the environment's GITHUB_TOKEN / GH_TOKEN, and a stale one there made every GitHub read fail, though GitHub serves the same reads without a token. ghtoken.Do now sends a GitHub API request with the token. When the token came from the environment and GitHub answers 401, it remembers that token as refused for the rest of the process (Token() skips it, so GH_TOKEN is still tried after a refused GITHUB_TOKEN, and Settings no longer shows it) and asks once more without Authorization, returning that answer. A token set in Settings is never dropped: its 401 is still Refused()'s error. An anonymous rate limit after the drop is said by LimitedBy as before. Every caller goes through it: plugin fetchJSONFrom (tagged-repo search, git plugin checks, githubHead) and getURLFrom (Bun), and library apiGet, skills fetch, skilltree fetchBlob and latestRTK via doGitHub. internal/davsync/github.go stays strict: its token is the one the user gave sync to write a private repo, outside ghtoken, and an anonymous retry can't write there, so it would only hide why sync failed. Tests (httptest only): ghtoken_test covers an env token refused then asked again without, not sent again (and GH_TOKEN tried next), a Settings token refused stays an error, an env token refused then an anonymous rate limit is reported, and another host untouched. plugin TestTaggedReposStaleEnvTokenDropped is till's case: TaggedRepos with GITHUB_TOKEN=stale-till lists 7 repos, no error. github_token_test and library TestGitHubRateLimitSaid now expect the env token dropped and the Settings token still refused. Broken by hand, each red: (a) no anonymous retry: every new env test, the plugin and library tests red, and TestTaggedReposStaleEnvTokenDropped shows till's exact error; (b) no memory of the refusal: NotSentAgain, the plugin and library tests red; (c) a Settings token also retried: SettingsTokenRefusedStaysAnError, the plugin and library tests red. Run on the commit before the rebase (base |
||
|
|
d2c434b5a6 |
gateway: ClinePass pins glm-5.3-flash through OpenRouter's provider.only (sdytman on Discord)
sdytman (#feedback, 10-20) found that Cline doesn't send every model through Vercel's AI Gateway: glm-5.3-flash goes through OpenRouter directly, which ignores providerOptions.gateway.only, so the Upstream tick ( |
||
|
|
a257319963 |
plugin: an install takes the versions no longer installed out of Bun's cache (#1988)
Bun keeps every package version it ever fetched in its install cache
(~/.cache/magpie/bun/install-cache) and never takes one out. Each
release of a moved subscription's plugin that keepMovedCurrent or the
hourly updates installed added one more: the owner's Mac had 131
versions of the community plugins there, 10M, and it only grows.
After a successful install (beside pruneDist), the cache's
name@version@@registry folders whose version isn't the one in
plugins/node_modules are removed, then the links left to nothing in
each package's folder of links. A package whose installed
package.json can't be read or parsed keeps its versions (unknown, not
"not installed"). @T@ tarball entries and .npm manifests are left as
they are. What is installed is a copy, so a version taken out is only
fetched again if it is asked for again.
Measured on a copy of the live install cache with the live
plugins/node_modules package.json files:
before: 10M, 131 entries under @magpie-community
after: 1.0M, 18 entries (9 packages, the installed version each)
Run:
- TestInstallPrunesBunsCache (Bun's real layout, through install with
the fake bun). With the pruneInstallCache() call commented out:
installcache_test.go:62: opencode-grok-auth@0.1.16@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
installcache_test.go:62: opencode-kiro-auth@0.1.5@@registry.npmjs.org@@@1 left in Bun's cache, not installed: <nil>
installcache_test.go:72: the link to the version taken out left: <nil>
--- FAIL: TestInstallPrunesBunsCache (1.51s)
With it: PASS. Also PASS on the Windows box (windows/amd64 binary).
- macOS, sandbox HOME: go test -count=1 -timeout 45m ./internal/plugin/
-> ok internal/plugin 2214.050s (load ~250)
- gofmt -l clean; go vet ./internal/plugin; GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean.
|
||
|
|
fb101b0d57 |
plugins: a GitHub list that couldn't be read says why with Try again, instead of the section vanishing (till on Discord)
till (Windows, v0.1.1293, Belarus network) saw no "Unofficial plugins ·
GitHub" section in Plugins › Discover; a magpie in Japan shows it. On
v0.1.1293 the section shows its loading skeleton and then disappears
whenever GitHub can't be read: plugin.TaggedRepos returned the last list
(or nothing) with no error when the topic search failed, and an empty
list with no error when the search answered but every package.json read
from raw.githubusercontent.com failed or timed out. /api/plugins/github
answered 200 {repos:[]}, and the page showed ghFailed only on an HTTP
error, never in a search, and never once a list had been had.
Now:
- TaggedRepos returns the error with what it has. A failed search keeps
the last list and says why (held a minute, like before); repositories
the search found but that couldn't be read come back as a
*TaggedMissing with their count and the last read error.
- /api/plugins/github sends error and missing beside repos; ?again asks
GitHub again at once when the last answer had an error.
- The page shows the reason and Try again: in place of the section when
nothing could be read (in Discover and in a search), and as a line over
the cards when some were read or an older list is kept. Try again keeps
the cards while it asks. zh, zh-TW, ja and de strings added.
No Windows-only cause was found in the code: the fetch goes through the
same netproxy on every OS (a PAC-only system proxy isn't read anywhere).
The likely cause is the network reaching api.github.com or
raw.githubusercontent.com, or the unauthenticated search limit; the page
now names which.
Run (worktree on
|
||
|
|
dd70c5e6ae |
provider: ClinePass's Upstream tick pins GLM models to Z.ai too (sdytman on Discord)
sdytman (#feedback, 10-19) asked for GLM to have what DeepSeek has: with
Upstream ticked, a cline-pass/glm-* request goes only to Z.ai. ClinePin
now reads a maker table (deepseek -> deepseek, glm -> zai) and appends
providerOptions.gateway.only = ["zai"] for a GLM model, at the body's end
as before so the cached prefix is unchanged. cline-free/ models are never
pinned, other makers are unchanged, and a client's own providerOptions is
kept as sent. The tick stays one control; its label and hint now name
DeepSeek and GLM in en, zh, zh-TW, ja and de.
The slug: Cline routes through Vercel AI Gateway. Vercel's provider table
lists Z.ai as slug "zai" (name "Z.AI", website z.ai), and
ai-gateway.vercel.sh/v1/models/zai/glm-*/endpoints gives provider "zai".
sdytman called the upstream "z.ai", Z.ai's site and shown name; the
routing slug Vercel takes is "zai". Not tried with a real request: there is no
Cline account here, and both gateways answer 401 without a key.
The Cline plugin got the same change in
@magpie-community/opencode-cline-auth 0.1.9 (plugins ff13aac). There is
no cline mover, so no min to raise.
Run at
|
||
|
|
f76201a84a |
plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里". Grok's plugin signs in through `grok login --device-auth`, and Grok Build (1.0.50, the webbrowser crate) opens the device page itself, through NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER; the macOS binary has no "BROWSER" string. magpie then opened the same URL from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a browser tab) or `magpie plugin login`. Reproduced in a sandbox HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not involved, with and without SSH_CONNECTION. Built-in grok is retired ( |
||
|
|
5774c790bd |
plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json
Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame)
went through json.Unmarshal into message. encoding/json scanned every
byte twice (validating, then decoding the string) and cost far more than
decoding the base64 itself. chunkFrame reads the one shape host.js's
chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line,
or one whose data holds a quote or a backslash, still goes through
json.Unmarshal. push checks the data is base64 of a frame's size either
way, as before.
Measured (64 KB frame, json vs chunkFrame, each followed by the base64
decode push does; -cpu 1, 6 runs, load average ~480, so absolute times
are inflated):
- json.Unmarshal + DecodeString: 7.3-14.0 ms/op, median ~8.7 ms
- chunkFrame + DecodeString: 0.11-2.3 ms/op, median ~0.33 ms
Test: TestChunkFrameReadsWithoutJSON. Frames json.Marshal'd with a \n,
\r\n or no line end must parse and equal what json.Unmarshal makes. It
also refuses 11 other shapes, among them:
- an escape in the data;
- a negative id, or 1e3;
- extra fields or trailing bytes;
- a 20-digit id;
- reordered keys.
Broken by hand (chunkFrame always false), it went red: "a chunk frame as
host.js writes it ... went through encoding/json".
Run (load ~420): go test ./internal/plugin -count=1 -run on the chunk
frame, host, flow, stream, chunk, credit and fetch tests: ok (54.0 s).
The whole package runs with the final checks.
|
||
|
|
ef75a9a2b5 |
plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.
Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)
Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".
Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
|
||
|
|
8f37ed57d2 |
plugin: plugin-auth.json is parsed once per version of the file, not on every request
Every request read and parsed plugin-auth.json in the host two or three
times: accountKey (when no account is named), fresh (is a renewal due),
and the plugin's getAuth from its loader's fetch. Reading and parsing a
20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine.
readAuth now keeps what it parsed while the file has the same mtime,
size and inode, as Go's filememo does. While the file's time is within
2 s of now it also keeps the bytes and compares them, so two same-size
writes inside one tick of a coarse clock (Linux) still read as two. A
file that doesn't parse is never kept, so the .bak recovery path is
unchanged. changeAuth still reads afresh under the lock. The kept
object is shared, so what a plugin is handed (getAuth for loader, usage
and check-in, the models hook's auth, pi.js's readAuth) is a copy of its
own (authCopy).
Measured (load average 360-460, so absolute times are inflated):
- readAuth on a settled 20 KB file, old and new interleaved in one bun
process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read
per call. New median 23 us (min 2.3), a stat, and 0 file reads.
- whole fetch (TestPerfScratch, not committed, {} body, 400 fetches):
host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise.
A control run without the big file read 875 us at the same load. Host
RSS 53 MB -> 42 MB.
Test: TestAuthReadOncePerVersion runs host.js's own auth section in node
with readFileSync counted. It checks:
- 100 reads of a settled file read it once;
- a rewrite is read;
- a same-size rewrite with the same mtime is read;
- authCopy's copies are the caller's own.
Broken by hand twice, red both times:
- readAuth made the old uncached read: "a settled file is read once for
100 reads, read 100 times".
- bytes of a just-written file not kept: "a same-size rewrite in one
tick is read".
Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with
TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s
(pinned pi install under load); in a full package run it hit its 4-minute
start deadline ("starting plugins: context deadline exceeded").
|
||
|
|
e3c09f4f36 |
plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.
infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.
Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.
Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).
Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
|
||
|
|
d783df46cb |
plugin: a plugin's page adds items to a provider's and an agent's row menu (P6)
package.json's magpie.actions: [{id, menu, title, titles}] puts items in
the row menus magpie draws, after its own: a provider row's (right-click)
and an agent row's (its handle, or right-click). Picking one opens the
plugin's page and posts it {event: "action", data: {id, provider|agent:
{id, name}}}, nothing else of the row; the bridge's magpie.onAction(fn)
gets it, and an action picked before fn was given waits for it.
- plugin.Window reads them (page.go): menu one of ActionMenus (provider,
agent; a session's menu is left out, its title is user content), id
^[a-z0-9][a-z0-9-]{0,39}$, an id given twice is the first's, 8 at most,
none for a plugin with no page.
- /api/plugin-pages carries them on the page; a missing title is the
page's, in each language (pluginpage.go).
- pluginpages.js: magpie.actions(menu, context) gives the row menu's
items; openRowMenu draws a plugin's name as written (literal), not
through t().
- The Plugins page says which menus a plugin adds to (actionsLine),
translated in zh, zh-TW, ja and de.
- Docs: plugin-runtime.md's P6 section and verification; the site's
plugin docs (en, zh, ja) gain "Items in magpie's menus".
- The core's budget (TestCoreScriptBudget) is not raised (#2710): with
P6 the core came to 1,447,648 bytes, 648 over. pluginpages.js's header
now says P5's and P6's part in one paragraph and points to
plugin-runtime.md, which says it in full, and plugins.js's panels and
actions lines share whereLine: 1,446,845, 155 under.
Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
built-ins-on commit since dropped for main's own
|
||
|
|
b9f790d37b |
plugins: panels in magpie's pages, a page that replaces a built-in one, titles in the window's language, and a look that matches
P5 of the plugin runtime (docs/subsystems/plugin-runtime.md):
- Panels (magpie.panels): a plugin draws a frame into a slot of a
built-in page (a provider's editor, Settings, Usage); magpie.context
says where it is, and the frame is as tall as what it draws.
- A page can replace a built-in one (magpie.page.replaces); show() opens
it in that page's place, and the sidebar row goes to it.
- page.titles and a panel's titles name it in the window's language
({"zh": …}); a malformed map is dropped, the title kept
(TestWindowTitles).
- main's #2501 already names wails:// in the policy of a page in the
desktop window (through ownWindow), which is why the usage page drew as
bare HTML from v0.1.1259. TestPluginPageLoadsItsFilesInTheWindow loads
a page through ownWindow in a real WKWebView, which Playwright on http
can't; the subsystem page says how.
- The bridge adds magpie's look for what a page leaves unstyled, every
rule in :where() so any rule of the page's wins, and the theme's
colours as --magpie-* variables.
One commit: the panels, the replacing pages and the titles share hunks
in page.go, pluginpage.go, pluginpages.js and the docs, and couldn't be
split cleanly.
Run:
- Full: this series (P5, the Plugins dot, the probe test, P6, and a
built-ins-on commit since dropped for main's own
|
||
|
|
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. |