dccfefdf722ea25f5cf2be1798d5686e43b89fbd
805
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ebf3f48f7f |
usage: a reported call takes first_text_ms and flow_ms, so a reasoning reply tells its speed and a burst is held (#2637)
POST /v1/magpie/usage/requests turned away first_text_ms and flow_ms as
"not a field a reported record takes", so a reported reasoning reply was
timed from its first reasoning token and a burst-at-the-end reply was
never held. The ingest now takes both, validated like ttft_ms (whole
milliseconds, 0..ingestMaxMillis, null = unset), and checks:
- first_text_ms <= ms, and first_text_ms >= ttft_ms when both are set
(the first text is content too);
- flow_ms <= ms*10/8+1, since the gateway's flow is the tenth-to-nine-
tenths span scaled by 10/8 and can exceed ms.
The fields reach usage.jsonl through the Record, so DecodeOf, Row.Decode
(ThinkPace, HeldShare) and the Reported totals read them as they do the
gateway's own rows. docs/reference.md and gateway-sessions.md say so.
Tests: TestUsageIngestTellsSpeed posts the reporter's literal repro
(grok-4.7, out 307, reasoning 129, ms 5035, ttft 4632, first_text 4700:
178 tokens over 335ms), a burst held by flow_ms, an even reply told, and
a ThinkPace hold, and checks the totals. TestUsageIngestTimesChecked
covers each bound, its edge, null and absent fields.
Broken by hand: old code fails both tests (field refused); dropping
FirstText tells repro-1 0; dropping Flow tells the burst 601/4035;
removing the ttft check accepts first_text 299 < ttft 300; bounding flow
by ms rejects the valid 1501.
Run at
|
||
|
|
333c167575 |
routing: a rule can set the reasoning its model is asked for (#2633)
dengtongcai asked for a routing rule that picks both the model and the reasoning it is asked for (a quick question goes to a cheap model at low). A rule now has an output field, useEffort (low|medium|high|xhigh|max). When the rule matches, its member is asked for that effort. A member's own fixed effort still wins. Otherwise the rule beats the model's suffix, the turn's pick and the agent's pick. The existing effort condition is unchanged. - The value is fitted to the model's levels (max -> high on a model that tops out at high). A model with no Efforts is sent what the agent asked, untouched. Unset changes nothing. Failover members are not affected. - The trace records it: Rule.UseEffort and the try's RuleEffort (the second Try construction in the candidate loop was missing it). - Saving a group rejects an unknown value or one on a pause (cleanRules). The CLI takes use-effort=; the TUI and CLI lists show " at <effort>". - GUI: a chip after the rule's model, picked from the app menu (pickFrom, no native select), set/changed from the rule's menu. A pause clears it. Strings in zh, zh-TW, ja, de. - A Gemini-protocol client is left unchanged, as with every effort magpie sets. - Docs: docs/subsystems/gateway-routing.md; site docs intent and start (en, zh, ja). What was run, at d4c03a2c5 (rebased on |
||
|
|
df3734b959 |
proc: the login shell's variables count only when exported, and Codex's proxy detail names the variable it read (#2627)
ReneXiong: Codex showed the "proxied" drift, "through the proxy at
http://127.0.0.1:7890, set in HTTP_PROXY", while Codex went direct. The
value was fish's universal http_proxy from an old Clash setup, never
exported (`set -S` says "unexported"), so no program fish starts has it.
shellEnv asks fish beside the login shell (zsh), and shellProbe printed
"$http_proxy" in the shell itself, which expands unexported variables too;
mergeShellEnv then filled zsh's empty value with fish's.
Fix at the shared reader: every shell is now asked to run
/bin/sh -c 'printf ... "$PATH" "$CODEX_HOME" ...', the form nushell already
used (still with its ^). A child sees only exported variables, so each
value is what an agent started from that shell gets. This covers every
reader of the probe: Codex's proxy (codexEnv), Claude Code's provider
switches (claudeShellEnv), and agentenv.Vars such as CODEX_HOME and
CLAUDE_CONFIG_DIR that magpie takes into its own environment; an
unexported zsh or bash variable no longer counts either, which matches what
an agent run from that terminal sees. Proxy variables are still merged from
fish when the login shell has none: a fish user who exports one runs Codex
with it from fish, so taking proxies from the login shell only (the
report's other suggestion) would miss that case.
codexProxyFor named HTTP_PROXY (or HTTPS_PROXY, ALL_PROXY) for a value in
the lowercase variable. It now names the one it read, in both the reqwest
and respect_system_proxy paths, and the detail's NO_PROXY advice matches a
lowercase name too (and not "the system's proxy settings").
Other proxy readers checked: the daemon's carried env, wslrun's proxyVars,
netproxy and the plugin host read magpie's own environment, not a shell;
the WSL probe scripts ask for no proxy variable.
Tests: TestLoginEnvUnexportedNotCounted, a login shell with the reporter's
literal values unexported beside an exported NO_PROXY; TestShellEnvRealFish
now writes the reporter's literal fish_variables lines and checks that
http_proxy, https_proxy and all_proxy read empty;
TestCodexProxyNamesItsVariable. Broken by hand, each went red: the old
in-shell printf (unexported values read back, in the fake shell and in real
fish 3.7.1), and env() naming keys[0].
Run: go test ./internal/proc and the codex proxy tests on darwin;
TestShellEnvRealFish, TestShellEnvFishLogin and
TestLoginEnvUnexportedNotCounted on real fish 3.7.1 in an alpine container
(linux/arm64), green with the fix and red without it; gofmt -l clean; go vet
-tags nogui ./... for darwin, linux and windows; the full go test -tags
nogui -timeout 45m ./... under pipefail, both fixes together on
origin/main
|
||
|
|
ed0335f75c |
gateway: an assistant turn cut off before it said anything is left out of what a Chat upstream is sent (#2599)
timonwong (#2599): after the user stops a reply while the model is still thinking, the agent keeps a turn with no text and no calls and sends it again on every later turn. Translated (buildChat) or relayed, it reached the Chat upstream as {"role":"assistant","content":""} (reasoning_content alone, on DeepSeek), and DeepSeek and Kimi turned every request of the conversation away: "Invalid assistant message: content or tool_calls must be set". One rule, withoutSilentAssistants (chat.go), runs on both Chat routes: buildChat before pairToolMessages (Claude Code, Codex and Gemini clients, and the plugins fed by buildChat), and silentAssistantsOut in passthrough next to developerAsSystem (a Chat client's own body). An assistant message with no content or only blank text parts, and no tool_calls or function_call, is left out; the user messages it stood between join into one (texts with a blank line, else their parts in order), so no two user messages stand in a row. A prefill (prefix, partial, a Resume), a legacy function_call, a refusal and an audio reply stay. A relayed body without such a turn goes byte for byte. TestChatThinkingOnlyAssistantKeptOutside- Exchange pinned the old pass-through; it now expects the joined message. Built on ggbdpq's patch (cb438ebb on their fork) and its fake upstream, written again because the review found it missed shapes the issue names: - after a tool result it kept the empty turn ("a strict template wants the reply behind its tool message"), so the interruption mid tool loop still sent content "" and still got the 400. tool then user is what any agent sends when the user writes after a tool result; it is now left out. - the relay dropped an assistant with a legacy function_call or a refusal and empty content, and a client's own prefix/partial prefill; kept blank text-part arrays (still refused); joined only string users; re-marshalled with HTML escaping. - its Resume check compared a joinSplitCalls turn index with len(r.Messages)-1. Verified (sandbox HOME, pinned caches, go1.26.8 darwin/arm64, base origin/main |
||
|
|
ec64543952 |
claude: a switch gives a Claude subscription's run the agent's instructions as its system prompt, in place of Claude Code's
Every request through a Claude subscription is answered by the real
Claude Code, which sends its own system prompt, with the agent's
instructions in the run's first user message. Settings › Replies › Short
Claude system prompt (claudeLeanPrompt, off by default) starts the run
with --system-prompt-file holding the agent's instructions instead
(without a client Claude Code's billing line, plus the tool-choice
line), and the first message holds the conversation alone. The file is
under the distro's mount in WSL. A request with client cache marks
(#1717) is never lean. The mode is part of the run's identity, so a run
started in one mode never takes the other's turns. The row says the
risk: requests look less like Claude Code's own.
Measured with a real Claude subscription, Sonnet 5.5, Claude Code
2.1.301, off then on:
- chat client, ~600-token prompt, 2 tools, 3 turns: 10,048 -> 6,580
input tokens (-35%)
- claude -p as the client, Read and Bash, 4 requests: 85,453/85,471 ->
81,948/81,977 (-4%)
A fixed ~0.9-1.2K tokens a request.
Run at this head (rebased on
|
||
|
|
72d6103e28 |
gateway: a Chat tool in MCP's or another API's shape goes upstream as a Chat function tool (#2622)
jinyue806 (#2622): ZCode sends its tools on /v1/chat/completions in MCP's shape, {"name","description","inputSchema"}, with no type and no function object. magpie relayed them as they came, and SenseNova turned every request with tools away ("field Tools[0].Type invalid, should be set"; a flat {"type":"function","name":…} got "function cannot be empty"). A missing type is invalid Chat Completions for every upstream, not SenseNova only, and the translated routes were broken too: parseChat read no name from such a tool, so Messages and Responses upstreams were offered a tool named "". shapeChatTools puts a tool with its name at the top (no type, or type "function" without a function object) into {"type":"function","function": {name, description, parameters, strict}}, parameters taken from parameters, inputSchema or input_schema; other fields stay beside it. It runs right after liftMessageTools at the same two choke points: handle, for every Chat body before routing (relay, schema fixers, redaction, plugins), and parseChat, for a body that never came through handle. A tool that has its function, a hosted tool (any other type) and one with no name are left alone, and a request with nothing to shape is relayed byte for byte. Verified: - TestChatToolInAnotherShapeIsShaped sends the reporter's curl body with each of the four tool shapes from the report through the Chat relay, Messages and Responses. With shapeChatTools made a no-op by hand all 12 subtests FAIL: relayed as {"name":"f","inputSchema":{…}} as it came, and translated as {"name":"",…}. TestShapeChatToolsLeavesChatShape (byte for byte on Chat-shaped/hosted/nameless tools; strict and cache_control kept) FAILs on the same break. Both pass restored. - gofmt -l: clean. go vet -tags nogui ./... for darwin, linux, windows: ok. - Full suite at |
||
|
|
a69cd07075 |
gateway: a Chat tool call kept with an empty id goes with one made from its place (#2611, RunMintOn)
RunMintOn's session held an assistant turn whose tool call had "id":""
and a tool result with "tool_call_id":"". magpie relayed it unchanged on
Chat->Chat, and WorkBuddy AI turned the whole request away (400, 11133).
Chat->Messages sent tool_use id "" and Chat->Responses gave the call a
random id while its result kept "".
- chatCallIDs (chat_call_ids.go) runs in attempt for every Chat request,
before the relay, the translation and a plugin's fetch alike (a moved
WorkBuddy AI goes through the plugin, so the edit must come first). An
empty, null or missing call id gets "call_" + a hash of the call's
message index, position, name and arguments: the same on every resend,
so the prompt-cache prefix holds. A result with an empty tool_call_id
takes the turn's unanswered calls in order. A body that already has its
ids comes back byte-identical.
- chatTidy gives a stream's first fragment of each (choice, index) call an
id when the upstream sent none, and drops an empty id on later ones;
chatWhole fills a whole reply's empty ids.
- docs/subsystems/gateway-routing.md says so.
Tests (chat_call_ids_test.go), fixtures from the issue's literal bytes,
against a fake that refuses as WorkBuddy AI does:
- TestEmptyCallIDRelayedWithOne, TestEmptyCallIDReachesPluginWithOne
(movedFake workbuddy-ai), TestEmptyCallIDTranslatedWithOne (messages,
responses), TestChatCallIDsLeavesWhatHasIDs, TestStreamedCallGivenAnID,
TestWholeReplyCallGivenAnID.
- Broken by hand, each watched red: edit removed (relay and plugin get
the 400; translations send an empty or unpaired id); a random id in
place of the placed one ("the made id changed between requests");
stream mend off (first fragments' ids ""); whole mend off ("id":"").
Run at this change on origin/main
|
||
|
|
9228bd443f |
library: skills are grouped by source when the skills CLI keeps its lock under $XDG_STATE_HOME (@_yukirock on X)
skills 1.7 writes its global lock to $XDG_STATE_HOME/skills/.skill-lock.json
when that variable is set, and only to ~/.agents/.skill-lock.json otherwise.
The Library read only the ~/.agents one, so with XDG_STATE_HOME set every
`npx skills add` skill had no repository and the "By source" view could not
group them. Both locks are now read, the XDG one winning per skill, since a
lock written before the variable was set still names older skills.
XDG_STATE_HOME joins agentenv.Vars, so the desktop app takes it from the
login shell like the other folder variables (TestFolderVarsAreListed).
Not handled: a project install's ./skills-lock.json.
Run (worktree at origin/main
|
||
|
|
1978eabe58 |
agent: Codex's background compaction is turned on from Settings › Long conversations (#2490, #2493)
Codex 0.163 can compact a long conversation in the background while a
turn goes on ([features.async_compaction]). A new row under Long
conversations turns it on, with the share of the window it starts at
(empty: Codex's own 65%). magpie writes it into each Codex config it
routes (codex_async.go):
- [features.async_compaction] enabled = true and
model_async_compact_threshold_percent. Codex reads the threshold only
in that table; one at the top level is ignored (tried).
- capabilities = { remote_compaction = "v2" } on [model_providers.magpie].
Codex starts a background compaction only on a provider with v2, which
it gives OpenAI and Azure alone. Tried with Codex 0.163 against a
sandbox gateway and a fake upstream reporting 70% use: without the
capability, no compaction in a whole turn; with it, compaction_trigger
requests ran beside the turn's steps and the next step's input held
the summary. The capability is written for a feature the user turned
on by hand too (#2493 asked whether magpie supports it: it didn't).
putProvider carries the table's capabilities over when a model switch
writes it again.
- What magpie wrote is in the stash (codex.async). A value the user set,
or changed since, is never written over and stays when the switch is
turned off; a bare async_compaction = true, an inline or a dotted
table is the user's as written. A config that doesn't parse is not
written to.
Not tried: Codex signed in with ChatGPT (openai_base_url to magpie on
the built-in provider, v2 by default), only the custom provider path.
Tests: TestCodexAsyncCompactionWritten, ...KeepsTheUsers and
...KeepsUsersCapability (internal/agent), each red with the matching
part removed by hand (no writing; no capability carry-over; no
ownership check on enabled). codex-async-compact.test.cjs: Chromium and
WebKit, en/zh/zh-TW/ja/de, red with the 1-100 check removed;
compact-at, i18n-keys, settings-general, settings-search pass.
TestSettingsSaveKeepsWhatItDoesNotSend holds the two new fields.
gofmt clean; go vet -tags nogui on darwin, linux, windows.
Full suite: go test -tags nogui -timeout 45m ./... (pipefail, suite-lock) at the four #2494/#2504/#2505/#2490 commits on origin/main
|
||
|
|
a2c4aab1ba |
gateway: DSH's session header and compaction mark are recorded, also through a remote magpie (#2505)
h4rk8s asked that the Requests list tell DSH's context compactions apart
and attribute usage per DSH session, also when the call goes through
Remote Magpie, from the headers DSH sends and never from the prompt.
- x-deepseek-harness-session-id joins sessionHeaders, after the others:
sessionOf / nativeSessionOf / conversationID take it, so usage, the
Routing page and affinity see DSH's session, and passOnCaller already
sends a native session header on to a remote magpie.
- x-deepseek-harness-compact set (any value but "", 0, false, no, off)
makes callKind "compact", which PurposeOf groups as Compaction. Only
display reads that kind; routing is unchanged.
- withCaller keeps the mark on the caller and passOnCaller sends it on to
a remote magpie, so the other magpie records the call as a compaction
too. Neither header reaches a vendor (the request to it is built fresh).
- docs/subsystems/gateway-sessions.md says so.
Run:
- TestDshMarksSessionAndCompaction: direct and through a remote magpie
(two gateways over httptest), marked and unmarked with a summarizing
system prompt. Red on the old gateway.go/codex_backend.go/
remote_magpie.go (session "", kind "", remote sent neither header),
green now; asserts the vendor saw no x-deepseek-harness-* header.
- TestRemoteMagpieKeepsTheSession still green.
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows.
Full suite: go test -tags nogui -timeout 45m ./... (pipefail, suite-lock) at the four #2494/#2504/#2505/#2490 commits on origin/main
|
||
|
|
7d7dba31ae |
provider: removing or turning off a moved subscription's plugin moves nothing back
The built-ins are being retired (the owner, 10-16: 陆续把内置Provider下线掉),
so the last way back to one is gone. MoveBack, moveBack and releasePlugin
are removed, with the Left flag they set.
- SetPluginOff only turns the plugin off. A moved subscription stays
moved, off with it.
- RemovePlugin records the moved ids as the new state "removed". The
record keeps its accounts, which plugin.Remove leaves in the plugin's
auth store. Nothing moves or installs it by itself: MoveRetiring
skips it and keepMovedCurrent reads only "plugin".
- HandOver turns a removed record whose plugin is installed and current
back into "plugin", record and all. So does Adopt (the editor's Move).
- MoveRetiring moves an old "back" record again, whatever Left said.
- Plugins page, rm/off confirms: "{names} stops working until the plugin
is installed again. Its accounts are kept." / "... while the plugin
is off." The status after removing no longer says it is back on the
built-in.
- Strings: five old strings dropped ("Moving back…" among them), three
new ones in zh, zh-TW, ja and de.
- `magpie plugins rm`/`off` say the same in their output.
- Docs: provider-plugins.md (the states table, the Move-back paragraph)
and AGENTS.md.
Tests:
- TestNoWayBack is new. It covers a "back" record moved again, the
plugin turned off (still moved, accounts kept), removed (removed, not
reinstalled by keepMovedCurrent or MoveRetiring), installed again
(HandOver), and removed again then Adopt.
- TestReleasePlugin and TestMoveBackKeepsLapse asserted the way back
and are deleted.
- TestMove, TestHandOver, TestMoveTidiesItsPlugin and
TestAdoptBeforeSigningIn no longer call MoveBack. TestKeepMovedCurrent
uses the removed state.
- plugin-release.test.cjs checks the new asks and that the status names
no built-in.
Run:
- Broken by hand:
- With HEAD's migrate.go, TestNoWayBack is red at "turning the plugin
off moved it back".
- With HandOver's removed branch disabled, it is red at "installed
again: map[], moved false".
- go test -tags nogui ./internal/provider -run
'TestMove|TestNoWayBack|TestHandOver|TestKeepMovedCurrent|TestAdopt|TestInstallPlugin|TestWorkBuddyCheckin|Plugin|Migrat':
ok.
- GUI (NODE_PATH playwright, --test-concurrency=1): plugin-release,
plugin-move and i18n-keys, chromium and webkit: 17/17.
- gofmt -l clean; GOOS=linux and windows go vet of provider, gui and cli.
- Full suite: go test -tags nogui ./... -count=1 -timeout 90m at this commit rebased on
|
||
|
|
f9ceac1628 |
provider: a move onto the plugin takes every account, and no model holds it back
The built-ins are retired (the owner, 10-16: 一定要下线完毕), so a move
can't be held back by something only the built-in could fix. Before, a
move failed when every account was lapsed, when one account's check
failed (the vendor unreachable through the plugin), when the vendor
refused every account, or when a model in use wasn't in the plugin's
list. Each of those left the user on a built-in that is going away.
Now Move installs the plugin and imports every account:
- one the vendor refuses goes along marked lapsed, as before;
- one already lapsed, or whose check fails otherwise, goes along untried
and unmarked, for the plugin's own reads to judge, and is logged;
- no model is checked against the plugin's list.
Only an install failure, the plugin not serving the id, or a sign-in the
plugin won't import fails the move, which puts everything back and is
tried again after moveRetry. The movers' served (Devin, Cursor) and
builtin (ZCode) hooks, modelsInUse, modelNames, lapsedAll and devinBase
had no other use and are gone, with the tests of the hooks. The page still
translates an older magpie's lapsed, unserved and account whys, which
migrations.json can hold.
Tests:
- TestMoveEveryAccountLapsed and TestMoveTriesEachAccount are new, and
TestMoveToPlugin's first case is now a refused account that moves.
importAuth is a seam: the fake mover's "r-noimport" sign-in fails part
way, so TestMoveToPlugin, TestMoveTidiesItsPlugin and TestMoveCutShort
still test putting back.
- TestMoveCutShort's cut-short record now carries the sent sign-in's
hash, as a real move writes it. Without it putBack took the built-in's
sign-in as renewed. The old test passed only because the check renewed
the token a second time.
- Broken by hand: with a failed check or a refusal returning an error
again, TestMoveToPlugin and TestMoveTriesEachAccount go red.
What was run:
- go test -tags nogui ./internal/provider -run
'Move|HandOver|Lapse|PutBack|Retir|Adopt|KeepMoved|ReleasePlugin|
ZCodeStartPlan|Devin|Cursor' passes.
- go vet passes and gofmt -l is clean.
- At ab7b28510 on
|
||
|
|
9fcf6a6e7f |
provider: every deprecated built-in moves onto its plugin, and there's no way back
The owner, 10-16: 陆续把内置Provider下线掉…一定要下线完毕. The plugins now do what the built-ins did (the parity batch up to |
||
|
|
2c72563dd1 |
usage: Requests splits and filters by gateway key, with "No gateway key" for the calls none made (#2521)
MauriceCarlo asked for two things on Usage → Requests. 1. The gateway-key filter should show even when one key has calls. The picker hides itself under two options, and with one key it had one, so calls made with that key couldn't be told from calls made with no key. A "No gateway key" choice (callerKey=none) now sits beside the keys whenever the period has calls with no key, or it is the current pick. A single key's picker therefore shows and separates the two. The hidden condition itself is left to #2499, which another session has. 2. The trend chart and the ranking can split by gateway key. LED_SPLITS gains "Gateway key". It's offered only while the period has a key's calls, and it falls back to Model otherwise. A click on a rank row picks that key, or none, and a second click lets go, as the other splits do. Server: - usage.Dimensions gains "callerKey". A row's key is its CallerKeyID, or NoCallerKey ("none") when it has none, and the filter takes "none" as calls without a key. - Filter.Without(d) is the one place that clears a dimension's own pick, so the by-split lists every value. RequestPage's fast and slow paths both use it now; they each had their own switch. - usageapi names the split's shares from the key labels: "No gateway key" for none, the ID if a key was deleted. - OwnPage keeps a held key's view to its own share in by and in the chart's split, so one key never learns another's name or numbers. The series was already only its own rows. - docs/reference.md documents callerKey=none and by.callerKey. "No gateway key" goes into the core i18n.js. The gateway keys page says "No gateway keys yet", and i18n-keys' "a plugin's words are its own" matches on substrings. Tests: - TestCallerKeySplitAndNone runs the fast and the slow path over {}, one key, none, and none+an agent, and checks by.callerKey. Broken by hand, it goes red: once with the none clause in the filter removed, and once with Without's callerKey case removed. - TestUsageOverGateway: on loopback the split names both keys. A held key's by.callerKey is only its own. With the OwnPage scrub skipped, it goes red (another key's name leaked). - usage-ledger-key-split is new, in both engines, all five languages, and 1400 and 760 px. It checks: - the picker's options with the none choice; - filtering on none; - the split's rows, and a click picking and letting go; - no sideways scroll; - that a period with no key's calls shows neither the picker nor the pill. 32/32 pass. With the none option removed by hand, 11 go red. Run on origin/main |
||
|
|
440f66701f |
gateway: a 429 for native compaction's one account says the compaction pinned it, not that every account is capped (#2517)
When a conversation was compacted natively, only the key or account that sealed the compaction can read it (#1099), so checkpointReaders keeps the candidates to that one. When that account was at its usage cap, the 429 and the call record said "every account that serves X is held at the usage cap", although the other accounts were never candidates. That sent lm0711 looking at routing modes, which can't change it. checkpointHeld tells this case apart: the plan held only the sealer's account(s), and others were left out for the checkpoint. The error then names the account and its window, says the compaction it sealed is what keeps the conversation there, that routing mode and stays don't change that, and to raise the cap / spend credits or start a new conversation. The record reads "native compaction's account at its usage cap" (or its credits / both variants). cappedError and cappedRecord are unchanged for every other 429; their text is split into heldReasons and heldAdvice so both share it. docs/subsystems/gateway-routing.md says so. Test: TestNativeCompactionWriterAtItsCap seals a checkpoint on one account, caps it, and checks the 429 body and the record. Broken by hand (checkpointHeld returning nil), it fails with the old "every account" text. Run on origin/main |
||
|
|
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
|
||
|
|
ea3dee96a8 |
gateway: a URL magpie didn't choose is downloaded from public addresses only, wherever the request came from
|
||
|
|
c5f15cae7c |
provider: Amazon Bedrock's Mantle endpoint (@marktoown on X)
"添加 AmazonBedrock 的时候,API 还是旧的 Bedrock-runtime 节点,不支持最新的
Bedrock-mantle 节点". The reporter wanted to add Amazon Bedrock at its
Mantle endpoint, but magpie only offered bedrock-runtime.
What it does:
- A new vendor preset, bedrock-mantle ("Amazon Bedrock (Mantle)"), takes
the same Bedrock API key as the runtime.
- It has 17 regions of its own (mantleRegions): the
bedrock-mantle.{region}.api.aws hosts that answered on 2026-10-16.
The runtime's eu-west-3 has no Mantle host.
- Chat completions and Responses go to /v1, and Messages to
/anthropic.
- Unlike the runtime, its models are listed from GET /v1/models.
NoList stays on the runtime preset only.
- Mantle serves each OpenAI-style model under one prefix.
- OpenAI's closed GPTs and xAI's Grok are under /openai/v1. Every
other model is under /v1. Asking at the wrong prefix gets "model `x`
isn't supported on this route".
- provider.MantleBase picks the prefix from the model id. The
gateway's forwardOnce and the provider test's tinyBody both use it.
- For a model whose maker the rule doesn't know, the gateway asks
again once at the other prefix when Mantle refuses it for its route
(internal/gateway/mantle.go).
- When the second prefix takes it, the gateway remembers that prefix
in unfit. When both refuse, the client gets the first refusal and
nothing is remembered.
- IsBedrockMantle is true for the preset and for any provider added at a
Mantle host. IsBedrock includes it, so the shared Bedrock rules apply
to Mantle too:
- Claude goes on Messages only.
- The key is sent as x-api-key alone, which is what Mantle's own
examples send.
- max_completion_tokens is used, and metadata is stripped.
- Beta renames and refusals apply.
- There is no Priority.
- GPTs go to Responses first.
- I checked every other IsBedrock caller. None is runtime-only except
the legacy /openai/v1 -> Responses migration in normalize, which is
harmless for Mantle.
- A provider added by its Mantle address gets the APIs it wasn't given
(mantleEndpoints, in normalize). A chat or Responses URL given at
/openai/v1 is moved to /v1, because /openai/v1/models is a 404 and the
list lives at /v1/models.
- GUI: the editor's Key header row is hidden for a Mantle Anthropic
address, as it already was for the runtime's.
- Docs: README (en, zh) preset lists, docs/reference.md,
providers-accounts.md (a new row) and gateway-routing.md (a new row,
plus a test command).
What was run, in the worktree at
|
||
|
|
e243937ca3 |
gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.
- The gateway marks those candidates `ultra` in fastPick.
- On Chat and Responses, a try sends service_tier "ultrafast".
- From Messages, a try carries withUltra to forwardTranslated, which
sets Request.Ultrafast for the ChatGPT backend.
- In every case, the #1784 check decides the account. One whose list
doesn't offer Ultrafast goes after a mate that does (tierMate). With
no mate left, it is sent priority.
- That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
"ultrafast" (Fast was false, Ultrafast unset). It now parses as
Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
CanUltra and UltraModels say whether one of Codex's accounts lists
Ultrafast on the model. UltraPicks follow a provider rename
(renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
flash button steps its modes. Ultrafast shows two overlapped bolts, in
the row and after the field's model. Tooltips and the status line are
in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.
Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
(acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
another agent unchanged, opencode/Chat and claude/Messages picks, a
Chat client's own ultrafast, and switching back to Fast or off.
- Red with ultra forced false (4 cases).
- Red without withUltra (claude went priority).
- Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
without the Ultrafast step.
Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto
|
||
|
|
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.
|
||
|
|
d9e87eb328 |
gateway: clients opt into Claude subscription cache marks and TTLs (#1717)
Problem: Messages clients need control of cache boundaries and TTLs when a Claude subscription answers. Ordinary clients must retain their run identity, prompt and environment. A routing group's API-key member keeps its marks and must not report the subscription bridge's drops. Change: Select client-owned marks only with X-Magpie-Cache-Marks: client. Map system and fresh-history boundaries and the request tail, default missing TTLs to 5m, validate slot and TTL order, and separate opted-in run identities. Retain prefix constraints across live and saved runs. Report unmappable marks only for the Claude subscription try. Bound its selection hold to two seconds and clear the report and hold for a non-Claude fallback. Check ordinary identity bytes without a version-specific hash golden. What was run: Sandbox HOME, nogui: go vet ./... on darwin; gateway vet with GOOS=linux and GOOS=windows; full gateway tests; focused cache and usage tests with -race. gofmt and git diff --check passed. The group probe failed before the fix with tools:1 on the API-key reply in both routing orders and both stream modes. Hand-broken candidate scoping, stale report clearing, keepalive holds and ordinary identity bytes each failed behavior tests. Live, Claude Code on a Claude subscription and an Anthropic API key, through a recording proxy: in a group whose API-key member answers, in either order and both stream modes, the reply has no dropped-mark header and upstream receives the tool mark; a Claude answer reports tools:1; a failed Claude try followed by an API-key answer leaves no report. With a delayed API-key reply, the group's first keepalive came 0.85 s after a direct request's. Without the header, the outgoing request equals one from a gateway built at the same base. No GUI or real Linux/Windows execution. |
||
|
|
a15e576564 |
agent: OpenPencil uses magpie's models (@JC_be_better on X)
OpenPencil (ZSeven-W/openpencil, the openpencil-desktop app) keeps the builtin agents its chat runs on in settings.json under Rust's dirs::config_dir()/openpencil (read from its settings_io.rs and settings_payload.rs). magpie adds one builtin_agents entry, id "magpie", kind openai-compat at the gateway's /v1 with the magpie-openpencil key, preset custom, the picked models as OpenPencil writes a list: the first as `model`, `models` only for two or more, at most 64. The user's other entries and settings stay, and so do the display_name and enabled they give magpie's entry; a sync with nothing to change doesn't write. A file magpie makes gets "version": 1 (OpenPencil sets a file without it aside as corrupt); a file with another version, or none, is left alone. Disconnect takes the entry out, and the file when nothing else is left. OpenPencil reads the file once at start and writes it all back when it quits, so a change is refused while openpencil-desktop runs (Windows can't be asked, so the notice says to quit it first). Notice translated in zh-CN, zh-TW, ja and de. README (en, zh-CN), docs/reference.md and docs/subsystems/agent-wiring.md list it. open-pencil/open-pencil, the other app of the name, keeps its providers in its webview's localStorage, so it gets no row. Run, under a scratchpad HOME with GOCACHE/GOMODCACHE pinned: - go test -p 2 -tags nogui -count=1 -timeout 45m ./...: ok, 66 packages ok, 18 with no test files - gofmt -l: clean; GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean - go test ./internal/agent -run '^TestOpenPencil': ok - node --test agent-notice-lang, i18n-keys, header-relang (Chromium and WebKit, every language, wide and narrow): 37/37 pass Broken by hand, each went red: the running check, the 64 cap, the version check, keeping the user's display_name, the no-op sync, and writing the version into a new file. Real use: OpenPencil v0.8.4 (latest release, arm64, sha256 checked against its SHA256SUMS) under a sandbox HOME, started on a settings.json magpie wrote with the user's own Anthropic entry beside it. It started and ran 15s with the file intact and no .corrupt copy. v0.8.4 has no `models` field, so it lists only the first magpie model; main lists them all. Not tried: a chat request through OpenPencil's UI; its exit save (it didn't quit on an AppleEvent and was stopped with TERM, so the write-back wasn't seen); Linux and Windows; a build of OpenPencil's main. |
||
|
|
7597c13237 |
gui: a curl example pasted into a provider's editor fills it in (@mark_li21 on X)
@mark_li21 asked: 能支持通过curl例子直接导入provider不? A curl example
from a vendor's docs, pasted into a custom provider's Base URL or API key,
now fills in the editor instead of being pasted as text.
curlOf (app.js) is one pure function. It reads the paste the way a shell
would: lines joined by \, cmd's ^ or PowerShell's backtick; curl.exe;
quotes and escapes. From that it takes:
- the API that the URL's endpoint names: /chat/completions is Chat,
/messages is Anthropic and /responses is Responses;
- the base URL before that endpoint, spelled by respellURL the way the
editor already wants it;
- the key from Authorization: Bearer, x-api-key or api-key;
- the model in the JSON body.
A key that is only a placeholder ($X, ${X}, %X%, <token>, YOUR_API_KEY)
is not taken. The key box is left empty and focused instead. A new
provider adds the model to its models. A saved provider's picks are left
alone, because adding to an empty list would narrow what it serves. A
preset's editor only takes the key.
A note in the editor says what was filled in. It also points out a
placeholder left in the URL, such as {WorkspaceId}, and a URL with no
known endpoint. Its four strings are translated into zh, zh-TW, ja and
de. Text that isn't curl pastes as before, including several keys at
once.
Found along the way: url.onpaste = fromCurl cancelled every plain paste
into the Base URL, because an on-handler that returns false cancels the
event. The handler is now wrapped. The test fails on the unwrapped one.
Fixtures, in internal/gui/tests/fixtures/curl, are the docs' own bytes:
- OpenAI chat (API reference) and Responses (quickstart);
- Anthropic Messages;
- DeepSeek, Zhipu, Moonshot and OpenRouter quick starts;
- Alibaba Bailian's Windows cmd example (^ and \"-escaped JSON);
- SAP AI Core's PowerShell one-liner (curl.exe, <Deployment_url>);
- Unsloth Studio's PowerShell example, with backtick continuations, as
its usage panel renders the template. This one is not copied from a
static doc page.
The doc row is "A pasted curl command" in
docs/subsystems/providers-accounts.md.
Run at
|
||
|
|
674b6ca288 |
gui: a provider's per-key proxy lines fold past eight keys (@NetRozee on X)
@NetRozee on X: a custom endpoint given a thousand keys froze magpie.
Cause. The editor's Advanced > Proxy drew a line for every key, each
with a Provider's proxy | Direct | Custom control. Each control, once in
the page, looked up its place among every .segs in the editor and slid
its thumb (segsPlace, slide): quadratic, with a layout read each. The
Accounts list above it already folded (keyFold); this list didn't.
Fix. proxyLines folds a provider's keys as keyFold does: past KEYS_FOLD,
the first KEYS_FIRST and those with a proxy of their own, then All N
keys; opened, a filter (keyMatches, as the Accounts list's) over
KEYS_PAGE lines and how many more, and Show fewer. Typing draws the
lines again under the filter, which stays in the page (#1055). A key not
drawn keeps its proxy: Save posts every key's own, drawn or not.
Subscription accounts' lines are unchanged. No new strings.
Measured (Playwright, the editor opened on a provider of N keys):
1000 keys 5000 keys
Chromium 1067ms -> 100ms 55.6s -> 93ms
WebKit 4809ms -> 68ms 203s -> 81ms
DOM 9388 -> 434 nodes 45388 -> 434 nodes
Tests: provider-many-keys-proxy.test.cjs (new, en and zh, Chromium and
WebKit): fails in all four on the old app.js (no All 300 keys). With
account-proxy, provider-many-keys, filter-ime, usage-keys-fold,
i18n-keys, click-scroll, provider-proxy, proxy-own-wording,
routing-proxy, plugin-proxy-page, signin-proxy and proxy-test: 221 of
221 pass in both engines.
Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on
|
||
|
|
af601541ef |
routing: a request opens to its request and response (Fate on Discord)
Fate asked on Discord to see what a single request on the Routing page sent
and got back, such as a Codex prediction. The bodies were captured already,
in the Gateway page's 40 recent calls and the opt-in request archive, but
nothing led there from a Routing request.
- gateway: a Call carries the Routing request it was (Call.Route = the
trace's Route.ID), set where serve, the Codex backend and a refused title
record it. Server.RouteCall finds it in the ring. A route id is not a
call id. A route names its archive copy (Route.Archive =
call.archiveName()), set only when the archive was on, so it reaches the
saved history too.
- gui: GET /api/gateway/call takes ?route= besides ?id=. It is the same
handler, the same no-store, the same key guard and the same 404 once the
ring has let the call go.
- Routing page: the story's head has "Request and response". It fetches
only when pressed, and shows the masked bodies through callBodyPanel (an
SSE reply reads as its events). A request the ring no longer has shows
the archive's copy through archivePanel when the route names one.
Otherwise it says the last 40 are kept until magpie quits and how to turn
the archive on. Nothing more is captured or kept than before.
- The head now wraps. At narrow widths its buttons ran past the story
("Back to live" was cut off at 440px).
- The two button words live in i18n.js: i18n-keys' "a plugin's words are
its own" found them inside core strings.
- docs/subsystems/gui-shell.md says how a route reaches its bodies.
Tests:
- TestRoutingRequestOpensItsBodies (new): each of two routes gets its own
bodies; route 0 and an unknown route get 404. Red without
`call.Route = tr.ID` ("route …: 404").
- TestArchiveWholeBodies now checks that the route names the archive. Red
without the t.Archive line (`route names archive ""`).
- routing-bodies.test.cjs (new), chromium and webkit at 440px, en, zh,
zh-TW, ja and de, 10/10. It covers the ring's copy read only when asked,
hiding, another request closing it, the archive's copy, the
how-to-keep note, nothing past the story and no left border.
- Red with the client asking ?id= and with the head's wrap removed.
- routing-request-metrics.test.cjs: with the head wrapped, its 480px
picker clicks in WebKit landed on the footer. Playwright's WebKit places
elements in the scrolled view hundreds of px lower than
getBoundingClientRect, which elementFromPoint agrees with. The test now
clicks where the page shows them. 5 runs of both engines, 20/20.
Run in a sandbox HOME at
|
||
|
|
ba17c4f90d |
provider: a Command Code plan key's card shows the month's credits as a meter (#2451)
tianxia3111 runs Command Code on the keyed preset with a plan's key. Its
card showed the 5-hour and weekly windows as meters, but the month's
credits only as dollars left ($5.27), with no share of the month. The
cause: billing/credits leaves out the planId, so the key's card couldn't
know the plan's monthly pool. The signed-in subscription's card gets
that pool from billing/subscriptions.
The key's card (planKeyWindows -> cmdKeyWindows) now asks
billing/subscriptions with the same key for the plan. It then makes the
month a "Credits" window beside the other two, through the same
cmdQuotaOf the subscription's card uses ("$4.78 / $10.00" on a Go plan).
- The plan id is kept per key for ten minutes, since
billing/subscriptions takes 15-20 s at times.
- The id read before still counts while the plan can't be read.
- A key whose plan was never read keeps its two windows alone.
- A pay-as-you-go key, with no windows, still gets no card.
planWindows' request and status handling move into planBody, so that
cmdKeyWindows can decode the reply itself; other vendors are unchanged.
Run:
- New TestCommandCodeKeyCardHasCredits uses the reporter's own
billing/credits reply. Its billing/subscriptions reply has the shape
the other Command Code tests use (individual-go-monthly), because the
reporter's plan id isn't known.
- With the new branch disabled by hand, the test went red: two windows,
no plan. With it, green.
- TestKeyQuotasKeepLast now answers billing/subscriptions with 503 and
still sees its two windows.
- gofmt; go vet -tags nogui for darwin, linux and windows.
- Not tried against Command Code's real API: there is no plan key here.
- Full suite (go test -timeout 45m ./..., at
|
||
|
|
97f264c7fb |
gateway: a 413 on the OpenAI routes says request_too_large, so pi compacts (@wilsonxuuuu on X)
@wilsonxuuuu's pi, on gpt-6.1 through magpie, stopped on
"magpie API error (413): {...,"type":"api_error"}" at 114k of a 1M
window and never auto-compacted. The vendor's 413 was a body byte cap.
pi's overflow table (pi-ai utils/overflow.ts) knows a byte cap only as
request_too_large, Anthropic's type, which magpie already gave on the
Anthropic route but not on chat/responses. writeErrorSaid now types
every 413 request_too_large (Gemini keeps its own status shape). The
status stays 413 and the byte-limit hint stays; it is not turned into
context_length_exceeded, so Codex and Claude Code read it as before
(Codex reads code, not type). pi compacts once and retries once
(_overflowRecoveryAttempted), so a body that is still too big after
compacting stops instead of looping.
Run:
- pi 1.1.0's own isContextOverflow on the reporter's body: api_error
false, request_too_large true.
- TestPayloadTooLargeSaysRequestTooLargeToPi (an nginx 413 page from a
chat upstream) and the new Chat/Responses rows of
TestBodyRejectionErrorShapes fail with the gateway.go change reverted
by hand, pass with it.
- go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME:
every package ok. gofmt clean; GOOS=linux and windows go vet of
internal/gateway clean.
Not tried: a real pi session hitting a real vendor 413.
|
||
|
|
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
|
||
|
|
bbf901570e |
provider: a WorkBuddy account's spent credits leave its free models counted out, as the plugin does (plugins#138)
hheei (magpie-community/plugins#138): an account at 560 / 560 credits
was ranked spent for deepseek-v4.1-flash too, which WorkBuddy serves at
x0.00 and which draws no credits. The plugin was fixed in 0.1.23
(notModels) and the mover min is 0.1.24 already; the built-in, which
users who haven't moved still run, had the same fault. wbQuota's
personal Credits window and the enterprise window now pass through
wbSpareFree, which scopes them (QuotaWindow.matches) to the models not
marked Free in the provider's last fetched list (catalog.Live). With no
list read, every model counts, as before. The 14018 "Credits exhausted"
rest already rests only the paid model (PaidBesideFree).
Run:
- TestWorkBuddyCreditsSpareFreeModels (new): with no live list the free
model reads 100%; with one, deepseek-v4.1-flash (either case) reads 0
while -sg (x0.03) and gpt-5.5 read 100. Broken by hand (wbSpareFree
returning early): red, "deepseek-v4.1-flash: 100% used, want 0".
- gofmt -l clean; go vet -tags nogui ./... for darwin, linux, windows: 0.
- Full suite: go test -timeout 45m ./... in a sandbox HOME, twice: every
package ok except internal/gui's TestPanelJoinsFullScreenSpaces ("the
panel shown doesn't take the keyboard"), which is red the same way
alone on a fresh origin/main
|
||
|
|
a80bc30092 |
agents: the Cursor editor's ~/.cursor is no Cursor CLI
The editor makes ~/.cursor on its own, so the folder alone says nothing
of cursor-agent (dirShared): cli-config.json or the command finds Cursor
CLI. The Library still writes the MCP servers and skills the editor reads
there when only the editor is here (SharedHere).
Run at this head before the rebase onto
|
||
|
|
486ea82378 |
agents: cursor-agent's row is Cursor CLI (@G_Z_Y on X)
@G_Z_Y looked for Cursor CLI on the Agents page and took the "Cursor" row
for the editor. The row is cursor-agent, so it is named Cursor CLI. What
it keeps in ~/.cursor is the Cursor editor's too (MCP servers, skills,
chats), so the Library and Sessions name it Cursor there (SharedName).
Run at this head before the rebase onto
|
||
|
|
7fefbc614e |
gateway: a relay's cap on one request's input fails over in a group (#2445)
B.ai answered a 380K request, under the model's 1M window, with 400
"Input token exceed the limit (request id: …)". No pattern in tooLongRe
matched it, and quotaWords wants "exceeded", so retryable() was false and
group/top's other three members were never asked (worksyang).
tooLongRe now also matches "input token(s) (count) exceed(s|ed) (the)
(max|maximum) limit". The refusal is taken as an overflow, so the chat
loop's existing #700 path asks the next member that may hold the request
(withRoom, failOverflow). Nobody rests, another account of the same model
isn't asked, and with no member left the agent is told it overflowed, to
compact. paceWords still keeps rate limits worded with input tokens out,
and a plain bad request still isn't asked of anyone else. System One's
decision groups (decide_group.go, which the report cites) are unchanged:
their requests are short decision text.
Test: TestRelayInputCapGoesToTheNextMember uses the reporter's message
verbatim. The JSON around it is not the reporter's; the issue shows only
the message. Docs: gateway-routing.md failure paragraph + verification.
Run:
- Broken by hand, the new test went red each time:
- pattern removed: group answered 400, member 2 never asked;
- paceWords check removed: two rate phrasings taken as overflow;
- retryable true for every 400: the plain bad request reached member 2.
- TestRelayInputCap, TestEveryVendorsOverflow, TestOverflow*,
TestContextOverflow*, TestOutOfBudget*: ok.
- gofmt -l: clean. go vet -tags nogui ./... on darwin, linux, windows: ok.
Full suite: go test -tags nogui -timeout 45m ./... at
|
||
|
|
7e4336e719 |
gateway: an event magpie appends to a cut stream begins after a blank line (#2446)
A passthrough stream cut mid-line got its error event written onto the half-written line, so the client read "event: error" as more of that line's data and never saw the error as an event. ggbdpq's patch (#2446) tracks whether the last write ended a line (passthrough's write, and holdWriter.atLine for cutLoop) and puts a blank line, two newlines when mid-line, before the appended event. The same join could happen to the other event passthrough appends: the finish_reason filled in for a Gemini OpenAI-compatible reply that ended done ( |
||
|
|
056cfe3323 |
provider: Codex's keychain read waits for the user, tells a refusal from no answer, and is kept while the item is unchanged (#2367)
Dony2050 (#2367) runs Codex with cli_auth_credentials_store = "auto" and no auth.json, so magpie reads "Codex Auth" through /usr/bin/security. Four faults: - One 10s timeout covered both of macOS's prompts and the user typing their password. A read they approved after 11-16s still failed. - A timeout and a refusal gave the same error. - A read was kept for 10s only. With "Allow" (once), background polls prompted again about every 30s. - Only a restart cleared the 10-minute failure cache. What changed: - Reading the secret is one ask per item at a time (askCodexKeychain). It runs in its own goroutine for up to 2 minutes (keychainAsk), outside codexKeychainMu, so no `security` run happens under a lock a reader needs. A reader waits at most 5s from when the ask started (keychainHold), then gets errKeychainWaiting. A request or a page never waits out the prompt. The ask's answer is kept when it lands, unless magpie kept a newer one after it started. - Each failure says what happened: - exit 44: no item. - exit 51 (errSecAuthFailed) or 128 (errSecUserCanceled): denied or cancelled (errKeychainRefused). Checked against SecBase.h. Exit 44 was also checked on a throwaway keychain in the scratchpad. - the 2 minutes ran out: no answer (errKeychainNoAnswer). - anything else: errKeychainUnread. None of them counts as signed out. - A successful read is kept while the item is unchanged. After 10s a reader runs Stat (find-generic-password without -w), which shows no prompt and returns only the item's mdat. The secret is read again only when the mdat changed. - Every write of the credential re-derives the cache: - codexStore.write keeps the date of what it wrote (keepCodexKeychain). - Switch, sign-out (deleteCodexLogin) and refresh forget a read (forgetCodexKeychain), so the next read checks the date. - forget keeps a refusal for its 10 minutes (#2408). - resetCodexKeychain clears everything. Only tests use it. - The saved accounts' line in the GUI has a "Try again" link beside Remove when a read was refused, got no answer or is waiting (Exclusion.Retry). It posts /api/provider/keychain-retry, and RetryCodexKeychain reads once past the refusal. - The reason now says "Always Allow" lets /usr/bin/security read the item, so macOS stops asking each time Codex changes it. - Two new strings in zh, zh-TW, ja and de. - docs/subsystems/providers-accounts.md: the "Codex's credential store" row describes the above. Tests: - TestCodexKeychainAskedSeldom (rewritten) covers: - an unchanged item over aged and forgotten rounds asks once; - a changed item asks again; - a gone item is not found without asking; - a refusal is kept through forget. - TestCodexKeychainPromptWaitedFor: a held prompt gives "waiting" to the first and to 8 concurrent readers without blocking. Once answered, the read succeeds with one ask. - TestCodexKeychainRetry: Retry and Why for refused, no answer and no item, and RetryCodexKeychain. - TestSecurityKeychainExits (codex_keychain_ask_unix_test.go): a fake `security` built with testenv.Program covers: - a 2s answer with keychainWait = 1s succeeds; - Stat parses the mdat; - exits 44, 51, 128 and 1 map as above; - a hang gives no answer. - signedout_test: Retry is set only for an unread item. - GUI keychain-retry.test.cjs runs in chromium and webkit, in en and zh: - order Try again, Remove; - the POST body; - the line leaves after a click; - no link without retry. Broken by hand (each restored after): - Find bounded by keychainWait again: TestSecurityKeychainExits red ("a read the user answered late ... no answer in time"). - exit 51 not classed as refused: TestSecurityKeychainExits red ("Find, denied"). - Readers wait on the ask (no hold): TestCodexKeychainPromptWaitedFor hangs; the package timed out. - forget clears every read: TestCodexKeychainAskedSeldom red (4 asks). - mdat match ignored: AskedSeldom red (7 asks). - Cache never re-checked: AskedSeldom red (the changed item wasn't seen). - RetryCodexKeychain also deleting the failure cache: still green, because a fresh read asks past a refusal. That loop was removed as redundant. Not tried: - A real macOS prompt, or an item Codex itself wrote. Every test uses a fake `security`; the real keychain and ~/.codex were not touched. - Put and Remove are still bounded at 10s. Run at this head, rebased on origin/main |
||
|
|
a6f908ba58 |
gateway: a Gemini OpenAI-compatible stream that lost its finish_reason is ended by usage, or cut
Linka (Discord #feedback): Gemini's OpenAI-compatible API sends a whole
function call (its thought signature, the usage) in one chunk and the
finish_reason in the next. When the upstream hung up between the two,
magpie relayed a stream that ended with neither, and Pi threw the
complete call away ("Stream ended without finish_reason") and asked the
whole 160k turn again. On a Chat upstream only a failed read was a cut,
so a clean EOF there went on as a stream with no end.
That API counts the usage only on the generation's last chunk(s): the
Vertex fixture (testdata/vertex_openai_thoughts.sse) has it only beside
finish_reason, Linka's frames have it on the call chunk and the finish
chunk, and Google's forum and third-party docs say the same; no Google
doc states it. So for a Chat upstream that is Gemini's (geminiCompat,
saysItsEnd) and ended without a finish_reason:
- its last chunk carried usage: the generation was done and only the
finish_reason was lost. It is filled in (chatTail), "tool_calls" after
a call and "stop" otherwise: relayed, as one chunk before [DONE]
(written only if [DONE] hadn't gone); translated, as the reply's normal
end (tool_use for Claude Code), streamed and unstreamed. Recorded ok.
- no usage at its end: the reply was cut, and the client gets "the reply
ended before it was complete" (errEndedShort), as a Gemini stream's
finishReason is told (#1643, #1644): the relay's error chunk, the
translated stream's error, an unstreamed 502.
A failed read keeps its own "connection lost mid-reply". Other vendors'
Chat streams are unchanged.
Tests (gemini_compat_cut_test.go, Linka's frames): relayed, the call
with usage ends with finish_reason tool_calls then [DONE], text with
usage with stop, the call without usage with the error and no
finish_reason; a whole reply with or without [DONE] goes as it came
with one finish_reason; kimi-k3 with and without usage unchanged.
Translated: with usage one message_stop with stop_reason tool_use and
no error, streamed, and a 200 tool_use unstreamed; without usage one
error and no message_stop, and a 502 unstreamed.
Broken by hand, each red: the relay fill off (relay test: no
finish_reason), the streamed fill off (0 stops, 1 error), the
unstreamed fill off (502), usage ignored in chatTail.finish (every
no-usage case ended as whole, unstreamed 200).
Run: gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./...
ok; go test -run 'TestGeminiCompat|EndedShort|TestStreamCut|
TestWellFormed|Sniff' ./internal/gateway ok.
Docs: gateway-routing.md says when the finish_reason is filled in.
Full suite: go test -tags nogui -timeout 45m ./... at base
|
||
|
|
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
|
||
|
|
a0a4d55ef7 |
gateway: a passed-through reply whose reasoning loops before it says anything is asked again once, and its tries counted (#2436)
lqisgod's five looped replies (pi → WorkBuddy, Chat in and out) each
ended at once with empty tries and status 200. The once-only re-ask of a
reasoning loop (loopReasks) lived only in streamTranslated's onLoop, so a
same-protocol passthrough had holdWriter.reask nil and cutLoop ran on the
first trip. A re-ask that did happen in place wasn't counted in the usage
record's tries either (tries came from route.Tries alone).
Now holdWriter lets such a try go (mayReloop/letGoLoop) when its
reasoning looped, nothing has spoken (loopGuard.spoke: no text or call),
the request has its re-ask left and its context is alive, and either
nothing of the try reached the agent (held bytes dropped, any protocol)
or the agent speaks Chat (bytes written up to the end of the tripping
event, the next try's chunks follow). The fallback loop records the try
as failLoop with reloopedError and asks the same provider again after
retryPause. In-place re-asks add to tries too. An Anthropic or Responses
stream whose reasoning already reached the agent still ends with the
loop error: a second message_start/response.created can't follow. The
plugin host's fetch goes through the same holdWriter
(TestLoopEndsWorkBuddysReply's plugin subtests).
Tests: loop_guard_test.go's chat case now expects 2 asks and an answer;
every passed-through `data:` line is valid JSON; the usage record has
Tries == asks and no error. docs/subsystems/gateway-routing.md updated.
Broken by hand, each red:
- hw.reloop = false (old behaviour): TestLoopEndsTheReplyOnEveryProtocol,
TestLoopEndsWorkBuddysReply, TestReasoningLoopIsAskedAgain fail.
- reasked not added to tries: the same three fail with "usage record's
tries 0, the vendor asked 2 times".
- spoke never set: TestLoopAfterTextIsNotAskedAgain fails.
Run: gofmt -l clean; go vet -tags nogui ./internal/gateway ./internal/usage
with GOOS=darwin, linux, windows ok; go test -run Loop ./internal/gateway ok.
Not tried: a real WorkBuddy account looping (the loop can't be forced).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... on base
|
||
|
|
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
|
||
|
|
abc9006819 |
gateway: a rule naming a group in the group keeps the group's own routing's order (#2407)
What changed
ruleFirst ranked the candidates of a rule's member by the group's flattened
member order, so a rule that names a group in the group erased whatever that
group's own routing had planned: a rotate group's turn advanced underneath,
but every request the rule put first was served by its first member again.
The rule's own member that is a group in the group is one member now — its
models rank as the group's block, in the order the group's routing planned
them; the members the rules after it name keep their own ranks, so a model
the rule names that the group has too still leads over them (#625,
TestRuleNamesAModelAGroupInItHasToo). TestRuleNamingARotateGroupKeepsItsTurns.
Run
HOME=$(mktemp -d) GOTOOLCHAIN=auto go test -tags nogui -count=1 -p 2 -run 'Rule|Rotate|Nested' ./internal/gateway/ — ok
HOME=$(mktemp -d) GOTOOLCHAIN=auto go test -tags nogui -count=1 -p 2 -timeout 45m ./internal/gateway/ — ok 304s
TestRuleNamingARotateGroupKeepsItsTurns on rules.go at
|
||
|
|
a786c51cb0 |
agent: a magpie-models.json that doesn't parse is kept aside, not written over or removed whole
What changed: #2263 gave magpie's state files whose reader takes an unparseable file as empty the lastgood.KeepUnparsed copy-aside, and its sweep named the files it covered. Codex's magpie-models.json was in neither its covered list nor its cache exemption, and its reader has the exact missed shape: codexcat.Keep (#1450) returns the new list for a file it can't parse, and the next sync, model switch or stepping back in wrote that over the file, ending the keys the user added by hand (supports_reasoning_summaries and friends) with no copy. Stepping out was worse: dropList took an unparseable file for one holding nothing of the user's and removed it outright. Now the three writers of the list go through writeOwnList, which keeps an unparsed file aside (magpie-models.json.bad-<time>) before the write and stops when the copy can't be made, and dropList keeps one aside before it removes the file. Run: - gofmt -l internal/agent: clean. - go test -tags nogui -p 2 -count=1 -timeout 25m ./internal/agent: ok (183s). - TestUnparsedCodexCatalogKeptAside fails on the code before this ("the unparsed list was written over with no copy kept"); the ablation replays it against this commit's parent. - go vet -tags nogui ./... for darwin, linux and windows ok; go build for the three ok (reviewer, at the batch head). Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every package (reviewer, at the batch head before #2424 was added). Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
d830d460f0 |
provider: a refused keychain read is not asked again for ten minutes (#2408)
What changed: copilotCLISecret backs a denied keychain read off (10 minutes, "don't ask again at once"), but the two other readers of the same family took every failure as an absent item and asked again after their ordinary 10s TTL. On macOS a denied item prompts again on every read, so a user who answers Deny once was asked again every 10 seconds while Cursor's status or Claude's credentials were polled, and every 10 minutes only for Copilot (#2408's report is the Copilot face of this). Now cursorKeychainToken and readClaudeKeychainItem (through claudeCredential's cache) treat any `security` failure but 44 — the item not being there, which asks nobody — as a read that may have shown the user a dialog, and don't repeat it inside keychainDeniedTTL (10 minutes, copilot's own pause). A sign-in or out in magpie reads afresh (forgetCursorStatus, forgetClaudeCredential clear the pause), and a fresh read in CursorToken is unchanged. Run: - gofmt -l internal/provider: clean. - go test -tags nogui -p 2 -count=1 ./internal/provider: ok (72s). - TestDeniedCursorKeychainReadIsNotAskedAgain and TestDeniedClaudeKeychainReadIsNotAskedAgain fail on the code before this (a refused read asked again 11s later). Not tried: a real macOS keychain dialog answered no (a fake `security` stands in for it); Copilot's own reader is unchanged. - go vet -tags nogui ./... for darwin, linux and windows ok; go build for the three ok (reviewer, at the batch head). Full suite: go test -tags nogui -count=1 -timeout 45m ./... ok, every package (reviewer, at the batch head before #2424 was added). Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
682e4253bf |
gateway: a Gemini call's thought signature is kept on disk and its id carries a 16-character key, not the signature — ids were 3KB+ and broke a client's PostgreSQL index (#2411, liangxyz)
Since #687 a tool call Gemini signed went to the client with the signature
inside its id (<id>__ts<n>__<base64url>), so the client's next request
brought it back. A Gemini 3 signature is often 2–6KB, so ids were too: LobeHub
stores tool_call_id in a btree index, whose rows are capped near 2.7KB, and
the write failed.
The signature is now written to <settings>/gemini-signatures/<key>, the key
being 12 bytes of its SHA-256 in base64url, and the id carries
__tsk16__<key> (≈36 characters). Coming back, the file is read and its hash
checked against the key; a file gone or changed is no signature, and the
call goes to Gemini with skip_thought_signature_validator, as an id a client
shortened already did. A file is touched when it is read or written again
and pruned 90 days after its last use (at most once an hour, on a write);
temp files from a write cut short go after an hour. When the folder can't
be written, the signature still rides in the id as before. Ids made before
this (__ts<n>__, __tsr<n>__, __ts__) are still read.
Real use: a sandbox HOME magpie serve with the owner's Antigravity account
copied in, antigravity/gemini-3.8-flash-high, a two-turn tool call over Chat
and over /v1/messages: ids came back as call_659137__tsk16__cOTtfB5LubcVSNaX
(36 characters), turn 2 answered from the tool result, and the store file
(584 bytes) was born on turn 1 and touched on turn 2's read.
gemini/gemini-3-flash-preview answered 502 (Gemini CLI no longer
supported), unrelated. Not tried in LobeHub itself; asked on the issue.
Tests: TestFortyCharacterIDThroughGateway now keeps the real signature
through a 40-character id; TestLongSignatureGivesShortID (6.4KB signature,
id ≤ 64, round trip); TestKeptSignatureGoneOrChanged; TestUnkeptSignature-
RidesInTheID; TestOldSignaturesPruned. Broken by hand: keepSignature
disabled fails FortyCharacter and LongSignature; the hash check removed
fails KeptSignatureGoneOrChanged.
Ran: gofmt; go vet -tags nogui ./internal/gateway/ for darwin, linux,
windows; targeted tests -count=3.
Full suite: go test -tags nogui -count=1 ./internal/gateway/ ok (466.9s);
the rest of the suite ran green on the batch this is rebased onto
(
|
||
|
|
a7a0122027 |
gui, gateway: the search grip's place is a class, not :has(), and Go no longer says the Routing plugin's words (batch GUI reds)
The full GUI run on this batch had two reds that are real, both from commits in it: - old-webkit "the styles hold up in Safari 15.0": 4b69460d1 (#2286) placed a search API's grip with `.search-unit:has(> .search-keys)`, which Safari before 15.4 can't parse. The unit now gets a with-keys class where its keys' row is added, as other rows in app.css do. - i18n-keys "a plugin's words are its own": 7ff5f595e's test name TestArkDrawsUnmarkedOncePerImage and f9ccca71e's comments in active.go and left_in_flight_test.go said "Unmarked" and "answering…", which are plugins/routing's words. The test is TestArkDrawsWithoutWatermarkOncePerImage (the subsystem page renamed with it) and the comments say it in other words. Run: node --test i18n-keys (3/3), search-order (16/16), old-webkit and mobile-web alone; gofmt; go vet -tags nogui ./internal/gateway. Not checked by a test: the grip's top under a unit with keys; the rule is the same, only its selector changed. Full suite: SUITE_LINE |
||
|
|
d6b045a7e7 |
usage: the Overview's lists fold under their headings and stay folded, the token totals can count the cache, and the Requests Tokens card wraps its cache count instead of cutting it (#2378)
The reporter asked for three things on the Usage page: fold Agents,
Models and Accounts from their titles and remember it (日常看账号维度
较多,都要拉到最底下); an option to count the cache in the token totals;
and the Requests tab's Tokens card cut its cache count off on a wide
window ("缓存 879…").
- Folds: each Overview list's heading (Agents, Models, Accounts, and
Gateway keys beside them) is a .fold button with its chevron, the
Gateway page's pattern. A click keeps the page still (backToReader).
What is folded is kept per viewer in localStorage magpie.usageFolded
(mountUsageFolds at the plugin's mount, showUsageFolds per render).
- Cache: the tokens tile's label is a pop-up (usageTokensPick, the app
menu, no <select>) of Without cache / With cache, kept in
localStorage magpie.usageWithCache. With cache, the tile, the chart,
and every row's count and share add cache read and written
(usageTokens), and the tile says the cache's count. Default unchanged.
- Cut count: a token line in parts (the Requests strip's Tokens card,
the Overview's tokens tile) wraps between its counts and keeps each
whole (usageParts, .parts); only a count wider than its card on its
own is cut. The part spans undo .kpi span's label capitals.
- Strings in zh, zh-TW, ja, de. docs/subsystems/gui-shell.md bullet.
- mobile-web.test.cjs: until BASE_REF has mountUsageFolds, the
desktop Usage comparison puts the new fold buttons and the pop-up
back to their plain labels and compares the rest as before. That
comparison caught the tile's line in the label's capitals and 5px
taller; both fixed, and usage-overview-fold now checks them.
Run at this head (base
|
||
|
|
b6fae8efd8 |
gateway: an advisor magpie leaves out takes its instructions and tool_addition with it, so the model no longer calls a tool it hasn't got (JackChou on Discord)
JackChou: "claude code 使用 advisor 返回找不到对应工具". Claude Code 2.1.300
(its request read from a fake ANTHROPIC_BASE_URL in a sandbox HOME, with
--advisor and a fake key) declares the advisor as the server tool
{"type":"advisor_20260301","name":"advisor","model":…,"defer_loading":true}
and also puts it in the conversation: a {role:"system"} message whose text
ends in "# Advisor Tool … call advisor BEFORE substantive work", and a
{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"}}
block.
|
||
|
|
d98e17808b |
gateway: a refusal that comes as an error ends the try at once, is read across writes after content, and the high-risk message alone is one (#2400, Jichao)
Three gaps Jichao reported, each reproduced on origin/main
|
||
|
|
6e17d58ebf |
usage: a top session only the gateway saw says "Gateway session", not "(no prompt)" with no folder (#2285)
The reporter's Usage › Sessions card listed seven Pi sessions on
deepseek-v4-pro as "(no prompt)" with no folder, and their routing group
has no DeepSeek. Those rows were gateway projections: Pi asked magpie for
deepseek/deepseek-v4-pro (every served model is in Pi's models.json), most
likely through a pi-subagents child, whose session file is in a temp folder
magpie never reads. The card gave no sign of that, so it read as Pi's own
sessions with an empty prompt, and our first reply took it that way.
The overview's summaries from MergeExternalStats now carry gateway: true,
as MergeExternal's list rows already did. The card shows "Gateway session"
where the folder would be, "(prompt not recorded)" as the title when no
text was kept, and a tooltip pointing to Record gateway conversations.
Strings in zh, zh-TW, ja and de. gateway-sessions.md says it.
Run in this worktree (
|
||
|
|
3f4186fd8e |
providers: a provider you added can skip its own host's certificate check, nowhere else (#2383, fangzhengjin)
A vLLM on the LAN, an Ollama behind a self-signed certificate or a company CA can't be reached over https today. A custom provider now has "Don't check its certificate" (Certificate, in its editor, shown while an address is https), with a short risk note, in en/zh/zh-TW/ja/de. Scope, enforced in Go, not only in the GUI: - Only a provider the user added with their own base URL takes it (TakesInsecureTLS: no preset, no account, no Vertex, no subscription id). Save refuses it on anything else, and Via ignores a hand-set flag. - It reaches the hosts of the provider's own base URLs alone (netproxy.WithUncheckedTLS): a redirect elsewhere, a models/balance/ image URL on another host, and a nested request for another provider (With drops it) are still checked. - Every route: it is set in Provider.Via, which the gateway's attempt and forwardOnce (count_tokens too), List, Test, Detect, balance, draw, embeddings and video all go through. - The unchecked host gets its own cloned transport (the route key holds the flag), so the leave never reaches another request. An https:// proxy is refused for it, because its TLS would be dialled with the same config and go unchecked too; http:// and socks5:// proxies work. - The editor shows the saved value, Test/Detect/Fetch carry it before a save, and a save that omits it keeps it. Backup, export and WebDAV sync carry it (backup.Collect). Rewritten from fangzhengjin's fork 749e82a25 rather than applied: it had no Go-side limit to custom providers, set InsecureSkipVerify for every host the provider's requests reached (redirects, other hosts, nested requests) and for an https:// proxy's own certificate, never showed the flag back to the editor (the next save cleared it), and didn't carry it into Test/Detect/Fetch. Its transport cache key holding the flag is kept. Run in this worktree (-tags nogui -p 1, sandbox HOME): - go test -run 'TestUnchecked|TestWith|TestDispatch' ./internal/netproxy ok - go test -run 'TestInsecureTLS|TestVia|Proxy' ./internal/provider ok - go test -run TestInsecureTLS ./internal/gateway ok (chat, responses, anthropic, count_tokens, gemini against a self-signed server) - go test -run 'TestProviderSaveInsecureTLS|TestProviderSaveKeeps|Typed' ./internal/gui ok - go test ./internal/backup ok - GUI provider-insecure-tls.test.cjs: chromium 30/30, webkit 30/30 (en, zh, zh-TW, ja, de at 1100 and 420) - gofmt -l clean; go vet -tags nogui for darwin, linux, windows on netproxy, provider, gui, gateway, backup clean Broken by hand, each went red, then restored: - With not clearing the leave -> TestUncheckedTLSOnlyItsHost - the https:// proxy guard off -> TestUncheckedTLSStillChecksItsProxy - TakesInsecureTLS always true -> TestInsecureTLSNotForPresetsOrSubscriptions - Via not setting it -> TestInsecureTLSOwnProviderOnly and all 5 routes of TestInsecureTLSEveryRoute - backup field tagged json:"-" -> TestRoundTrip - save not keeping an omitted flag, providerInfo not showing it -> TestProviderSaveInsecureTLS - draftOf/asTyped not carrying it -> 2 of 3 GUI tests (en 1100 chromium) Not tried: a real vLLM or Ollama behind a self-signed certificate; the image, video, balance, embeddings and draw routes are covered through Via, not each by its own test. The full suite was not run. Co-authored-by: fangzhengjin <12680972+fangzhengjin@users.noreply.github.com> Full suite: SUITE_LINE |
||
|
|
dc8dcc85d1 |
provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.
- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
the user's own Balance URL only; a vendor magpie knows is asked as
before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
other value is refused and the saved one kept); `magpie provider <id>`
shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.
Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
a POST-only httptest server, POST (any case) reads $0.94 from a string
usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
("asked GET, want POST"); balanceMethodOf passing any method turns it red
(PUT and DELETE sent); the CLI taking any value turns
TestProviderSetBalanceMethod red; the Check balance body without
balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
named and titled in the language, fits beside the URL with no page
scroll, the other pick goes in the check and save bodies). Siblings:
balance-parts, balance-field-default, balance-fix, catalog-hint,
duplicate-pause, key-balance-card, local-address, provider-base-api,
provider-auth-header, provider-gemini, provider-search,
provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
Default: "unavailable 405 Method Not Allowed"; balance.method=post:
"$0.94 from POST …/api/check-balance $usd_balance", the server saw one
POST with Content-Length 0 and the Bearer key; balance.method=PATCH
refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.
Full suite: SUITE_LINE
|
||
|
|
afb0ff7720 |
gateway: a tool Pi adds in a message of its own joins the request's tools on every route, once by name (#2322, deephbz)
Pi 1.2.0 with supportsMidConvoToolAdditions sends a tool it adds
mid-conversation as {"role":"system","tools":[...]} with no content and
keeps top-level tools as they were. parseChat read only top-level tools
and the Chat relay sent the message on as it came, so the tool could be
called on no route, and the tools-only message became an empty part of
the system text ("</cwd>\n\n\n\nUpdated ...").
liftMessageTools (message_tools.go) moves message tools into the
request's tools. handle does it for every Chat body, before serveAgent,
so the Chat relay, schema fixers, redaction, the prompt shown and
routing all see them; parseChat does it too for a body that never came
through handle. Each tool joins once by name and the first definition
wins (top-level, then the earliest message's), as liftAdditionalTools
and a tool_addition in withoutDeferredTools do. A system or developer
message that carried only tools is left out; one with content keeps
its place without tools. Message order is unchanged: the in-place
system message / inline-tools beta part of #2322 is not in this commit.
6312af989 (#2338, inline-only tool_addition joins tools) is not on
origin/main
|