Commit Graph
21 Commits
Author SHA1 Message Date
yetone a1c30b5be9 gateway: a user message the agent wrote alone is no new turn, and routing asks about and keys on the user's own words (#1826)
What: one helper, userWords/userSaid in prompt.go, says what the user
said in a text: it drops <system-reminder …> blocks (now with a source=
attribute too, as ZCode sends) and any text that begins as an agent
writes for the model alone, and keeps only what follows the Codex app's
"## My request (for Codex):". The leads, beside agentsFor: Codex's
<environment_context>, <user_instructions>, <turn_aborted>,
<user_shell_command>, <subagent_notification>; Claude Code's and
ZCode's <task-notification>, <subagent-notification>, agent lists
("Available agent types …", "New agent types are now available …"),
TodoWrite and task-tool nudges, rewind notices; ZCode's
<plugin_reference>; the Codex app's <in-app-browser-context …>. Each
was taken from the clients' own code or a real transcript (Claude Code
2.1.296, ZCode.app's zcode.cjs, Codex CLI 0.162.1, ChatGPT.app).

Everything that asks "did the user say something" now goes by it:
- turnIn: a user message with nothing of the user's (and no image or
  file) begins no turn. After an answer or a tool round it carries the
  turn on (within), so the turn's rule and stick hold and the classifier
  isn't asked; right after the user's own message it leaves that turn as
  it began.
- userText: the classifier is asked about the last user message with
  words of the user's, only those words (it was the last user message,
  ZCode's agent list after the user's plugin question).
- firstWords (ruleKey and the affinity scope): the words of the first
  user message that has any, so an instruction file or notice the agent
  changes beside them no longer moves a conversation to a new key
  mid-turn. A conversation with no words yet keys on its first message
  as before.
- lastUserText (Copilot's Auto, a sibling): the same.
- userSays (the prompt breakdown's turns) is userWords != "".

Why: #1826 (ZCode) and @321sssrt-bit's comment (Codex): a TodoWrite
nudge was classified as a new, harder turn and sent a 常规 turn to the
复杂 member; a task notification or agent list re-classified the turn;
one ZCode session had three firstWords keys, and the turn that lost its
key fell to the group's first member.

Upgrade: a conversation whose first user message held injected text
gets a new key once (its words only), so its stick and turn rule are
looked up afresh on the first request after the upgrade.

Run: user_said_test.go (TestTurnInSkipsWhatTheAgentPutIn,
TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid,
TestLastUserTextSkipsWhatTheAgentPutIn,
TestIntentHoldsPastWhatTheAgentPutIn end to end through the server,
TestUserSaysPastAReminderWithASource) fails on the old code (all six
red with the five source files put back) and passes now; go test
./internal/gateway -count=1 green (323s); gofmt -l clean; go vet ./...
on darwin, GOOS=linux -tags nogui and GOOS=windows clean.
Not tried: a live ZCode, Claude Code or Codex session against a
group with intent rules; fixtures are the clients' literal strings.
Not done here: persisting turnRules beside the sticks (the issue's
idea 3); the classifier-failure fallback is the next commit.
2026-10-13 00:19:50 +08:00
yetone 908c910931 gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
2026-10-12 23:16:54 +08:00
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00
yetone 35eea09464 gateway: a provider routed its own way keeps that order inside a group that routes another way (kchen0x on X)
kchen0x had a Smart routing group with Antigravity (9 accounts, set to
按顺序) and a Business account. Requests still went to the 9th account, the
one renewing soonest. planLevel pooled every member's keys and accounts
into one list for any group not routed in order, so the provider's own
routing was never read; Smart then put the soonest renewal first.

Now a member whose provider routes other than Smart, and other than the
group does (ownRouting), is planned as a nested group already is: a unit
weighed by the first account or key it would try (firstAwake), then tried
whole in its own order. A provider left on Smart is pooled as before.
leastHeld, which reorders a rotate group's first request, leaves such a
group alone as it does one holding a nested group (without that, a
rotate group still came back "k2 k1 k3 kb").

GUI hint (GROUP_NEST, 4 languages), start docs (en, zh, ja) and
gateway-routing.md say so.

Run:
- TestProviderKeepsItsOwnRoutingInAGroup covers outer Smart, rotate,
  usage, pace and manual, plus a Smart provider still being pooled. On
  the old planLevel it fails with "k3 k2 k1 kb" (the reported order).
- go test -tags nogui -count=1 -timeout 40m ./...: all ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet ./internal/gateway.
- GUI: i18n-keys, gui-ja/de/zh-tw and every *group*/*routing* test, both
  engines: 765 pass. A first run beside the full go test had 9 webkit
  timing reds (routing-group-fold, routing-keys-fold, routing-ctx-still,
  gateway-key-groups); each file passes alone, and the whole set passes
  when nothing else runs.
2026-10-11 19:54:55 +08:00
yetone 0d20aaba45 gateway: under In turn routing, new conversations sent at once spread over the accounts instead of all going to the one least held, which held one Antigravity account busy while the others sat idle (#1342, handong66)
leastHeld counted only conversations already answered, so every new
conversation in a burst saw the same counts and picked the same account.
A conversation that is opening now counts until it is answered or its
request ends.

Run: go test -tags nogui ./internal/gateway (ok); -race -count=5 on the
rotate/affinity tests (ok); go vet darwin, linux, windows (ok).
TestRotateSpreadsABurstOfNewConversations fails without the fix
("k1 got none of 6 new conversations sent at once ...: map[k2:4 k3:2]",
3 of 3 runs).
Not tried: a real burst on Antigravity accounts. The default (smart)
routing keeps using the first account while it has quota, by design.
2026-10-09 01:29:46 +08:00
yetone 555f570660 gateway, provider: the Routing page says what a lone key or account has left, and a key bought as a plan (Kimi Code, GLM Coding Plan, MiniMax, OpenCode Go, Command Code) is weighed by its plan's windows (#1016, gphysign: Kimi Code (China) with one key on, Smart routing; the card said only "Kimi Code (China) 只启用了一个 Key,无需选择。" while /v1/magpie/quotas had its 5 hours 49 used, 51 left and its 7 days 45 used) — two gaps. weighRouted returned before reading anyone's allowance when there was one candidate, so a lone key or a lone subscription account was never known in the trace, and the Routing page, which shows a bar and "{n} used · renews in {d}" for a known row, had nothing to show; every single-account subscription said "what's left not known yet" the same way. And KeyAllowance read only a sub2api key's limits, so a key whose plan the Usage page reads (planQuotaSourceOf: Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code) was never known to routing, with one key or several. weighRouted now reads what each candidate has left before returning a lone one (one alone is still weighed against nobody). readsKeyWindows takes a plan key too; keyWindows reads it through planKeyWindows (planWindows, with Zhipu's team quota behind a key that has none of its own, as PlanQuotas does), and PlanQuotas' own read of a card is noted for routing at once (noteKeyAllowance), so the Usage page and routing never ask twice; the card kept on disk seeds it after a restart (keyCardTag keys a plan card as plan:, a sub2api one as balance:). A key at such a vendor that turns out to be pay-as-you-go, with no windows, is asked again every 30 minutes (keyNoWindowsAge), not every minute it is used. So, beyond the issue: several plan keys on one provider are now weighed by their windows under Smart, usage and pace, and a plan key the vendor refuses as out of quota rests until its window renews and comes back once read short of full, as a sub2api key does. affine no longer says a lone key or account all but used up "moved" its conversation: there is nobody to move to (at > 0). The GUI needed no change. TestLoneOneTellsWhatItHasLeft (a lone Kimi key known at 49% with both renews, the week first; a lone Codex account known; a plain DeepSeek key not), TestLoneSpentKeyKeepsItsConversation (fails with the at > 0 guard taken out), TestPlanKeyAllowance (the windows read behind the request, asked once; DeepSeek and Moonshot keys never asked), TestPlanKeyAllowanceFromItsCard (PlanQuotas' read known at once without a second ask; after a restart with the vendor down, the card on disk stands in and a failed read keeps it) and TestPayAsYouGoKeyAskedSeldom (a GLM pay-as-you-go key asked once, not two minutes on, again 31 minutes on) all fail without the change and pass -race -count=20 (provider) / -count=10 (gateway). routing-key-windows.test.cjs gains a lone Kimi Code key at 1100px and 440px (the one-key story, the row's bar at 49%, its provider row "49% used · renews in …" fitting, no sideways scroll) and passes in full on Chromium and WebKit in en, zh, ja and de; routing-quota-left and panel-routing pass. go test -tags nogui ./internal/..., go test -race on ./internal/provider and ./internal/gateway in full, go vet, gofmt -l, darwin, linux and windows (nogui) builds pass. Not tried with a real Kimi Code key. StepFun's Step Plan is read through a sign-in, not the key, so it isn't one of these. docs/subsystems/gateway-routing.md, providers-accounts.md and docs/reference.md say it. 2026-10-06 20:25:04 +08:00
yetone aab93f9fa8 gateway: in turn, a new conversation goes to the model or account the fewest live conversations are on, so two sessions of one routing group kept for the session no longer share a model (#946, Moody-Sin) — in turn counts requests, not conversations, so a second session started after the first had sent an even number of requests went to the model the first was kept on. leastHeld counts the conversations of the scope answered in the last 30 minutes per key/account and model and puts the least held first; ties, resting ones and a group with a group in it keep routing's order. TestRotateSpreadsSessions is new and fails (after 2 and 4 requests) without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows), the gateway package and go test -race -count=20 of TestRotateSpreadsSessions/TestAffinity pass; go test -tags nogui ./... under a temp HOME failed only TestWSLProbeFindsBunOmp, TestProvidersAnswerWhileListsComeIn, TestUserPath and TestClaudeSignedOut under the full run's load, each passing on its own. 2026-10-06 03:33:04 +08:00
yetone 3ec6b4da27 gateway, gui: a provider's keys can be routed by weight, a key weighing 3 taking three requests for every one a key weighing 1 takes (dengtongcai, #841) — Routing already spread requests over a provider's keys in order, in turn, least used first or by pace, but never in a set proportion: two team keys meant to split 75/25 could only go evenly or one after the other. Routing now has By weight (routing "weight") for a provider with keys: each key that's on shows its weight and its share beside it in the editor (Weight 3 · 75%), a click edits it in place and posts keys/weight (provider.SetKeyWeight, 1 to 1000; none or 0 counts as 1, kept out of the file), and providers.json takes it as "weight" on each of keys (keyWeight for the first). The gateway picks as NGINX's smooth weighted round robin does (weighted.go): 3, 1 and 4 go round in every 8 requests in that ratio, never bunched; the others follow in their order for failover. A key resting after a failure is left out of the round while it rests, the others taking its share by their weights, and goes last. A conversation still stays with its key as Stays says (cache-warm across turns by default, within a turn always), and a request kept so is counted against the key that took it, not the one the round picked, so new conversations make up the share; Stays Off gives the ratio request by request. The weight goes with its key through Make first, the editor's Save, backups and WebDAV sync. The Routing page offers By weight for key pools and explains a pick by it; sink (Goes to the back) is off for it as for In turn. zh, ja, de strings. TestWeightedKeys (3:1:4 exact in each of 50 rounds of 8 through perKey and route; with one resting the other two 75/25 and the resting one last; a kept request made up by the next picks) and TestSetKeyWeight fail on the old code (no Weighted); key-weight.test.cjs (WebKit, en and zh: By weight shows the weights and shares, a click sets one and the shares redraw, Smart hides them, no scroll) fails on the old code (no By weight). key-import, panel-routing, routing-save, rate-limited-sink, routing-reset-deadline, account-arrange, gui-ja, gui-de and click-scroll pass on WebKit. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-05 08:50:57 +08:00
TryWorld dd4801e92a fix(gateway): forget a broken-off reply's stick by the account alone (#776)
affine keeps a conversation on the account that answered it three ways:
the account and the model, the account and the model without its effort,
and the account alone — "the account alone when the model is gone", for a
group whose answerer's model has since left it. unanswered, which takes
the stick away when that reply breaks off (#733), asked for the model to
match as well. So a conversation kept on an account by the widest match —
the model it answered as has left the group — kept its stick when the
reply broke off with nothing resting it (a refusal, a request too long
for the model), and the agent's retry, which routing would have sent
elsewhere, went straight back to the account whose reply had just broken
off. The same stick a rest would have protected was left standing with
no rest at all.

unanswered forgets a stick whose account matches, whatever model it
answered as: the stick is one record of "this conversation stays with
this account", and a reply that broke off books nothing. A stick of
another account, or another conversation's, is left alone.

TestUnansweredForgetsTheAccountWhenItsModelIsGone fails on the old rule
("the conversation is still kept on the account whose model has left the
group") and passes: a stick kept by the account alone is forgotten when
the model that answered is gone from the group, and another account's
stick and another conversation's are not. TestLateStreamErrorNotKept,
TestAffinity and the rest of the gateway's affinity tests pass
unchanged.

Validation on Windows: go test ./internal/gateway ./internal/provider
under a temp HOME — the gateway package's failures are the Unix-only
ones the base commit leaves there (TestSweepBridgeProjectsTakesOnlyThe
BridgesFolders); go vet ./internal/..., the darwin, GOOS=linux and
GOOS=windows builds pass.
2026-10-04 17:41:39 +08:00
yetone 7cfb6d35e7 gateway: a reply that breaks off after it began isn't booked as an answer, and the conversation's retry goes to another member (#733, congee949 on v0.1.801: Codex on group/grok4-7 got Cursor's "Unable to reach the model provider" eleven times in a row, each retry kept on Cursor by the turn's affinity, last:cursor kept:true why:turn, while the group's Grok member was fine) — after hw.release() the call.Status < 400 branch took any try whose status was under 400 for an answer, and a stream that has sent its 200 and some text and then fails comes back from translate/relay as 200 with call.Error set: servedCandidate ended the member's rest and its failure count, answered() remembered it as the conversation's answerer, and ruleAnswered booked it for the rule, so the agent's retry went straight back to the member that had just failed. Such a try (status under 400, error set) now books none of that: unanswered() forgets the conversation's stick when it names that account and model (and rewrites affinity.json), and when the error reads as the vendor failing, not a conversation too long for the model (tooLong) or a request it refuses as it reads (refusedWords) — lateRests — and the agent hasn't gone, the member rests as restAfter says for the error at that status (a minute's cooldown, longer each time it fails again; out of credit or quota as those read), so the next request in the conversation goes to another member first; a group of one still asks it, at the back. A reply the agent stopped itself (its request context ended) is booked as before, its stick kept. The partial stream stays as it was, its error event included: nothing is spliced in or replayed. The trace's try keeps status 200 and its error, and gains a Fail (the rest's why) and the Rest; the Routing page reads a try with status under 400 and a fail as broken off (tryOk), not answered: its line says it began answering and broke off, and how long it rests, with the vendor's words below it (zh strings), the row and the member's tally count it as failed, and its rest isn't taken for lifted. Usage is kept as it was, error included, as the tokens were spent; the trace's Served/Swapped/Routed still name the model that began the reply. TestLateStreamErrorNotKept (a group of two, the first member streams text then an error with status 200, for a Chat and a Responses client; the same conversation's next request must go to the second, with no stick left and the try told as failed and resting) fails on the old code (tried broken,broken; no Fail, no Rest) and passes. go vet ./internal/..., builds (darwin nogui, GOOS=windows, GOOS=linux nogui) and go test -tags nogui -count=1 ./internal/gateway/ ./internal/provider/ under a temp HOME pass; node --check on routing.js and i18n.js, the Playwright GUI tests not run (no playwright in the worktree). Not tried with the reporter's Cursor plugin; why Cursor's backend broke off is not known. 2026-10-04 09:31:48 +08:00
yetone 817a5f50d5 routing: In order keeps sending to the first account until it is used up or refused, and a tick keeps Codex or Claude Code signed in to the first account (#530: an account In order at 98% of its week, its five hours untouched, stopped getting requests; #524: "不允许切换首选账号的登录状态", the agent's own sign-in must stay on the account made first while the gateway still spreads requests) — since #209 magpie signs Codex and Claude Code in to the next ticked account with room once the one they are on reaches 98% (provider.SpentShare, the share Smart counts an account spent at), and since #408 back once the first is under 90%. The account the agent is signed in to is the one every routing tries first (the others stand behind it, AlsoOn), so In order the 98% switch put the second account ahead of the first, which is what #530 saw as the first being dropped; and the gateway counted an account at 98% as full whatever the routing, so a passing failure on it (a 502) rested it until its week renewed (39 hours there), not for the usual backoff. Now SpentShareOf gives 100 In order and 98 otherwise: the login switch moves the agent off an account In order only once a window of it is used up, the gateway's full (the rest after a failure, the quota rest's window) and affinity's "spent" go by the same share, and a vendor's 429 or usage-limit refusal still rests the account until it says it's back, as Smart does; a window used up is out, as before. Smart, In turn and Least used are unchanged. For #524, the subscription keeps KeepLogin (providers.json, beside Routing, kept across an editor Save; POST provider/keeplogin, only for Codex and Claude Code): with it on, magpie never moves the agent off the account it is signed in to, however used up, while the gateway still routes requests through magpie to the other ticked accounts; a pending return to the first (#408) still happens, that being the first. The tick sits at the foot of the Accounts list, under the rows where Make first is, shown only for Codex and Claude Code with more than one account on: "Keep {agent} signed in to the first account" / "{agent} 始终登录首选账号", its tooltip saying requests through magpie still go to the other ticked accounts. The Routing note follows it: kept, it says the agent stays signed in to the first whatever it has left; In order, that magpie moves it on once it is used up; otherwise the 98% wording as before. TestCodexLoginOrderedAndKept (In order stays at 98% and moves at 100%, back once renewed; Smart moves at 98%; kept, it stays at 100% and the setting survives a SetRouting; let go, it moves) and TestOrderedKeepsAnAccountAt98 (In order an account at 98% isn't full and a 502 rests it by backoff, Smart rests it to its week, a refusal rests it either way) fail without the change. keep-login.test.cjs (en and zh, Chromium and WebKit: the tick, its tooltip and Chinese strings, the post, the note when kept and In order, no tick with one account, the page doesn't move) fails without the UI and passes with it (12/12, Playwright 1.61); account-return, routing-account-order and account-arrange pass; click-scroll fails in Chromium here on origin/main too and passes in WebKit. No request was made to any vendor and no live agent config was touched. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestClaudeRunEndsWhenTheClientLeaves, TestClaudeAccountNamedAsItsLogin and TestClaudeIdentityServedWhileAsked failed once under the full run and pass alone). Turned on after magpie has moved the agent off the first, it goes back to it at once rather than once that has room again. 2026-10-02 15:48:16 +08:00
yetone f45e9737b3 gateway: a conversation stays with the account that answered it across a restart of magpie, and routing goes by each account's last known allowance until the first reading since the start is back (vincentzhang on Discord: in smart routing a restart moved a session to the first account, an update and restart back to the second, and the prompt cache was read by neither) — who answered a conversation last was kept in memory only, so after a restart every conversation was "first" and went to whoever routing put first; and until the accounts' allowances were read again (a first wait of 3s, the read itself up to 30s) none was known, every account counted as unused and the first in order went first, until the reading came back and put the one renewing soonest first again. Who answered is now also kept in affinity.json next to the providers (0600, written atomically, the latest 512 conversations, none older than the 24h a conversation is remembered), read again when a conversation isn't known here and the file changed — after a restart, or written by the magpie handing over. The rules for when a conversation moves are unchanged: within a turn it stays, across turns while the vendor read enough from its cache within the last five minutes, and never to an account resting, all but used up or gone. While the first reading is out, Allowances returns each account's last reading kept in quotas.json, its windows past their reset counted empty. Prompts and headers are unchanged. TestAffinitySurvivesRestart and TestAllowancesBeforeFirstReading fail without the change; TestAffinityFileBounded keeps the file bounded. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestFetchNewLeavesListedPlugins and TestFXInState flake under load on main too, pass alone). 2026-10-01 20:09:25 +08:00
yetone e0e93c2ec5 gateway: a Codex conversation compacted on GPT goes on after switching to Grok (waroy on Discord: Grok (SuperGrok): Could not decrypt the provided encrypted_content) — when Codex compacts on OpenAI's own models, the earlier turns become a compaction item sealed by OpenAI (encrypted_content), which magpie kept for magpie models. Grok can't read it, any more than another vendor's reasoning. The retry after such a refusal (2476cd5) left out only the sealed reasoning and asked once, so Grok refused the compaction too and Codex got xAI's error. It now asks again without the compaction when the refusal comes back (or there was no reasoning to leave out), and remembers the compaction with the reasoning as refused for that conversation and account, so later turns leave both out up front while Grok's own reasoning goes along; each step remembers only what it took out. The summary of the turns before the compaction is lost to Grok; what was said since stays. TestForeignCompactionToGrok (Codex path, a SuperGrok-like upstream refusing in the stream) fails without the change with the reporter's error. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestClaudeSignedOut, TestClaudeAccountNamedAsItsLogin, TestClaudeIdentityServedWhileAsked, known flakes under load, pass alone). Not tested against xAI itself. 2026-09-30 16:40:41 +08:00
yetone ba9f0c610d routing: a group's member may be a model at an effort of its own, provider/model:low (#189, @luw2007: model + effort 才是完整的组合项) — a member was only a model, reasoning as the agent asked or as the group's classifier picked, so "the same model, cheap and quick" and "the same model, thinking hard" could not both be in a group, nor could a rule send to one of them. A member now may carry an effort (none … max): a request routed to it is asked for that much reasoning whatever the agent asked or effort=auto picked, at the level the model has nearest, while the vendor is asked for the model's own id. The same model at two efforts is two members that rules (use=m:high), stickiness and the trace tell apart; an id whose own last part is a colon (a :free, :7b, :0) stays the model's. The group's reasoning levels are those of its members that follow the agent, and the editor has a reasoning button on each member. Tested with a fake provider through a sandbox magpie: the upstream bodies carry the fixed effort in Chat, Responses and Anthropic shapes, and the routing view shows m1:low / m1:high as two seats, light and dark 2026-09-29 13:45:29 +08:00
yetone 2476cd5c1a gateway: a Codex conversation moved to another Grok account or vendor goes on (waroy: Could not decrypt the provided encrypted_content … 中途换 routing)
Codex hands every earlier turn's reasoning back sealed (encrypted_content) by whoever answered it. When a routing group moved the conversation to another member, a second Grok/SuperGrok account in waroy's case, xAI answered "Could not decrypt the provided encrypted_content. Ensure the value is the unmodified encrypted_content from a previous response." The gateway already asks again without the sealed reasoning when OpenAI refuses it (#63), but it knew only OpenAI's words ("The encrypted content … could not be verified", invalid_encrypted_content) and only as a 400, so xAI's refusal went straight to Codex and ended the session. xAI's words are now known too, as a 400 or as the stream's own error. And what a key or account refused in a conversation is remembered (by its hash, beside who answered it last), so the conversation's later requests there leave that reasoning out up front rather than being refused and asked again each turn; the reasoning the new one sealed itself still goes along, for its cache and train of thought, and a conversation that stays where it was is sent everything as before.

Tested with two fake Grok-like Responses upstreams in a routing group, each reading only its own seal, the second refusing another's with xAI's 400 {"code":"Client specified an invalid argument","error":"Could not decrypt …"} and, in a second run, with a response.failed event: the first member got its own seal back; with it down, the second was asked once with the first's seal, refused, and answered without it; the next turn reached it once, carrying only its own seal. Without the change the switch fails with the reporter's exact error. Not tested against xAI itself, so the status it really answers with isn't confirmed (any 4xx/5xx carrying the words is taken); go test -tags nogui ./... passes and CGO_ENABLED=0 builds for darwin, linux and windows.
2026-09-28 23:55:01 +08:00
e136cf9a27 gateway: Gemini PDF and audio files kept on text-only routes (#95)
* gateway: keep Gemini document and audio file data on text-only routes

* fix(gateway): avoid translating Gemini files as images

* fix(gateway): preserve Gemini files for Code Assist while translating safely

* fix(gateway): retain Gemini file placeholder for Claude subscriptions

---------

Co-authored-by: Instinct Agent <agent@instinct.com>
Co-authored-by: Charan Rathore <charan-rathore@users.noreply.github.com>
2026-09-27 04:24:03 +08:00
yetone 0f59ca2fc0 routing: a turn a rule sent to one of a group's models stays on it for its tool rounds when another member is on the same account — the conversation was kept to the account that answered, so its next request went to that account's first member: Claude Code's turn Jev sent to codex/gpt-5.5 had its tool results answered by claude/claude-sonnet-5, both served by one provider (as Opus and Sonnet on one Claude sign-in are). And a group whose intents are levels has every turn at one of them however torn Jev is: 继续,再加一个基准测试 after a 复杂任务 came out 0.54 to 0.46, below the confidence counted, and went to the group's first member; a torn turn now stays at the level of the one before, or takes the likelier. Tested with Claude Code through Jev and the real Claude and ChatGPT subscriptions 2026-09-27 02:25:24 +08:00
yetone 696c8e70e7 group: rules send a kind of turn to a chosen model — a group's Rules (Routing view, or magpie group rule add|rm|mv) put one of its models first for a turn that is long (tokens ≥ N), carries an image, asks for reasoning (on or at least a level) or comes from certain agents; the first that matches decides as the turn begins and the turn stays there through its tool rounds, moving only if it outgrows its model's context, the others staying behind it for failover; a subagent keeps a place of its own so a rule can send it elsewhere while its agent stays; the trace says which rule sent a turn where. Turn affinity also now sees past the system message Claude Code puts after tool results, which made each of its tool rounds look like a new turn 2026-09-26 03:53:33 +08:00
yetone 43a30080d0 gateway: an account or key added while an agent works no longer takes over its running conversation (#63) — who answered a conversation was remembered only when there were two or more to route to, so the first request after a second ChatGPT or Claude account (or key) was added went wherever routing put it, and Codex reasoning sealed by the first account came back 400 "The encrypted content … could not be verified" and ended the session; who answered is remembered with one as well, and matched by the key itself, not by an id that changes once a second key is on. A conversation that still reaches another account (the first used up, or magpie restarted) has the other account's sealed reasoning taken out and is asked again, and the routing page says so 2026-09-25 21:29:05 +08:00
yetone 06997e90eb gateway(routing groups) + gui(picker, gateway, routing) + codex: routing groups come first in the model picker under a routing icon of their own, each shown as its providers' icons stacked, and are listed first in the Gateway view's models too; a model is found to be the same under the ids its vendors give it — claude-opus-5-5 and claude-opus-5.5, dated or not — so the Claude subscription's Opus 5.5 joins its group; keys made for different protocols are pools apart, a request going round the keys that suit it before trying another's; Codex's model list is asked for as the newest Codex on the machine (codex --version) rather than the version its cache last wrote, so models only newer clients are shown — GPT-6 Sol and Luna — are listed; the Routing view keeps its providers in one order rather than reshuffling them per request; mask icons in the picker have a size to fall back on, so OpenRouter's and Copilot's show 2026-09-25 05:01:18 +08:00
yetone 520a2425fc gateway(routing groups, affinity) + gui(routing): routing groups — several models, from one provider or many, that an agent picks as one (group/<id>), routed over all their members' keys and accounts together, smart, in order, in turn or least used first; a model more than one provider serves is a group magpie finds on its own, and becomes the user's once changed. Affinity keeps a conversation with the key or account that answered it — for the session, within a turn, never, or by default while what the vendor read from its cache is worth keeping and not yet cold — so the prompt cache holds; in turn now spreads turns rather than requests, a turn's tool results staying where it began. The Routing view shows each agent's requests in its own colour, the magpie flying them through the gateway's box rather than jumping across it, groups and why a conversation stayed or moved; and a Hide emails switch blurs the email addresses on the page, for a screenshot to share 2026-09-25 04:07:40 +08:00