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.
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.
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).
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.
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.
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.
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.