8a4e32febef69bb797cdf3003ec1395e725d5d63
1793
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
8a4e32febe |
tests: the overflow memory's compacted and answered cases stay one conversation (#3453)
TestOverflowRefusedOnceIsAskedLast's "compacted" request changed the conversation's only user message. A ruled group keeps a conversation by its first user message (firstWords in the stick key), so that request was another conversation, and passed with behindOverflow's size check taken out. Nothing asked that what a member answered is forgotten. The conversation now has turns after its first user message, and the compacted request keeps that message and drops the rest: the same key, a smaller body. a answers it, and the conversation grown back to the size a once refused begins with a again. Run on mote, -tags nogui ./internal/gateway/: - -run TestOverflowRefusedOnceIsAskedLast: ok. - size check taken out (size >= r.bytes always true): FAIL at overflow_learn_test.go:71 "compacted: ... (a 0, b 1)". - forgetOverflow call taken out: FAIL at :81 "after a answered: ... (a 0, b 1)". - -race -count=20 of this test, TestOverflowMemoryReadWhileNoted and TestRelayInputCapGoesToTheNextMember: ok. |
||
|
|
3af592f587 |
gateway: the overflow memory is read under its lock, so two requests of one conversation don't crash the gateway (#3453)
Review follow-up to ggbdpq's 075aaef62. behindOverflow took the conversation's inner map under overflowLearned's lock, let go, and then read it, while noteOverflow and forgetOverflow write that same map under the lock. Two requests of one conversation at once (a turn beside its title ask, a client's retry) read and wrote one Go map together, which is a fatal "concurrent map read and map write", the whole gateway gone. The loop now runs under the lock. TestOverflowMemoryReadWhileNoted notes and forgets on one goroutine while another orders members by the memory. Before this commit, on mote: go test -tags nogui -race -count=1 -run TestOverflowMemoryReadWhileNoted ./internal/gateway/ -> "--- FAIL: TestOverflowMemoryReadWhileNoted ... race detected during execution of test". With it, -race -count=20 of that test, TestOverflowRefusedOnceIsAskedLast and TestRelayInputCapGoesToTheNextMember: ok. Also: behindOverflow's comment said resting members keep their order; the code moves a refused member behind every other one, resting or not, so the sentence is dropped. gateway-routing.md now describes the memory beside withRoom's overflow paragraph. |
||
|
|
e0a5091b7d |
gateway: a member that refused this conversation as too long is asked last, not first
What changed: an overflow (400, "prompt is too long") is the request's
length, not the account's, so it rests nobody — and left no trace: the
next request of the same conversation tried the member again, failed the
same way, and fell back again, for every request (#3453: a rule sent
every turn to a Claude subscription bridge that answered "Prompt is too
long" and DeepSeek answered; two consecutive requests of one turn each
paid the refused try first). Now the conversation remembers, per
provider's model, how large the request was when it was refused, and the
member is put behind the others — behind, not out: it is still asked
when every other member has failed, a rule that names it is still
heard (ruleOver has run), and what it answers makes magpie forget the
refusal. A request smaller than what was refused — the agent has
compacted the conversation — finds the member where the rule put it.
Another conversation is unaffected, and a byte cap (413) is not
remembered: it is not the conversation too long for the model.
TestRelayInputCapGoesToTheNextMember's second phase shares its server
with the first, whose overflow left this conversation's memory of a's
refusal behind; as that phase says how a plain bad request is classed,
its memory starts empty.
Run: go test -tags nogui -count=1 -run
'TestOverflowRefusedOnceIsAskedLast' ./internal/gateway/ (red on
|
||
|
|
9a4eaab82a |
gateway: a Chat body relayed to Gemini's OpenAI-compatible API goes without Ollama's options (#3097)
What changed: a client that takes the gateway for an Ollama server (its
/api/show is answered in Ollama's shape) sends Ollama's per-request
options beside its Chat fields. The google preset serves a model on
Gemini's OpenAI-compatible endpoint, so such a request is relayed as it
came, and that endpoint reads proto JSON: an unknown name turns the
whole request away with 400 "Invalid JSON payload received. Unknown
name \"options\": Cannot find field", every call, whatever the effort.
A body relayed to a Gemini OpenAI-compatible upstream (geminiCompat)
now goes without the top-level options, whose runner settings have no
place on a Chat API, as the Ollama route's own body builder already
leaves them out (ollamaChatBody). Another vendor's Chat upstream still
gets the body as the client sent it, and translated requests are
unchanged: they are built from the request's own fields, which never
carried options. geminiCompat is worked out once where the thought
signatures ask for it too.
Run: TestGeminiCompatRelayLeavesOutOllamaOptions fails on the old code
with "Ollama's options reached Gemini's OpenAI-compatible API" and
passes with the change; a request to another vendor's Chat upstream
still carries options there. go test ./internal/gateway/ ok (346.6s);
go test ./... -timeout 45m: 66 packages ok, internal/agent TestMothX
and internal/gui TestProxyCheckSaysAProxyPassedBy red, both red with
the change stashed on
|
||
|
|
026d4423d0 |
gateway: a Command Code stream that ends with no finish_reason is a cut (#2471)
What changed: a Chat stream of Command Code's whose reply ends with no finish_reason anywhere - esp32gallery's day had 665 requests, 624 ended with one, and the 20 that didn't were turns its slow starts lost to a killed worker, each a ledger 200 with no stop and no error while the client read "Stream ended without finish_reason" - was taken for a turn that ended as it should, silence in the ledger and a bare half-reply for the agent. Its API joins Gemini's OpenAI-compatible one in saysItsEnd: every whole reply of its says its end, so a stream that stops short of a finish_reason is said as the cut it is, in the stream, the same way a relayed Gemini one is (#1644) - and one still held, with nothing of the reply said yet, fails there for the group's next candidate. Another vendor's Chat stream may still end whole with neither a finish_reason nor [DONE]: nothing changes there. Run: Four new tests, the first two red on cef8c1a4a before the change (the cut passing as a whole reply, the next member never asked): TestCommandCodeRelayEndedShort, a half-reply cut ends with "the reply ended before it was complete", no finish_reason filled in; TestCommandCodeTaillessFailsOver, a held lead-only stream fails 502 for the next member; TestAnotherChatStreamWithoutAFinishReasonStaysAsItCame, another vendor's tailless stream goes as it came; and TestCommandCodeRelayWholeStaysWhole, a finished reply is never given a second end. TestGeminiCompatRelayEndedShort and TestGeminiCompatTranslatedEndedShort green throughout. Not tried: a real Command Code upstream (the frames are the reporter's ledger shapes, the host the one balance.go reads). Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
eb7e72cc7f |
gateway: a response.completed with no output and no tokens fails over (#2471)
What changed: a Responses upstream that ends its 200 stream with a
response.completed carrying no output and counting no token - WorkBuddy
AI's account answered Codex's request with created, in_progress,
completed and `output: []` three times running (MurmuredVelpro) - had
the completed event taken for a reply's end: the held stream went to the
agent as a completed turn, the try stood as a 200 success, and the
group's healthy members were never asked. streamEvent now reads a
completed with an empty output and a zero usage as the no reply it is -
the same shape a translated reply that said nothing and counted nothing
has failed as since #2086 (repliesCounted) - and fails the held try for
the group's next candidate, in the candidate walk as an empty reply's
does: nobody rests, as the reply's shape failed, not the account. A
completed that counted a token stays a reply, as Claude's own empty
end_turn does; and an event this reaches is one nothing was said before,
since the hold lets the first content through and reads no event beside
it, so nothing of the try has reached the agent when it fires.
The fields said are what is read: a completed that names neither field
goes as it came, as the streamEvent table pinned it
(TestStreamEventRefusals, which caught the first draft reading an
omitted output as an empty one), and a completed that counted a token
stays a reply.
Run: TestEmptyCompletedFailsOver (new) red on
|
||
|
|
c079b9ad7e |
claude: an interactive run's side question is branched before, not told whole (bbfatx on X)
Claude Code asks for a prompt suggestion as the conversation plus one more user message (#1638). A claude -p run takes that aside and goes on; on the next real turn the bridge rewinds it to the line before the aside (behindKey/behindTurn and --resume-session-at). An interactive run ignores --resume-session-at, so the bridge aborted it and told the next turn whole to a new run: every turn after a suggestion wrote the whole conversation into the cache again. That is bbfatx's second suggestion (save a checkpoint at a history prefix and fork from the deepest one) in the one place where it rewrites the cache today. Now the run remembers the last session line it wrote before each turn (lastLine, backLine, behindLine). When the next real turn finds an interactive run behind an aside, the bridge cuts a copy of the run's session at that line before the abort removes the file (branchAt, the cut copy from the previous commit), and the new run resumes the copy in interactive mode and is told only the new message. Run (mote, at this tree): - go test -tags nogui -count=1 -timeout 30m -run "Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit|Fork|Branch|Shelf|Shelve" ./internal/gateway: ok (70.7s) - go test -tags nogui -count=1 ./internal/claudetui: ok - gofmt -l internal/: clean Broken by hand (TestClaudeInteractiveSideQuestionBranchesBeforeIt): - the old code (HEAD 37ff7356f): red, the turn after the suggestion is "had 0 turn 1" (told whole to a fresh run). - backLine left "": red, "had 0". - cut at the run's last line (after the suggestion) instead of the line before it: red, "had 6". Not tried: a real interactive Claude Code prompt suggestion end to end; the test uses the fake claude with the helper stand-in. The cut copy itself was measured with real Claude Code 2.1.316 in the previous commit. Not taken from the suggestion: a general store of checkpoints by history prefix. The bridge already keeps one run per conversation and resumes it at the line it is behind; the only case that lost the prefix was the interactive aside, so only that case gets a cut. Prompt and system text sent upstream are unchanged. |
||
|
|
8215164296 |
claude: a branch is a cut copy of its run's session, in its run's mode (bbfatx on X)
A sub-agent's first request that answers calls another request already answered branches off the lead's run's session (branch). That branch was `claude -p --resume S --fork-session --resume-session-at U`, and claudePrint forced every branch to -p, because Claude Code's interactive mode ignores --resume-session-at (Claude Code 2.1.316 on mote: it resumes the whole session). Runs are the interactive mode by default now, so the lead's cache has the interactive prompt, and a -p branch of it read only tools and system from the cache and wrote the conversation again (measured on mote, sandbox HOME, 30 MCP tools: an interactive fork of a -p session read only tools and system; the other way round was not measured). With "Interactive only" no branch was made at all, and the fork was told the whole conversation. Now the branch's run copies the session's lines up to U into a new session file next to it, with sessionId set to the copy's id (cutSession), and resumes it with --resume <copy> in the mode its source run had (savedSession.tui). claudePrint keeps "branch" only for a branch of a -p run. Under "Interactive only" a -p run's session isn't branched. The run owns the copy, as it owns an unshelved session. The copy waits up to 2s for U's line to be fully written; if it never is, the turn is told whole, as before. claudetui's translator now passes each assistant row's uuid through, as -p does, so an interactive run's lines can be cut. Measured on mote with real Claude Code 2.1.316: a cut copy resumed interactively read 7648 and wrote 14; with -p it read 24009 and wrote 13. Run (mote-run, this tree): - go test -tags nogui -count=1 -timeout 30m -run 'Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit|Fork|Branch|Shelf|Shelve' ./internal/gateway: ok 63s - go test -tags nogui -count=1 ./internal/claudetui: ok - go vet -tags nogui ./internal/gateway ./internal/claudetui; gofmt -l: clean Broken by hand (each red, then put back): - old claude_subscription.go and transcript.go (cutSession stubbed): TestClaudeForkBranchesOffTheLeadsSession interactive (branch ran -p), interactive only (told it whole), print (old flags), TestClaudeCutSessionCopiesAsFarAsTheLine and TestTranslatorTellsTheRowsUUID red - claudePrint's branch reason for every branch again: interactive and interactive only red - the copy taking the whole file: all three subtests and the cut test red - branch() refusing every run under Interactive only: interactive only red Not tried: a real fork sub-agent through the gateway. The cache numbers come from copying by hand with real Claude Code; the tests use a stand-in. Windows and WSL keep no session on disk, so they never branch, as before. Not taken from the suggestion: the fork's own runtime and TypeScript wrapper. The cut is done here at the one place a branch starts. |
||
|
|
85ab325d48 |
claude: a title asked between turns leaves the conversation's run waiting (bbfatx on X)
bbfatx on X: the Claude subscription bridge spends more of the quota than it should. While checking which of the suggestions cause real cache writes, this one turned up. A client asks a title or a summary between a conversation's turns, the conversation so far and a question more, with tool_choice none or with no tools. Such an aside cost the conversation its run, in one of two ways: - tool_choice none: the aside went to a run of its own, and retire, which lets go of the runs a new run carries the conversation on from, let go of the run the conversation waited in. - no tools: looseTurn's key has no tools, so the aside was taken as the conversation rewritten (#912), and the conversation's run went on with it, to wait at the aside afterwards. Either way the conversation's next turn found no run. A new Claude Code was told the whole conversation in one message, and all of it was written to the cache again. Now an aside of a run that was told tools neither retires it (retire takes the request; asideOf) nor takes it as rewritten. The aside is answered by a run of its own, as before, and the next turn goes on in the conversation's run. A client with no tools at all is unchanged: asideOf holds only for a run that was told tools. Run (mote, go1.26.8): - go test -tags nogui ./internal/gateway -run TestClaudeAsideLeavesTheConversationsRun -count=1: ok. - go test -tags nogui ./internal/gateway -run 'Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit' -count=1: ok (75s). Broken by hand: - HEAD's claude_subscription.go: red. With none, the next turn went to a new run told it whole. With no tools, the title went on in the conversation's run. - The rewritten check only: red (no tools). - The retire check only: red (both). Not tried: a real client's title request on a real account. The aside still costs one new Claude Code told the conversation whole. The next commit branches it from the run's session instead. |
||
|
|
e02df9e226 |
claude: a tool_choice none turn is offered the client's tools, and may call none (bbfatx on X)
bbfatx on X: the Claude subscription bridge spends more of the quota than it should. Suggestion 1 was to keep a turn's tool definitions apart from whether it may call them. bridgeTools dropped every tool for tool_choice none. Anthropic caches a prompt as tools, then system, then messages, so such a turn (a title or summary asked with the tools as ever) was a prefix the cache had never seen. All of it was written again, Claude Code's own tools and system prompt included. Now a none turn's MCP helper offers every tool the client sent. A call the turn makes anyway is answered at once with an error result (mcpCall), and toolStart treats it as Claude Code's own call, as it does magpie's web search. The client never sees it, and the reply goes on in words. A named tool_choice still offers only that tool. The allowed set (subscriptionRun.allowed) is set for each turn: at start, on resume, and with tool results (a client may choose none once it has its results). The system prompt and the turn's text are unchanged. Measured with the real Claude Code 2.1.316 on mote, in a sandbox HOME and CLAUDE_CONFIG_DIR, against a stand-in Anthropic that counts cache reads and writes the way Anthropic's cache does (30 MCP tools): - the same turn with no tools: 0 read, 7595 written; - told whole in a new session with its tools: 15780 read (tools and system), only the history written. Run (mote, go1.26.8): - go test -tags nogui ./internal/gateway -run TestClaudeToolChoiceNoneKeepsTheTools: ok. - go test -tags nogui ./internal/gateway -run 'Claude|Bridge|ToolChoice|Subscription' -count=1: ok (54s). Broken by hand: - HEAD's claude_subscription.go: red, the helper was offered [], the call was not refused, and the client was shown a tool_use. - Only the refusal turned off (mcpCall and toolStart): red, the call was shown to the client. Not tried: a real client's tool_choice none request through the gateway to a real account. The measurement drove Claude Code directly. Not taken from the suggestion: nothing of the fork's code is ported. The fork drops a none turn's tool calls in its own runtime. Here the call is refused where magpie already answers its web search. The only new text upstream is that refusal, a short tool error result naming neither magpie nor a vendor, and only when the model calls a tool anyway. |
||
|
|
1adff37796 |
claude: a refusal Claude Code falls back from goes on to the fallback model's answer (Chixi_Fang on X)
Claude Code 2.1.316 doesn't end a turn at a refusal. It asks the same
model again, then its fallback model (claude-opus-4-8 for Opus 5.5),
whose answer ends the turn with result success. The bridge ended the
reply at the first stop_reason refusal, so the client got "Partial "
plus a refusal, and the gateway's hw.refused moved to another account
or handed the refusal back. That is the "model error" the reporter saw.
readOutput now holds a refusal from Claude Code's own model and goes on
with the next message as one reply. Not held: a client tool call, or a
schema reply. The refusal's stop_details are held too. The refusal is
told only if it stands: at a result with no API status (Claude Code's
model_refusal_no_fallback, -p or TUI) or at the end of output. Then
hw.refused and b01766d13 see it as before. A result with a status after
a refusal is that error, not a refusal. The continuing message's model
goes on the KUsage as Model and Served. The try records the fallback
model, and a reply told whole names it. A stream's message_start can't
change it. Prompts and system text sent upstream are unchanged.
Real behaviour: Claude Code 2.1.316 on mote, in a sandbox HOME and
CLAUDE_CONFIG_DIR, against a fake Anthropic upstream that refuses
claude-opus-5-5 (or every model). The -p and TUI stream-json lines were
captured and trimmed into the fixtures in
claude_refusal_fallback_test.go.
Run (mote-run, worktree at base
|
||
|
|
726544eed7 |
browser: with two browsers connected, an agent lists them and picks one
With Magpie Browser in two browsers (Chrome and Edge, or two profiles),
every call went to the last to connect and nothing said there was another
(packinggoodsllc_07668 on Discord: which one is controlled?).
- Each connection gets an id (b1, b2, in connect order) and a name from its
User-Agent (Edge, Opera, Vivaldi, Yandex say so; Brave, Arc and other
Chromium browsers read as Chrome).
- browser_tabs action browsers lists them, * on the one calls go to; action
use with browser (an id, or a name only one has) moves this session's
calls there. Other sessions stay where they were; a browser that
disconnects drops every session's pick of it.
- With two or more connected, browser_tabs list says whose tabs it lists.
The default is still the last to connect.
Run (mote-run): go test ./internal/gateway -run Browser ok (new
TestBrowserMCPPicksAmongBrowsers, TestBrowserName); go vet, GOOS=linux and
windows go vet ./internal/gateway ok.
Broken by hand: forSession ignoring the pick, the new test red ("s1 after
picking chrome: ... b2's tabs (Edge 141)").
Not tried: two real browsers at once; the GUI still shows only the last
connected browser.
|
||
|
|
3cb8b17312 |
browser: two agents at once each work in a tab and tab group of their own
Magpie Browser kept a tab per session, but a session with no tab took the
tab the user was looking at, so two agents started together worked in one
tab, and every agent's tabs went in one "Magpie" group
(packinggoodsllc_07668 on Discord).
- A session whose first call finds the shown tab held by another session
gets a new background tab of its own.
- Each session's tabs go in a group of its own: "Magpie", then "Magpie 2",
"Magpie 3" beside other live sessions (session → group kept in
storage.session with the tabs).
- browser_tabs list marks another session's tab ~ and names each tab's group.
- A link that opens a tab moves the session that clicked it (t.by), not the
first session found holding the old tab.
- Instructions and the popup's hint say so; extension 0.1.1.
Run (mote-run, MAGPIE_BROWSER_CHROME = Playwright's Chrome for Testing
1234): TestBrowserToolsInARealBrowser and the new
TestBrowserSessionsApartInARealBrowser (two sessions, real tabs and groups)
ok; go test ./internal/browserext; ./internal/gateway -run
'Browser|MCP|Hub'; GOOS=linux and windows go vet of gateway, library,
browsermcp, browserext ok.
Broken by hand: the new test against the old background.js is red ("both
sessions work in t803211511").
Not tried: real Chrome/Edge with a user profile, a person watching the
groups; t.by with two sessions (the click test has one).
|
||
|
|
de74cb53f7 |
mcp router: each caller gets its own Magpie Browser session
The router keeps one backend per Library server for every agent, so all agents behind it shared one `magpie mcp browser`, one browser session and so one tab (packinggoodsllc_07668 on Discord: two agents through a remote router fought over one tab). - serveMCP gives a client that initializes an Mcp-Session-Id (nothing is kept or checked by it). - hubSession names each tools/call's caller: _meta magpie/session from a router in front, else hub-<agent>-<Mcp-Session-Id>. - The router passes it in _meta magpie/session to `magpie mcp browser` and to another magpie's router only (keepsSession); the bridge sends it as that call's X-Magpie-Browser-Session (callerSession). A call naming none goes as the bridge's own session, as before. Run (mote-run): go test ./internal/browsermcp; ./internal/gateway -run 'MCP|Hub'; ./internal/library -run 'TestHubTellsMagpieBrowser|TestKeepsSession|TestHubGivesMagpieImage'. ok. Broken by hand, each red: no meta from the library (library test), no Mcp-Session-Id from serveMCP and ignoring _meta in hubSession (gateway test). Not tried: a real remote router chain between two machines. |
||
|
|
4a4a82cd49 |
gateway: TestSearchAPIAsksAreLogged's query has no number a port can hold
The Linux box's full suite failed it: "the query's \"7781\" is in
usage.jsonl", where the only 7781 was the fake server's random port,
host 127.0.0.1:37817. Every row logs the host, so any query word made of
digits can match a port now and then. The query is letters only now; the
check that no query word reaches usage.jsonl is unchanged.
Run on mote at this tree (origin/main
|
||
|
|
403323af7f |
claude: a switch waits for another magpie's runs in the account's directory (#4532)
StringKe's audit, item 2. claudeDirRun is an in-process RWMutex, so
`magpie accounts switch` from the CLI never waited for the app's /usage,
warm-up or keep-alive run in the saved account's directory: it handed
Claude Code the refresh token that run could still spend, and removed
the directory under it. And the gateway's hand-over let go only of idle
runs; a run in a turn when the switch came was kept for its next turn,
waiting up to idleLongest in the removed directory with the same token.
- inSavedClaudeDir also holds a lock file of its own beside the
account's directory (markClaudeRun, <dir>.run-<pid>-<n>.lock,
filelock), removed as it ends.
- switchSavedLogin waits on every such file (waitClaudeRuns) up to
claudeRunWait (90s), then fails with errClaudeRunning and leaves the
sign-in as it was. A file whose run ended without removing it is free
and taken out.
- handedOver marks the account's runs in a turn (subscriptionRun.handed);
keepIdle ends such a run instead of keeping it.
Shelved (parked) sessions hold no process or token; a later turn starts
a new run under the account the gateway picks then, so nothing changes
there.
Run (mote, nogui):
- new tests TestClaudeSwitchWaitsForAnotherMagpiesRun,
TestClaudeSwitchRunHeldAndLeft, TestSavedClaudeRunHoldsItsLock,
TestClaudeHandOverEndsTheAccountsBusyRuns, plus TestClaudeSwitch*,
TestSavedClaude*, TestClaudeHandOver*: ok.
- Broken by hand (wait call, run mark and the handed check taken out,
helpers kept): all four new tests red ("switched while another magpie
ran Claude Code…", "got <nil>", "a left lock file kept", "run locks []",
"a run of the handed-over account was kept for its next turn").
- go vet darwin/linux/windows for provider and gateway: ok.
- Windows (win-run): the three provider tests and
TestSavedClaudeUsageKeepsRotatedSignIn: ok.
Not tried: two real magpie processes with a real Claude Code (the other
process is a second open of the lock file, which flock and LockFileEx
treat as another holder; filelock's own test covers a real second
process). Not covered, filed as #4750: a run queued behind the switch
makes the handed-over account's directory again, and a run in a turn
can still refresh during that turn.
|
||
|
|
01ccbd40a0 |
library: an MCP router says which computer it is, so an agent can pick between two (packinggoodsllc_07668 on Discord)
Two magpies, one in China and one in Los Angeles, each serve the same tools through their MCP router (/mcp/magpie/hub). An agent connected to both saw two identical web fetches and couldn't pick the one in Los Angeles to reach Google. Each router now says where it is: - initialize's instructions end "This router: <name>. Each of its tools' descriptions starts with [<name>]; ...", and serverInfo.title is "Magpie MCP hub · <name>"; - each tool's description in tools/list starts "[<name>] " (once: a description that starts so already, another magpie's router behind this one, isn't given it twice). <name> is the user's words (settings.RouterNote, one line, 80 characters at most) to every caller. With none it is this computer's name, to callers on other computers only: an agent on this computer has one router at hand, and its prompts stay as they were. RouterNote is this computer's own (KeepOwn): library.json is synced, settings.json isn't, so a sync never brings the other machine's name. It is set in the Library's MCP tab, in a Router name row under the router's address (shown while the router is on): a plain field with the computer's name as placeholder, saved on Enter or leaving it, Escape puts the saved words back, an input method's Enter is its own. POST /api/settings keeps it. Translated in zh, zh-TW, ja, de. docs/subsystems/mcp-router.md has the rule. Run (mote, at |
||
|
|
39bade71d1 |
gateway: a plain <invoke> written into a reply's text is the call it is, on a relayed Messages reply too
packinggoodsllc_07668 on Discord (#general): Claude Code v2.1.316, magpie's routing group "Hard to strong, easy to cheap", asked to open Google in magpie's browser. The reply showed <invoke name="ToolSearch"><parameter name="query">select:…</parameter></invoke> *Result: Tool loaded.* <invoke name="mcp__magpie__magpie-browser__browser_navigate">…</invoke> *Result: Navigated to https://www.google.com — page title: "Google"* 已用 magpie 的浏览器打开了谷歌 ... as text. Nothing ran: the model wrote its calls and made up their results. Asked, the reporter said the group holds only Claude models (v0.1.2545). Cause: Claude wrote its own call form as text, and none of magpie's readers of written calls knew that form on the routes Claude takes. - The plain <invoke name=…><parameter name=…> shape (Claude's own calls, MiniMax's in <minimax:tool_call>, Claude's in <function_calls>) wasn't a mark: only <tool_call> and DeepSeek's DSML invoke were. - A reply relayed as it came on the Messages API (a group member on a provider that speaks Messages itself: MiniMax, Kimi, GLM, DeepSeek, Claude relays) was never read for written calls at all; the subsystem doc said so. Claude Code's request to such a member takes that route. - A Claude subscription member runs Claude Code itself (the bridge), whose textCalls held back only "[tool call …]" lines. Not the cause: history isn't flattened (tool_use/tool_result translate to native calls on every API), and this was the conversation's first turn. Fix: - textcalls.go: the invoke regexes take DSML's pipes, a namespace, or nothing; <invoke name=, <function_calls> and <minimax:tool_call> are marks; their leftover tags go. Text after a call read out, other than tags, ends the calls and goes with all after it: it is the model going on as if the call had run. This changes the old rule for every shape: prose after a Hermes call ("Done.") went on as text and now goes (TestTextWrittenCallCutEarlyNotCalled updated). - textcalls_anthropic.go: anthropicTextCalls in passthrough, for a streamed Messages reply (holds the text block's start and stop with the held text, adds tool_use blocks after it or in its place, stop_reason tool_use) and a whole one. - claude_text_calls.go: the bridge's textCalls also holds a line opening <invoke name= or <function_calls>, so the run is asked once to make the calls (textCallsAsk no longer names the "[tool call …]" form only). - Responses and Gemini relays still aren't read: #4743. Tests (textcalls_invoke_test.go), on the reporter's literal text: parse, a relayed Chat stream, a Messages passthrough through a routing group (streamed, with lead text, a lookalike left alone, and whole), and a Chat upstream translated for a Messages client. TestClaudeTextInvokeCallsAreMadeForReal: the bridge, bare and wrapped. Run: - On origin/main |
||
|
|
d614f21721 |
gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.
What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.
Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.
Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).
Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.
Run at this tree (
|
||
|
|
c688211d13 |
gateway: a ChatGPT (Codex) account gets loaded tools where they were loaded, keeping its cache (#4738)
infinitex233 (#4738, Discord): Claude Code -> magpie -> a Codex account, and every ToolSearch load dropped cache_read to 0. loadsInPlace sent the additional_tools item (#2660) only to OpenAI's own API, so for an account the loaded tool went into the top-level tools and the cached prefix broke at the tools. Tried on the real ChatGPT backend first (owner's account, sandbox HOME on mote with a copied auth.json whose refresh_token was replaced, so the live token was never rotated; ~/.codex untouched). A probe client sent Claude Code's shape: ToolSearch with two deferred mcp tools, then the tool_reference result, then the calls, 4 requests per run. - additional_tools item (on, and this commit's default): request 2..4 read 7680-8320 tokens from cache on gpt-5.6-terra, gpt-6-luna and gpt-6-sol; the model called read_a and read_b from the item; no "turned away additional_tools" in the log. - tools top-level (off): request 2 and 3 read 0 from cache (8044 and 8163 tokens in), as the reporter saw. So the backend takes it, and this makes it the default for a ChatGPT account (p.Account.Agent == "codex"). Copilot and other sign-ins stay off: not tried. - loadsInPlace: AdditionalToolsOff wins, then AdditionalTools, then an account is in only if it's Codex's, then OpenAI's API as before. - `magpie provider set <id> additional-tools=on|off|default`: off is new (AdditionalToolsOff, kept through an account's Save by accountSettings and through the GUI editor's save like AdditionalTools). The old "off"/"no" meant default; now they turn it off where the default is on. - The 400/422 fallback that names the item still applies, so a backend that stops taking it costs one retry and then sends tools top-level. - No prompt, instructions or identity line changed. Run (mote, at base |
||
|
|
9feb1024c7 |
zen: free models are asked as OpenCode 2.2.5 asks them (#3491)
laomao04_65777 on Discord: Zen's free models answered 429 "Free usage limit reached. Free models work in OpenCode" to the built-in OpenCode Zen provider, while real OpenCode 2 on the same machine was served. magpie sent OpenCode 1.x's shape. It now sends what OpenCode 2.2.5 sent in a captured request (internal/provider/testdata/opencode-2.2.5-chat.json, from a recording proxy), as the zen-free plugin does since plugins d62193c and 8501988: - User-Agent opencode/latest/<v>/cli. <v> is the version OpenCode's updater (opencode.ai/update/api/latest/cli/npm) names, never below 2.2.5 and never anything but a plain x.y.z. It is read in the background at most every 6h, with a 3s timeout and no redirects. - x-opencode-project is OpenCode's project id for the folder the agent says it works in: sha1 of git-remote:host/path (origin, else the first remote; worktree .git files followed), else of directory:<root or folder>. It is no longer "global". - b3 and traceparent: one trace a conversation, a new span a request. - The session id goes in x-opencode-session, x-opencode-session-id, x-session-affinity and x-session-id. Accept is */*, and x-opencode-request is gone. - On a free request the agent's own headers (Claude Code's x-stainless-*, Codex's originator) are dropped. Only Content-Type and Anthropic-Version and Anthropic-Beta are kept. - The core tools are edit, glob, grep, read and shell with 2.2.5's schemas, strict false on Chat. Claude Code's Read, Edit, Glob and Grep are offered under those names. Its Bash is no longer bash: shell is a stub. - OpenCode's <env> block, word for word, for the agent's folder, is added to the system prompt unless it has one already (OpenCode's own). - Paths are the v2 catalog's: /inference/openai/v1 for Chat and Responses, and /inference/anthropic/v1 for Messages. The models list is unchanged. Every route takes this: chat, responses and messages through forwardOnce, the Test button's probe (tiny/zenFreeProbe), and the models list (listHeadersAt: UA and x-opencode-client). Sibling: paid Zen and OpenCode Go share OpenCodeClient, so they get 2.2.5's headers. Their /zen/v1 and /zen/go/v1 paths are left as they are: #4740. Run on mote (mote-run) at this tree: - gofmt -l . is clean. - GOOS=darwin and windows go vet ./... pass. GOOS=linux go vet passes for internal/provider and internal/gateway. The whole-tree Linux vet stops in Wails' cgo when run from macOS, and in WSL for want of gtk4, before it reaches this change. - go test ./internal/provider ./internal/gateway -count=1 -timeout 45m: ok provider (154s) and ok gateway (715s) on base |
||
|
|
4c815ac2a5 |
search: searchers picked to follow the one named, tried in their order when it fails (axelburks on Discord)
axelburks asked for more than one searcher, so that when one fails another provider searches. A searcher named in Settings gave way to no other provider before, only to the Search APIs. Automatic already fell back to up to three. - settings: SearcherThen, the searchers after the one named. Entries are trimmed. Blanks, "off", the named one and repeats are dropped. - gateway: when the named searcher fails (the context still live), modelSearch asks each of SearcherThen in order and skips one that can't search now or is the same model. The first that searches answers, and the call is marked searchingInstead, so the Routing row says why the named one didn't search. If all of them fail, their errors go back together, saying "the searchers picked ..., in their order", and webSearch goes on to the Search APIs as before. SearchFailure.Instead names the one that searched in its place. - gui api: searchFailed.instead. A save takes only searchers that Searchers() offers. A save without searcherThen keeps the list, since the page's prefsKeep doesn't send it, and [] clears it. - Settings › Web search (plugins/search/settings.js, outside app.js's budget): an "If it fails" row under a named searcher, with numbered chips and Add. A chip's picker changes the chip or removes it. The row is hidden for Automatic and Off. The failure line names who searched instead, or says the ones after it failed too. The help text says the same in en, zh, zh-TW, ja and de. - docs: gateway-routing's failing searcher, and gui-shell. Tests: - TestPickedSearchersInTheirOrder (gateway): one test where the named searcher answers without searching and one where it fails. A gone entry and one that can't search are skipped, and the third searches once. With no working entry, the error says so and Instead is empty. - TestSearcherThenSaved (settings) and TestSearcherThenFromSettings (gui): what is saved, kept and cleared; refusing an entry that can't search. settings_keep_test sets SearcherThen. - searcher-then.test.cjs: chromium and webkit, en, zh, zh-TW, ja, de, at 560 and 1000 wide. Checks the row's place and words, what Add offers, the posted lists, that the chips fit with no horizontal scroll, that no click moves the page, and both failure lines. Broken by hand: running no fallback turned TestPickedSearchersInTheirOrder red (both subtests: "ds2 searched []"). Not keeping the list on save turned TestSearcherThenFromSettings and the keep test red. Run on mote (mote-run): - At the pre-rebase tree (base |
||
|
|
0b4aa96fd0 |
gateway: a relay whose models are typed in by hand is offered as a searcher (axelburks on Discord)
axelburks added a custom provider on OpenAI's Responses API and ticked "Searches the web by itself", but Settings › Web search's searcher picker didn't offer it. Searchers() and namedSearcher took a provider's models from Available() alone. A relay with no /models list has its models typed in by hand (Exposed) and none available, so it was left out of the picker, while the same row named it among the relays to pick there. searcherModels gives what the provider lists, then the hand-typed ones it doesn't. A relay that lists its models was offered before this already. Tests: - TestSearcherRelayWithoutModelList (gateway): a Responses relay with no /models and a typed model is a searcher and is resolved by name. - TestSearcherPickerOffersResponsesRelay (gui): the relay saved the way the editor saves it is in SearchChoices with its model. Both were red on the old code. Run (mote-run), at this commit alone: go vet of gateway and gui, and go test -run 'Searcher' of gateway and gui: ok. The full checks ran with the next commit; its body has them. Not tried: the reporter's own relay (we don't know whether it lists its models; the reply asks). |
||
|
|
a5a9cdf7be |
gateway: a refused big conversation isn't told again to the Claude subscription's other accounts (Aisiverto on X)
Aisiverto on X: a refused turn of a ~900K-token conversation made magpie switch accounts and send it again, "one user action becomes several expensive requests". In the usage, pairs ~100ms apart: one read the whole conversation from the cache, the other read ~26K and wrote ~877K. The cause: a refusal goes to the next candidate under RefusalRetries (unset: every one left), and matesFirst puts the same model's other accounts first (#248, where a verified account may answer). For a Claude subscription each other account is a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content that it most likely gives too. Now, before a Claude subscription account's try, a conversation of retellMost (100K) tokens or more by estimate (tooBigToRetell) leaves the subscription's other accounts out if that account refuses (otherThanClaudeAccounts). Other members are still asked; with none left the refusal is the agent's, and it isn't handed over mid-stream to nobody (handsOver is given last). A smaller conversation goes to the next account as before. The size is measured only when another Claude subscription account is left. gateway-routing.md says so beside RefusalRetries. Run: - TestClaudeSubscriptionBigRefusalNotToldAgain (new; streamed and not): red on the old code (runs "own,tok-spare"), green with the fix, the agent getting the refusal. TestClaudeSubscriptionRefusalMovesToNextAccount (small conversation, spare still asked), TestRefusalRetries* and TestPolicyRefusal* green. - Broken by hand: tooBigToRetell always false, red. - On mote: gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/gateway ok; go test -tags nogui -timeout 45m ./internal/gateway: ok (702s). The whole suite ran at the parent commit (its body); this commit touches internal/gateway only. Not tried: - The handsOver change: the test's refusal comes with no reasoning before it, so nothing is handed over, and taking the change out stays green. Not covered by a test. - A large conversation where another member of the group is a Claude subscription of a different provider id: it is left out too, as every Claude subscription account is. - A real Claude refusal on a real account. |
||
|
|
2af4d8c62d |
claude bridge: tool results another request answered first branch off the run's session (Aisiverto on X)
Aisiverto on X: a Claude Pro account's five hours went from 96% left to
1% in about five messages of a ~900K-token conversation. The usage had
pairs of requests about 100ms apart: one read ~900K from the cache, the
other read ~26K and wrote ~877K.
The cause: Claude Code's fork sub-agents start from their lead's
conversation, each of the lead's calls answered "Fork started", and they
come with the lead's own next turn. One of them goes on in the run that
made the calls. Each other one (and a resend, or one after the run has
delivered) got a new Claude Code told the whole conversation in one
message, a prefix Anthropic's cache had never seen. So it was written
to the cache again, about a fifth of the plan's five hours each time.
Now the run keeps where in its session each call of the client's tools
was written: the uuid on Claude Code's stream-json assistant line
(noteLines). As it parks, it also keeps the conversation those calls
answered. A request no run takes, whose last reply's calls a live run of
the same owner made from the same conversation, goes on in a -p branch:
--resume <session> --fork-session --resume-session-at <uuid>. That is the
conversation as Claude Code sent it to Anthropic, so it reads the
cache, and it is told only the results and the directive after them. The
lead's session file stays the lead's. There is no branch with client
cache marks, in interactive-only mode, or from a rewound, closed or
sessionless run. Then, and if the resume fails, the old path is taken.
The -p reason is "branch", worded in claudemode.js and i18n.js (zh, zh-TW,
ja, de). The subsystem doc's section says so.
Run:
- Claude Code 2.1.316 (real binary, on mote), against a fake Anthropic API and a
fake MCP tool. --resume S --fork-session works while another
process holds S. --resume-session-at <assistant uuid> cuts the copy
there even after the lead went on, and the prefix up to the tool_use
matches the lead's. Calls it answered nothing for get a
synthetic error result.
- TestClaudeForkBranchesOffTheLeadsSession (new): red on the old code
("told it whole"), green with the fix.
- Broken by hand, each red: park() not stamping the conversation the
calls answered; serveSubscription not asking branch().
- On mote, before the rebase onto origin/main
|
||
|
|
7503beee72 |
plugin, settings: a model's load goes past 100% for a vendor that queues (axelburks on Discord)
axelburks, on v0.1.2547: their vendor queues, so a model's load can be
past 100%, even 200%. magpie clamped every load to 100, and Busy models
last allowed 1-99 only.
- host.js reportLoad and plugin.noteLoads keep a load from 0 up. The
floor is still 0, null still clears it, and a sanity cap of 10000
(LOAD_MOST, plugin.LoadMost) keeps an absurd value from reaching the
UI or the trace.
- settings.BusyLoad takes 1 to 9999 (BusyLoadMost-1). The segment
choices stay Off/50/70/80/90, and a value set in settings.json (150)
shows as its own choice, as before.
- The editor's badge reads "180%". It is a badge, not a bar, so nothing
assumed 100 wide; the test checks it stays on one line.
- Docs: site plugins page (en, zh, ja) Values and Routing bullets, and
provider-plugins.md and gateway-routing.md.
Run on mote via mote-run, on origin/main 8d8df0639+ rebased:
- go test ./internal/plugin ./internal/gateway ./internal/settings -run
'ModelLoad|TestBusy' -v: all pass. TestPluginReportsModelLoad has
over:250 kept and huge:1e9 at 10000. TestBusyModelGoesBehind has 180
behind 120 at a threshold of 150, and 10000 refused.
- Broken by hand in a copy, with the old 100 clamps and the 99 limit:
TestPluginReportsModelLoad red ("ModelLoad(over) = 100; want 250"),
TestBusyModelGoesBehind red (150 refused).
- node --test model-load (with Queued 180% in every language, Chromium
and WebKit, 420 and 900, plus Over 150% picked at 420) and i18n-keys:
46/46 pass. go test ./internal/gui -run Budget: ok.
- gofmt -l: empty. GOOS=linux go vet -tags nogui and GOOS=windows go
vet on plugin, settings and gateway: ok.
Not run before the push (owner: push and tag first): go test ./... and
the whole GUI suite. They are queued on mote behind another session's
suite.
|
||
|
|
f2f75ee4ae |
provider: Volcengine Ark's System One API, in beta, as a decider (axelburks on Discord)
Ark answers System One at https://ark.cn-beijing.volces.com/api/v1/systemone (and /api/v3/systemone) only with the beta header ark-beta-systemone-api: true; without it the reply is a bare 404. The new volcengine-decision preset asks it with an Ark API key, and magpie sets the header (DecideHeaders) on Ark's own host only, ark.<region>.volces.com, in both the gateway's /v1/systemone and the provider's Test. Its decision model, doubao-seed-2-1-lite-260915 (ArkDecision), is kept apart from Ark's chat list as Bailian's is (vendorDecision), since no /models names it. Learnt from the real API on 11-01 with the owner's Ark key (read from magpie's config, never printed): only doubao-seed-2-1-lite-260915 answers; doubao-seed-2-1-pro-260628, doubao-seed-2-0-lite-260428 and deepseek-v4-1-flash are refused 400 "does not support the SystemOne API". The Coding and Agent Plans' paths (/api/coding/v3, /api/plan/v3, their v1s) answer an empty 404 even with the header, so it bills as pay as you go. An image in the request was left unread (a red square came back 0.48, input tokens as for no image), so images are off. The tests' replies are the real response bytes. Run: - Real: a magpie built from this tree on mote, in a sandbox HOME: `magpie provider add volcengine-decision <key>` and `provider test` (decide ok, 413 ms), then `magpie serve` on a free port and POST /v1/systemone through it: a real 200 with Ark's choice. - gofmt -l internal/: clean. go vet darwin, linux, windows of internal/provider and internal/gateway: ok. - mote-run go test -count=1 -timeout 45m ./internal/provider/ ./internal/gateway/ ./internal/gui/ ./internal/cli/ at base |
||
|
|
788057340b |
library: Magpie Image Recognition in Discover beside Magpie Image and Web Search (matrix0487 on Discord, #4653)
matrix0487 asked on Discord (#feedback) for all three of magpie's own MCP servers, image recognition, image generation and search, in the Library's Discover. Image generation and search were there; image recognition was an address to copy in Settings only (#4653). - `magpie mcp vision` (browsermcp.RunVision) relays stdio to the gateway's /mcp/magpie/vision, as `mcp search` does. analyze_image's relative image path is made one in the agent's folder on the way (imageFrom), since the gateway can't know where the agent runs; an absolute path, ~, a URL or a drive goes as written. - library: magpie-vision is a featured, opt-in server (no agents until picked), any binary's `mcp vision` is one server (serverKey), and it gets the 120s tool timeout (selfTimeout). - Settings › Models › Images: the Image recognition row has Give agents Magpie Image Recognition… / Turn on the Library, none with recognition off or in gateway mode. The three links are one helper, libWay, used by Image generation and Web search too (no budget raised: core 1,533,011 of 1,533,105). - Never a dead tool: Discover lists all three whatever is set up, and one that can't answer yet says why (gateway.OwnUnready, set by /api/library/market/servers as `unready`): a "Not set up yet" badge on its card with the reason as its title, and the reason in its sheet (nothing set up, or turned off in Settings / Plugins). It can still be added; its tools already answer with the same reason until then. - Strings in en, zh, zh-TW, ja, de; docs/subsystems/library.md. Run, all on mote (macOS 27) through mote-run, at this head's tree (rebased on |
||
|
|
8d8df06399 |
plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.
- A provider plugin calls input.magpie.load(provider, {"<model id>":
0-100 | null}) whenever it likes, from its own timer. host.js
(reportLoad) clamps each number to 0-100, null clears a model, every
other value is dropped, at most 1000 a call, and it returns the count
taken. A provider that isn't a string or loads that isn't an object
throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
id. ModelLoad answers unknown once a load is older than LoadFresh
(5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
1-99 by hand): restLast puts a model reported over it behind the
ready candidates, ahead of the resting. The trace row has busy:<load>.
At a new turn affine moves a conversation off it (Why "busy",
busyBehind); within a turn it stays. after, readyForNew and leastHeld
skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
table; docs/subsystems provider-plugins.md and gateway-routing.md.
Run, all on mote via mote-run at a42736807's tree rebased on
origin/main
|
||
|
|
b683f1c0e1 |
gateway: a search on Volcengine Ark asks for no include value Ark refuses
axelburks on Discord #feedback (1566310723922042991): every web search on an Ark model (ark.cn-beijing.volces.com) failed with 400 "The parameter `include` specified in the request are not valid: unknown type: web_search_call.action.sources". buildResponses adds that value to every Responses request offering web_search on any host but api.x.ai (#315, |
||
|
|
ed5872d186 |
gateway: a kept previous response holds its input, not the body it came in
previousResponse kept each turn's input items as views into the request body, so every response kept for previous_response_id held its whole body: tools, instructions and anything else the client sent. own counted only the items, so prevCap's 256 MB bounded far less than was held. The input is now copied out (ownItems, as the Codex socket does since |
||
|
|
ec0a11d47f |
gateway: a Codex socket's held reply keeps its input, not the frame it came in
A held turn's fresh input items were views into the response.create frame they were decoded from, so each held reply kept that whole frame alive: Codex's tools and instructions with it, for as long as the socket held the reply (~39 MB of a long session's live heap). keep now copies the fresh items into one buffer of their own; the conversation held before is already owned, and the reply's items were already copied. Run on mote: go vet ./internal/gateway; go test -run 'TestHeldTurnOwnsItsInput|TestResponsesSocket|TestCodexSocket' ./internal/gateway ok. Broken by hand (keep appends fresh as views): TestHeldTurnOwnsItsInput fails, held items read back as the overwritten frame. Not run: the full gateway package before the push, and a real Codex session over the socket. |
||
|
|
36af588e2c |
gateway: "Context window is full" is a conversation too long for the model
ergou0954_54426 on Discord (#feedback, 11-01) routes by intent across several models, one a "kiro opus" of an API-key relay (not magpie's Kiro plugin). On long conversations the relay answered 400 "Context window is full. Reduce conversation history, system prompt, or tools. (request id: …)". That is the wording kiro.rs (src/anthropic/handlers.rs) and kiro2claude (error-mapper.ts) give Kiro's CONTENT_LENGTH_EXCEEDS_THRESHOLD, always as a 400 invalid_request_error, with new-api's request id after it. tooLongRe had no words for it, so the 400 was an ordinary request error: the group never asked the next member, and the agent got the relay's 400 as a plain error, with no context_length_exceeded to compact on. In a stream's error event it stood for a 502 (streamStatus), a passing vendor fault that rests the account and is asked again. tooLongRe now takes "context (window )?(is )?full", so overflowed, failure, retryable, streamStatus, lateRests and writeErrorSaid all read it the same way: on 400, 413 or 422, or in a stream's error event, the member is passed for one with room (failOverflow, no rest), and alone the agent is told context_length_exceeded. Not changed: a 5xx carrying the words is still the vendor's fault (tooLong is 4xx only, as TestContextOverflowSaidTheClientsWay holds for a 502), and tooLongUnsaid still covers a 5xx only where the window is known. Routing could not have skipped the member up front: a custom relay's model has a window only from its own /v1/models list, models.dev by id (catalog.ContextOf, with its spellings), or the user's Context setting. A relay id such as "kiro-opus" matches none, so the window is unknown (0), roomy keeps it and withRoom counts it as having room. A probe in a fresh HOME gave windowOf 0 for claude-opus-4-6, kiro-claude-opus-4.6 and kiro-opus on a custom provider. TestContextWindowFullIsAnOverflow and TestContextWindowFullGoesToAMemberWithRoom are built from the literal text, with and without the request id, Anthropic- and OpenAI-shaped, plus kiro.rs's sibling "Input is too long. Reduce the size of your messages."; ordinary 400s (invalid model, model not found, messages required) stay non-overflows. Found and filed, not fixed: the last candidate's stream error event that says too long reaches the agent as the vendor wrote it (#4675). Run on mote, on this change at base |
||
|
|
6d23a4282f |
provider: whether a model sees images doesn't wait for usage readings; start ~9 s → <3 s
magpie's gateway listened ~9 s after start. A goroutine dump 3 s in had
main in provider.Allowances' first-ask wait: the start's migrations
(agent.RenameLegacy) read Pi's effort field, which builds Pi's model list,
which asks provider.Described (does any model see images), which ranks
the vision models by spent accounts, which asks each agent's allowances.
Each agent's first ask waits firstWait (3 s) for its accounts' usage over
the network. Every agent's model list asks Described, so the GUI's first
lists waited the same way.
Described only asks whether a model is there, not which account a request
goes to, so it now runs under provider.Unwaited: Allowances answers from
what is last known (the readings kept on disk) and starts the reading
behind it, as after firstWait. A request routed by the gateway still waits
as before.
Real history in a sandbox HOME (17,140 session files, every account
copied from this Mac's), the network blocked by a dead proxy, `magpie web`
started twice each:
- before (v0.1.2528 tree): gateway up at 9.8 s and 8.8 s.
- this change: 2.8 s and 0.6 s; first /api/sessions answered at 4.5 s and
2.1 s, against 12.2 s and 10.7 s.
Tests, on mote: TestUnwaitedAllowancesDontWait is new. Broken by hand
(Allowances waiting under Unwaited too) it fails: "took 20.0s".
go test ./internal/provider/ ./internal/gateway/ ./internal/agent/ ok
(gateway 740 s). gofmt -l clean; go vet (darwin), GOOS=windows go vet,
GOOS=linux go vet -tags nogui of provider and gateway ok.
Not run: the full suite; a start with the network up (the wait there
was the vendor's answer time, up to 3 s an agent); Windows and Linux.
Picked onto
|
||
|
|
2be5d206e1 |
gateway: a Codex summary request too large for the vendor is asked again as text, then compacted locally (celestial_eagle_99230 on Discord)
celestial_eagle_99230 (Discord #general, v0.1.2403) runs Codex on official DeepSeek (DeepSeek-V4.1-Flash, 1M window) and gets "413 Request Entity Too Large: Failed to buffer the request body: length limit exceeded". The turn path was fixed by |
||
|
|
90c02326bb |
gui: an app takes the gateway over from its older copy once idle, and says any other version serving it (matrix0487)
matrix0487 on Discord: after an update, pi said 404 'magpie knows no model "kimi/k3.1-pro" ... add a provider in magpie first'. The app had written pi a model its older gateway didn't know, and updating the gateway fixed it. A magpie that finds another one serving the gateway used to log it and wait for that one to quit (watchGateway took the port only once nothing answered). Only the Gateway page said so. Now (otherServes, gateway_older.go): - An older released copy of the app (it says serves app or tray, and a pid) is this app's predecessor. Once its /v1/magpie/concurrency says nothing is in flight (gateway.ServedBusy; unknown is never idle), the app quits it the way the Gateway page's button does (quitMagpieOnPort: a magpie only, by its program) and serves the gateway. A stream through it runs to its end first. watchGateway looks again every 15s while another serves. At most three times a run; a quit that fails is left to the button. - Any other one (magpie serve or the service, magpie web, a TUI, a newer magpie, a build of its own) is left running. /api/state carries it as gatewayOther, and the Agents page says it above the list with what to do, plus the take-over button for an older one (gatewaySkewLine, in plugins/gateway/client.js so app.js stays under its budget). A dev build of this magpie says nothing. New strings in zh, zh-TW, ja and de. How the reporter's older gateway outlived the update isn't known: they never said whether one ran separately. A failed handover leaves the old app serving for up to 15m, and a magpie serve left running is another source. Both are covered now: the first is replaced, and the second is said. Known gap: a request that starts between the idle read and the quit gets the older app's short drain. A socket handover between two running apps (no gap) is not built. Run on mote at 0f8ea30bb (this change on |
||
|
|
0c31638045 |
kiro: the mover installs 0.1.24, which says a too-long conversation as one
ergou0954_54426 on Discord routes by intent across Kiro's Claude and GPT models and DeepSeek, and sometimes a turn failed with Kiro saying the context was exceeded. Kiro says a conversation is past the model's window in three ways, and the plugin up to 0.1.23 turned only the HTTP 400 into the "input is too long for the model's context" that the gateway reads as an overflow (tooLong). The same ValidationException as an exception in Kiro's event stream came out as a 502, so the gateway took it for a passing vendor fault: it rested the account, asked Kiro again (15 asks for a lone provider in a probe), and never told the agent context_length_exceeded, so the agent never compacted. A reply Kiro stopped with MODEL_CONTEXT_WINDOW_EXCEEDED came out as finished. plugins e8050e8 (kiro 0.1.24, on npm) answers both as the 400 that says too long. Routing was already right: roomy skips a member whose known window the request is past, and withRoom moves an overflow to a member with room. The min goes to 0.1.24 so keepMovedCurrent updates every moved user. TestKiroMoverHasTheTooLongFix holds it there. TestKiroPluginOverflowGoesToAMemberWithRoom pins what the gateway does with 0.1.24's two wordings: in a group the other member answers, the try is failOverflow with no rest, and alone the agent gets context_length_exceeded after a single ask. Run on mote: go vet ./internal/provider ./internal/gateway; go test -timeout 45m -count=1 ./internal/provider (ok 150s) ./internal/gateway (ok 712s). gofmt -l clean. Broken by hand: at origin/main's min 0.1.23, TestKiroMoverHasTheTooLongFix fails. A probe with 0.1.23's 502 body showed Fail other, a rest, and a vendor 502 for the lone provider. Not run: the full ./... suite (another session's full suite held mote), and a real Kiro account pushed past its window. |
||
|
|
f435aadbf3 |
gateway: an image is described once, whatever model describes it, and a canceled request stops its descriptions
Pkh on Discord (0.1.2509, Linux, QwenPaw, Auto routing): with images in the conversation, the Routing view filled with "Image description" rows, one request asking for 63 in ~60ms, and the request they were for had no row of its own. Causes, each red on origin/main |
||
|
|
9be72c9480 |
zcode: a level's thinking carries its budget, and the user's own level options stay (#3852)
Review of d7e1e284f, two things it changed beyond its case:
- Every level that thinks was written as {"thinking":{"type":"enabled"}}
with no budget_tokens. ZCode puts a level's options in the request, so
a Claude before 4.6 (Sonnet 4.5, Haiku 4.5, a relay's) asked through
magpie at any level would be sent "enabled" without the budget
Anthropic's Messages API requires with it, a 400 it didn't get before.
Each level now carries the budget the gateway reads that effort as
(gateway.ThinkingBudget, budgetOf: low 4096 ... max 32000). The
gateway already makes it adaptive for Claude 4.6 and later
(adaptiveThinking; ZCode's output_config.effort wins over the budget)
and fits it under max_tokens (maxoutput.go).
- providerOptionsByLevel was written over on every sync. A user who put
their own there (the workaround for this very bug) lost it. A level's
options already in config.json now stay; no magpie before #3852
wrote any, so whatever is there is the user's.
Tests: TestZCodeOutputAndReasoning expects the budgets;
TestZCodeKeepsTheUsersLevelOptions keeps a hand-written high level and
fills the others.
Run on mote: go test -run TestZCode ./internal/agent, ok. Broken by
hand: the kept options ignored and the budget left out, and those two
tests fail.
Not tried: a real ZCode 3.x (this Mac has Z Code 0.9.1, a different
app; mote has none), so ZCode putting the options in the body is the
reporter's and the author's reading of zcode.cjs, not seen here.
Batch record (gua's #2833 #3052 #3205 #3867 #4107 #4247 #4245 #4113
#3852 and the three review follow-ups; #4106 left out, its test isn't
red without its fix, see the issue):
- Full run on mote before the rebase (base
|
||
|
|
15ffd3b681 |
gateway: a compaction rule sees Alma's first compaction too (#2833)
Review of e72e97ef9: it knew Alma's compaction only by the ask of a later one, "Merge the previous summary with the new conversation.". Alma 0.4.335 (its app.asar, read on this Mac) has two: the first compaction asks "Here is the full conversation to compact." under the system prompt "You are compacting a long conversation so it can continue WITHOUT losing context.", and a merge sends "You are UPDATING an existing conversation summary ..." as its system prompt. The ask and both system prompts are now known. TestRuleCompactAlma also posts the first ask, and each system prompt with an unrelated user message. Run on mote: go test -run TestRuleCompactAlma ./internal/gateway, ok. Broken by hand: the three new entries taken out, and the three new cases go to the other rule (b/big). Not tried: a real Alma compaction through magpie. |
||
|
|
73528a9a03 |
gateway: x-bili- headers go only to a /bili/ URL of the user's own provider (#3052)
Review of 5d5a148ab: it sent every x-bili- header the agent sent to every provider, Claude and Codex accounts and every vendor included. They are the billion-context proxy's own headers, so they now go on only when the request's URL is in bili's prefix form (http://host:8787/bili/<upstream>, the form its README gives for putting it in front of a gateway and the one the report uses), and never for a signed-in account. TestForwardOnceKeepsBiliHeadersFromOthers: a plain URL, a URL with /bili/ deeper in its path, and an account on a /bili/ URL get none. TestForwardOnceCarriesBiliHeaders now posts to a /bili/ URL. Run on mote: go test -run 'TestForwardOnce(Carries|Keeps)BiliHeaders' ./internal/gateway, ok. Broken by hand: the condition set to true, and the new test fails for all three requests. Not tried: a real bili proxy. |
||
|
|
9a951eb038 |
gateway: end the cgroup memory walk at "/" on every host (#4113)
What: the cgroup v2 walk read the path from /proc/self/cgroup with
filepath, whose separators and root are the host's. On Windows the
root is "\", so filepath.Clean("/"+dir) was
"\system.slice\magpie.service" and filepath.Dir stops at "\", which
is never "/": the loop read \memory.max and \memory.high until the
suite's timeout, holding internal/gateway with no result on Windows
(TestClaudeMemRunsFromTheCgroup, 45m). The cgroup path is a "/" path
whatever the host reads it on, so the walk is path's now (Clean, Dir,
and the label's Join); filepath.Join stays only for the limit file
under the cgroup root, which is a host path. On Linux and darwin,
where filepath's file is path's own code, nothing changes: the walk
reads the same files and the limits, and the "cgroup ..." label, are
byte for byte what they were.
Run: TestClaudeMemWalkEndsAtRoot is new: it runs memLimit("linux", a
fixture whose cgroup path is /system.slice/magpie.service) under a
one-minute watch and fails if the walk never ends at "/". On this
macOS machine it is green before the change too — filepath is path's
code there, so old and new cannot disagree on unix; on Windows it is
red before the change by construction (filepath.Dir of "\" is "\"),
and Windows is the reported host: the reporter's 45m stack at main is
the red this test gives there. With the change it passes, and
go test -count=1 -timeout 45m ./internal/gateway is green (461s),
-tags nogui green (464s); gofmt -l clean; go vet ./... on darwin,
GOOS=linux -tags nogui and GOOS=windows clean (the internal/gui cgo
warnings are main's); go build on the three.
Generated-by: GLM-5.3-Flash (ZCode)
|
||
|
|
0d76d16ec6 |
test(gateway): let only the gateway's deadline end a stall's fake answer
What changed: the fake relays in TestStalledAnswerSaysUrlOrB64 and TestVendorThatStopsMidAnswerIsSaid waited on r.Context().Done() with a time.After(5 * time.Second) fallback of their own. Under load the fake's 5s could end its answer before the gateway's 500ms stall deadline (drawUnit = 100ms) was acted on, so the gateway read a cut body and said 502 "isn't an images API's: unexpected end of JSON input" instead of the stall's 504 (#4245). The fakes now wait on the context alone: the deadline's cancel is what ends them, so the order can't flip. No product behavior changes; both tests still assert the same 504 wording. Run: go test ./internal/gateway -run 'TestStalledAnswerSaysUrlOrB64|TestVendorThatStopsMidAnswerIsSaid' -count=5 - ok. go test -tags nogui -timeout 45m ./internal/gateway/... - ok (500s). go vet ./... and GOOS=windows go vet ./... - ok; GOOS=linux go vet ./... fails in wails (undefined: pointer) at the base commit too. CGO_ENABLED=0 GOOS=linux|windows|darwin go build -tags nogui . - ok. Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
837ea5f565 |
gateway: a Kimi tool schema with items is an array, not its enum's string, as Gemini's is now (#3867)
yetone, #3867: kimiSchemaType and collectUntypedEnums read an untyped schema's enum or const before its keywords, so a tool's {"items":{"type":"string"},"enum":["a","b"]} reached Kimi typed "string" with items beside it — the shape its Gemini sibling went out in until |
||
|
|
7bdf08f18d |
gateway: no type beside the $ref a Kimi schema's target is
kimiToolRefTypes wrote a type into each schema a tool's $refs reach that
has none. When the target was itself a $ref — zod writes one beside what
it changed of a reused schema, a format and a description among them, as
Codex's automation_update's targetThreadId reaches {"format":"uuid",
"description":"tt","$ref":"#/$defs/__schema1"} — the type went beside
that inner $ref, and Moonshot refuses one there, 400 "At path
'$defs.__schema14': when using $ref, type should be defined in the
referenced schema instead of the parent schema" (#3205), so every turn
failed though the tool is never called. The plugin side had the same bug
and fixed it in kimi-work 0.1.5.
The chain a $ref names is now followed to the schema it ends at, and it
is there the type goes, or nowhere when the chain ends at a ref to
nowhere or never ends: schemaTypes already resolved chains to say what
the type is, so only the place it is written moves. Codex's own
automation_update schema (the fixture its tests and magpie's root-union
tests share) goes as it was sent: its defs are notes beside a $ref to a
typed target, which Kimi takes.
Fixes #3205
Generated-by: GLM-5.3-Flash (ZCode)
|
||
|
|
ee031e9539 |
gateway: a billion-context proxy in front of the provider gets the client's x-bili- headers (#3052)
What changed: forwardOnce copies the client's x-bili-* headers on to the request it builds for the provider, by a biliHeader predicate beside claudeCodeHeader and codexClientHeader — an x-bili- prefix, in the shape of the anthropic-, x-stainless-, x-claude-code-, x-openai- and x-codex- families already on the allowlist. The headers carry the cooperative plugin's name, conversation and context window, never a key; a header no family allowlists, and the client's own key, still stay off. Why: forwardOnce builds the upstream request from nothing and copies only allowlisted headers, so a client talking to a billion-context (bili) proxy put in front of its provider lost the x-bili- ones that name its cooperative session — bili then saw an anonymous session and injected a duplicate set of compression tools beside the plugin's own (#3052). Whether to generalize this into a per-provider "pass-through client headers" setting, beside PassUserAgent (#1851) and a provider's own Headers, is the maintainer's call; this change only admits the family the issue reports. Run: go test -run TestForwardOnceCarriesBiliHeaders ./internal/gateway fails on the baseline with the three headers empty and passes with the change (httptest, no network); ablation (product file back at baseline, test kept) fails again. gofmt -l clean; go vet ./..., GOOS=linux and GOOS=windows go vet -tags nogui ./... clean; native, GOOS=linux -tags nogui and GOOS=windows builds clean; go test -tags nogui ./internal/gateway green. Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
f0ff905167 |
gateway: a compaction rule sees Alma's compaction ask (#2833)
What changed: compactAsks in internal/gateway/compacting.go gains Alma's compaction ask, "Merge the previous summary with the new conversation.", which opens the last user message of Alma's compaction request. A group's compact rule now matches it. No compactSystems entry was added: neither the repository nor the report carries the opening of Alma's compaction system prompt, so none is invented. Why: compacting.go matched the compaction prompts of Claude Code, Codex, OpenCode, Pi, Gemini CLI, Qwen Code, Minis and Kimi Code literally. Alma was not in the table, so its compaction fell through to the intent classifier and was routed by another rule's model, making every compaction cost more than the group's compact rule intended. The ask sits at byte 0 of the user message, well inside compactLead (2048), so one table entry recognises it. Test: TestRuleCompactAlma drives a group whose rule 1 is compact and rule 2 is tokens >= 1 through the gateway. With the fix the Alma request is answered by rule 1's member and X-Magpie-Model says a/small; without it the request goes to b/big. The same test asserts a long message that only quotes the ask past compactLead is not a compaction; raising compactLead makes that assertion fail, so the bound is what keeps notes from matching. Run: go test -tags nogui -count=1 -run 'TestCompact|TestCompacting|TestRule' ./internal/gateway/ (ok, 2.839s); go test -tags nogui -count=1 ./internal/gateway/ (ok, 344.144s); go test -race -tags nogui -count=1 -run 'TestCompact|TestCompacting' ./internal/gateway/ (ok, 2.172s); gofmt -l internal/gateway/ (empty); go vet -tags nogui ./internal/gateway/ and with GOOS=linux and GOOS=windows (all ok); go build -tags nogui ./..., GOOS=linux go build -tags nogui ./..., and GOOS=windows go build -tags nogui -o /dev/null . (all ok). Not tried against a real Alma client: the wording is quoted from the report. Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
ccb75030aa |
gateway: a held request body is known by where it is, not summed again (#4371)
Each of the dozen decodes, topMember reads and validity checks a request
body goes through summed all its bytes with maphash to find what
validMemo knew of it: about 5% of the gateway's CPU on long Codex
requests (#4371). A body being served (holdBody) is not written while
held, so longBody and jsonValid now know it by its address and length,
check and split it once, and keep that in heldBodies.long until it is
released, as factsOf keeps its facts. Any other long body is summed as
before.
Run on mote at this tree:
- gofmt, go vet (darwin, GOOS=windows, GOOS=linux): ok
- TestHeldBodyIsNotSummed, TestHeldBodyNotJSON, TestDecodeJSON*,
TestRequestBodyRawValuesShareIt, TestTopMember*, TestWithoutTopMember*:
ok 3 of 3 alone, ok under -race
- go test -timeout 45m ./internal/gateway: ok (609s)
- Broken by hand: held lookup skipped -> "a held 84077-byte body was
summed 18 times"; release left the finds kept -> "a released body's
finds were kept".
- BenchmarkHeldBodyDecodes (1.8MB Responses body held, 12 decodes plus 12
topMember reads an op): 3.31ms/op before, 7.9us/op after, allocations
the same (24/op).
Real use: sandbox HOME copied from the owner's, real DeepSeek account,
deepseek-flash, four turns of a 115-123KB history through
/v1/chat/completions with masking on: every reply HTTP 200 (three "ok",
one empty at finish_reason length, the model's reasoning using
max_tokens, as on the old binary).
Not run: the full ./... suite; a real Codex account; Windows and Linux
runs of the tests.
Picked onto
|
||
|
|
9162277b91 |
routing: Until used up stays on the next account once the first is used up (dzxx0496)
dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.
A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.
Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).
Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
through a rate limit, all used up, a seat gone, per pool, Forget,
Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
In order goes back to k1. Red without the Drained hook (request 3 went
to k1). A rate limit comes back to k1; drain is saved on a provider and
a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
languages, 1100px and 420px, Chromium and WebKit; red on the old assets
(20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.
Run on mote (macOS) at origin/main
|
||
|
|
699ddf1524 |
gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then the subscription's credits. Until now an account at 100% that holds credits either kept its place and spent them there (on) or was held (off). This adds a third way per account, "last": - settings: CodexCreditsLast []string, empty by default, so a setting saved before it keeps its order. provider.CodexCreditsLast, CodexCreditsMode and SetCodexCreditsMode(user, on|last|off); SetCodexCredits(on) still means "in its place" and clears last. - gateway: candidate.creditsLast is true for such an account once a window for the model is used up and it is going on its credits (a call ChatGPT counts in no window stays in its place). restLast orders ready, then resting, then those, and marks Weighed.CreditsLast. restLast runs over the asides too, so such an account goes behind a provider's reserves (Accounts at once, |