1ccacad63281094de8a3372d5a507d38f9969e5c
231
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7476328901 |
settings: one longest context for every model (WJaunita45604 on X)
Settings > Models > Routing has a Longest context field (magpie model context-cap [<size>|off], POST /api/settings/context-cap). It lowers every model's window to it, so a user need not set each model. A window the user set on a model, or on its provider with "*", wins and is not capped; a model whose window is unknown stays unknown. It is applied where the window is derived, provider.windowIn, so /v1/models, every agent's catalog, group windows and the compaction thresholds that follow the window all agree. Codex's own models take it through CodexNativeWindow, CodexWindow and codexcat.Cap on the list the gateway serves; the list's ETag carries the cap so Codex asks again. The provider editor's Listed value stays the vendor's. Run (mote): provider, codexcat, cli, settings, settingsapi, gateway tests; GUI context-cap, model-load, settings-places, i18n-keys, settings-general in chromium and webkit (en, zh); TestCoreScriptBudget; gofmt; vet on darwin, linux nogui and windows. Broken by hand: windowIn without the cap turns TestContextCapHoldsEveryModelButTheOnesTheUserSet and TestModelsListContextCap red. Not tried: the whole GUI suite (one row added to an existing list, no new API read on page load), a real Codex reading the capped list, Windows run. Not covered: Claude Code's own [1m] choice (claudeRunName) and agent/claude.go's fallback when a ref has no window. |
||
|
|
418bb6c9e1 |
codex: Show Codex's own models off leaves them out of Codex's own picker (iiiiiimone on X)
The switch (#1642) only narrowed the Agents page's pickers. Codex's own list, which the gateway hands it beside its sign-in and as the Codex app's list file, kept every model of the ChatGPT account, also with the Codex provider switched off. codexMerged now leaves the sign-in's visible models out when the switch is off (provider.CodexOwnLeftOut); the model Codex is set to, models magpie serves on a ChatGPT account and hidden jobs stay, and the list's ETag carries the switch so Codex asks again. Codex has one openai_base_url for every model, so one it is still set to goes through the gateway to OpenAI on its own sign-in; a model of it can't be sent direct beside magpie's models. Run: TestCodexListWithOwnModelsOff, red with the filter turned off (own models all listed, ETag unchanged); gateway, provider tests at this tree. Not tried: a real Codex app against the list. |
||
|
|
e6f151507f |
sessions: each session's output speed, a curve of its last two minutes
The owner liked a tweet's token-speed curve and approved a mockup
(claude.ai/artifact/7mrkMKdVi6jA3HA1Z6pRr5). Each Sessions row now
shows its output speed with a small curve; clicking it opens a popover
with the current tok/s, two minutes of seconds, tool gaps, and the
round's average, fastest second and output so far. A row not live
shows "Avg {n} tok/s".
Gateway: a curveMeter (session_speed.go) on the Server counts every
reply's content bytes per agent and session, from liveRow.observe, the
same count the Live view uses, and turns them into tokens with the
learned per-model rate (tokenRates.rate). A model with no rate yet
shows the curve's shape and no number: a guess would be a wrong
number. counted() opens a session's in-flight span, so a second with
nothing in flight is a gap (a tool ran), not a zero. A pause past 2m
starts a new round; 10m of quiet forgets the session; at most 256
sessions. Codex's own sign-in (codex_backend.go) went past serve and
liveRow before; it now has a liveRow too, so its sessions are counted.
GUI: GET /api/speeds, kept out of /api/sessions* so a once-a-second
poll doesn't set off session reading. The page polls only while
Sessions is shown and visible. managedJSON gains keys, so a row
matches a session the gateway saw under another of its keys. The
curve hides below 620px.
Run (mote's sshd resets every connection today, so Linux and Windows):
- Linux (magpie-desktop, wsl-run): gofmt clean; go test -timeout 45m
./internal/gateway ./internal/sessions ok except
TestGroupFailoverTimesEachTry, red once under load, 5/5 green alone
here and on main (#5948); node --test over every sessions-*.test.cjs
and i18n-*.test.cjs: 546/549, the reds sessions-export en in both
engines, the same on origin/main
|
||
|
|
f1996e7e5d |
gateway: a provider named past its usage cap is not sent on to a group (Anotiaww on X)
Anotiaww on X: magpie on server B asked magpie on server A for claude/claude-opus-5-5. A's Claude account was past its usage cap (the trace: "a usage window at 98%, over the account's 98% cap"), and the Claude provider had no fallback set. The request was answered by a WorkBuddy member of the user's routing group claude-opus-5.5 (the trace row marked Fallback), with nothing said. They expect the cap's refusal. Cause: |
||
|
|
1ad9d157fe |
gateway: a compaction a ChatGPT-account relay refuses as system asks again with the roles as sent (#5067, acui145 on X)
Codex's summary ask to a provider that isn't OpenAI's carries its developer messages as system ones (forVendor, #2955). A plugin provider fronting a ChatGPT account (magpie-sub2api -> sub2api -> Codex backend) is such a provider, and the backend behind it takes developer alone: every compaction came back "System messages are not allowed", the sessions that got through fell to the conversation-as-text summary, and the ones whose refusal came as an error event after a 200 skipped every retry and were held after three (compactFails). Now a summary refused "System messages are not allowed" (as passed through, or as a current sub2api words it), or with a relay's bare "Upstream request failed" (the reporter's sub2api), as a 4xx or as an error event in the stream (roleRefused), is asked once more with the roles as Codex sent them (askAsSent turns off the compaction marker, whose only reader is forVendor's swap), then as text, then made by magpie. A summary with no developer message to give back is not asked the same twice. Every route a compaction reaches a Responses provider by (CodexPath, Codex's own models through magpie's accounts, the mask route, a CC Switch table) goes through codexCompact and serve's one forVendor call, so all of them are covered. #2955's chat-only vendors take system and are unchanged. Ported from ggbdpq's patch (fix/5067-compaction-system-messages, 79ec15d26), which matched only the passed-through wording on a 400. The review added the reporter's own "Upstream request failed", the error-event shape, the developer gate, lazyre for the words, and the subsystem page. Run on mote at this change on 6a253f8af; rebased onto |
||
|
|
f2b9ec354a |
gateway: Codex's auto-review goes on where its conversation does when the sign-in is out (riverleaf88 on X)
riverleaf88 on X: with Codex's ChatGPT allowance spent and magpie routing Codex on to another model, Codex's automatic review still failed. Codex's guardian (codex-rs guardian-v2 sync_reviewer) asks the same provider, so magpie's /backend-api/codex/responses, on codex-auto-review (approval_review_preferred_model) with x-openai-subagent: guardian. On a spent sign-in codexFallsBack and serve's groupsAfter looked for fallbacks and routing groups of codex/codex-auto-review, a model no group names, so the review was handed ChatGPT's 429 while the conversation's turns went on to the group. - codexReviewAfter: an auto-review on the codex sign-in takes the model its conversation's own turns go on (codexLeads). A codex model brings that model's fallbacks and groups (fallbacksOnly on the lead too); a magpie model the caller may use (servedSession) is tried itself. codexFallsBack and groupsAfter add them. - codexHolds: once a 429 naming a reset held the account, later turns (main turns too) were answered with the held refusal before any fallback. The held branch now hands a /responses turn with fallbacks to codexFallBack as the first spent turn was. - docs/subsystems/gateway-routing.md says both. Run (mote): go test -count=1 -run 'TestCodexReviewSpent|TestCodexHeld| TestCodexOneAccount|TestCodexSpent|Hold|Held' ./internal/gateway/ ok 71.2s; gofmt -l clean. New tests red on the old code: TestCodexReviewSpentFollowsTheGroup and ...FollowsMagpieModel (review got 429 usage_limit_reached); the held case in TestCodexHeldTurnFollowsTheGroup. Broken by hand: codexReviewAfter returning nil turns TestCodexReviewSpentFollowsTheGroup, ...FollowsMagpieModel and TestCodexHeldTurnFollowsTheGroup red; dropping the held-branch fallback turns TestCodexHeldTurnFollowsTheGroup and ...FollowsTheGroup red. Not tried: a real exhausted ChatGPT account; guardian-v2's async scorer; the multi-account pool path past serve's candidate loop is covered only through the one-account tests. Also run (mote, at this tree): go vet ./internal/gateway/ for darwin, GOOS=linux -tags nogui and GOOS=windows: clean. go test -count=1 -timeout 45m ./internal/gateway/: ok 1037.9s (base |
||
|
|
add0dadd4f |
codex: a service tier set in Codex's settings goes on every request of Codex's (JackyFill on X)
JackyFill asked for a choice in Codex's agent settings that rewrites
service_tier: follow the request, force Fast, force Ultra Fast. Codex's
settings on the Agents page now have "Codex service tier", picked from
the app menu: As Codex asks (the default, nothing changes), Standard,
Fast or Ultrafast.
The values are Codex's own request values (codex-rs protocol
config_types.rs ServiceTier, tui service_tier_resolution.rs): Fast is
"priority", Ultra Fast is "ultrafast", and Standard sends no
service_tier. Flex isn't offered: the ChatGPT backend's requests drop
it (codex_request.go).
settings.CodexServiceTier ("", "default", "priority", "ultrafast";
anything else refused) is set through POST
/api/settings/codex-service-tier. codexTiered rewrites the body where
Codex's requests come in, on both ways: codexBackend (Codex signed in,
/backend-api/codex) and the main handler's Codex-on-Responses block,
which a websocket turn goes through too. It applies only when the
request is Codex's (fromCodex or agentOf == codex). Everything after
treats it as Codex's own ask: an account whose list lacks Ultrafast is
put after a mate that has it or sent priority. A bare model (Codex's own
sign-in, whose plan magpie doesn't know) gets ultrafast only where one
of magpie's Codex accounts lists it on the model (UltraModels), else
priority. The body is edited with topMember/withoutTopMember, no full
decode. Fast picks still apply after, unchanged.
Run (mote):
- TestCodexServiceTierSet, TestWithServiceTier: ok. The test signs in a
Plus and a Pro ChatGPT account against a fake backend whose lists offer
gpt-6-luna's Ultrafast to Pro only, and checks the tier sent for each
setting x what Codex asked, through /v1/responses (account:tier tried)
and on /backend-api/codex for a model with Ultrafast and one without;
OpenCode's own priority is left alone; "flex" is refused.
- go test -count=1 -timeout 45m ./internal/settings ./internal/provider
./internal/gui ./internal/gateway: ok but internal/gui, which was red
twice: TestCoreScriptBudget (1,535,075 > 1,533,802) and
TestSettingsSaveKeepsWhatItDoesNotSend (a save of the Settings page
dropped the tier). Paid for by eight Codex-row comments cut in app.js
(now 1,533,416), no raise; settingsapi.Apply keeps CodexServiceTier
as it keeps the other Codex rows. At the pushed head: go test
./internal/settingsapi ./internal/settings ./internal/gui ok, the two
gateway tier tests ok.
- go vet darwin; GOOS=linux -tags nogui; GOOS=windows (gateway,
provider, settings, gui): clean. gofmt -l: clean.
- GUI, chromium + webkit: codex-service-tier (new, en/zh/zh-TW/ja/de at
900 and 400px: 20/20), agent-prefs (56/56, Codex's row list updated),
i18n-keys, i18n-en-no-cjk, settings-search, codex-titles,
codex-subagent-model, settings-general, codex-sheet-providers,
click-scroll: all pass; at the pushed head codex-service-tier,
agent-prefs, i18n-keys, settings-search, codex-titles,
codex-subagent-model, settings-general, click-scroll: 166/166.
Broken by hand:
- codexTiered returning the body as it came: TestCodexServiceTierSet red
(17 lines).
- the Ultrafast-to-Fast downgrade for a bare model removed: red on
gpt-6-sol (sent ultrafast, want priority).
- the GUI posting to the wrong path, and the row left out of Codex's
AGENT_PREFS: codex-service-tier red in chromium and webkit.
- settingsapi without the CodexServiceTier keep:
TestSettingsSaveKeepsWhatItDoesNotSend red.
Not tried: a real ChatGPT account's Ultrafast or Fast request with the
setting on (only the fake backend), a real Codex websocket session, and
Windows/Linux runs of the GUI.
|
||
|
|
59d9f5c7d9 |
gateway, redact: compile their 275 package-level regexps on first use, not at every start
magpie is one binary, so every package's init runs on every launch, including `magpie statusline`, which Claude Code runs on every message. internal/gateway and internal/redact compiled 275 patterns at init: 3.7 MB + 2.3 MB and ~38k allocations per launch, most of them for vendors and rules that launch never reaches. New internal/lazyre: RE holds the source and compiles it through a sync.Once on first use, with the *regexp.Regexp methods magpie calls delegating to it (Of wraps one already compiled, for the user's own privacy rules). A one-off Go AST rewrite turned every regexp.MustCompile in a package-level var (outside func literals) into lazyre.New; the struct fields, map and parameter that hold them took the new type. A bad pattern now panics on first use instead of at start, so TestAllCompile in gateway and redact compiles every registered one. Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts, v0.1.3515 ( |
||
|
|
9309e28ced |
plugins: a plugin's provider in front of a vendor's API is that vendor to the gateway (songlairui on X, #5462, #5464)
A plugin whose provider's `api` is on a vendor's preset host (a Mistral Vibe plugin's https://api.mistral.ai/v1) got none of what magpie does for that vendor, since its Host() is the plugin's id. An earlier turn's thinking went to the plugin's fetch as reasoning_content, and Mistral turned the whole request away (422 extra_forbidden); the plugin had to rewrite the body itself. provider.VendorHost and VendorPreset now resolve a plugin's declared `api` host to the preset that names it (every Chat, Responses and Anthropic base of every preset and region; local and remote magpie presets excluded, and an api on loopback, a private address, .local or .localhost names no vendor). For every other provider, and a moved subscription, they are Host() and Preset as before. The gateway's vendor checks read them: 38 p.Host() sites, Mistral's, OpenRouter's, DeepSeek's, Kimi's and DashScope's preset checks. Host() stays the plugin's id where calls are kept and shown; requests still go only to the plugin's fetch. Search and the video plan check are unchanged. No community plugin's api is on a preset host today (checked at plugins 7b52e3fc), so none changes. Any plugin gets this with no new field; documented in docs/subsystems/provider-plugins.md and the plugin docs (en, zh, ja). Run (mote): go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows; go test -count=1 -timeout 45m ./internal/provider ./internal/plugin ./internal/gateway: ok (provider 209s, plugin 182s, gateway 1002s). gofmt -l clean. Broken by hand: pluginVendor resolving nothing (the old behaviour) turns TestPluginVendor red, and TestPluginInFrontOfMistralIsMistral red on both halves: the translated Claude Code turn is answered Mistral's 422 extra_forbidden, and the relayed Chat request carries reasoning_content. Not tried: a real Mistral Vibe key through the reporter's plugin; Windows and Linux runs of the tests (no OS-specific code). |
||
|
|
ca5e537ecb |
usage: traffic over time in Requests' chart, and how fast it flows now (songlairui on X)
songlairui on X asked for the gateway's bandwidth: many LLM calls, base64
images above all, weigh on the network. Each request's row already kept
its bytes up (UpBytes) and down (DownBytes), shown in its details and as
the period's "↑ · ↓" under the Requests card. What was missing was
bandwidth over time and right now.
- The Requests chart's metrics take Traffic: each hour's/day's bytes up and
down, stacked by model, provider or agent. Its axis is in bytes ("4 MB"),
its tooltip splits a column into "↑ up · ↓ down", and the ranking's
values are bytes with the same split under each. A period with none
says "No traffic counted in this period". A chart point's Part now
carries up_bytes/down_bytes, from rows (Part.add) and from the request
page's cells (Part.plus). The cells already kept Totals, so no cache
version bump is needed.
- While requests are in flight, the Requests card says how fast traffic
flows now: "↑ 1.0 MB/s · ↓ 40 KB/s", over the last ~3s, read from the
new GET /api/usage/traffic a second apart. That route reports the
gateway's running totals (Server.Traffic) and its requests in flight.
The totals are atomics added where a row's bytes are added (sentUp,
downCount.Read). So a stream counts as it arrives, nothing is buffered
or scanned, and the totals and rows count the same bytes once. Polling
runs only while Usage → Requests is shown and the window is visible.
The line goes when nothing is in flight and nothing flowed. When another
magpie serves the gateway, the route answers {} and the page shows no
rate.
A Codex turn on the Responses WebSocket (
|
||
|
|
7c1dc198d1 |
usage: a turn over the Responses WebSocket counts what the socket was sent, and says so
A Codex turn kept on a Responses WebSocket sends only the new items as a
delta, but the row's ↑ was the whole HTTP body magpie built before the
transport ran, so a long conversation read as ~13MB up per turn
(matrix0487 on Discord). overSocket now records what each socket write
carried (wroteSocket) and, when the turn went out on the socket alone,
replaces the HTTP figure with those bytes (sentOnSocket); a turn that fell
back to HTTP keeps the HTTP body and adds any socket write made before the
fallback. errCodexSocketAgain's retry on a new socket counts both writes.
The row remembers that it went over the socket: Record.Socket (json "ws"),
packed as Flags bit 16384 (rowSocket, added to TestRowFlagsApart). The
Requests table's protocol badge says "Responses · WS" and the details'
Protocol line "Responses · WebSocket".
Run on mote at this commit (rebased on origin/main
|
||
|
|
803d7747e7 |
gateway: an account rate limited till a time its vendor named is not asked again before it (hsjzg58958 on X)
hsjzg58958 on X: a vendor limited an account for 300 seconds, and magpie asked it again about every half a second as the agent retried, until the vendor flagged two accounts. Cause: a candidate resting on a 429 was still "tried all the same" when it was the last one left (restLast/probeOne), and the last one left was never rested at all, so every client retry went upstream. Codex on its own sign-in is relayed by codexUpstreamOn outside the candidate loop and had no hold at all. Fix: - timedHeld/vendorTimed (fallback.go): when every candidate left rests on a 429 whose time the vendor named (Retry-After, anthropic-ratelimit-*- reset, x-ratelimit-reset-*, resets_in_seconds/resets_at), none is asked; the agent gets 429 with Retry-After = when the first is back. A ChatGPT account out of its allowance is answered as the backend's usage_limit_reached with its x-codex-* windows (Rest.out/outHeader). - The last one left now rests too on such a 429 (vendorSaidWhen); a 429 naming no time rests nobody, as before. - codexHolds (codex_held.go): Codex's own relayed sign-in is held till the vendor's time; its retries are answered locally with the stored body, x-codex-* headers and Retry-After. Lifted by restarted() for quota holds. - Not held: LimitRestOff accounts (the user's setting), auto-reset weeks, rests "there" (answered by the vendor's own hold), Codex's API key. Run: - New TestRateLimitedKeysHeldUntilTheirReset (4 signals x 1 and 2 keys) and TestRateLimitedCodexAccountsHeldUntilTheirReset (3 refusals x 1 and 2 accounts): red at |
||
|
|
dae104bfac |
capre: a length check, not an unrolled repeat, holds nine patterns
Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.
capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.
Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
./internal/library ./internal/sessions ./internal/agent ./internal/gui
. : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
over 14 units x 19 lengths (0..300, at each bound +-1); with the
length check taken out it is red (1586 mismatches).
TestItemIDRefusalAsTheRegexp holds the function against the old
regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
(gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
4.54MB -> 3.01MB.
Not tried: the full ./... suite; the gateway package beyond the run
above.
|
||
|
|
44d6dd75d1 |
gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.
Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.
Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
the model in them and another member to go on to, in the user's order;
auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
left, CapStop off), or for a turn codexFallBack handed on, the provider
is planned again with those groups after its own fallbacks
(groupsAfter), each group routed as a request to it is. One place, so
it holds on every protocol (chat, responses, messages, Codex's backend
path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
before any fallback, the groups included).
Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
/v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
|
||
|
|
c9d253e4a2 |
gateway: an agent's compaction is recorded as Compaction, not a plain turn
shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show in Usage → Requests. Through the gateway they were recorded and counted, but as ordinary turns (Kind ""), so nothing read as a compaction: the Compaction purpose listed none, the OTel export skipped them as turns the transcript has (Claude Code's compaction is skipTranscript, so it has none), and the reply ended the agent's turn. The main handler now marks a call compacting() recognises (Claude Code's summary ask, OpenCode's and the other agents' prompts) as KindCompact, on every route it serves (messages, chat, responses, gemini), unless a header already set its kind. The check reads the facts parse the request already makes (bodyFacts.compact). Codex's backend route already took the kind from its header; it now uses the same constant. Not fixable here: Claude Code used directly (not through magpie) never writes a compaction's usage to its transcript (only compact_boundary with token counts before and after), so magpie can't count those. Run (mote, at this change on |
||
|
|
7a56c83e72 |
gateway: a compaction Copilot sealed stays out of Codex's auto-review
echo_ts (Discord #feedback) runs Codex Desktop's turns on GitHub Copilot
through magpie, with Copilot's native compaction on, and Codex's
auto-review on its built-in codex-auto-review through the ChatGPT
sign-in. The guardian's review carries the conversation's history, so
after the first compaction it carried Copilot's sealed compaction item
too. A request for one of Codex's own models with no magpie Codex
account to route it is relayed to the sign-in as it came, and
codexInputAs keeps any non-magpie1: compaction ("OpenAI's own, for
OpenAI"), so OpenAI was sent Copilot's ciphertext and refused every
review: 400 invalid_encrypted_content "The encrypted content P4ih...bDU
could not be verified". After the next compaction, the new ciphertext.
The siblings: a side call routed through magpie (the auto-review set to
a magpie model, a subagent or a title on another provider's model)
met checkpointReaders, found no writer among its candidates and was
refused with checkpointError, so the review failed there too. A turn or
a /responses/compact on one of Codex's own models relayed to the sign-in
sent the seal to OpenAI to be refused (sealedCompact took a Copilot
writer for the sign-in's own and relayed it).
Now:
- compactionAside names the calls Codex makes beside the conversation
with its history in them: the guardian (or anything asked on
codex-auto-review), memory, subagent, title, description, thread
summary, prediction and suggestion. In serve, when the writer of the
sealed compaction isn't among such a call's candidates, it goes on
without the compaction item (withoutCompaction, body and plain);
instructions, developer/user messages, the turns since and their tool
calls and outputs stay. The conversation's own turns are still held
to the writer or refused saying why (#1099), unchanged.
- foreignToSignin: on the relay to Codex's own sign-in (codexBackend), a
compaction magpie recorded as sealed by a provider other than the
Codex subscription is never relayed. A side call goes without it; a
turn or a /responses/compact is answered checkpointError, magpie's
own explanation, with nothing sent to OpenAI. A seal with no record
(OpenAI's own, compacted on the sign-in), one the codex provider
sealed, and one whose provider can't be read are left as before.
No portable plaintext summary exists for a native compaction (only the
writer can read it), so the side call goes without it rather than with
a summary.
Run (on mote, through mote-run, at
|
||
|
|
e215d335a6 |
gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.
- access: Key and Change get MaxConcurrency, and Identity carries it, the
issuer's cap included. The concurrency-key action refuses a value
below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
key's cap, however the request came (loopback, LAN, a Remote magpie, a
Responses socket's turn). One request too many waits in the key's
queue in arrival order. It shows as "slot" in Active, and its wait goes
into the try's Queued. A request whose agent goes away while it waits
leaves the queue and sends nothing. A stream holds its slot until it
ends. serve's routes (chat, responses, messages, ollama, gemini, the
Codex backend) wait inside the try, after keepQueued, so a streaming
agent gets keepalives while it waits. The other model routes (images,
embeddings, rerank, audio, videos, search, decisions, native) wait
before their handler runs. forward and codexUpstreamOn take the slot
too, so nothing reaches a vendor without one. A key issued under
another waits for its own slot, then for its issuer's.
/v1/magpie/concurrency lists each capped key under "keys", and counts
its waiters in "waiting". A key's limit (key_limit) reports the cap.
Not held, as a provider's MaxConcurrency doesn't hold them: GET,
HEAD, OPTIONS, count_tokens, :countTokens and MCP.
TestKeySlotEveryRoute fails when a route is judged neither held nor
free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
negative, over 1000, a fraction, a word, --help or an extra argument
with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
and Other… takes a number typed in place. A value that isn't a whole
number up to 1000 is refused and nothing is sent. Browser and
read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
de. An unset badge, which a hover shows, gives way before the masked
key (flex-shrink 8). Without that, at 420px in en and de, the extra
badge squeezed the key until its copy button slid under the pointer
that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.
Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto
|
||
|
|
7d196b6797 |
gateway: what a proxy says of the caller reaches no vendor, ChatGPT backend or MCP server
Behind Tailscale Serve, a Cloudflare Tunnel or another reverse proxy, the request magpie gets carries what the proxy says of the caller: Tailscale-User-Login, -Name and -Profile-Pic (the user's email, name and picture), True-Client-IP, X-Forwarded-*, Cf-*. The native route dropped X-Forwarded-*, Forwarded, Cf-*, X-Real-Ip and Via, but not True-Client-IP or any Tailscale-*, even though lanGuard itself reads True-Client-IP and Tailscale-User-Login as forwarded (forwardHeaders). The Codex passthrough and relay to the ChatGPT backend (copyHeaders) and the MCP proxy dropped none of them. proxyIdentity names them once: every forwardHeaders entry; any X-Forwarded-*, Cf-* and Tailscale-*; Forwarded, Via, X-Real-Ip, True-Client-Ip, X-Client-Ip and X-Original-Forwarded-For. nativeHeaderDropped, copyHeaders and the MCP proxy's header loop all skip them. The caller's other headers still go on. Checked and left as they are: a provider's PassHeaders (names the user chose), Codex's allow-listed codexHeader, the Codex websocket's headers and passOnCaller. Tests: TestNativeAnyDropsProxyIdentity (native route, under MAGPIE_TRUST_PROXY) and TestPassthroughDropsProxyIdentity (Codex relay through copyHeaders, and /mcp/<server>). Each sends twelve identity headers and checks that none arrive and that X-Custom still does. Broken by hand: with native.go, codex_backend.go and mcp.go at their parent, both tests are red. The native vendor was told True-Client-IP and the three Tailscale-User-* headers. The ChatGPT backend and the MCP server were told all twelve. Run on mote at the pushed head 883690a0b (this commit and the one before, on origin/main |
||
|
|
ff415f39cb |
gateway: a compaction refused for an input kind it doesn't take is asked again as text (#5181, #5259)
Command Code's /responses takes messages, function calls, their outputs and reasoning only. A Codex subagent's compaction carries agent_message, custom_tool_call and compaction_trigger items, and Command Code answered 400 unsupported_input_item (param input). codexCompact didn't count that as a reason to ask again with the conversation as text, so the 400 went back to Codex three times and compactFails held the conversation for 5 minutes. inputKindRefused now asks again as text on unsupported_input_item or "unknown item type" (Grok's 422) in a 400, 422 or 502 (another magpie in front wraps it), or in a stream's error / response.failed event. A 401, 403 or 429 with the same words still goes back as it came. itemText reads an agent_message as the user's turn, so the subagent's task and follow-ups are in the text summary and in the local one. No plugin change: the Command Code plugin passes /responses through, and the fallback covers it direct, through a remote magpie and in a stream. Run (mote): - go test -run 'TestCodexCompact|TestCodexCompacts|AgentMessage' ./internal/gateway: ok - go test -timeout 45m -count=1 ./internal/gateway: ok (809.6s) - gofmt -l clean; go vet ./internal/gateway native, GOOS=linux -tags nogui and GOOS=windows: ok Broken by hand: - origin/main's codex_backend.go: every AsksAgainAsText subtest red (400 / 502 back to Codex). - agent_message case removed: the text lacks the subagent's task. - status guard loosened: the 401/403/429 test red. Not tried: a real Command Code account (the keys on this machine are answered 401), the reporters' own sessions; why the compaction reached /responses rather than chat is not confirmed. Reported-by: Mmx233 <36563672+Mmx233@users.noreply.github.com> Reported-by: Edward4226 <Edward4226@users.noreply.github.com> Reported-by: mahiro233 (Discord) Co-authored-by: Mmx233 <36563672+Mmx233@users.noreply.github.com> |
||
|
|
8b70b7d976 |
usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now keeps what each request received back (down_bytes) beside what it sent up (up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the upload (image_files_saved). Shown in Usage → Requests: - a row's details: "Sent upstream", "Received" and "Saved by image files", each only when it is above 0. A row from before has none of them, not 0; - under the Requests card, the period's "↑ up · ↓ down", with "{n} saved by image files" when there is a saving. Its title gives the exact bytes. A period with no counted bytes shows no line. What is counted: - Down bytes are counted as the reply body is read, after Go's transport has undone gzip, so a gzipped reply counts its plain size, not wire bytes. A plugin's row counts the local hop to the plugin host. A 101 body is not wrapped. Every try counts, so a refused try plus the answering one add up (TestLedgerKeepsDownBytes). - Image files saved, per try: the body before the swap minus the body sent, minus the upload bytes this request itself paid (len(b64)/4*3). It can be negative on the turn that uploads; the GUI shows only a saving above 0. Gaps: an upload that finishes after the wait timeout or ctx-done is not subtracted (as with up_bytes); a joined upload flight is paid by the request that started it; multipart overhead is approximate. - packedRow grows by three int32 (152 bytes, still within the test's bound), clamped to the int32 range. Totals sum all three. - settledCountVersion goes 1 → 2, because Totals now count bytes. The settled page, heat and effort caches recount once, on the first start after the update. The heat key hash includes the new fields. Run on mote at |
||
|
|
1100ed6494 |
gateway: an overlong item id goes left out on every kind that may go without one, and under its kind's own prefix on the rest (echo_ts, web_search_call)
echo_ts (Discord, Codex on GitHub Copilot, after |
||
|
|
125fd93ecd |
gateway: an overlong message or call id goes left out, and any other is bound under its kind's prefix, which Copilot checks (echo_ts, #5266, #4972)
echo_ts (Discord #feedback, v0.1.3058): after Codex's native compaction, a tool call on GitHub Copilot failed with an empty 400 "invalid_request_body". Copilot had handed the call a 452-character opaque id (Base64, + and / in it, no fc_ prefix). plainItemIDs, on every relay that checks ids (validatesItemIDs, Copilot among them), sent any id over 64 as boundItemID's sha256. That kept an id's own prefix only when it had one, so an opaque id went as a bare 64-hex digest. Copilot refuses that. By hand, the reporter got 200 with the original id and 200 with the id left out (call_id kept). isnine found the same thing for a message on #4525/#5266: left out 200, bare digest 400, msg_+hash 200. The bare digest dates from |
||
|
|
9a51d644d6 |
gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275)
hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a ~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB summary request was still being written to Ark at 299s (TryNet Send ~299s, no first byte), Codex gave up at 300s (499), and only then did magpie log "the reply ended before it was complete; compacting locally". That local summary went to a request nobody was reading, and compactFails.done cleared the conversation's count as if it had worked. Codex sent the same history again, three times, 300s each, and the conversation never got shorter. - codexCompact gives the summary compactWithin (4 minutes, a minute short of Codex's 300s stream idle timeout, as agentQuietMost). Past it the vendor is no longer waited on (the ask's context ends with a sideTimedOut cause, so the usage log says "magpie stopped waiting: its compaction summary had no answer in 4m0s", not the agent canceling), and magpie's own summary (localSummary, saying "no summary came in 4m0s") goes to Codex while it still waits. Checked after the first ask, the ask as plain text, and the as-text ask after tool calls, so a late first ask is never followed by another ask of the same body. - A compaction Codex left before it was answered is counted a failure (499, "Codex left before the summary reached it") and nothing is written; done() is no longer called for it. After compactFailsMost in a row, the next is held with a 400 at once instead of another 300s. Why the upload was slow: not shown to be magpie's. From here a 3.1MB whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s (HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB control not finishing in 40s by any route, point at the uplink or the Shadowrocket TUN in their path. Not tried through a TUN. Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix; both red on the old code (the first: no answer before the client's 10s; the second: a completed compaction written to a Codex that left, and the next not held). go test -run Compact ./internal/gateway ok; go vet of internal/gateway for darwin, linux and windows ok; gofmt clean. Full suite: run after the push (go test -timeout 45m ./... on mote, log teed), result on #5275. Not tried: a real Codex Desktop session against a slow uplink; a reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex still leaves first, and the count holds the conversation after 3). |
||
|
|
34116ec012 |
gateway: Codex signed in to one account lists another account's models
bigfisheatsmall on X: Codex was kept signed in to ChatGPT account A, on the Free plan. Account B (Team) was the only account on in magpie. dsh listed B's models and Codex didn't. codexMerged added CodexListed(), which leaves out every ChatGPT account's own models because it assumes the backend lists them. But the backend list is fetched with Codex's own sign-in (A, Free), so B's plan-only models were listed nowhere. Routing already sent codex/<model> to B (codexAccounts). - provider.CodexListedBeside(backend) lists an account's own model by magpie's id (codex/<slug>) when the sign-in's backend list lacks it. codexMerged uses it, and FitOwn keeps those entries. - spawnChoices (spawn_agent's models) had the same gap. It now uses the same rule with the slugs in Codex's models cache. - buildCodexListTag covers the accounts' own models, so another account gaining or losing one has Codex ask for the list again. Every Codex asks once after the update. - TestSyncCatalogAgesCodexCache built its "current" tag by hand from CodexListed(). It now uses provider.CodexListTag(), the tag SyncCatalog compares against. Tests (sandbox HOME, fake backend with per-plan lists): TestCodexListHasAnotherAccountsModels covers the list, routing of codex/gpt-6.1-sol to the Pro account, and spawn_agent's choices. TestCodexListOneAccountNoneTwice checks that a single account gets no codex/ duplicates. Run on mote at this tree: go vet (darwin, windows, linux) on gateway, provider and agent: ok. go test -count=1 on provider, agent and codexcat: ok. go test -run 'Codex|Spawn' on gateway and gui: ok. Run at the tree before the sync_test change and the buildCodexListTag tidy: the full gateway package was ok (1224s). Agent was red only in TestSyncCatalogAgesCodexCache, fixed above. Broken by hand: on the old codexMerged, the new test fails with "Codex's list lacks codex/gpt-6.1-sol: [gpt-6-luna gpt-5.6-terra gpt-5.6-luna]". With only codex_spawn_models.go reverted, it fails with "spawn_agent's models lack codex/gpt-6.1-sol". Not tried: real accounts or a real Codex. Not a full go test ./... run. Not tried: models the backend marks hidden. A Codex here for failover alone (codexOwnOnly) is unchanged. |
||
|
|
1e1068c86c |
codex: "Same as the lead" holds every subagent to the lead's model (cleverpigo on X)
cleverpigo (Windows, Codex App 26.1027.6604.0) had Codex's lead on WorkBuddy's DeepSeek-V4.1-Flash, the subagent model on what the GUI called "Same as the lead", and the Routing page still showed a subagent on gpt-5.6-sol through Codex's own sign-in. Cause: that setting, unset, never held a subagent to anything. Since |
||
|
|
78667e9b77 |
gateway: a request in flight shows its model's context window
packinggoods on Discord: Routing's context window card said "the model's
window isn't known" for a request on remote-magpie/claude/claude-opus-5-5
that was still answering, though the remote magpie's list gives that
model's window. The window was put on a route's prompt only when the
request ended (calibrate at the route's end). A live request always
showed it as unknown, on every provider.
Now the window of the model a try goes to is read as the try goes out.
That is windowOf(c.p, c.model), the same call the route's end makes. It
is kept on the route (Route.window, unexported), and the prompt shows it
while the request is under way (livePrompt). This holds whether the
prompt is read before or after the try starts. A fallback to another
model updates it. At the end the answering model's window still comes
first, as before. Codex turns through magpie's Codex backend now work out
Codex's own window (CodexWindow, else models.dev) when the turn begins,
not when it ends, so they show it live too.
Run at this head (rebased on
|
||
|
|
b59e4b747f |
gateway: a conversation on a new account leaves out the old one's seals (#3887)
hheei (#3887): a Codex conversation with a web search in it (OpenAI's own web_search, a web_search_call in its history) failed on every turn with "HTTP 400: Codex: Encrypted content could not be decrypted or parsed. (code: invalid_encrypted_content)" once magpie had moved it to another ChatGPT account of the same routing group: after its affinity went cold ("why": "cold", over two hours on), or after the account it was on was used up or rate limited. What an account's turn wrote comes back sealed for that account (encrypted_content): its reasoning, a web search, and with Codex's output token replay on (codex-rs core/src/client.rs: only for a provider named "OpenAI", which Codex signed in reaches magpie as) each message and call. Codex hands it all back on every turn, and between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as it came (forVendor, |
||
|
|
694f4a6d65 |
gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.
- Codex's own path (codexBackend, the Codex relay, the Responses
WebSocket's read limit, keyLimited on CodexPath) reads to
codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
It is still the bomb guard: nothing decodes past it, and the zstd
decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
the 512 MB of every other route once its model is read: it is
translated, at several times its size. Its 413 says one of Codex's own
models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
GetManyBytes, which copied the whole input (the body's size: 300 MB of
a 300 MB turn in the alloc profile). It reads in place now.
Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.
Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
turn of generated images in Codex's shape): reaches the fake ChatGPT
backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
"one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).
Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
|
||
|
|
affa979d56 |
gateway: Codex's one account used up goes on to the Codex subscription's fallbacks
adorable_piglet on Discord: once the ChatGPT (Plus) account's quota ran
out, the Codex app couldn't send at all, and magpie never moved the turn
to the fallback they had set (their own API key, another provider).
Cause: with one ChatGPT account and nothing to route, a turn on Codex's
own sign-in is relayed as it came (codexUpstreamOn). The relay handed an
overload on to the subscription's fallbacks (codexFallBack), but a
quota, credit or rate refusal went to Codex as the backend said it, the
429 usage_limit_reached with its x-codex headers. Codex then stops.
Change: codexAccountOut names the refusals that are the account's, not
the request's: failure() quota, credit or rate, as a status or as a
stream's failure before any reply (response.failed, an error event, a
stream without Content-Type), and a 403 usage_not_included. Never a 401:
Codex renews its own sign-in on it. When the subscription has fallbacks
(codexFallsBack, never a compaction), such a refusal now goes on to them
once the credits retry and the automatic reset have been looked at, as
an overload does; the trace keeps the try's real failure kind. With no
fallback set, Codex still gets the backend's refusal.
What Codex's own client does: it greys Send from its own /wham usage
read. magpie already gets past that once the usage reading says used up
(codex.out with the app-server restart, #540,
|
||
|
|
8819beeb0e |
gateway: a display reads routing as it happens at /v1/magpie/route-events (#3387)
joe21_eee (sywyyhykkk on GitHub) wrote this for an ESP32 screen that shows each agent's requests live: started, each try, the first content, fallback, done. Ported from their route-events branch (42e1fa43f) with the changes below. What a display gets (route_events.go): - GET /v1/magpie/route-events/snapshot: cursor, active, routes (every request the trace has that is still going). - GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID): SSE, one "route" event a change, id = cursor, from a 512-change ring under trace.mu, so a short request is told step by step. 409 snapshot_required for a cursor not this process's or too old, "event: reset" for a reader that fell behind, a heartbeat every 15s, a 10s write deadline. - A route is routeActivity, an allow list: trace id (base 36), time, agent label, the provider of the seat the last try went to (never the seat id, which names an account or a key fingerprint), model, attempt, fallback, phase, status, failed, ms, ttft_ms. No session, account, key, folder, prompt, reply or error text. - firstToken.onFirst tells the first content as it comes (serve and the ChatGPT backend's reads), written to an unexported Try.firstMs so the full trace's TTFT is unchanged. Changed from the branch: - No new key type. The branch added an "sk-magpie-route-" key, its CLI flag and its own Authenticate path through access, identifyCaller and corsGuard. main has read-only keys now (readOnlyGuard), and the feed is answered as /v1/magpie/usage is: this computer, and another machine with an enabled key while shared; a held key is refused (refuseHeld). Both GETs are in readOnlyRoutes, so the display gets `magpie gateway-key add Screen --read-only`. A full key already reads more than this (every call's usage). access, cli, cors.go and lan.go are untouched. - A route the trace drops unfinished (drop: an unrouted request's stand-in once its own route begins; trim past twice traceKeep) is told request_dropped and marked offFeed. The branch kept its own active map that only "done" cleared, so a stand-in stayed going forever. The snapshot is read from t.routes, no second map. - A stream ends when the gateway stops serving (Server.streamsEnding, closed first thing in ListenAndServe's drain). Before, an open stream held srv.Shutdown for its whole drain, 15 minutes on a handover. - Revocation is access.On(KeyID) (identifyCaller swaps the secret out before handlers see it), asked at most once a second when there are changes and at every heartbeat, and remoteKeyed for a remote reader. A rotated key keeps its id, so its open stream goes on until it reconnects (said in the docs). Docs: gateway-routing.md "Route events for a display" and the read-only key's route list; reference.md beside the usage API. Run at the pushed head on mote (Go 1.26.8): - At daaafeb6e (rebased on |
||
|
|
c86fa2a341 |
gateway: a relayed citation without the offsets OpenAI's schema wants is dropped, the thread healed (#4921)
A thread a routing group served once on Volcengine Ark (or another vendor whose Responses endpoint writes its url_citations with no start_index/end_index) never worked on a codex member again: magpie relayed the reply's annotations as they came, Codex stored them, and the ChatGPT backend refused every later replay of the history whole — "Missing required parameter: 'input[221].content[0].annotations[0]. start_index'" — five retries a turn, on any codex member, through any upgrade (#4921, the reporter's routing log and rollout). This is #2855's defect with a different field: what magpie hands a client must be something magpie could send again. Such an annotation goes, at both seams, as the reasoning-item fix did: - a whole reply streamed as the vendor's own events (responsesWholeEvents) drops it in every place a client reads a citation: its annotation events, the content part, the item and the reply the client keeps (dropOffsetlessCitations); - the history Codex replays loses it on its way to the ChatGPT backend (withoutOffsetlessCitations, the same leaving-out as a reasoning item's text, #1411): to the backend by its own sign-in and compaction relay (codexUpstreamOn), to it as a group member or an openai.com or Azure upstream (the provider loop, beside withoutReasoningText), and asked again without it where a relay in front of it names the parameter (refusesCitationOffsets), marked so it is never sent one again — a thread already poisoned heals on its next turn, no new thread needed. The text, and a citation that carries its offsets, go as the vendor wrote them; a turn with no "annotations" in it is not decoded (anyInputItem scan, itemCitesWithoutOffsets; the undecoded-turn test holds, allocations and all). Run: the three new tests fail on the base with the reporter's exact 400 and pass here (ablation: the tidy call and the rewrite's body neutralized, tests kept); TestCodexRewritesAsBefore, TestCodexRewritesLeaveTurnUndecoded and the fuzz hold the rewrite to its scan; the citation/whole/reasoning neighborhood ok (23s); gofmt, go vet (linux, windows) and go build -tags nogui clean. Review: this is skygunner's version of the fix (fcea11649), not ggbdpq's 57dc7b420. ggbdpq's stripped citations only for a request that wasn't for a magpie model, so the reporter's own path (a routing group's codex member, the history passed through) kept the bad annotation. ggbdpq's parity table and verification of the report were used to check this one. Changed in review: annotationLacksOffsets looks only at url_citation and container_file_citation, the two types OpenAI's schema gives start_index and end_index. file_citation and file_path carry a single index, so the patch dropped every one of them as "offsetless". TestCitationsWithOneIndexKept (added in review) holds both kinds and checks that a history with only file_citations is sent byte for byte. Broken by hand at the reviewed head: annotationLacksOffsets made to return false, all four citation tests red; the type check removed, TestCitationsWithOneIndexKept red. Restored, green. Run at the pushed tree (this stack of nine on origin/main |
||
|
|
4bac5eed26 |
usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted ~900 MB up in 45 minutes, and no ledger row said what a request sent. A row now has up_bytes, the bytes that went on the wire, every try and every second ask summed (zstd's size for a ChatGPT turn), and plain_bytes, the last try's body before compression. They are summed in the request's context on its own goroutine, set in serve and, for Codex's own turns that come from the mux and not through serve, in codexUpstreamOn. Handed-on rows carry neither; rows from before carry neither. From ggbdpq's patch (via gua2100), two changes: - the patch counted in codexUpstreamOn but set the context only in serve, so a Codex turn on its ChatGPT sign-in, the zstd case the issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes); - a second request inside one try (RetryOneAuth, RetryZhipuCoding, RetryOpenCodeFreeOnZen) went up uncounted; it counts now (TestLedgerCountsATrysSecondAsk). Request bodies to other vendors stay as their client sent them; zstd stays Codex's (the owner's call, on the issue). Run at this tree on mote: go test ./internal/gateway -run 'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok; go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean. Broken by hand: no context in serve: TestLedgerKeepsUpBytes and TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn: TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444); the second ask not counted: TestLedgerCountsATrysSecondAsk red. Not tried: a real session's numbers against a proxy's; the GUI shows neither field yet. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
f822689ada |
gateway: a relay's "referenced reasoning item" refusal is read as an unreadable item (#3062)
What changed: unreadableItem, the matcher that reads a 400 as "this input
item can't be read", now also takes the wording a Responses passthrough
relay answers in — "Referenced reasoning item 'rs_…' was not found or has
expired" — beside OpenAI's own ("Item with id 'rs_…' not found",
"encrypted content for item"). The refusal is recognized wherever the
matcher is read: the passthrough turn is asked again without the bare
reasoning (and the provider's model isn't sent them again), the ChatGPT
backend drops the named item and asks the rest again, and a compaction
refused so is asked again as text.
Why: a Codex thread behind such a relay (opencode.ai's OpenCode Go)
collects reasoning ids the relay can't resolve, two ways — a turn failed
over to a provider magpie translates leaves Codex reasoning items magpie
minted (an rs_ id and a summary, nothing sealed), which never existed on
the relay's store; and the relay seals its own reasoning only briefly, so
after a resume gap ids from its earlier replies read as expired. Codex
replays the whole history every turn, and the relay's 400, worded by the
relay and naming no input param, passed refusesInput unread — so the
thread 400s on every later turn. The reporter's repro now strips the
named bare item, asks again, and answers 200.
Run: TestRelayRefusedReasoningItemReadAsUnreadable and a TestRefusesInput
row for the reporter's exact body are red before the change and green
after; the bare-reasoning, foreign-seal and item-not-found families stay
green (also with -race, and under an ablation and a mutation of the new
wording, where the old wordings' tests stay green); gofmt clean; go vet
on darwin, linux and windows; builds with -tags nogui on the three. Full
./internal/gateway/ is green on the third run (511s); a first run hit go
test's default 10m timeout and a second failed only
TestAsyncGatewayResponseDoesNotHoldStream — a fixed-10s-guard streaming
hook test unrelated to this change, which passes 3/3 alone.
Generated-by: GLM-5.3-Flash (ZCode)
Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id
checked against the issue) by yetone, rebased on origin/main 2026-11-03.
Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of
internal/gateway with -run over this batch's tests and their families
(PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay,
Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of
the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway
and gofmt -l clean. The full gateway-and-importers run, started at an
earlier base, was still running at the push; its reds get issues.
Broken by hand: the regexp change reverted, test kept:
TestRelayRefusedReasoningItemReadAsUnreadable red; restored, green.
Not tried against the reporter's relay; the fixture is its literal body.
|
||
|
|
5ec2375688 |
gateway: a call's HTTP headers both ways, masked, folded under its bodies
usrname1833 on Discord asked to see the raw request and response HTTP headers (查看原始请求和原始响应的http头), to debug as with a capture. magpie kept the client's request headers and its own response headers only in the request archive, and nothing of what went upstream. Now a call keeps its headers both ways (internal/gateway/wire_headers.go): - the client's, as they reached magpie: headerLogged in Handler() clones them for every request that isn't a GET, HEAD or OPTIONS; - each request magpie sent upstream for the call: method, address, headers, and the answer's status, protocol, headers and time, or the error. rpmTransport (under s.client) records it as it is sent; provider.SendsThroughPlugin records a plugin account's hand-off, shown as handed to the plugin, since the plugin's own request to its vendor is made in Bun and magpie doesn't see it (the view says so). The first 8 tries are kept, the rest counted. Recording copies each header map; nothing is masked or sorted as a request goes. Secrets are taken out when the headers are read (Call.Headers): by what each header is (new redact.SecretHeader, now behind redact.ScrubHeader: Authorization, cookies, x-api-key, api-key, any *-Key, *-Token, *-Secret, *-Auth, *-Signature, but Idempotency-Key and a count of tokens such as anthropic-ratelimit-tokens-remaining), any Bearer or Basic value, and redact.Scrub on the rest; an address loses its password, a secret-named query value (?key=) and its fragment. They live with the call in the 40-call ring; /api/gateway/call gives them as "headers". The request archive keeps the upstream ones as "upstream" beside the request's and response's headers, masked the same way. No body is stored that wasn't before. GUI: under a recent call's bodies on Gateway and a request's on Routing, "HTTP headers" folds open the client's headers, then each upstream request beside its answer (wireHeadersView, plugins/usage/page.js); the archive's copy shows its upstream requests too. Strings in all four languages. docs/subsystems/gui-shell.md describes it. Also changed by SecretHeader: the request archive no longer masks a rate-limit count header (…-tokens-remaining), which the old name rule took for a token. (provider.SecretHeader, which backups use, is another function and unchanged.) Tests: TestRecentCallHeadersBothWays (a fake vendor; the client's key and cookie, magpie's upstream key and the vendor's Set-Cookie all masked; status, protocol and response headers kept), TestRecentCallHeadersEachTry (a 429 then the next key, both kept in order), TestPluginHandOffHeaders, TestScrubURL, TestSecretHeaderRealNames (real header names both ways), TestArchiveOnThisComputer and TestRecentCallBodiesOnDemand extended, call-headers.test.cjs (Gateway, Routing and the archive's copy; chromium and webkit; en at 1100px, zh, zh-TW, ja, de at 380px and Routing at 440; nothing out of the box, no left-border accent). Run (on mote, macOS 27.2, through mote-run, unless named): - Full suite at ebd22b1b4 (the same change on |
||
|
|
07f4d46c52 |
gateway: a Codex reply that ends early, and any failed call, is written to app.log
wjh66 (Discord, Windows, v0.1.2696) saw Codex on a ChatGPT sign-in with
gpt-6.1-sol show "reconnecting 5/5" and then `error decoding response
body`, and app.log around 15:27 held nothing about it. That text is
reqwest's for any read error in a body (a reset, a chunk cut short, a
timeout), so it says the connection broke mid-reply, not which side broke
it. The cause is not found; this change only makes the next report carry
evidence.
- record logs a failed call (status >= 400 or an error) when debug is off,
once a minute per agent/provider/model/status/error, counting repeats.
- codexUpstream logs a reply that ended before its last event (or a
non-SSE body cut by a read or write error): bytes passed on, whether
OpenAI's stream failed or ended, and whether Codex went away, a write
to it failed, or it was told response.failed.
- Shutdown with requests in flight says they are cut (Windows has no
handover, so a quit or update cuts streams after shortDrain).
Run at this head (rebased on 4bd0d6f38; the new and stream-cut tests and vet run again after the rebase on mote and Windows, the full gateway run on Linux was at
|
||
|
|
58541e5b8c |
gateway: a turn that ended failed, cut or canceled says no task done (#4866)
emo172 (mochi) reported that "<agent> 已完成" was shown for Codex turns
that never finished. On Codex signed in with ChatGPT
(/backend-api/codex), three cases were recorded as a clean 200 and
ended the turn: Esc or a closed window mid-reply, a response.failed
under the backend's 200, and a response.incomplete. codexUpstreamOn
looked only at the status and codexStreamCut. codexStreamCut says ""
when sniff.failed is set, when the stream is whole, or when the
context is done. trace.go:790 then ended the turn with final true.
The fix is in the one place both turn paths share, the reply scan
(toolScan) every byte to the agent goes through, and turnFinal, which
now decides `final` at trace.go:790:
- A cut mark makes a reply unfinished: an error event in each wire
format (Anthropic/Responses "type":"error", Chat/Gemini "error":{…}),
a Responses reply failed, incomplete or cancelled, and a reply cut
at its length (stop_reason max_tokens or
model_context_window_exceeded, finish_reason length, finishReason
MAX_TOKENS). Keys are matched with their quotes, so text or tool
arguments that mention them escaped never match. "error":null on a
success doesn't match.
- The agent's request being done before the reply's last event
(response.completed, message_stop, a stop reason, [DONE]) makes it
unfinished too. A client that hangs up after the last event, as
Codex does, still ends its turn.
- A Responses tool_search_call that Codex runs itself
("execution":"client") counts as a tool call. It was missing from
toolValues.
Codex direct also records what it saw, as the routed path does: 499
canceled when Codex went away mid-reply, and the backend's
response.failed as the row's error. Covered: the Codex HTTP and
upstream-socket paths, Codex's own socket to magpie
(response.interrupt), and routed Chat, Responses and Anthropic relays,
plugins included, since they go through captureResponseWriter.
Scene A, a model ending its turn with a question for the user: no
change. Nothing in the bytes tells "asks the user" from "done" without
reading the text, and a turn's end with the agent waiting on the user
is what the alert is for. Structured asks are tool calls and don't
alert already.
Tests (turndone_unfinished_test.go), from real event shapes:
- TestReplyScanUnfinished: 14 replies, each split at six points.
- TestTurnDoneCodexBackendUnfinished: failed, incomplete and canceled
(the agent hangs up on its first write). No end, the route says
error or 499, and a whole reply after each ends the turn.
- TestTurnDoneCodexSocketInterrupt.
- TestTurnDoneRoutedUnfinished: Chat error and length, Responses
failed and incomplete, Anthropic error and max_tokens.
Run on mote:
- go test -timeout 45m ./internal/gateway at c08d02adf (this change
on
|
||
|
|
b4a9cd8db5 |
codex: a tool name the ChatGPT backend refuses goes as one it takes, and comes back as the agent's
wing3556 on Discord (11-02): a compaction through a Codex account failed 400 "Codex: Invalid response.create payload: Invalid 'input[83].name': string does not match pattern. Expected a string that matches the pattern '^[a-zA-Z0-9_.-]+\z'." The ChatGPT backend checks every tool name in a request, a call's in input as well as a tool's in tools, and refuses the whole request when one fails. A conversation can hold a call by such a name: a model another provider served wrote one with a space, a colon or non-ASCII in it, and the agent kept it beside its "no such tool" answer. Every request that replayed it, the compaction above all, then failed on Codex. Nothing on the way checked: buildResponses copies a call's name as it is, and redaction keeps names as written. What changed: - provider.CodexToolName: a valid name stays as it is. Otherwise each refused byte becomes "_", the result is cut to 55 and gets "_" plus 8 hex of its sha256, so it is the same on every request and two names never meet. CodexToolNames applies it to tools (namespace children too), function_call/custom_tool_call items, additional_tools and tool_search_output items, and tool_choice. A body with no bad name goes byte for byte. - It runs where every request to the ChatGPT backend passes: codexBody (an account's, translated or relayed) and codexUpstreamOn (Codex's own sign-in, /responses and /responses/compact), beside DeclareSearch. - A tool the agent declared under such a name is called back by its own name: translated replies through decoderFor (now given the request's tools; codexNamesBack), relayed Responses replies through nsTidy's new back map (codexRenamedIn). - docs/subsystems/gateway-routing.md says so beside #1270's paragraph. Not covered: namespaces, the OpenAI API (whose pattern has no "." and a 64 limit), Azure and Copilot Responses, filed as #4875. Run on mote at this head: - TestCodexToolNamesTheBackendTakes and TestCodexToolNamesKeepValid pass. The fake backend refuses a bad name with the reporter's 400 word for word; the test covers Claude Code's compaction on /v1/messages with four bad history names (sent twice, byte-equal), Chat with a declared "search:web" called back by that name, Responses relayed the same, and Codex's own /backend-api/codex/responses. - go test ./internal/provider ./internal/gateway (-timeout 45m): provider ok; gateway ok but TestCodexPoolSaysTheClientsVersion, the red already filed as #4807 (full package run only, another test's Codex identity reaches it); it passes alone at this head. - go vet ./... (darwin) and GOOS=linux/windows CGO_ENABLED=0 go vet -tags nogui ./...: ok. gofmt -l: clean. Broken by hand: - codexBody hook off: compaction red with the reporter's 400. - codexUpstreamOn hook off, decoder restore off, passthrough restore off (together): the codex, chat and responses cases each red. Not tried: wing3556's real conversation (we don't have its bytes, and the agent is unknown; Claude Code is likely). No real ChatGPT account was asked with a bad name, so whether the real backend also limits length is unknown. |
||
|
|
dd809ea60f |
gateway: an input item's id longer than the 64 an upstream that checks ids takes goes shorter, as its kind's prefix and the sha256 of the whole of it (#4525, #4527)
Codex carries every id an earlier turn came back with, and Copilot gives its items ids hundreds of characters long: 420 as isnine's sessions each showed (#4525), 444 as ghjkllasdf-fake's approval session and its guardian review did (#4527), all of the characters OpenAI takes an id of. plainItemIDs checked the characters only, so every later turn went to Copilot as it came and was turned away 400 "Invalid 'input[N].id': string too long. Expected a string with maximum length 64, but got a string with length 420 instead." — the conversation stuck, a tool call never answered, Codex's automatic approval review failing over it. An id longer than the 64 goes as its kind's prefix ("msg_", "rs_") and the sha256 of the whole of it, cut to fit: the same id to the same shorter one every turn, and no two ids land on one, where a plain cut could (ids of a vendor can begin alike). Copilot's own reasoning, overlong but of the right characters, keeps its place with its seal — an upstream that checks ids made that one, its encrypted_content is its to read, unlike another vendor's, which still goes as it did. A call's call_id was bound already (BoundCallID); one shorter than 65 goes as it came. What changed - gateway: itemIDCap (64) and boundItemID, and plainItemIDs bounds an input item's id at them, on every relay that checks ids as OpenAI does — Copilot's /responses among them (validatesItemIDs) - tests: an id checker that turns an overlong id away word for word as isnine got it; Codex's turn over a Copilot conversation of overlong ids asked twice, the same bound each turn; the 64/65 boundary, determinism, idempotence, two ids that begin alike going to two; the parity harness holding plainItemIDs to it beside what it was Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
cbfbcb383b |
usage: a lead's answers are looked up in the blocks that name its conversation (#4370)
loggedAnswers, which leadFirst falls back to when affinity has lost a Codex subagent's lead, read thirty days of the log into a Record a row and kept the rows of one conversation. usage.VisitSessions reads only those rows: a block whose Session and NativeSession strings don't name the conversation is skipped, a row of another session is passed over by its shape's string ids without becoming a Record, and a matched row's strings are cloned out of the lent decode buffer. Each packed block's sessions are kept once it is decoded (blockSessions, by weak pointer, so no block the log let go is held), so a lookup decodes only the blocks the conversation is in and the open tail. A page's copy with Codex identities (which rewrite Session as a row is read) is read whole and filtered on its records. Run on mote (macOS 27.2), at load ~70: - BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300): visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and 12KB. - A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions, 18 blocks): every session looked up both ways gives the same records; 6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for a conversation that isn't there. - TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions, red with the known-sessions skip taken out. - GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean. - go test -race of the new tests and the gateway tests of a lead's answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s). - go test ./internal/usage ./internal/gateway (whole packages) was still running on mote at load ~190 when this was pushed; its result goes on #4370. Not tried: a real Codex subagent whose lead lost affinity; the lookup's callers and filters are as they were, and the gateway's loggedAnswers tests cover them. |
||
|
|
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 |
||
|
|
e4384fc3cd |
gateway: a Codex stream cut inside a line still has its failure read (#3377)
#3377's patch writes response.failed when the upstream cuts a Codex stream mid-reply. When the cut lands inside a line, the half line was still open, so the events streamError writes were read as more of that line's data and the client never parsed the failure. A blank line now goes first, ending the half event (as #2446 and #2580 do on the other relays). TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's data and checks every event the client reads parses, apart from the half line itself, and that response.failed is among them. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
cbefb65987 |
gateway: a compaction summary answered 502 for ending short compacts locally too (#3526)
#3526's patch compacts locally when the summary ask ends short with an error. The same cut can come back as a recorded 502 whose error says it ended short (errEndedShort), with no error returned, and that still went to the client as a 5xx. The local fallback now runs before the status check, for both shapes (summaryEndedShort), and says why from the recorded error. A 502 that says anything else still goes to the client as it did. Edward4226 pointed at the 502 shape in the thread. TestCodexCompactCutShapesCompactLocally covers a stream error, a 502 saying it ended short (compacts locally) and a 502 saying more (stays 502). Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
5b63dfd1a8 |
gateway: a Codex stream the upstream cut mid-reply is told to the client as its failure, and the row says why (#3377, Azir-11)
The ChatGPT backend cut every relayed stream about two minutes into the reply (121-125s, deltas flowing to the end): no response.completed, no error event, no usage, and Codex read a bare EOF, "stream disconnected before completion". Nothing in magpie bounds a stream that way — the gateway's client sets no Timeout, the upstream transport's only waits are ResponseHeaderTimeout (10 minutes, to the headers) and IdleConnTimeout (idle connections alone), the server sets no WriteTimeout, and the body's read deadline is dropped once the body is read — so the relay passed the cut on as it came, and was silent about it: the client's stream just ended, and the usage row recorded a clean 200 with nothing of why. Now a relayed stream that ends mid-reply — SSE, no failure said, no last event reached, the client still there — is answered with the stream's response.failed saying how long it had gone and that the reply is lost, and the row records the 502 with it. What magpie cannot do is keep the upstream talking past its cut: the wall itself stands on the magpie-to-chatgpt.com leg (the reporter's direct Codex ran 480s and 719s on the same machine and network), and telling it apart is what the honest failure is for. TestCodexStreamCutToldTheClient fails without the change: the fake upstream ends its stream after one delta, and the client heard no failure and the row said 200. go vet clean; go test -tags nogui ./internal/gateway/ passes in full. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
6f041c292c |
gateway: a Codex compaction relayed to a vendor that isn't OpenAI's asks as system, not developer (#2955)
forVendor, the fitting a relayed Responses request gets before it goes to a provider that isn't OpenAI's, now turns the developer messages of a summary ask magpie made itself (codexCompact) into system ones, where they stand (developerItemsAsSystem). Codex's own turns keep the role the client sent, which a relay may be checking them by (#350, #1758), and OpenAI's own API and the ChatGPT backend, which take developer as Codex sends it, get the compaction as it came too. Why: on a provider whose Responses endpoint fronts a chat-only vendor (a relay of one; DeepSeek's preset names one base for chat and responses alike), every Codex compaction failed there with 400 "developer is not one of ['system', 'assistant', 'user', 'tool', 'function']", retried five times, while the turns around it passed: the summary request is relayed as Codex sent it (tools: [], #378), and the compaction carries a developer message its turns don't. The translated route already lifts such messages into the system prompt; the summary ask now says them as system on the relayed route too, in place, so a thread's cached prefix keeps its shape (#502) — what Zed's cloud is already given (ZedBody) and what a Chat Completions upstream is given (developerAsSystem). Run: TestCodexCompactDeveloperAsSystemOnAVendorRelay (red before, green after; ablated and mutated), the compaction families (TestCodexCompact*, TestLocalCompaction*, TestNativeCompaction*, TestVendorRelay*, TestAdditionalTools*, TestCodexOpenAIFields*), the full gateway package, -race over the families, go vet and go build of the package on darwin, linux and windows. Refs #2955 Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
78632d4b84 |
gateway: a Codex compaction cut short with no candidate left compacts locally (#3526, Edward4226)
A summary wanted whole whose stream every candidate broke off reached codexCompact as an error none of its fallback conditions name: not a 404, not an unreadable item, not "Upstream request failed", not "response protection is unavailable". The relay ends such a stream with a response.failed event saying "the reply ended before it was complete" (#2274), and with nobody left to fail over to, that error fell out of the 404/protection family and went to Codex as a 502. Codex asked the same huge summary over, three times, each paying for the whole conversation, until compactFails answered 400 and held it: the conversation could neither compact nor go on. That is the no-candidate case #2274 left, after it made a cut summary fail over where there was someone to fail over to. The summary is magpie's own then, as when no model can be asked at all (#866, #1008, #1270 end so). The summary as text isn't tried either: the cut was in what the model wrote, not in what it was asked, and that would be another ask of the same huge prompt. The words before the cut are never taken: the local summary is built from the request's own items. A summary that failed halfway, or ended incomplete — the output limit's own event — is still told to Codex as it came and still counts the guard; only the bare break-off turns local. 401, 403, 429 and request-shape refusals are untouched. Run: TestCodexCompactCutAloneCompactsLocally (new) is red on the parent with the issue's 502 ("the reply ended before it was complete, so there is no summary") and green here — 200, one magpie compaction holding the local handoff, the cut stream's words in none of it, the last ask the fake saw still the original summary request (no plain-text retry). The #2274 tests keep their shape: TestCodexCompactCutSummaryFailsOver (a whole fallback summary still wins) green unchanged; TestCodexCompactCutSummaryIsNoSummary now covers the halfway and incomplete shapes alone (the cut one moved to the new test); TestCodexCompactKeepsFailingIsHeld holds on the incomplete shape, which still fails and rests nobody. Ablation: only codex_backend.go put back to the parent, tests kept — the new test is red again, restored, green. go test -tags nogui -p 2 -count=1 ./internal/gateway: ok (350.8s). Targeted TestCodexCompact with -race -count=2: ok. ./internal/usage: ok. gofmt -l clean; go vet -tags nogui on darwin, linux and windows clean; CGO_ENABLED=0 go build -tags nogui on all three ok. docs/subsystems/gateway-routing.md says the new terminal state. Refs #3526 Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
bb50f4ad94 |
gateway: a Codex passthrough member OpenAI doesn't know is left out and asked again
xuanwo on X: every new conversation in the Codex app (two agents) ended
at once with the ChatGPT backend's 400 "[ObjectParam]
[input[55].internal_chat_message_metadata_passthrough.content_token_count]
[unknown_parameter]". The member is new in the Codex app's bundled
build; no open-source Codex sends it (main 67f0994, npm 0.166.0), and
openai/codex#52313 was the same refusal of content_item_metadata in
0.163.0-alpha.1. magpie sends the passthrough as Codex wrote it to
OpenAI hosts and ChatGPT accounts (forVendor), so the refusal reached
the app. The reporter's own look at magpie's routing log: the main
conversation failed at input[49] and input[55], and a conversation
with no subagent failed the same way, so subagents aren't the cause.
The member is Codex's own attribution, not the conversation. A turn
turned away over one passthrough member, or the passthrough as a whole,
is asked once more without it on every item, with the other members
and every other byte kept as written. The provider isn't sent that
member again (unfit, as for a tool's strict). The signed-in Codex
relay's retry (withoutUnreadable) takes the same refusal.
Run (mote, go1.26.8):
- TestPassthroughMemberLeftOutWhereRefused, TestPassthroughRefusalWordings,
TestWithoutPassthrough: ok.
- Broken by hand: with the retry turned off, TestPassthroughMemberLeftOut
WhereRefused gets the reporter's exact 400 back.
- At
|
||
|
|
9551fadcb4 |
gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at base |
||
|
|
0956ca49d7 |
gateway: Codex's own sign-in asks again after a connection dropped with no reply
aetrox333 on Discord: on Codex, bare gpt-6-luna and gpt-6.1-terra
failed with 502 "OpenAI can't be reached (Post …: EOF)" after 43ms
every time, through a fake-IP proxy (chatgpt.com at 198.18.0.12),
while auto/gpt-6-luna and auto/gpt-6.1-terra answered 200 every time.
Cause: a bare Codex model goes to ChatGPT on Codex's own sign-in
(codexUpstreamOn), which ended the turn with 502 at the first transport
error. Go's transport sends a POST again by itself only on a reused
connection (replayable, #2136), so an EOF on a fresh one, a proxy
closing it before a byte of a reply, came straight back to Codex.
auto/ and codex/ go through the accounts loop, which takes the same
502 as passing and asks again after a pause on a new connection, or
asks the group's next member. Both routes share one client, transport,
proxy choice and HTTP/1.1; a recorded diff of the two requests showed
no difference that would change how a proxy treats them (the routed
one adds instructions, Openai-Beta, Session-Id and its own token).
Now a dropped or reset connection with no reply on the own sign-in's
/responses is asked again, retryPause<<n apart, up to lastRetries, as
an overload is (askAgain: the trace shows each try, Codex is kept
alive). The caller gone and a wait that ran out are not asked again.
After the last try Codex is told OpenAI can't be reached, as before.
Run (mote, at this head rebased on
|
||
|
|
b62fa332f3 |
provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and asked why "Send requests unmasked" (请求不脱敏) isn't offered for it. |
||
|
|
dafe4af822 |
gateway: the ChatGPT backend's "auto"/"default" tier is recorded as unknown (jjt on Discord)
The ChatGPT Codex backend says service_tier "auto" in response.created and "default" in response.completed whether priority ran or not. jjt's measurements on gpt-6.1-sol with a Plus account: Fast decodes at about 200 tok/s, without it about 110, and the reply says "default" both times (real-priority.sse, speed-plus.txt). magpie copied that into tier_served, so the usage log, its CSV and /v1/magpie/route said served = default for requests that ran Fast. servedTierAt (tier_record.go) leaves those two words empty when the reply came from CodexBase's host. It is applied once per routed try, in attempt (gateway.go, a defer, so every return path and the route's tries see it), and on the relay of Codex's own sign-in (codexUpstreamOn). OpenAI's API, where service_tier means what it says, keeps it as given: a provider at api.openai.com and Codex with an sk- key relayed to it. "priority" or "ultrafast" said by the ChatGPT backend is still kept. Display: tier_served is shown by the CSV (an empty cell), the JSON log and /v1/magpie/route (omitempty). No GUI page or TUI shows a tier (grep of internal/gui/assets and internal/tui for tier_served, tier_asked, tierServed: none), so no strings changed. docs/reference.md and docs/subsystems/gateway-routing.md say it. Tests: - TestChatGPTBackendTierUnknown (new): the backend says auto, then default (jjt's events, cut to the fields read); a routed try asked priority and one asked nothing, and Codex's own sign-in relayed, all record "" in usage and the route. - TestOpenAIAPITierKept (new): api.openai.com's "priority" and "default" kept, routed and through the sk- relay. - TestTierRecordedPerTry: its "none asked" case on the ChatGPT backend now expects "" where it expected "default". Run on mote (mote-run; the wider run at base |