88b4c00ea11c8653cada22e11edf20ab1594de43
115
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
4fbb75c3a8 |
gateway: Codex's 507 "exceeded request buffer limit" is asked again and told as a 503, not relayed as it came (#2034, sparrowu93)
sparrowu93's pi, on a ChatGPT account, stopped on "Codex: 507 Insufficient Storage: exceeded request buffer limit while retrying upstream". That text is Envoy's (ChatGPT's front): its first try at the backend failed, and the body was more than it buffers to try again. It is the same backend failure as #1628's 503 "reset before headers", which magpie already asks again for without resting anybody, only for a body the front couldn't retry itself. magpie relayed the 507 as it came; pi's _isRetryableError (pi-coding-agent 0.73.0, agent-session.js) matches 503 but not 507 or these words, so the turn just ended. codexDropped now reads that 507 (by Envoy's words alone, any size, since the 507 itself says the body was large) the way it reads the large request's 503: the accounts loop asks the next account and the last one again, nobody rests, and the agent is told a 503 with Envoy's words and what may help (/compact, fewer or smaller images). The relayed path (codexUpstreamOn, Codex's own sign-in) asks again the same way: the two share edgeMayDrop/edgeSaidDrop. A 507 in other words is relayed as it came. gateway-routing.md says so. Run: - New TestCodexUnbufferedAskedAgain, TestCodexUnbufferedTold503, TestCodexUnbufferedRelayed, TestCodexOther507Stays, with the reporter's literal Envoy text as the fixture. On the old code the first three fail: "status 507, want 200 pong: {...\"message\":\"Codex: 507 Insufficient Storage: exceeded request buffer limit while retrying upstream\"...}" (the reporter's message byte for byte), and "507 once: 507 ... tried [acct-1]". With edgeSaidDrop matching every 507, TestCodexOther507Stays fails. Restored, all pass, with #1628's TestCodexReset* tests. - go test -tags nogui ./internal/gateway/ (sandbox HOME, pinned caches), gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet (with and without nogui) on internal/gateway. Not tried: a real 507 from ChatGPT (it needs the backend to fail a request over Envoy's buffer, which can't be made to happen on purpose). |
||
|
|
12ecb6d8e9 |
gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget, and that key still read every account's quota and balance. A held key (heldKey: a budget, models or accounts) is someone else's to use, so it now gets 403 with code gateway_key_held (refuseHeld) on /v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and /v1/magpie/concurrency. That holds from loopback as well as the LAN, the same as usageSummary already did. /v1/magpie/route tells it only the routes of its own requests. Route.callerKey is set by trace.beginFor at all five begin sites, so a route begun without it fails closed. It still reads its own limit at /v1/magpie/limit. Unrestricted keys and the local owner are unchanged. Client side (remote magpie): a 403 gateway_key_held drops the cards kept from before and shows only the key's own card, instead of "isn't shared". The cache is now keyed by provider and key (remoteCardsID), so a changed key never shows what the old one was told, and keepRemoteCards keeps a read only over one asked before it, so a slow pre-held answer can't bring cards back. Decided against letting an account-held key see its own accounts' cards: that would still show the host's account email and balance to the key's holder. Run: - New TestHeldKeyToldNoAccounts covers keys held by budget, models and accounts plus one held to nothing, from 127.0.0.1 and 192.168.1.9. Every route goes red with the refuseHeld calls or the route filter removed by hand. - New TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard goes red with the errKeyHeld mapping removed. TestRemoteMagpieCardsKeptByKey goes red with the cache keyed by p.ID alone. - gofmt -l and go vet (darwin, linux -tags nogui, windows) are clean. - go test -tags nogui ./internal/gateway ./internal/provider -count=1 passes in a sandbox HOME. Not tried: two real machines over the LAN; the tests drive the handler with LAN remote addresses. An older client shows "isn't shared" (or its cached cards until they expire) against an updated host until it updates too. |
||
|
|
ea1ba22c32 |
gateway, gui: Codex's composer predictions go where Settings › General says, Off among them (#1970)
pluo's Usage view showed Codex calls of kind composer_predictions at
133k-231k tokens each with no cache read: ChatGPT.app's Codex guesses the
user's next message with a hidden turn on a fork of the thread, on the
thread's own model, reading the whole conversation again each time. It
asks only when the thread's provider is "openai", so through Codex's own
ChatGPT sign-in (and a custom table pointed at magpie). The app's bundle
(fge) asks for {suggestion: string|null} and uses b.suggestion||null.
What changed:
- settings.CodexPredictions: "" as Codex sends it, "off", or a model id
(provider/model, group/<id>); anything else is refused on load.
- gateway: codexPredictionsTo + codexPrediction, wired beside the
descriptions at both entrypoints (gateway.go and codex_backend.go).
Off answers {"suggestion":null} from magpie and sends nothing (the
title Off path made generic as sentNowhere). A model's answer goes back
only as the object Codex asked for (predictionJSON: think tags and code
fences stripped, suggestion trimmed, blank = null). Plain text is never
taken as a suggestion, since Codex would put it in the user's composer
as their next message; it gives null and is recorded as a failure
("prediction: ...").
- usage: purpose "Prediction" for composer_predictions (purposes.js
regenerated).
- gui: POST /api/settings/codex-predictions, kept by the general save;
Settings › General row "Codex composer predictions" (Codex's own / Off /
magpie's models, the app's picker), hidden in gateway mode; Routing's
story for the kind says Codex's own switch (Settings › General › Show
predictions) and magpie's. i18n in zh, zh-TW, ja, de.
- docs: gateway-routing.md's Codex section, reference.md's gateway-mode
list. site/ docs left for the owner.
What was run:
- go test -tags nogui ./internal/gateway/ (full, -timeout 40m),
./internal/gui/ ./internal/settings/ ./internal/usage/: pass.
New: TestCodexPredictionsSetting (default to ChatGPT, off sent nowhere,
model routed, plain turn untouched, ledger kinds), TestNoPrediction,
TestCodexPredictionOnMagpie (/v1/responses and the backend path),
TestPredictionJSON; gui TestCodexPredictionsSetting.
- Broken by hand, each went red: backend wiring removed; plain text
accepted as a suggestion; the general save not keeping the setting;
the Routing story's kind check.
- Playwright codex-predictions.test.cjs: chromium + webkit, 1100 and 420
wide, en/zh/zh-TW/ja/de (20 pass). routing-kind (with the new kind),
codex-descriptions, codex-titles, i18n-keys, gateway-mode,
purpose-filter, routing-purpose-state, settings-general,
settings-sections, settings-search: pass.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows.
Not tried: the real ChatGPT.app's predictions against magpie (the
feature is gated server-side by /wham/predictions/config and isn't on for
the owner's account); the reply shape is from the app's bundle.
|
||
|
|
9b52fb504a |
gateway: Codex's web search on magpie's models answers, no longer 404 (anton on Discord)
anton on Discord (Linux): asked to look something up, Codex called its web.run tool, which posts to <base_url>/alpha/search, here http://127.0.0.1:3425/v1/alpha/search. magpie had no such route and answered 404, and Codex takes any failed web.run as fatal, so the turn ended. Why Codex sends it: since 0.143 (#29909) Codex offers web.run to a provider that sends x-openai-actor-authorization, as magpie's provider table does, on a model whose catalog entry says use_responses_lite, as a ChatGPT account's models do in magpie (codexcat copies Codex's own entry). The request is codex-api's SearchRequest (id, model, input, commands.search_query/open/click/find..., settings, max_output_tokens) and the reply is {encrypted_output, output, results}, output being what the model is shown. What changed: - POST /v1/alpha/search and /alpha/search are served (codex_search.go). - A ChatGPT account's model goes to the ChatGPT backend's /backend-api/codex/alpha/search, as the official client sends it: on the account's sign-in (codexSign, no SSE Accept), the model bare, the body otherwise as it came (through redaction), only Codex's own x-openai-*/x-codex-* headers kept (codexHeader: never magpie's token or the actor header). Its own paused sign-in is passed over, the key's account and model holds kept, and the next account is asked on a non-2xx; the backend's answer is relayed as it is. - Any other model's search_query/image_query (domains as site:) is searched by webSearch, as magpie searches for a model that can't. When nothing answers, or only open/click/find were asked, the reason goes back as a 200 with output, which the model reads, instead of a failure that ends the turn. A ChatGPT search that fails on every account falls back to the same, saying why. - On the Codex backend path a magpie model's /alpha/search is served the same, never relayed on Codex's own sign-in; one of Codex's own models goes through magpie's accounts when its turns would (codexAccounts), else is relayed as before. - docs/subsystems/gateway-routing.md names the route. What was run (worktree on origin/main, sandbox HOME, private GOCACHE): - New tests from Codex's own wire fixture (codex-api endpoint/search.rs): TestCodexWebRunSearchesOnChatGPTAccount (both paths; acct-1 429 -> acct-2, bare model, body kept, no magpie token/actor header, turn metadata kept), TestCodexWebRunChatGPTFailsSearchedByMagpie, TestCodexWebRunOnOtherModelSearchedByMagpie (no searcher hint, search API asked "OpenAI news site:openai.com", open-only, bad JSON 400, and a stub ChatGPT backend that fails the test if reached). - Broken by hand three ways, each red: without the /v1 route (404 as anton saw), without the codexBackend case (relayed to the backend on Codex's sign-in), without the ChatGPT forward (searched by magpie). - go test ./internal/gateway/ -timeout 30m, gofmt -l, go vet darwin, GOOS=linux go vet -tags nogui, GOOS=windows go vet. Not tried: the real codex binary against a sandbox magpie, nor a real ChatGPT account's /alpha/search; the shape is from Codex's source and its own test fixture. |
||
|
|
30869e35a7 |
usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
them as its last three columns.
- tier_asked is the client body's service_tier (Claude's speed fast reads
"fast").
- tier_sent is the tier the try's last request actually went out at. It
is noted in forwardOnce after every rewrite (a fast pick's priority,
Ultrafast turned to priority on a plan without it, buildResponses
dropping a tier the host can't take) onto the per-attempt wireAt. So a
handed-on try's own row has its own tier.
- tier_served is only what the reply said: service_tier at the top level,
in response.service_tier, or in an Anthropic usage. It is read by the
relay sniffer and by both translated readers, and is empty when the
reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
tierServed. The session route has asked_tier, tier, tier_served and each
try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.
Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.
What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
ultrafast, the second priority, and the final record has asked=ultrafast,
sent=priority and served empty while the fake doesn't echo. With an
echoing fake, served is what it said ("ultrafast", and "default" when
none was asked). It also checks the CSV columns, and the Codex relay path
with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
response.completed, a Responses body, an Anthropic message_start and
message_delta usage, null, an over-long tier and non-JSON, as well as
bodyTier per protocol.
- Broke it by hand:
- with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
red (route tries' tier empty, TierSent empty);
- with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
nogui.
Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
document, not from saved replies. Whether chatgpt.com's Codex backend
echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
|
||
|
|
b6831d83e1 |
gateway, gui: Codex's thread descriptions go to a model picked in Settings, apart from its titles (#1198, congee949)
Codex asks its own model, through its ChatGPT sign-in, for each thread's description (thread_description), even while the conversation runs on magpie's models. Settings › General gets "Codex thread descriptions" beside "Codex thread titles". It defaults to Codex's own, which sends the request as Codex sent it, or it can name one of magpie's models or a routing group. The answer is wrapped as description-only JSON. The titles setting is untouched. Usage and Routing show these requests under their own Description purpose. The setting is kept across unrelated Settings saves. There is no Off yet, because Codex's handling of an empty description hasn't been checked. This is a first slice of #742. Squashed from the PR and merged onto current main. Conflicts resolved: - codex_backend.go: the description branch comes after the title branch, ahead of main's subagent pick. - gateway.go: main's CC Switch #1301 comment above the compaction block is kept; the PR had shortened it. - app.js: the gateway-mode list of hidden rows takes the new row. - i18n.js and settings_keep_test.go: both sides kept. - purposes.js: regenerated with go generate ./internal/usage. Run on the merged tree: - gofmt -l is clean. - go vet passes on darwin, linux -tags nogui and windows; the builds on all three succeed. - go test -tags nogui passes for ./internal/gateway, ./internal/gui, ./internal/settings and ./internal/usage. - GUI, chromium and webkit: codex-titles, gateway-mode, purpose-filter, routing-purpose-state, gui-de, gui-ja, gui-zh-tw, i18n-keys, settings-general/-groups/-sections/-search and click-scroll: 118/118. Broken by hand: with the description branch removed from codexBackend and handle, TestCodexDescriptionsSetting, TestCodexDescriptionFallbackOnMagpie and TestNoDescription fail. Not tried: a real Codex thread_description request, and whether Codex's sidebar takes the answer. |
||
|
|
2d3b33bb78 |
usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas. Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement. Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/ Queued/Tries row fields, HandedOn and the Codex speed floors were resolved by keeping both. The packed row's ReasoningHidden bit was 64, which main has since given to block_price.go's swapKnown, and main's rowHandedOn took 128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512 (rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and their sample JSON are left out of the tree; they stay on the contributor's branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/ and the gateway's reasoning/speed/TTFT tests, ok. |
||
|
|
d4c2512d2d |
usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
|
||
|
|
841af36bfc |
gateway: models the user disabled are refused on every route, and leave every list (#1867)
oxsean asked for one place to turn a model (claude-fable-5) off for good:
not reached by a direct request, an old session, a routing group member,
a fallback, a sub-agent, count_tokens or a decision model.
What changed:
- settings.DisabledModels: patterns, an exact id or a glob (* any run, /
included; ? one), matched ignoring case against provider/model, the
bare id and its last segment (provider/disabled.go). Empty by default,
so nothing changes for anyone who doesn't set it.
- Lists: buildEntries (entriesOff) leaves a disabled model out of the
catalog, so /v1/models, agents' model files and pickers, Codex's list
and every group go without it; membersIn skips it as a member, Deciders
as a decision model; codexModels drops Codex's own disabled slugs and
codexListTag changes so Codex refetches.
- Requests (gateway/disabled.go): 403 "model <id> is disabled in magpie"
in each API's error shape, at #882's choke points: serve (idOff),
perKeyBarred (no candidate: group next member, provider Fallback),
count_tokens and Gemini :countTokens, serveSystemOne,
serveDecisionGroup and postDecide, draw/video/embeddings, and
codexBackend for Codex's own bare models. A group with a member left
goes on without it; one with none left is refused naming them. A bare
id the catalog no longer has is refused as disabled, not 404. A Codex
sub-agent pick onto a disabled model stays on its lead's model.
- An unreadable settings.json is never "none disabled": the list read
last stays; with none read, every request is refused; nothing is
written over the file.
- CLI: magpie model disable <model|glob>..., enable ..., disabled
(list-disabled).
- GUI: Settings > Models > Disabled models: each pattern with the models
it matches now and Enable; Disable... opens the model picker, which
also takes a typed glob. Says only requests through magpie are covered.
POST /api/settings/disabled-models; POST /api/settings keeps the list.
Strings in zh, zh-TW, ja, de.
- docs/subsystems/gateway-routing.md: Disabled models section.
What was run (worktree at origin/main
|
||
|
|
125dad5cbb |
gateway: a codex provider used only through routing groups keeps the ChatGPT account's own models out of Codex's list (#1602)
With Codex signed in to ChatGPT, Codex asks magpie's /backend-api/codex/models
for its list, and codexModels passes the backend's own models through,
narrowed only by the codex provider's picks (CodexNativePicked) and the
Agents page's hides (CodexNativeHidden, built from Catalog()). A provider
set to "Only through routing groups" (Provider.Unlisted) has none of its
models in Catalog(), so neither filter saw them: all of the account's
models stayed in Codex's picker, and the Agents page had no Codex group to
hide. Every other agent's list is Catalog-based and already left them out.
provider.CodexNativeUnlisted says which of the account's models are kept
out of agents' lists: every one when the codex provider is Unlisted, and by
slug those a group with Unlists names. codexModels drops them (hidden
entries such as codex-auto-review stay, as with picks; a Codex reached for
failover alone keeps them, as it is handed no groups), spawnChoices drops
the same ones from spawn_agent's list, and CodexListTag carries them so
Codex refetches. gateway-routing.md says so.
Test: TestCodexModelListUnlistedForGroups (a group unlisting gpt-5.5 takes
gpt-5.5 alone; the provider Unlisted takes gpt-6-sol and gpt-5.5 and keeps
codex-auto-review; ETag changes; spawn_agent offers neither; own-only keeps
them). With codex_backend.go and codex_spawn_models.go reverted it fails on
all three checks. Not tried with a real ChatGPT sign-in and Codex app.
Run (sandbox HOME, private GOCACHE, worktree at origin/main
|
||
|
|
689edbd6be |
gateway: a Codex subagent refused for a sealed task is told the task itself is sealed, which fork_turns="none" doesn't change (#1855, hanekoo)
hanekoo's Codex Desktop lead on gpt-6.1-sol (Codex's own ChatGPT sign-in)
spawned a subagent on antigravity/gemini-3.8-flash with fork_turns="none"
and got the sealed-task refusal, which read as if the lead's turns were
the problem and fork_turns="none" should have avoided it.
What Codex rust-v0.162.0-alpha.17.2 sends (read from its source, not the
reporter's bytes, which aren't available): spawn.rs's fork_mode is None
for "none", so no turn of the lead's is copied in. The subagent's task is
spawn_agent's `message` argument; the ChatGPT backend returns it sealed
(the function call's encrypted_function_args), router.rs's direct_source
makes it ToolCallSource::Direct, agent_message_from_tool makes it
AgentMessage::Encrypted, and to_model_input_item writes it as the
agent_message's encrypted_content under the NEW_TASK header. So the one
sealed thing in the subagent's first request is the task itself: there is
nothing magpie can leave out and still give the subagent work, and no
request flag in Codex asks the backend for plaintext arguments. The
refusal stays; it now says why.
- codex_backend.go: sealedTaskItself, added to all three sealedTaskError
variants (lead unknown / Codex's own sign-in, a relay that sealed it,
plugins#70's earlier chat provider): what is sealed is the task the
spawning agent wrote in spawn_agent, and fork_turns="none" keeps only
the lead's turns out, not the seal. The existing advice (the lead's
model for the subagent, or a lead not on the ChatGPT backend) stays.
- docs/subsystems/gateway-routing.md: the same, under sealed tasks.
- sealed_fork_none_test.go: the fork_turns="none" first request rebuilt
from Codex's source (developer + environment_context + the sealed
NEW_TASK with Task name/Sender lines), a lead first on Codex's own
sign-in, the subagent on a chat provider. It is refused before the
provider is asked, with no ciphertext in the reply, and says the task
itself is sealed whatever fork_turns says.
Run: with the old codex_backend.go put back,
TestSealedTaskWithForkTurnsNoneSaysTheTaskItselfIsSealed fails ("the
refusal doesn't say the task itself is sealed whatever fork_turns
says"); with the change it passes. gofmt -l (empty), go vet / GOOS=linux
-tags nogui / GOOS=windows go vet ./internal/gateway, go build, GOOS=linux
-tags nogui and GOOS=windows go build ./..., go test -tags nogui
./internal/gateway (ok, 353s) under a sandbox HOME with a private GOCACHE.
Not run: the whole `go test ./...` (only the gateway package changed);
no real Codex Desktop or ChatGPT account was used, so the reporter's
bytes are not reproduced; the GUI's sealedKept text is unchanged. The
502 "context canceled" on gpt-6.1-sol in the report is Codex's own
sign-in request most likely cancelled by Codex itself (the client went away), a separate
request, and wasn't chased.
|
||
|
|
60808fd9cf |
usage, gateway, gui: magpie's own requests are told apart from the agent's, and a classifier on a subscription says it asks it every turn (#1839)
kensenzhao saw a subscription's allowance spent by requests the agent
didn't make: a routing group's classifier, set to a subscription's model,
asks it as every turn begins, and those calls looked like the agent's own.
What changed
- usage.Group has an own share (calls, tokens, cost) of the calls magpie
made by itself, filled for models, keys and accounts. Record.ByMagpie
is the test: agent "magpie", or one of its own User-Agents
(magpie-router/1, magpie-search/1, magpie-vision/1) where the agents
aren't loaded. The calls still count in the group's totals, as they
went to the same key or account. A group with none sends no "own".
- The classifier's calls are Kind "routing": callKind marks RouterAgent's
requests, and the decision model's record (Jev / System One) is written
with it. A "Routing classifier" purpose names them in the ledger.
- Usage page: magpie's row among the agents and its ledger rows carry a
"magpie's own" mark; an account's, key's or model's row adds "{n} by
magpie itself"; an account's card says how many of the period's
requests were magpie's own, drawn again once the summary arrives after
the allowances.
- Routing page: /api/groups marks a model a subscription account serves
(modelRef.Sub, servedRef). Beside a classifier on such a model, or a
group whose first member is one, the editor says every turn starts
with a request to that subscription, two when it picks both intent and
effort in words. A classifier on a key or a free model says nothing.
- New strings in zh, zh-TW, ja and de. The mark is a muted chip with an
even border all round (no left stripe).
Tests
- TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie (usage).
- TestIntentRoutesATurn and TestJevPicksTheIntent (gateway) now check
the classifier's records are Kind routing and magpie's own, and the
agent's records are not.
- TestServedRefSaysASubscription (gui).
- own-requests.test.cjs: Chromium and WebKit, 1100 and 390 wide,
en/zh/zh-TW/ja/de, the API faked; no click scroll, no sideways page.
- Broken by hand, each turned its test red: addOwn counting nothing;
callKind's routing case removed; decide.go's Kind blanked; the ledger
mark, the agents' mark, the "{n} by magpie itself" line, the card's
line, its redraw after the summary, the Routing hint, its group case
and modelRef.Sub each removed.
Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above, the ledger, routing-intent and translation tests.
Not done: the warmups (warmClaude/askClaude) write no usage record at
all, so they can't be marked; that is left as it was. Not tried with a
real subscription classifier against a live account.
|
||
|
|
5d33f060b7 |
gateway: Codex's spawn_agent names every model a subagent may be put on, not only the first five (Gearclickist on Discord)
Gearclickist turned on "Codex subagents on any model", but when Codex dispatched subagents only a few models could be picked. Codex itself caps the list: spawn_agent's description names only the first five show_in_picker models of its catalog (codex-rs child_config.rs MAX_SPAWN_AGENT_MODEL_OVERRIDES, multi_agents_spec.rs spawn_agent_models_description), Codex's own ahead of magpie's. Yet it takes any catalog model by name (find_spawn_agent_model_name). So the lead saw none of magpie's models. spawnAgentModels (codex_spawn_models.go) adds the rest of the catalog Codex was handed after Codex's own list, under a line of its own, at most 200. It covers spawn_agent at the top level and in Codex's multi_agent_v1 namespace, at CodexPath (codexBackend) and at /v1/responses for Codex (handle). - At CodexPath the list is Codex's own listed models less those hidden on the Agents page, then CodexListed unless Codex is held to its own. - At /v1 it is CodexCatalog under the key's allowance. - A lead the ChatGPT backend answers in multi-agent V2 seals its subagents' tasks for a ChatGPT account (#619), so it is offered Codex's own only. Only the tool's description changes, never base_instructions. With V1 on, it does change in requests to the ChatGPT backend too. Not covered: the model_catalog_in_context feature (under development, off by default) puts a five-model catalog in context, and it is not widened. Run: - go test ./internal/gateway ./internal/agent -count=1 under a sandbox HOME: ok. - TestSpawnAgentNamesEveryModel uses 40 models on a real Codex 0.162.0 request (testdata/workdir/codex-0.162.0.json). Its 4 subtests are CodexPath, /v1, a sealed V2 lead and a V1 lead, and all pass. - With spawnAgentModels returning body by hand: CodexPath, /v1 and V1 go red. - With the sealed rule taken out: V2 goes red. - go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows; gofmt -l is clean. Not verified: a real Codex lead picking one of magpie's models past the fifth from the longer list. |
||
|
|
908c910931 |
gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.
The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
moving;
- one removed, turned off, barred or not allowed for the key counts as
gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.
Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).
Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
./internal/provider ./internal/tui ./internal/cli: ok. The three
TestStrictAffinity* tests fail on the code before this commit (200
where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
fails 15 of 15 in chromium. routing-*.test.cjs pass but for
routing-steady's webkit 1.69px shift, which fails on the old assets
too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
the push.
Not tried: a real agent conversation held on a real rate-limited
account.
Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
|
||
|
|
86b2f4d053 |
provider, gateway, gui: an account whose sign-in its vendor revoked or refused reads as signed out and is passed over, not asked on every request (#1793 ysicing, echo_ts on Discord)
What changed, one fix for the class:
- ChatGPT and the other built-in subscriptions (#1793): ChatGPT answered
401 token_revoked on every request, request after request (~18 rows in
the reporter's log), because a refused sign-in was just "other" and
rested a while, then asked again. Now a 401 whose words say the sign-in
is gone (provider.SignInRevoked: token_revoked, token_invalidated,
invalid_grant, refresh_token_reused/invalidated/expired; never
token_expired, a 403, a 5xx or a network error) marks the account for
the credential it was sent with (a 12-byte hash of the header, never the
credential), in logins.json as Refused "revoked:<mark>" plus Lapsed.
A saved ChatGPT account is refreshed first, as Codex does on a 401; a
refresh that goes through marks nothing. The routing loop fails it as
failAuth (next member at once, no rest); forwardOnce answers its later
requests with magpie's own 401 without asking the vendor; compaction
on a magpie account (compactOn) picks a marked one last. Signed in anew
(upsertLogin with another credential, addSideLogin), refreshed, or a
request served, the mark is gone. Claude, Copilot and plugins keep
their own marks; a key's provider answering the same words rests as
before.
- Copilot (echo_ts): a built-in Copilot account whose GitHub token GitHub
refused (401/403 on the token exchange, the CLI stand-in or the usage
read) is marked lapsed on its own account (copilot_lapsed.go), unless a
working CLI stand-in serves; cleared when a token is served or it signs
in again. 5xx and network errors never mark it.
- GUI: such an account's row says Sign-in required with Sign in again
(Copilot's on its GHE.com host) and Remove, the reason on its allowance
line in the user's language (zh, zh-TW, ja, de added); the card says
Signed out once every account in use is.
- docs/subsystems: providers-accounts "A revoked sign-in", gateway-routing.
What was run (sandbox HOME, caches pinned, worktree only):
- go test -race on the new tests: provider TestSignInRevokedWords,
TestRevokedSideLoginMarkedTillSignedInAgain, TestRevokedCodexRefreshedFirst,
TestRevokedSignInLeavesOthersMarks, TestUpsertLoginKeepsRevokedMarkForTheSameSignIn,
TestCopilot* (7); gateway TestRevokedSignInPassedOverTillSignedInAgain
(fake ChatGPT backend, zstd, real routing: turn 1 asks acct-1 then
acct-2, turns 2-4 and after a restart acct-2 only with no rests, after a
new auth.json acct-1 again and the mark gone),
TestRevokedSignInNotCompactedOnAgain, TestRevokedWordsFromAKeyRestAsBefore.
- Broken by hand, each turned a test red: the forwardOnce short-circuit,
the failureOf clause, noteSignIn in codexUpstreamOn, compactOn's skip,
ServedSignIn, its in-memory delete, the 401-only check, refresh-first,
upsertLogin's keep and its sameAuth, sideLogins' Lapsed and
addSideLogin's clear; and the six Copilot breaks. GUI: the signedOut
and quotaError lines each turn revoked-signin-account red.
- GUI (Chromium and WebKit, 420 and 1100, en/zh/zh-TW/ja/de):
revoked-signin-account (new), copilot-signed-out-account (new), and the
account-*, claude-*, codex-*, plugin-*, quota-*, signin-*, routing-*,
usage-accounts* suites: 1605 pass, 7 fail. Six are WebKit
routing-group-fold/routing-sessions/routing-steady cases that fail the
same on a clean
|
||
|
|
8f2a314cf9 |
gateway: a ChatGPT account's turn goes zstd-compressed, as Codex's own client sends it (ylorn on X)
ylorn (X, v0.1.1202) sent a text-only gpt-6-luna turn of 1,100,224 bytes
straight to chatgpt.com/backend-api/codex/responses. Sent plain it got 503.
The same turn zstd-compressed (259 B) got 200. magpie decodes Codex's
inbound zstd and sent the backend plain JSON, so the turn got 503 through
magpie too.
What Codex does (openai/codex a9b08151, 2026-10-11):
- codex-rs/core/src/client.rs:1704-1712 responses_request_compression:
Zstd only with the enable_request_compression feature, a sign-in that
uses_codex_backend, and the OpenAI provider.
- client.rs:1780: used for the POST /responses stream only.
/responses/compact and /models go plain.
- codex-rs/features/src/lib.rs:1411-1416: the feature is Stable and on by
default.
- codex-rs/protocol/src/auth.rs:54-63: uses_codex_backend is true for the
ChatGPT sign-ins and false for ApiKey and Bedrock.
- codex-rs/codex-api/src/endpoint/responses.rs:130-147 sets it for
/responses.
- codex-rs/http-client/src/request.rs:196-217 compresses with
zstd encode_all at level 3, sets Content-Encoding: zstd, and never
compresses twice.
What changed:
- provider.CodexCompressed compresses a body sent to CodexBase/responses
with klauspost zstd, already a dependency. It uses SpeedDefault (about
level 3) and no frame checksum, like libzstd's default. It sets
Content-Encoding, Body, GetBody and ContentLength to the compressed
bytes, and returns the wire size.
- It is called once the body is final and signed: in forwardOnce for a
codex account, in codexUpstreamOn (the relay) on every try (so a try
again or a body without an unreadable image is compressed afresh), and
in warmCodex.
- Unchanged: /responses/compact, an sk- key's requests to api.openai.com,
every key provider (even one at the same URL), and a body already
encoded.
- The plain body is still what magpie keeps, masks, traces and shows.
- codexDropped (#1628, a2b96139c/8029d98b7) judges "large request" by the
bytes sent on the wire. A text turn that compresses to a few KB and is
reset is a small request's 503, not a "MiB" hint asked again. A
screenshot's random bytes stay past 1 MiB, and those are still asked
again.
- The gateway and provider TestMains leave turns plain
(CodexZstdForTests), since their fake backends read the body as JSON.
The new tests turn it on.
- TestAsksOwnBackendAgreesWithTheGatewayDispatch read any call whose sixth
letter is upper case (CodexCompressed) as a serveX dispatch. It now
needs the "serve" prefix. Removing "kiro" from asksOwnBackend still
turns it red.
- docs/subsystems/gateway-routing.md: the "sent plain JSON" line now names
this exception.
Tests: internal/gateway/codex_zstd_test.go covers the accounts loop, the
relay (inbound zstd and plain), a try again after a drop, compact and an
API key plain, a key provider at the same URL plain, and a reset judged by
wire bytes. internal/provider/codex_zstd_test.go covers the round trip,
GetBody, Content-Length and the URLs left alone. Broken by hand, each went
red:
- no compression in forwardOnce: Account and AskedAgain
- no compression in the relay: Relayed, AskedAgain and JudgedByBytes
- no account guard: KeyProviderTurnStaysPlain
- compact compressed: CompactAndAPIKeyStayPlain
- the drop judged by len(body): JudgedByTheBytesSent
Real account (the owner's ChatGPT sign-in, gpt-6-luna, 1,100,279 B
text-only body, 391 B zstd):
- Direct to chatgpt.com, twice: plain 200/200, zstd 200/200. ylorn's 503
did NOT reproduce from here (
|
||
|
|
5feadabef6 |
gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.
decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.
Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:
CPU in the request's handler time per request
(pprof, per request) (ns/op)
anthropic 154ms -> 45ms 208-212ms -> 52ms
anthropic, group 178ms -> 51ms 249-262ms -> 65-67ms
chat 122ms -> 35ms 167-254ms -> 50-54ms
responses 215ms -> 56ms 294-452ms -> 70ms
TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).
Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
Responses; direct, through a group, translated to each other protocol,
with images, thinking, escapes, odd spacing, a repeated key, and four
2 MB conversations) and compares what the vendor gets with
testdata/upstream_bodies, recorded on the code before this change
(all 18 identical; three runs agreed). Breaking decodeJSON's \n
unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
the gateway's, and jsonValid with json.Valid, over seeds, every cut
and a changed byte at every place of each seed, and 2.5 minutes of
fuzzing (~1.75M inputs). Breaking the validator's control-byte check
by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
origin/main
|
||
|
|
221e24a3c7 |
agents, gateway: Codex's subagent model offers every provider's models, not only ChatGPT's (#1633, laacmilan)
The Agents page's Codex "subagent model" field (settings.CodexSubagentModel,
which the gateway puts x-openai-subagent collab_spawn requests on) listed
only the ChatGPT accounts' models, and its setter refused any other
provider's. A user whose lead runs on a chat provider (Token中心, 智谱Plan)
couldn't put its subagents there.
- provider: CodexSubagentModels is Codex's shown catalog
(CatalogFor("codex"), so hidden or unpicked models stay out), ChatGPT
accounts first, routing groups included. SetCodexSubagentModel takes any
provider/model or group id, refuses a bare Codex name.
CodexSubagentUnserved says "magpie doesn't serve it now" for a non-ChatGPT
id that isn't served. CodexAccountModel exported.
- gateway: codexSubagentPick gets the body. When the lead ran on the
ChatGPT backend the task arrives sealed (encrypted_content), and only a
ChatGPT account can open it: set to another provider, such a subagent
stays on the model asked for, with Kept = sealedKept in the route trace
(#1613's constraint; the reverse, a chat lead with a subagent on ChatGPT,
was already handled by
|
||
|
|
8029d98b7e |
gateway: a large Codex request ChatGPT closes on is asked again, not told 413 (#1628, ScarfQian)
ScarfQian (#1628, v0.1.1184, Codex desktop computer use on a ChatGPT
subscription): a 1.1 MiB turn answered with ChatGPT's 503 "upstream
connect error or disconnect/reset before headers. reset reason: remote
connection failure" came back as a2b96139c's 413 "dropped this 1.1 MiB
request ... magpie didn't retry it". Codex doesn't retry a 4xx, and every
later turn carries the same screenshots, so each one got one try and the
same 413 and the conversation was stuck.
|
||
|
|
7cba316b90 |
gateway, gui: a notification when an agent's long task is done, opt-in in Settings › Usage (itieniu on X)
itieniu asked for a "ding" when a long Claude Code or OpenCode task
finishes. magpie sees every request an agent sends through it, so the
gateway now follows each agent session's turn and the app notifies at
its end.
Gateway (turndone.go): a request is of the turn unless it is one the
agent makes on the side (Kind) or a Claude Code subagent's. Its reply is
scanned on the way to the agent for a tool call in every wire format
(Anthropic tool_use, Chat tool_calls/function_call, Responses
function_call/custom_tool_call/local_shell_call/..., Gemini
functionCall), as a JSON value, never a key ("tool_calls":[]) or text.
The turn is done when no request of it is going, the last reply was
whole, under 400 and called no tool, and nothing more came for 4s; a
session idle past 30m starts over. The ChatGPT backend path is followed
too. Only a turn at least Settings' TurnDoneAlert seconds long is told,
and only when the app set gateway.TurnDone: magpie serve follows nothing.
Settings: turnDoneAlert (seconds, 0 = off, the default, at most a day).
GUI: Settings › Usage "Task done alert": Off / 1 / 3 / 10 min; the
notification says "Codex is done", "Took 1m 8s · folder", in en, zh,
zh-TW, ja and de. A click on it doesn't open the Usage page.
Tests: TestTurnDoneSaidAtTheTurnsEnd (chat and anthropic through the
gateway: a tool reply, a subagent's last reply and a short turn don't
fire; a final reply fires once with session and folder),
TestTurnDoneCodexBackend, TestTurnDoneWaitsForEveryRequest,
TestTurnDoneOff, TestToolScan (every split point), TestTurnDoneText,
settings' range. Broken by hand: without the capture's scan, without the
subagent exclusion, or without the codex backend's scan, they go red.
turn-done.test.cjs: every language, 900 and 380px, chromium and webkit.
The new row moved the Usage tab's geometry: usage-alert and currency
now wheel their row clear of the header before clicking it, as a reader
would (both green 5/5 here; on base they were green as before).
Run: gofmt -l; go vet darwin, GOOS=windows ./..., GOOS=linux gateway and
settings; go test ./... (gateway alone: ok, 863s under a GUI suite's
load); the full GUI suite in both engines. codex-credits and
gateway-key-models fail now and then here on base
|
||
|
|
149ab950e7 |
gateway: a Codex lead on a chat provider goes on when its subagent on one of Codex's own models sends it a message, the sealed message left out with a note (#1613, laacmilan)
laacmilan's lead was on token/gpt-6.1-sol, an API key on Chat Completions. Codex put a subagent on one of its own models, which magpie serves from the ChatGPT account. The ChatGPT backend seals that subagent's send_message, and Codex hands it to the lead as an agent_message: a plain "Message Type: MESSAGE" header plus encrypted_content (codex-rs protocol.rs to_model_input_item). serve's sealed gate (#619, #1237) took any sealed agent_message as a task. Only the ChatGPT backend can read it, so the lead's next turn was refused. The refusal said the lead "has since been on one of Codex's own models", which it never was. This had been so since the gate was added, not only since yesterday's release. - A sealed message (not a task) that no candidate can open is left out now (withoutSealedMessages). An input_text note naming its sender goes in its place, and the request goes on where it was. The subagent's final result still reaches the lead as text. A sealed task (NEW_TASK, or an item with no header) is still refused, as in #619: without it the subagent has nothing to do. - The refusal for a sealed task, where the provider that answered the lead can't seal, no longer says the lead switched models. It says the task came from an agent of this thread on one of Codex's own models, and points to Codex's subagent model on the Agents page. - docs/subsystems/gateway-routing.md says so. Run: - The new tests in sealed_message_left_out_test.go. The lead and subagent cases fail on the old code with the reporter's exact message, and also fail with the strip turned off by hand. - go test -tags nogui -run 'TestSealed|Codex|Sealed' ./internal/gateway. - go test -tags nogui -timeout 40m ./internal/gateway. - gofmt -l. - GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway. Not tried: real Codex desktop with a real ChatGPT account and a chat provider. The requests are Codex-shaped fixtures built from codex-rs's item format. |
||
|
|
398f8469be |
gateway: Codex's compaction on a custom provider goes on when its relay answers the summary 400 "Upstream request failed" (#1511, TooPub; #1523)
TooPub reported (#1511) that Codex through magpie to a custom relay provider stopped compacting with {"error":{"code":null,"message":"apex: Upstream request failed","param":null,"type":"invalid_request_error"}} while Codex pointed straight at the same relay compacted fine, and a new conversation worked. #1523 (jswysnemc, anyrouter) is the same failure. magpie answers Codex's compaction_trigger for a magpie model itself: it asks the model for a summary with the raw history (codexCompact). Normal turns are translated and worked; the summary request goes as it is, and the relay turned it away with its own generic 400. codexCompact's fallback (ask again with the conversation as text, then compact without a model) took the relay's generic failure only as a 404 (#866, "flyapi: Upstream request failed"), so the 400 went back to Codex and the compaction aborted. - upstreamFailed: a 4xx (not 401/403/429) whose body says "upstream request failed" now takes the same fallback as #866's 404. - The summary request sends "tools": [] instead of leaving tools out. Captured with Codex 0.162, that is the one difference between magpie's summary request and the summary request Codex sends a custom provider itself, which is what worked for the reporter. The relay hides the upstream's reason, so which of the two the relay objected to isn't known; the fallback covers it either way. Siblings: Chat-only custom providers go through the same codexCompact (covered in the test for both protocols). Other agents' compaction is a normal request through the translators, with no magpie-side compaction step. A pass-through option (#1523) wouldn't help: Codex compacts a custom provider it reaches itself locally, which is what magpie's summary request mirrors. Run: - New tests from the reporter's literal body: asks again as text, compacts locally (Responses and Chat), and 401/403/429 with the same words still go back to Codex. TestCodexCompactsThroughCodexRelay now and TestResponsesRelayCallIDs' compact cases now require "tools":[]. With the change reverted by hand, all three fail; TestCodexCompactOther400Stays and TestCodexCompactOtherFailuresStay stay green. - Real Codex 0.162 in a sandbox CODEX_HOME against an in-process magpie gateway and a fake relay answering the summary with the reporter's 400: on the old code "Error running remote compact task: {...apex: Upstream request failed...}" exactly as reported; with the change, "context compacted" and the turn completes. - go test ./internal/gateway and go test ./... (nogui); gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway. Not tried: the reporter's actual relay. |
||
|
|
a2b96139c9 |
gateway: a Codex request ChatGPT drops for its size is told as too large, not retried or rested (ylorn on Discord)
ylorn (Discord #general, v0.1.1179): through a ChatGPT account, every turn a PNG screenshot took past about 1 MiB was answered HTTP/2 503 content-type: text/plain server: cloudflare upstream connect error or disconnect/reset before headers. reset reason: remote connection failure also without magpie, and the same screenshot as a JPEG went through. magpie took that 503 as the backend's trouble: with two accounts on, the turn was asked of acct-1, then of acct-2 three more times, acct-1 rested for it, and the next turn moved to acct-2. The same bytes are dropped the same way on every account, so none of that could help, and the agent was handed a 503 it retries again with the same body. codexDropped (codex_dropped.go) makes a 503 whose body says "upstream connect error or disconnect/reset before headers", to a request of 1 MiB or more, the 413 it stands for, with a message saying the request was dropped for its size (in MiB), that magpie didn't retry it or rest the account, and to /compact or remove or shrink the images (a JPEG in place of a large PNG screenshot). It runs on a ChatGPT account's replies in forwardOnce (the accounts loop, any agent) and on the ChatGPT passthrough in codexUpstreamOn (Codex's own sign-in alone). A 413 already skips the other accounts of the same provider and rests nobody, and Codex doesn't retry a 4xx. The same 503 to a smaller request stays the 503 it is, retried as before. 1 MiB isn't the backend's limit for everyone: from here, on a Pro account, gpt-6-astra direct to chatgpt.com/backend-api/codex/responses answered 200 to bodies of 0.5 to 20 MiB, plain and zstd, and to 3456x2234 PNG screenshots up to 5.6 MiB. So nothing is refused before sending; only this drop, on a body this large, is taken as the request's. Tests (codex_dropped_test.go), with an httptest backend that answers ylorn's literal 503 (text/plain, Server: cloudflare) to bodies over 1 MiB: - TestCodexDroppedBigBodyIsTheRequests: two accounts, a 1.2 MiB turn is 413 with the message, asked of acct-1 once, nobody rests, and the next small turn goes to acct-1. On the old code: 503, asked [acct-1 acct-2 acct-2 acct-2], acct-1 rested, next turn on acct-2. - TestCodexDroppedBigBodyRelayed: Codex's sign-in alone, 413 with the message (old code: the 503 relayed). - TestCodexEdgeResetSmallBodyStays503: a small body's 503 is relayed. Run: go test -tags nogui ./internal/gateway (new tests red before, green after), gofmt -l, go vet -tags nogui with GOOS=darwin, linux and windows on ./internal/gateway. Not tried: ylorn's own network or account, where the drop happens. |
||
|
|
a98ab77fde |
gui, gateway: a context window's part, cell or item clicked opens the text the request sent there (masaka)
masaka on Discord asked to see the whole context behind the context window
card: click the agent's prompt, or any other part, and read it.
What changed:
- gateway: the trace keeps the last 10 request bodies in memory only
(promptBodies; at most 32 MiB each and 64 MiB together, oldest dropped
first), masked as the vendor got them. For a model the user let have
the request unmasked, the masked copy is kept all the same. Never
written to disk, never in telemetry. Route.Prompt and the routing
history keep names and sizes only, as before.
- gateway: Server.PromptText re-reads a part's items and their text from
that body (prompt_text.go). promptBuilder gains a keep mode that records
each item's pieces: system text, tool definitions laid out as JSON, each
turn's user/thinking/assistant/call pieces, tool results, and images
or sealed reasoning named with their size. Sizes are unchanged.
- gui: GET /api/context/text?id=&kind=[&item=] (no-store; 404 "not kept"
when the body is gone or another process serves the gateway).
- gui: in the card, a legend part, a waffle cell or a content row
(click, Enter or Space) opens a wide modal: one item alone with "All of
{part}", or the part's list 100 rows at a time, each item's text
fetched when it is opened and shown 20000 characters at a time, with
copy buttons. Strings in zh, zh-TW, ja and de.
- docs: gateway-routing and gui-shell subsystem pages; the site's start
page (en, zh, ja) says the text is kept for the last 10 requests in
memory and sent nowhere. The README Privacy is unchanged, since nothing
more is sent.
What was run:
- go test -tags nogui ./... (temp HOME). internal/gateway hit the 10m
default under the full parallel run, in TestRequestTailAfterOldLimit,
which takes 57s alone on the base commit too; the package run alone
with -timeout 30m: ok (700s, the machine shared with other runs). Every other package: ok.
- New tests TestPromptTextIsWhatWasSent, ...KeepsOnlyTheLastBodies,
...ChatPieces, TestContextTextAPI. Broken by hand: keeping the unmasked
body fails (the key shows), and dropping keepBody fails ("not kept").
- gofmt -l; go vet, GOOS=linux and GOOS=windows go vet on internal/gateway
and internal/gui.
- GUI: tests/context-text.test.cjs in Chromium and WebKit, en/zh/zh-TW/
ja/de, at 1100 and 420px: legend, row, cell and keyboard open the text,
long text grows on demand, the page never scrolls, and a gone body is
named. It fails with the click wiring removed. Under a load average of
~140 one case failed once: the test read the list while the dialog
still said "Reading…". Reproduced with a 400ms reply, fixed by waiting
for the list; the mock now always answers after 200ms. A second case
("a click doesn't move the page", 662 vs 605 on the contents row) came
from taking the page's top while a wheel scroll was still easing: the
test now wheels to the row like the other cases, and wheelTo waits for
three equal looks. Four full runs at load ~150 then passed (80 cases). context-window,
i18n-keys, held-animations and the modal tests (dialog-backdrop-drag,
editor-short-window, readable-focus, ux-safety, whats-new, add-sheet,
api-key-theme) pass in both engines.
- Real use: a sandbox magpie (own HOME, ports 3486/3487, the Codex login)
served a real `claude -p` (Claude Code) request on codex/gpt-6-luna
that read a file. In its web UI, Usage > Context: each of System
prompt, Tools, Memory, Files and Conversation, a waffle cell and a
contents row opened the request's real text (Claude Code's system
prompt, 21 tool definitions, the CLAUDE.md reminder, main.go's Read
result, the turn with its thinking and call). No page errors.
|
||
|
|
d75ea9282b |
gateway: a Codex conversation moved from Muse Spark to GPT on Copilot is answered, not refused over Muse's "rs_…:rs_…" item ids (echo_ts)
echo_ts (Discord) switched a Codex conversation from Muse Spark (OpenCode)
to gpt-6.1 on GitHub Copilot and every turn failed:
Copilot: Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009'.
Expected an ID that contains letters, numbers, underscores, or dashes,
but this value contained additional characters.
Cause: magpie does not build that id. Muse's upstream hands Codex reasoning
items whose id is two ids joined with a colon; Codex sends every earlier
item back on each turn, and magpie relayed them to the new upstream as they
were. OpenAI checks every input item id against [A-Za-z0-9_-], and Copilot
(and the ChatGPT backend, Azure, relays in front of OpenAI) pass that 400 on.
The existing foreign-seal retry did not fire, because the refusal is about
the id, not the encrypted_content.
Fix (plainItemIDs, codex_backend.go):
- reasoning whose id has another character is dropped: an upstream that
checks ids never minted it, so its encrypted_content is another vendor's,
which it couldn't read either;
- any other item (message, function_call, custom/tool_search call) keeps
its content, its id with each other character as "_"; call_id is not
touched, so outputs stay paired.
Applied up front to OpenAI's API, Azure, the ChatGPT backend (Codex
sign-in path and Codex's own models' passthrough) and Copilot; any other
Responses upstream that refuses with OpenAI's id message is asked once more
with plain ids and remembered (itemIDsRefused, per model). OpenCode itself
still gets Muse's items byte for byte, so Muse can read its own reasoning.
Siblings checked: translated Chat and Messages upstreams never get item ids
(probe: only call_id goes, as tool_call_id / tool_use id), so they are not
affected by this; tool_use ids on Messages are a separate commit.
Tests (internal/gateway/item_ids_test.go), fixtures built from echo_ts's
literal id and error text:
- TestCopilotTakesAnotherVendorsItemIDs (copilot/gpt-6.1 via /responses)
- TestRelayRefusingItemIDsAskedAgain (unknown relay: 2 asks, then 1)
- TestMuseKeepsItsOwnItemIDs (OpenCode gets them as sent)
- TestCodexOwnModelTakesAnotherVendorsItemIDs (ChatGPT backend passthrough)
Broken by hand: old code -> Copilot/relay/native red with the reporter's
400; no up-front pass -> "asked Copilot 2 times"; no retry -> relay red;
no native pass -> native red; reasoning kept with a rewritten id -> all
three red ("Muse's reasoning sent").
Run: go test -tags nogui ./... (sandbox HOME, pinned caches), gofmt -l,
go vet + GOOS=linux / GOOS=windows go vet -tags nogui ./internal/gateway/.
Not run: a real Muse Spark reply (OpenCode Go refuses this account: the
model trains on request data and the workspace hasn't allowed it), nor a
real Copilot request.
|
||
|
|
437bf023b8 |
codex, chatgpt-api: a conversation with tools reuses its cached prompt, its session sent in session-id/thread-id as Codex 0.162 sends it (#1473 inthink, #933 Scallions)
The ChatGPT backend looks up a conversation's prompt cache by the session headers, not by the body's prompt_cache_key. I probed a real Pro account (gpt-6.1-sol, 13 tools, about 7.6K-token prompt) directly: - key in body only, 6 requests: cached 0 every time - no key and no headers: 0 every time - session-id + thread-id: 0, then 7552 x5 - old session_id/conversation_id: 0, then 7552 - a bare request with no tools: 4096 every time. That is the instructions' shared cache, so #1473's "bare requests hit" pattern fits this. Codex CLI 0.162 (captured with codex exec against a fake server) now sends only session-id and thread-id. It no longer sends the underscored names, which a proxy may drop. Changes: - codexSign: sets session-id and thread-id from the prepared body's key (sessionHeaders). It drops the underscored names. A keyless body keeps the session the client named. - codexHeader: relays session-id/thread-id from Codex clients. - ChatGPT API (SIWC) provider: it sent only Authorization. Now it names the conversation (conversationKey for keyless clients) and sends the same session headers. Scallions' screenshots: chatgpt-api/ got 0% cache where codex/ got 10-99%. This was NOT tried against api.openai.com with a real ChatGPT API sign-in, since none is available here. Left for the reporter to confirm. Run: - Sandbox magpie on a real Codex account, client sending no key: old build cached 0/7296 erratically; new build 0, 0, then 7296 x4. - go test ./internal/provider ./internal/gateway: ok. - Break check: reverting codex_request.go and chatgpt_api.go turns TestCodexSignSessionHeaders, TestCodexSignAndBody and TestChatGPTAPISession red. - gofmt -l: clean. GOOS=linux and GOOS=windows go vet: clean. base_instructions and the identity line are unchanged. |
||
|
|
250d3561cb |
gateway: a Codex subagent refused a sealed task no longer names a chat provider the lead used earlier as its sealer (plugins#70, yygutn)
yygutn's Codex lead ran on the Qoder plugin, then on one of Codex's own
models (GPT Sol), and spawned a subagent set to qoder/dfmodel in
~/.codex/agents. The ChatGPT backend sealed the task, and the refusal
said it "was sealed by the server that answered its lead (qoder)" and to
"use a model on qoder for the lead and the subagent", which can't work:
Qoder serves Chat Completions and neither seals a task nor opens one.
Affinity still had Qoder for the lead's thread, since magpie keeps no
record of Codex's own model answering it.
When the provider found for the lead couldn't have sealed the task
(canSeal: not a ChatGPT account, and not a provider of no sign-in on the
Responses API, the same line sealedReader draws), the refusal now says
the ChatGPT backend sealed it and that the provider answered the lead's
earlier turns only. Who may read the task doesn't change: it is still
turned away before Qoder is asked.
Run: TestSealedTaskNotPinnedOnALeadsEarlierChatProvider fails on the old
code with the reporter's message ("sealed by the server that answered
its lead (qdr) ... use a model on qdr"), passes with the change.
go test -tags nogui ./internal/gateway ./internal/provider under a temp
HOME, gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on both.
Not run with a real Qoder account and Codex App.
|
||
|
|
a21a2b54f1 |
gateway: a Codex title the model was cut short on before any text goes back as response.incomplete with its reason and usage, not as a completed reply with nothing in it (#1466, Edward4226)
codexTitle read the title model's reply with compactReply, which kept
the output and usage of response.completed and response.incomplete alike
and dropped how it ended, and writeTitleReply always wrote status
"completed". A title cut short at max_output_tokens (all of it spent
reasoning) reached Codex as a finished reply with output [].
What changed:
- compactResult keeps the response's status and incomplete_details
(from the terminal event's response, or its type).
- codexTitle: when no title can be read and the reply was incomplete,
writeTitleEnd streams response.created then one response.incomplete,
status "incomplete", the vendor's incomplete_details and usage. A
title read from the reply still completes with it; Titles off still
completes with nothing (writeTitleReply is writeTitleEnd "completed").
- Compaction (codexCompact) is left as it was: a summary cut short with
text in it is still used.
Codex: codex-rs/codex-api/src/sse/responses.rs takes response.incomplete
with a reason other than interrupted/content_filter as a stream error
("Incomplete response returned, reason: max_output_tokens"), which
core/src/responses_retry.rs retries up to the provider's
stream_max_retries; then the hidden title turn fails and
tui/src/temporary_structured_request.rs sets no title, as it did for
the empty completed reply. This is what Codex does when its own backend
answers so.
Run:
- TestCodexTitleIncompleteStaysIncomplete (Responses upstream, #1466's
two-field schema) and TestCodexTitleIncompleteFromChat (Chat upstream,
finish_reason length) fail on the old code (one response.completed,
status completed) and pass now; the same test's whole title under the
same schema completes. Existing TestCodexTitle*/TestTitle* pass.
- gofmt -l clean; go vet -tags nogui ./internal/gateway on darwin,
GOOS=linux, GOOS=windows.
- go test -tags nogui -count=1 ./... under a temp HOME: all ok (with
./internal/gateway and ./ rerun after this change).
- Real use: the built binary's gateway in a sandbox HOME with only the
owner's DeepSeek provider, the issue's title request on
deepseek-flash. max_output_tokens 16: old response.completed,
output [], status completed; new one response.incomplete, reason
max_output_tokens, usage 16 reasoning tokens. 2048: a title and
description, response.completed, before and after.
|
||
|
|
61e296688e |
gateway: Codex's model list keeps codex-auto-review when the user picked models on the ChatGPT account, so auto-review runs on it again, not on the conversation's model at low (#1460)
10086gg reported that Codex's auto-review through magpie almost never used codex-auto-review. It ran on the conversation's own model at low effort, which costs more. Cause: codexModels narrows the ChatGPT backend's list to the models the user picked on the codex provider (CodexNativePicked). Hidden entries (visibility "hide") never reach magpie's catalog (parseCodexModels), so no one can pick them, and the narrowing always dropped them. codex-auto-review is one of those hidden entries. Codex 0.162 picks the reviewer this way (codex-rs/ext/guardian-reviewer/src/model.rs, select_review_model): 1. the entry's auto_review_model_override; 2. else codex-auto-review, if the list has it; 3. else the conversation's model, at low effort. So once the list was narrowed, every review fell to step 3. On a relay model it was charged to the relay; on a ChatGPT model it ran on that model. OpenCodex had the same bug: lidge-jun/opencodex#6712 recorded direct ChatGPT login as codex-auto-review/low and their proxy as Sol/low. Fix: the narrowing keeps hidden entries. No picker shows them, so the user's picks still decide what Codex's /model lists. A user who wants reviews on a relay model can still set Codex's auto-review model (#938), and that setting still wins (step 1). Which account pays changes for a user with picks whose conversation runs on a relay model: auto-review moves from the relay to the ChatGPT account's codex-auto-review. That is what Codex does without magpie. OpenAI's help article "Using Codex with your ChatGPT plan" says: "When you're signed in with a ChatGPT account, auto-review safety checks are free and don't count toward your plan's usage limits." New test TestCodexModelListPicksKeepHidden. It fails on the old code: after the picks only gpt-6-sol is listed, with no codex-auto-review. docs/subsystems/gateway-routing.md says this. Run: - gofmt -l internal/gateway - go vet -tags nogui ./internal/gateway, on darwin, linux and windows - go test -tags nogui ./... with a temp HOME and pinned caches: green Not run: a real Codex signed in to ChatGPT through the gateway. The reviewer choice was read from the Codex source. |
||
|
|
3e5bc3d8fe |
gateway, usage: conversation text is kept only under a session the client named, and a client's "request-…" session counts like any other (#1355)
What changed: with recording on, a request that names no session used to get a made-up "request-…" id and its text saved under it. Nothing listed that id and GatewaySessionByID turned it away, so the text could never be opened. magpie now makes up no id: such a request isn't recorded, and the X-Magpie-Session reply header only echoes the client's own session. With no made-up ids left, the "request-" prefix checks in appendUsage, OTel, Usage's sessions, Routing's vias and the gateway Sessions projection only dropped sessions clients named themselves (appendUsage wiped them from the ledger). They are gone. The tests that held the old rule now say the new one, and gateway-sessions.md says it. Run: TestGatewayConversationNeedsTheClientsSession and TestGatewayConversationClientRequestPrefixedSession fail on the PR's code (a made-up id is returned; the ledger keeps 0 of 2 calls) and pass here; putting appendUsage's prefix check back turns the second red again. gofmt -l clean; go vet; GOOS=linux and GOOS=windows go vet -tags nogui on gateway, gui, sessions, settings, usage; go test -race -timeout 900s on those five: ok (gateway's TestCORSKeyThroughTheServer rerun after its fix). GUI: gateway-conversations, gateway-mode and all sessions-* tests, 216 cases in Chromium and WebKit: pass. |
||
|
|
c9b8263378 |
sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the gateway (from the usage ledger, read-only, a native session of the same id wins), and shows in gateway mode. A Sessions switch, off by default and confirmed before it turns on, records each gateway exchange's text under the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly). Settings sync and restore can't turn it on; POST /api/sessions/recording turns it on or off and can clear what was kept. Why: users of magpie as a gateway (gateway mode, LAN clients) had no way to see their conversations; the owner chose this design on the PR. Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md (kept main's placeMenu text, took the PR's Sessions in gateway mode) and settings_keep_test.go (main's fields plus GatewayConversations). Run: go build ./..., go vet on gateway, gui, sessions, settings, usage; go test -race -timeout 900s on those five packages: all ok. |
||
|
|
189586612e |
agents, gateway: Codex's subagents go on a model set in its row, a ChatGPT account's (willz on Discord)
Codex's lead names each subagent's model itself in spawn_agent, and
Codex's [agents] config can't overrule it. The Agents page's Codex row
now has a "subagent model" square (the app's model picker, Default
first). Its options are only models a ChatGPT account in magpie serves,
because a subagent's task is sealed for ChatGPT accounts.
- settings.CodexSubagentModel holds it. It is an agent Field
(subagent_model), so the TUI/CLI, profiles, davsync's "agents" part
and WSL twins carry it too. The setter refuses another provider's
model. It keeps a ChatGPT account's model that isn't served now, so a
backup restored on another computer still applies (ApplyFields stops
at the first failed Set). POST /api/settings keeps it.
- The gateway (codexSubagentPick) moves a collab_spawn request onto it.
codexBackend does this for Codex's own bare models; serve() does it
for any other model. When no ChatGPT account on in magpie serves it,
or a held gateway key may not use it, the request stays on the model
asked for. Route.Subagent records asked/to/kept. The lead's turns,
titles, guardian and the rest are never moved. Off (the default)
changes nothing.
- Routing page: kindWhy says the subagent was put on the model set, or
stayed on its own and why. "only account on for" names the model it
went on. Strings added in zh, zh-TW, ja and de.
- docs/subsystems: gateway-routing.md and agent-wiring.md describe it.
Run (darwin, rebased on origin/main):
- gofmt -l internal/: clean.
- go vet -tags nogui on gateway, provider, agent, gui and settings:
darwin, GOOS=linux and GOOS=windows.
- go build ./...
- HOME=<temp> go test -tags nogui ./...: all ok.
TestSettingsSaveKeepsWhatItDoesNotSend flagged the new field; it is
now set there.
- GUI tests, Chromium + WebKit:
- codex-subagent-model.test.cjs: 20/20 (en, zh, zh-TW, ja, de at
1100 and 560 px).
- Also green: routing-kind, subagent-effort, codex-memories,
codex-memories-settings, i18n-keys, gui-ja, gui-de, gui-zh-tw and
click-scroll.
Failing without the change (codexSubagentPick returning nil):
- TestCodexSubagentPutOnTheModelSet
- TestCodexSubagentOnAnotherProviderPutOnTheModelSet
- TestCodexSubagentModelNotServedKeepsTheAsked
- TestCodexSubagentModelHeldKeyKeepsTheAsked
TestCodexSubagentModelLeavesOtherRequests guards the other side: the
lead's turns, titles and guardian stay untouched.
Not tried with a real Codex CLI and ChatGPT account. A subagent spawn
needs a signed-in Codex home, and this session may not touch the live
~/.codex. The fake ChatGPT backend tests cover both routes.
|
||
|
|
acdaa28aa1 |
codex: a conversation that searched the web declares cached search to the ChatGPT backend, so its compaction and turns aren't refused "response protection is unavailable" (#1270, #1099)
The ChatGPT backend answers HTTP 200 and only `event: error` "response
protection is unavailable" to any request whose input replays one of its
own web_search_call items while the request doesn't declare the web_search
tool. Probed on a real ChatGPT Pro account (gpt-6.1-sol, 2026-10-09) with
a real searched turn: refused with tools [], with function tools only and
with a compaction_trigger; answered once {"type":"web_search",
"external_web_access":false} is declared. A Responses Lite request refuses
a top-level web_search (400) but takes it in an additional_tools item. So
xjdata's case (Codex compacting a custom provider's conversation itself, a
plain /responses with tools [] that magpie's codexCompact never sees) failed
every time once the session had searched, and congee949's thread
descriptions too.
What changed:
- provider.DeclareSearch / declareSearch: when the input holds a
web_search_call and nothing declares search, add cached-only web_search to
the tools, or for Lite (header, reasoning.context all_turns, or an
additional_tools item present) to the additional_tools item (prepended
when there is none). With no tools offered, tool_choice becomes "none" so
the model can't search; a forced choice is kept. Otherwise the body is
unchanged (bytes untouched when no web_search_call is in it).
- codexBody (every ChatGPT account route: serveAgent, codexCompact, warmup,
magpie's codex/* models) calls it; codexUpstreamOn calls it for Codex's
own sign-in relayed to the backend's /responses.
- Not changed: siwc, API-key passthrough to api.openai.com, the legacy
/responses/compact endpoint (no evidence they are refused so; not probed).
- docs/subsystems/gateway-routing.md names the cause and the fix.
Tests: internal/gateway/search_history_test.go replays the backend's real
items from that probe against a fake that refuses as the backend did.
TestSearchedConversationCompactsOnAnAccount, ...FunctionTools and
...OnCodexSignIn fail on the old code with "event: error"; ...CompactionTrigger
fails with "asked 2 times, not once". TestUnsearchedConversationUnchanged
and provider TestDeclareSearch cover what's left alone.
Run: gofmt -l (clean); go vet, GOOS=linux go vet -tags nogui, GOOS=windows
go vet -tags nogui on internal/provider and internal/gateway; HOME=<temp>
go test -tags nogui ./internal/provider ./internal/gateway (ok). Real
account, sandbox magpie on 127.0.0.1:3491 under a scratch HOME, replaying
the real searched history: old binary -> /v1/responses codex/gpt-6.1-sol
text compaction with tools [] and /backend-api/codex/responses (standard
and Lite compaction_trigger) all "response protection is unavailable";
new binary -> all response.completed, Lite with a compaction item.
Codex CLI 0.161.0 end to end was not done: on a custom provider it
offered no web_search tool, so no search could get into its history.
|
||
|
|
ecc94dbf41 |
gateway: a routing group's DeepSeek reasoning, its text in it, no longer sticks a Codex conversation on OpenAI destinations (#1411, cth123456: "Invalid 'input[n].content': array too long")
A group turn served on DeepSeek hands Codex a reasoning item with both content (reasoning_text) and encrypted_content. Codex sends it back on every later turn, and the /backend-api/codex handler keeps reasoning for a group (codexInput(body, true)). Routed next to a Codex account or a relay in front of OpenAI, the request was turned away with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0 ...", which neither the foreign-seal retry nor #1044's bare-reasoning retry matched, so every later turn failed the same way. In passthrough, for an upstream that isn't sent reasoning text back (not replaysReasoning, so DeepSeek still gets it): - a Codex account, openai.com or Azure is never sent a reasoning item with content parts (withoutReasoningText), as codexInput already leaves it out for Codex's own models; its seal is the other vendor's, so the item goes; - any other upstream that answers 400 naming input[n].content "array too long", where item n is reasoning with content, is asked once more without such items, and the provider's model is marked unfit for them (reasoningTextRefused), so later turns go without them the first time, as #1044 does for bare reasoning. The destination's own sealed reasoning, messages and tool calls stay. Verified: - TestReasoningTextLeftOutWhereRefused (group to a strict relay, the issue's literal item) and TestReasoningTextNotSentToCodexAccount (group to a Codex account) fail without the change with 400 "AgentRouter:/Codex: Invalid 'input[1].content': array too long ..."; the relay is asked twice then once, the account once. TestReasoningTextKeptWhereTaken keeps the item for an upstream that takes it. - Real ChatGPT backend (the owner's Pro account, gpt-5.5, store false): the issue's item answers 400 "Invalid 'input[1].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead." param input[1].content, code array_above_max_length; the test fixture uses those bytes. The same request without the item completes. Not tried against AgentRouter itself. - gofmt -l, go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway, go test -tags nogui -count=1 ./internal/gateway under a temp HOME: all pass. |
||
|
|
0b5b10da2a |
agent, gateway, gui, tui: a Codex that goes through magpie only to fail over to the user's other ChatGPT accounts says so on the Agents row and keeps to its own models (#1385, shenghsi)
With several ChatGPT accounts on, failover writes openai_base_url into ~/.codex/config.toml so a turn the signed-in account can't pay for goes on to the next account. With Codex's switch off, the row said only "not connected", but every request still went through the gateway, and the gateway's /backend-api/codex/models answer added all of magpie's models (62 for the reporter). - agent: Agent.FailingOver means not wired, while the stash's codex.failover (or a CC Switch mirror's codex.mirror_failover) base URL points at magpie. FailoverSaid is the line the CLI list and the TUI show. CodexOwnOnly is true for this machine's Codex when it is failing over and no WSL Codex is connected, since a WSL Codex shares the gateway path. Sync ages a models_cache.json that isn't tagged with the own-only list. - gateway: codexModels leaves out provider.CodexListed when gateway.CodexOwnOnly (set by main to agent.CodexOwnOnly) says so. The ETag and X-Models-Etag carry provider.CodexOwnListTag. Neither tag contains the other, so Codex fetches the list again when it is connected or disconnected. - gui: /api/state carries failover. The row says "Not connected · goes through magpie only to fail over to your other ChatGPT accounts". Its title says what turns it off. A "ChatGPT accounts" button opens Providers › Codex. Strings are in zh, zh-TW, ja and de. openProvider no longer draws the Providers list before it has loaded. It was only safe once the tab had been opened, and this is its first caller from another page. - docs: agent-wiring and gateway-routing describe the failover-only Codex and list the new tests. A user's hand-written openai_base_url (#856) isn't failover's, so it stays a plain not-connected row. Verified: - TestCodexFailoverOnlyKeepsOwnModels (agent) builds the reporter's state in a temp HOME: Codex signed in, two more ChatGPT logins on, Sync, so the stash has codex.failover=1 and no joined/beside. It checks that the row is not wired and is FailingOver, that FailoverSaid names Providers › Codex, and that the real gateway handler's /backend-api/codex/models lists only the backend's gpt-5.5. It also checks that the cached full list is aged, and that after Join magpie's fake/m1 is back. - TestCodexModelListOwnOnlyForFailover (gateway) checks the list and both ETags with the hook on and off. - agent-failover.test.cjs checks the row text, title and button in en, zh, zh-TW, ja and de, at 980px and 420px, in Chromium and WebKit (20 pass). It also checks that the button opens Codex's editor, that the page doesn't scroll sideways, and that no click moves it. - Broken by hand, each test goes red: - codexModels ignoring the hook fails both Go tests. - failingOver returning false fails the agent test. - dropping the Sync cache case fails the agent test. - removing the GUI branch fails the GUI test. - drawing the list before it has loaded (the old openProvider) fails the GUI test. - go test -tags nogui ./internal/agent ./internal/gateway ./internal/provider ./internal/gui ./internal/tui ./internal/codexcat . in a temp HOME: all ok. - node --test agent-*.test.cjs (254 pass) and i18n-keys, gui-ja, gui-de, click-scroll: all pass. - gofmt -l is clean. - go vet -tags nogui on darwin, linux and windows: clean. - go build, and GOOS=windows go build: ok. |
||
|
|
34a598372c |
providers, gateway, gui, cli: each usage window of an account can have a cap of its own beside the account's (willz on Discord)
willz asked for a cap per window: a friend's account should stop at 50%
of its five hours, while its week has its own 40%. Until now an account
had one usage cap, the same share of every window.
What the user sees: the account's pill still sets the cap for all its
windows and stays the default. Each window's meter on the account's row
is now a button: a click opens the app's own menu headed "Cap for
<window>" with the account's cap, No cap on this window, 50–90%, and
Other… typed in place. A window with its own cap says it beside its
figure ("Cap 50%", or "No cap"), its mark sits there, and the account's
pill says "Caps by window" when only windows have caps. The account is
held while any window is past its own cap, and the row's note, the
gateway's 429 and the Routing trace name that window's cap. CLI:
magpie provider account-cap <id> <account> --window "5 hours" 50
(none: no cap on that window; default: back to the account's), and
`account-cap <id>` lists the overrides.
How: Provider.AccountWindowCaps (providers.json, by account and the
window's capId, its name in lower case; 1–99, or 100 for none) beside
AccountCaps. provider.WindowCaps gives a window its share (its own, else
the account's); Allowance.CapHeld and capReached judge each window by
its own share and report the fullest holding window's cap.
provider.HoldShare becomes HoldCaps, used by gateway capHeld (plan and
group filtering, cappedError, trace) and codex_backend's route-or-relay
choice; codex_switch's NextLogin moves the agent off at per-window caps.
QuotaWindow carries capId; Limit.name is exported as Limit.Name. A
config with no window caps reads and routes exactly as before
(TestSetWindowCap reads an old one). The meter is a span with
role=button, Enter/Space: a <button> as a flex item of the wrapping
meter line kept WebKit's row at its one-line height until the next
layout, so the row grew under the pointer at the first click.
Verified:
- go test -tags nogui ./... in a sandbox HOME: all ok. New
TestWindowCapHeld and TestSetWindowCap (provider), TestWindowCapsHoldTheAccount
through the real gateway (5h 60%/cap 50 goes to the spare; 20/30 under
50/40 is used; 20/45 with the spare past its own cap is a 429 naming
"past its 40% cap"), TestAccountCapCmd --window cases.
- Break check: with WindowCaps.Of ignoring the window's own share,
TestWindowCapHeld fails ("5 hours at 60% of 50%: <nil>") and
TestWindowCapsHoldTheAccount fails (the request is answered 200 by the
capped account).
- internal/gui/tests/window-cap.test.cjs: Chromium and WebKit, 420 and
1100 wide, en, zh, zh-TW, ja, de (60 tests): held note per window,
marks, menu from the meter with no native select, keyboard, posts of
50, typed 45, 100 and 0, no page scroll on a click, no sideways scroll,
no left border stripes, every new string translated. With
windowOwnCapOf returning 0 it fails.
- account-cap, gui-zh-tw, gui-ja, gui-de, i18n-keys pass; full GUI suite
in both engines (483 files, concurrency 6): 4315 of 4323
pass; the 8 that failed (library-servers-bulk, purpose-filter,
routing-proxy, routing-zcode-blocked) touch no account row and all 32
of their tests pass when run alone
- gofmt -l clean; go vet -tags nogui ./... on darwin, linux and windows,
and windows without the tag for ., internal/gui, internal/provider,
internal/gateway; go build ./...
- Not tried in the real window with a live gateway or real accounts.
Docs: gateway-routing.md (HoldCaps, window caps, tests),
providers-accounts.md (AccountWindowCaps, tests), reference.md.
|
||
|
|
3e9bbdaae9 |
gateway: a paused Codex sign-in isn't spent by native compaction either (JasonLeeForOnly on Discord: a ChatGPT account turned off in magpie still had its quota used)
The account Codex is signed in to can be paused in magpie while another of its accounts is on (#263: the user's own ChatGPT account kept for Codex's remote control and Computer Use, another doing the work). Turns on Codex's own models already passed over it (codexAccounts, routing and OwnPaused), but /responses/compact for one of those models still relayed as it came, on the paused account's own token, and on history the others had sealed. compactOn now picks, for that case only, the first of the other accounts on that isn't resting, and codexUpstreamOn relays the compaction signed as that account (its token and chatgpt-account-id, through its proxy), keeping the Accept Codex sent. A gateway key held to some accounts (#905) is asked of the account it goes to, not the paused sign-in. Not paused, nothing else on, an API-key Codex, or a request naming an account: the relay is as before. Not changed: a Codex provider switched off (Off) still relays Codex's own model requests (the Codex app's gpt-5.6-luna/terra side generations, memories, codex-auto-review, native compaction) on the sign-in as they came; that is a design question, reported separately. Tested: TestCodexPausedOwnAccountNotCompactedOn (in use: on the sign-in; paused: acct-2 with its own token; key held to the paused sign-in: 403 with nothing asked; held to the spare: acct-2; the spare off: the sign-in again) fails on origin/main at the paused step (tried [acct-1]) and passes. gofmt; go vet -tags nogui ./internal/gateway on darwin, linux, windows; go test -tags nogui ./internal/gateway ./internal/provider ./internal/agent under a temp HOME pass. Not tried with real accounts. |
||
|
|
bf4d55acdd |
gateway: a Codex task sealed by a custom Responses provider still goes back to it after magpie forgets who answered the lead — a day later, after a restart, or after the lead's reply broke off — and the refusal says how to go on (#1367)
Autsunset (#1367): Codex with the lead and its subagents all on xxxx/gpt-6-astra, a relay of ChatGPT Pro behind new-api. After quota and overload errors, continuing the task was refused before xxxx was asked: "This subagent's task was sealed by the ChatGPT backend that answered its lead ... xxxx/gpt-6-astra is neither." The cause: who sealed a task (#1109, #1237) was read only from the affinity stick of the lead's conversation, and that record is lost in three ways: it is kept 24 hours; a restart reads back only the latest 512 conversations from affinity.json; and a reply that breaks off after its 200 (response.failed server_is_overloaded) deletes it (unanswered, #733). Once lost, every later turn carrying a sealed message was refused before anyone was asked, so nothing could answer the lead again to remember it: the task stayed stuck. When the sticks don't make the asked provider a reader, the usage log's answers to the lead's thread and the request's own conversation in the last 30 days now count too (loggedAnswers). A refused or failed call, a title and Codex's own sign-in (Provider "openai" on /backend-api/codex, still told of as the ChatGPT backend) count for nothing. The sibling leadFirst, which puts the lead's ChatGPT account first in a group, reads the lead's key or account from the log the same way. The refusal names who answered the lead when the log knows, and both messages now say how to go on: use the lead's model, or have the lead spawn the subagent again. Verified: - TestSealedTaskStillGoesToTheLeadsProviderAfterItsReplyBrokeOff and TestSealedTaskStillGoesToTheLeadsProviderADayLater (fake Responses relay over httptest, Fernet-shaped gAAAAAB... payloads, lead and worker on xxxx/gpt-6-astra) fail on origin/main with the reporter's exact 400 and pass with the change; the sealed payload reaches xxxx as it came. - TestSealedTaskLogDoesNotOpenItToAnotherProvider: a lead answered by another provider names it; a lead never answered (refused twice) and an answer older than 30 days stay refused. With the 30-day bound removed it fails. - TestSealedTaskGoesToTheLeadsLoggedAccountFirst: with the leadFirst fallback removed the group's other account (acct-1) is tried first. - TestSealedTaskFromChatGPTLeadStillRefused fails if Codex's own sign-in is not left out of the log's answerers. - TestSealedReplyRefusedWhereTheLeadWasNotAnswered now expects the lead moved to another provider to be named "(third)". - go test -tags nogui ./internal/gateway passes (sandbox HOME, pinned caches); sealed tests pass under -race -count=5; gofmt -l clean; go vet -tags nogui ./internal/gateway for darwin, linux and windows. Not verified: real Codex with a real CPA/new-api relay of ChatGPT Pro. If such a relay sends the subagent's request to another ChatGPT account than the one that sealed the task, that account can't open it either; magpie can't see or fix that. |
||
|
|
de5455b8fe |
gateway, usage, gui: a reply whose vendor sent its first words and held the rest to send in one burst tells no speed, not 1,367 tok/s (John on Discord)
John's request (OpenCode, a group served by Kimi Code at api.kimi.ai, Chat) showed 1,367 token/s: its tokens counted over the time from its first token to its end, though nothing came in between and the rest came at once. The 100 ms / 10,000 tok/s bounds catch a burst only when the first content comes with it. firstToken now reads on past the first text and marks when each content event's bytes came (one mark a millisecond, up to 65,536 marks and the 8 MB it reads), and flowMs is how long the content took to come from where the speed is counted: the span from a tenth of its bytes to nine tenths, scaled to the whole. A steady stream gets about its whole window; one let go in a burst about 1 ms. It is kept as Call/Try/Route .flow and usage.Record.flow_ms (and the Requests page's packed rows), and usage.DecodeOf, routing.js's decodeOf and app.js's ledDecode count no longer a window than it. A record without it reads as before. Verified: TestBurstTellsNoSpeed, a fake Chat vendor that sends a word, waits 600 ms, then 199 words and the end in one write (1,000 tokens), for a Chat and a Responses agent: no speed; before, 1636 and 1655 tok/s. Its steady case (a word every 60 ms) keeps 200 tokens over most of its window. TestCodexBackendBurstTellsNoSpeed is the same through Codex's own ChatGPT backend (before: 1,000 tokens in 601 ms). TestFirstTokenKinds now expects the stream read past its first text. Go tests ran on Linux (golang:1.26 in Docker; this Mac's syspolicyd held new test binaries at launch). GUI: routing-burst-speed (a route with John's 5.1 s first token, 6.7 s and a 2 ms flow: was "1367 tok/s", now none) and usage-speed (a row with flow_ms 2 shows "—") fail without the JS change and pass with it, with reasoning-speed, routing-request-metrics and usage-ledger-detail, in Chromium and WebKit (en/zh, ja/de where the tests have them); no strings changed. Not reproduced with Kimi Code itself: whether it holds the stream so is inferred from the numbers. |
||
|
|
7d8cda18aa |
gateway: a magpie-model compaction the ChatGPT backend breaks off after the reply began, HTTP 200 and an error event "response protection is unavailable", is asked again as text and else compacted locally, as the 502 is; the error nested in an error event is read, not "the model failed" (#1270)
Ran: go test -tags nogui ./internal/gateway (green; an earlier full run had TestOTelExportsWholeBodiesWhenOn panic once under load, passes alone -count=3 and in the rerun); GOOS=linux/windows go vet ./internal/gateway. The new tests failed before the fix with the reporter's "502 compaction: the model failed". Not tried with the real backend or Lody. |
||
|
|
814dca9390 |
gateway: the ChatGPT backend's 502 "response protection is unavailable" is the request's, not the account's: asked once, no account rests, and a magpie-model compaction refused so is asked again as text (vs on Discord)
A long Codex conversation's compaction refused so went to every ChatGPT account in turn, each rested on a growing backoff, then the last was asked twice more: 5 upstream tries per Codex request with 3 accounts, times Codex's own retries. Now the provider's other accounts and models are not asked it, nor the same one after a moment; another vendor left in a group is asked once. A reply broken off with it rests nobody either. codexCompact falls back to plainCompact on it, as vs's control experiment (the same history as text) was answered. TestProtectionRefusalAskedOnceNobodyRests fails on the old code with "asked 5 times ([acct-1 acct-3 acct-2 acct-2 acct-2]), not once" and two accounts resting; TestProtectionRefusedCompactionAsText with status 502. The error body's exact bytes are not the reporter's; no real ChatGPT account was tried. |
||
|
|
1efa4c642f |
gateway: a Codex lead's turn carrying its subagent's sealed reply goes back to the Responses provider that answered the lead, instead of being refused as a subagent task "sealed by the ChatGPT backend" (#1237)
SuperrNaruto (#1237), and PennyVibe on #1109 with v0.1.1108: Codex with the lead and its subagents all on one custom Responses provider serving gpt-6-astra. #1109's fix sends the subagent's sealed task back to that provider, and the subagents ran. But when a subagent answers the lead with send_message, Codex hands the lead an agent_message to /root whose payload the provider sealed, and hasSealedAgentMessage marks the lead's next turn as a sealed task. The lead has no parent thread, so leadProvider found nobody, sealedReader accepted only a ChatGPT account, and the lead was refused before anyone was asked with "This subagent's task was sealed by the ChatGPT backend that answered its lead ... is neither". The main conversation stopped while the subagents finished. The providers that can read a sealed message are now those that answered the lead (the parent thread, as before) and the one that answered the request's own conversation (leadProvider of its conversationID): a subagent sent a task sealed by the lead's provider had to be on that provider, so its reply was sealed there too. A lead moved to another provider, one magpie never answered, and a subagent whose lead a ChatGPT account answered are still refused before anyone is asked, with the same messages. Verified: TestSealedReplyGoesBackToTheProviderThatAnsweredTheLead (lead, subagent, then the lead with the subagent's sealed FINAL_ANSWER reply, all on third/gpt-6-astra with Codex's web_search tool) fails on origin/main with the reporter's exact 400 and passes with the change; the reply's ciphertext reaches the provider as it came. TestSealedReplyRefusedWhereTheLeadWasNotAnswered and TestSealedTaskFromChatGPTLeadStillRefused (lead on gpt-5.5 through the ChatGPT sign-in, subagent on the custom provider) pass on both. go test -tags nogui ./internal/gateway passes; the sealed tests pass under -race -count=5; go vet -tags nogui ./internal/gateway passes for darwin, linux and windows. Not tried with real Codex and a real relay of the ChatGPT backend: the reply's item is built from the "Message Type: FINAL_ANSWER / Task name / Sender / Payload" layout in the codex 0.160.1 binary and PennyVibe's description, not from a captured request. |
||
|
|
b6f33753ce |
gateway: a gzip or zstd request body is read on every route, so Codex with a custom provider on /v1/responses no longer gets "expected a JSON object" (#1223)
Only the Codex backend path decoded a Content-Encoding (codexReader); /v1/responses, /v1/chat/completions, /v1/messages, count_tokens, Gemini's routes, embeddings, images, videos and System One read the compressed bytes as JSON. Codex sends zstd to a custom provider's /v1/responses by default. readBoundedRequestBody now always decodes (decodedBody, moved from codexReader): identity, gzip and zstd are read, the header is dropped so the provider gets plain JSON, the size limit holds for the decoded bytes (413), and any other encoding is refused 415 naming it. keyLimited reads a limited key's compressed body the same way, so its reservation is the decoded size, not the compressed one. Verified: request_encoding_test.go posts real gzip and zstd bodies to a running httptest server of New().Handler() on every route. Without the change TestEncodedBodiesOnEveryRoute and TestEncodedEmbeddingsBody fail with 400 "expected a JSON object" / "the body isn't a JSON object", TestEncodedBodyInflatedPastLimit gets 400 instead of 413, TestUnknownBodyEncodingRefused gets 400/502 instead of 415, and with only key_limit.go reverted TestKeyLimitReservesDecodedBody fails "held at 19 tokens for a 40061-byte body sent as 79 bytes". gofmt; go vet -tags nogui ./internal/gateway for GOOS linux, windows, darwin; go test -tags nogui ./internal/gateway (temp HOME, pinned caches) ok; the new tests -race -count=5 ok. Not tried with the real Codex CLI. |
||
|
|
586f2bce8f |
context: magpie inspects the context window of every request, session and agent
The gateway reads each request's prompt into its parts (system prompt, tools and MCP servers, memory, files, tool results, chat), measured against the model's window and calibrated to the tokens the vendor counted. Routing shows a request's window as a card: a 400-cell grid by part, a hover naming what is largest in a cell, and the contents by part. The Usage page's Context tab scores each agent out of 100 (cache reuse, how lean it starts, how fast it grows, how reliably it answers), tags it (lean, cache-friendly, mcp-heavy, compacts, near-full…), and draws each session's growth with its latest request's card. Older Safari (15) gets media-query and solid-colour fallbacks for the card's container queries and color-mix. |
||
|
|
842272df84 |
gateway: a Codex subagent's sealed task goes back to the Responses provider that answered its lead (a Sub2API relay of the ChatGPT backend), relayed as it came, instead of being refused before it is asked; the refusal names who sealed it (#1109)
Codex on Ultra with s2a/gpt-6-astra for both the lead and the subagent, s2a a Sub2API relay: the relay's ChatGPT backend sealed the lead's spawn_agent task, and magpie turned the subagent away because only a Codex account counted as able to read it, telling a user already on a magpie model to "use a Magpie-served model for the lead". The provider that answered the lead (leadProvider, from the lead thread's affinity in any scope) now reads it too when it is a key provider serving the model on Responses; the task is relayed, even when Codex offers web_search (it was translated, which dropped the agent_message's encrypted_content). A subagent on another provider, or whose lead magpie never answered, is still refused before anyone is asked, with a message naming the lead's provider when known. Verified: TestSealedTaskGoesBackToTheRelayThatSealedIt (lead and subagent on s2a/gpt-6-astra, with Codex's web_search tool) fails without the change with the old 400; without only the relay part it fails with the ciphertext dropped from the upstream request. TestSealedTaskRefusedByAnotherRelay covers a lead on s2b and an unknown lead. go test -race ./internal/gateway, go vet ./..., GOOS=linux and GOOS=windows builds pass. |
||
|
|
de2c84ace7 |
gateway: a Responses relay that turns away reasoning with nothing sealed in it, naming only the input, is asked once more without it, and isn't sent it again for that model (#1044: Codex's /compact through Anyrouter failed with 400 invalid_request_error param=input on old conversations)
Codex hands back reasoning items with no encrypted_content (an rs_ id and a summary, as magpie's translated replies give it). #1008 left them out only for OpenAI's API and Azure OpenAI. A relay in front of OpenAI turns them away the same way but with its own message ("bad response status code 400", param "input"), so the compaction, which is relayed as it is, failed. They are not left out for every other upstream: a DeepSeek model behind a Responses relay wants its reasoning back (#388), and magpie's own translator reads the summary as thinking. passthrough now, on a 400 to a Responses request whose error names the input (refusesInput: param input / input[…], or an item named by id), asks once more without the bare reasoning (withoutBareReasoning), sealed reasoning and every other item kept; once that works the provider and model are remembered (bareReasoningRefused) and later requests go without it at once. Any other 400 goes back as it came. TestBareReasoningLeftOutWhereRefused (the reporter's item kinds: message, function_call(_output), custom_tool_call(_output), two bare reasoning items and a sealed one; the relay's 400 word for word) fails without the gateway.go change for both the compaction and a relayed turn (400 back to Codex) and passes. TestBareReasoningKeptWhereTaken and TestBareReasoningKeptOverAnotherRefusal guard the upstreams that take it and other 400s; TestAzureCompactionWithoutMagpiesReasoning (OpenAI/Azure unchanged) still passes. -race -count=5 on these, TestCodexCompact* and TestImageTool*; go test -tags nogui ./internal/gateway ./internal/provider, go vet ./internal/..., gofmt, linux and windows (nogui) builds pass. Not tried against Anyrouter itself (no account); the 400 is from the issue's capture. |
||
|
|
e6dd5d20bb | usage, gateway, gui: a reply that reasoned is timed by its answer, from its first text, not by all its output from its first token (tony on Discord #general: Usage › Requests read "gpt-6.1-sol 163 token/秒 · 8,036 个请求 · 首字 14 秒" and asked whether subagents were added up) — speed was every output token over the time after the first content (text, reasoning or a tool call). Output counts the reasoning, and a model whose reasoning is hidden (OpenAI's encrypted reasoning, a summary sent when it is done, Claude's omitted thinking) writes it before the stream shows anything, inside the TTFT; so a 2,000-token think and a 200-token answer over the 1.5 s after the first token read 2,200 in 1.5 s, 1,467 tok/s. Concurrency was not the cause: the aggregate is Σ tokens over Σ per-request windows, so subagents running at once never add up. In the owner's own usage.jsonl codex/gpt-6-luna turns read up to 600 tok/s (out 496, reasoning 224, 11,055 ms, ttft 10,228) and its aggregate 133; it is 80 now. usage.DecodeOf is the one rule: a reply with reasoning counts out − reasoning over ms − firstText, one that reasoned and wrote only tool calls tells no speed, one without reasoning is timed from its TTFT as before; DecodeWindow's burst cut (#731) still applies. Record.Decode feeds summarize, the ledger's Totals and its timeline Parts; a route keeps its reply's reasoning (Route.Reasoning, from gateway.go and codex_backend.go), and routing.js's decodeOf/speedOf times its rows, the story and a session's average by it (an older route takes its served usage's reasoning); app.js's ledDecode does the Usage page's rows, whose tooltip says the reasoning left out, and the Output speed help says the rule, in en, zh, ja and de. History is read the same way, as it keeps the reasoning and the first text. Routing never ranks by speed. TestReasoningReplyTimedByItsAnswer (the 2200/2000 turn, a summary 10 ms before the text, a concurrent subagent, tool calls only, reasoning over output, no reasoning, not streamed: 1,200 tokens in 11 s through summarize, addRow, LedgerSeries and Decode) fails without the change and passes -race -count=10; TestUsageKeepsTimeToFirstToken now has its paced replies report reasoning and checks the route keeps it. reasoning-speed.test.cjs (Routing rows 133, 100, none and 100, the story never 1,467, the session 105; the Usage rows, tooltip and KPI the same; no sideways scroll) passes on Chromium and WebKit in en, zh, ja and de, and fails against the old assets (1467 tok/s); routing-request-metrics, routing-burst-speed, usage-speed, usage-ledger-detail, i18n-keys, gui-ja, gui-de, ledger-hscroll and click-scroll pass on both. go test -race -tags nogui ./internal/... under a temp HOME passes but internal/proc's TestUserPath ("the login shell's PATH never came"), which failed under the full run's load, passes 3/3 alone and is not touched here; go vet, gofmt -l, linux and windows (nogui) builds pass. Not tried with tony's data. docs/reference.md says how output speed is counted. | ||
|
|
b56bfb5a94 | gateway: an upstream that answers 200 with a web page, with nothing at all, or with JSON that isn't, has failed as a 502 does, so a group asks its next member (#1012, cth123456: Codex on group/medium, agentrouter/deepseek-v4-flash now and then answered 200 text/html; the log said status=200 done=true in=0 out=0 served=null, codex/gpt-6-luna was never asked, and Codex failed with "stream disconnected before completion: stream closed before response.completed") — the candidate loop judged a try by its status alone, and holdWriter passes a 200 that is neither text/event-stream nor application/json straight to the agent, so the page went to Codex as the reply. notAnAPIReply now reads every 2xx (but 204) an upstream gives, in forwardOnce (every relayed and translated request, every API, plugins included) and in the built-in clients' own requests (the ChatGPT backend's /responses, Kiro, Zed, Qoder, Devin, Cursor, Command Code): a text/html reply, a body that begins as a web page whatever its Content-Type, an empty body, or one sent as JSON that doesn't begin with { or [ is turned into the 502 it stands for, with a JSON error saying what came back ("answered 200 OK with a web page (text/html), not an API reply: “Just a moment...”", the firewall hint for a block page). It then fails over, rests a minute and is logged as any 502 before the reply begins does; a provider with nobody after it hands the agent that 502 rather than the page. Only the first bytes are peeked, which a stream waits for anyway; a read that fails is left to the reader, a compressed body and anything else as it came. TestNotAnAPIReplyFailsOver (Chat, Responses and Messages, streamed and not, a member answering a Cloudflare page as text/html, as JSON and as SSE, an empty body as JSON and as SSE, and plain text as JSON; the next member must answer and the log name why) fails without the change in all 36 cases (the page relayed to the agent, or b never asked, or no reason logged) and passes; TestNotAnAPIReplyAlone (a 502 with the reason, logged 502) and TestCodexBackendWebPage (the ChatGPT backend's page reached Codex as a 200) fail without it and pass; TestAPIReplyUntouched keeps JSON after whitespace, SSE with and without a Content-Type, gzip, XML, a 204 and a 404 as they came. -race -count=10 on them; go test -tags nogui ./internal/gateway ./internal/provider, go vet (darwin, windows), gofmt -l, linux and windows (nogui) builds pass. Not tried with the reporter's relay (agentrouter) itself; the page is a Cloudflare challenge's, as the issue has only its Content-Type. docs/subsystems/gateway-routing.md says it. | ||
|
|
6ba82d2f07 | gateway: reasoning magpie made isn't relayed to Azure OpenAI or OpenAI's API, and a summary request refused for an item not found is asked again as text (#1008, zhouxiong100: Codex on an Azure OpenAI deployment failed every compaction with "Azure OpenAI: Item with id 'rs_18dbe693b3dce4800000003c' not found", Reconnecting 5/5, store=true by a middleware no help) — Codex offers web search on every turn, so its turns on Azure went out translated, and the translated replies gave Codex reasoning items magpie made: rs_ and newID (the reporter's id is one, a UnixNano in hex and a counter), a summary and nothing sealed. Codex hands them back on every turn. buildResponses replays no reasoning to Azure, so the turns worked; Codex's compaction offers no tools, so it isn't translated but relayed as it is, and Azure, with store false, looked rs_… up among stored items, found none and answered 400 for the whole request. codexCompact asked again as text only on a 404 (#866), so the 400 went back to Codex. passthrough now drops reasoning with no encrypted_content from a Responses request to OpenAI's API or Azure OpenAI unless store is true (withoutBareReasoning): both look such an item up and can't have it, its summary being the model's notes no model reads back; their own sealed reasoning still goes, and every other host gets the request as before (a relay may read the summary for a vendor that wants reasoning back). The same holds for any turn relayed as it is, Codex's with web search off for one. codexCompact's fallback also takes a 400 naming an item not found (itemNotFound: unreadableItem and "not found"), as a relay in front of either passes on; any other 400 still goes back as it came, and the local summary names the status it got. TestAzureCompactionWithoutMagpiesReasoning (the Azure preset at a fake /openai/v1/responses answering a storeless request with a bare reasoning item Azure's 400 word for word; the compaction and a relayed turn, each asking Azure once with the sealed reasoning kept and magpie's dropped) fails without the passthrough change (the turn 400 with the reporter's exact message, the compaction asking twice) and passes; TestCodexCompactItemNotFoundAsksAgainAsText fails without the codexCompact change (400 to Codex) and passes; TestCodexCompactOther400Stays guards other 400s. -race -count=10 on them, TestCodexCompact* and TestAzureRoutes. go test -tags nogui ./internal/gateway ./internal/provider, go vet, gofmt -l, linux and windows (nogui) builds pass. Not tried with a real Azure OpenAI resource (none on this machine); the 400's text is from the reporter's screenshot and issue. docs/subsystems/gateway-routing.md says it. | ||
|
|
c394097e02 |
gateway: a key held to some accounts may not compact on the sign-in Codex is on either, the last path #967 left open (a follow-up to #967, on the maintainer's invitation, LCorleone) — /responses/compact for one of Codex's own models relays as it came, deliberately (#876): the encrypted history it carries is readable only by the ChatGPT backend that sealed it, so native compaction keeps its own sign-in. But that relay spent the account Codex is signed in to with nothing of the calling key asked, so a key held to some accounts (#905) could spend an account it may not use through compaction alone, after #967 held its turns. compactSigninHeld asks, before the relay, whether the sign-in (resolved as codex/<model>, the id the catalog gives Codex's own) is one of the key's accounts — and fails closed, as the review asked: a Codex switched off in magpie, or a sign-in nowhere resolvable, is refused as an account the key may not use is, the relay reaching the sign-in all the same; the one allowance is Codex signed in with its own API key, told from auth.json's auth_mode (provider.CodexAPIKeySignedIn — the request's own Authorization can't tell it, magpie's token already in it for a keyed request). A refusal carries the API's own 403 shape naming the model and the accounts the key may use, and the two ways out: add the signed-in account to the key, or use one of magpie's models, whose compaction goes through a compaction_trigger on /responses and the key's accounts — native compaction has no other route, its history bound to that account. The account in use compacts on it as it always did, the relay untouched; a key that names no Codex account (AllowsAccount's rule), one held to some models alone, and a free key are relayed as they were. TestGatewayKeyAccountsHoldCodexCompact (held to a spare account: refused with nothing asked of OpenAI; held to the sign-in: the compaction relays as it came; naming no Codex account: allowed as ever; a free key: unchanged; and the provider switched off: refused with nothing upstream, the review's repro) fails without the gate and passes, TestGatewayKeyCompactOnCodexAPIKey pins the allowance; go test ./internal/gateway/ ./internal/provider/, go vet, linux(nogui)/windows(nogui) builds pass. (#976)
POST /backend-api/codex/responses/compact for a bare native model relays on the account Codex is signed in to (#876) before codexAccounts (#967) is asked, so a gateway key held to some accounts (#905) could spend an account it may not use through native compaction. compactSigninHeld now refuses it with a 403 permission_error, nothing sent upstream, unless the signed-in account is positively one of the key's (AllowsAccount on codex/<model>): it fails closed when Codex is switched off in magpie, unresolvable or has no account. Codex signed in with an API key (auth.json auth_mode "apikey") and keys that name no account relay as before. A key held only to other accounts can never compact natively; the message says to add the signed-in account to the key or use one of magpie's models. TestGatewayKeyAccountsHoldCodexCompact (refused / held to the sign-in / no Codex account named / free key / Codex off) fails without the gate and with a fail-open gate; TestGatewayKeyCompactOnCodexAPIKey pins the API-key case. |