ac4af582301a4e8a29245dbba767eba31334ddf9
219
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
dae104bfac |
capre: a length check, not an unrolled repeat, holds nine patterns
Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.
capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.
Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
./internal/library ./internal/sessions ./internal/agent ./internal/gui
. : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
over 14 units x 19 lengths (0..300, at each bound +-1); with the
length check taken out it is red (1586 mismatches).
TestItemIDRefusalAsTheRegexp holds the function against the old
regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
(gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
4.54MB -> 3.01MB.
Not tried: the full ./... suite; the gateway package beyond the run
above.
|
||
|
|
44d6dd75d1 |
gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.
Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.
Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
the model in them and another member to go on to, in the user's order;
auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
left, CapStop off), or for a turn codexFallBack handed on, the provider
is planned again with those groups after its own fallbacks
(groupsAfter), each group routed as a request to it is. One place, so
it holds on every protocol (chat, responses, messages, Codex's backend
path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
before any fallback, the groups included).
Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
/v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
|
||
|
|
c9d253e4a2 |
gateway: an agent's compaction is recorded as Compaction, not a plain turn
shangyuan0818 (Discord, v0.1.3354): Claude Code's compactions don't show in Usage → Requests. Through the gateway they were recorded and counted, but as ordinary turns (Kind ""), so nothing read as a compaction: the Compaction purpose listed none, the OTel export skipped them as turns the transcript has (Claude Code's compaction is skipTranscript, so it has none), and the reply ended the agent's turn. The main handler now marks a call compacting() recognises (Claude Code's summary ask, OpenCode's and the other agents' prompts) as KindCompact, on every route it serves (messages, chat, responses, gemini), unless a header already set its kind. The check reads the facts parse the request already makes (bodyFacts.compact). Codex's backend route already took the kind from its header; it now uses the same constant. Not fixable here: Claude Code used directly (not through magpie) never writes a compaction's usage to its transcript (only compact_boundary with token counts before and after), so magpie can't count those. Run (mote, at this change on |
||
|
|
7a56c83e72 |
gateway: a compaction Copilot sealed stays out of Codex's auto-review
echo_ts (Discord #feedback) runs Codex Desktop's turns on GitHub Copilot
through magpie, with Copilot's native compaction on, and Codex's
auto-review on its built-in codex-auto-review through the ChatGPT
sign-in. The guardian's review carries the conversation's history, so
after the first compaction it carried Copilot's sealed compaction item
too. A request for one of Codex's own models with no magpie Codex
account to route it is relayed to the sign-in as it came, and
codexInputAs keeps any non-magpie1: compaction ("OpenAI's own, for
OpenAI"), so OpenAI was sent Copilot's ciphertext and refused every
review: 400 invalid_encrypted_content "The encrypted content P4ih...bDU
could not be verified". After the next compaction, the new ciphertext.
The siblings: a side call routed through magpie (the auto-review set to
a magpie model, a subagent or a title on another provider's model)
met checkpointReaders, found no writer among its candidates and was
refused with checkpointError, so the review failed there too. A turn or
a /responses/compact on one of Codex's own models relayed to the sign-in
sent the seal to OpenAI to be refused (sealedCompact took a Copilot
writer for the sign-in's own and relayed it).
Now:
- compactionAside names the calls Codex makes beside the conversation
with its history in them: the guardian (or anything asked on
codex-auto-review), memory, subagent, title, description, thread
summary, prediction and suggestion. In serve, when the writer of the
sealed compaction isn't among such a call's candidates, it goes on
without the compaction item (withoutCompaction, body and plain);
instructions, developer/user messages, the turns since and their tool
calls and outputs stay. The conversation's own turns are still held
to the writer or refused saying why (#1099), unchanged.
- foreignToSignin: on the relay to Codex's own sign-in (codexBackend), a
compaction magpie recorded as sealed by a provider other than the
Codex subscription is never relayed. A side call goes without it; a
turn or a /responses/compact is answered checkpointError, magpie's
own explanation, with nothing sent to OpenAI. A seal with no record
(OpenAI's own, compacted on the sign-in), one the codex provider
sealed, and one whose provider can't be read are left as before.
No portable plaintext summary exists for a native compaction (only the
writer can read it), so the side call goes without it rather than with
a summary.
Run (on mote, through mote-run, at
|
||
|
|
e215d335a6 |
gateway: a gateway key can cap its requests at once; the rest wait their turn
young02036 on Discord: a provider can be given a concurrency, so why
can't a gateway key? A key now has an optional MaxConcurrency, from 1
to 1000. Left unset (every key today), nothing changes.
- access: Key and Change get MaxConcurrency, and Identity carries it, the
issuer's cap included. The concurrency-key action refuses a value
below 0 or above 1000.
- gateway (key_slots.go): every route that asks a model is held to the
key's cap, however the request came (loopback, LAN, a Remote magpie, a
Responses socket's turn). One request too many waits in the key's
queue in arrival order. It shows as "slot" in Active, and its wait goes
into the try's Queued. A request whose agent goes away while it waits
leaves the queue and sends nothing. A stream holds its slot until it
ends. serve's routes (chat, responses, messages, ollama, gemini, the
Codex backend) wait inside the try, after keepQueued, so a streaming
agent gets keepalives while it waits. The other model routes (images,
embeddings, rerank, audio, videos, search, decisions, native) wait
before their handler runs. forward and codexUpstreamOn take the slot
too, so nothing reaches a vendor without one. A key issued under
another waits for its own slot, then for its issuer's.
/v1/magpie/concurrency lists each capped key under "keys", and counts
its waiters in "waiting". A key's limit (key_limit) reports the cap.
Not held, as a provider's MaxConcurrency doesn't hold them: GET,
HEAD, OPTIONS, count_tokens, :countTokens and MCP.
TestKeySlotEveryRoute fails when a route is judged neither held nor
free.
- cli: magpie gateway-key concurrency <id> [<n>|off]. It refuses 0, a
negative, over 1000, a fraction, a word, --help or an extra argument
with its usage.
- gui: the key row gets a badge in the provider concurrency badge's
style. It opens the app's menu with No limit, 1/2/3/5/10 and Other…,
and Other… takes a number typed in place. A value that isn't a whole
number up to 1000 is refused and nothing is sent. Browser and
read-only keys have no badge. Strings are in en, zh, zh-TW, ja and
de. An unset badge, which a hover shows, gives way before the masked
key (flex-shrink 8). Without that, at 420px in en and de, the extra
badge squeezed the key until its copy button slid under the pointer
that came to drag the row, and gateway-key-arrange went red.
- docs/subsystems/gateway-routing.md describes it.
Run (on mote, at this tree on origin/main 0f8c3d867; rebased onto
|
||
|
|
7d196b6797 |
gateway: what a proxy says of the caller reaches no vendor, ChatGPT backend or MCP server
Behind Tailscale Serve, a Cloudflare Tunnel or another reverse proxy, the request magpie gets carries what the proxy says of the caller: Tailscale-User-Login, -Name and -Profile-Pic (the user's email, name and picture), True-Client-IP, X-Forwarded-*, Cf-*. The native route dropped X-Forwarded-*, Forwarded, Cf-*, X-Real-Ip and Via, but not True-Client-IP or any Tailscale-*, even though lanGuard itself reads True-Client-IP and Tailscale-User-Login as forwarded (forwardHeaders). The Codex passthrough and relay to the ChatGPT backend (copyHeaders) and the MCP proxy dropped none of them. proxyIdentity names them once: every forwardHeaders entry; any X-Forwarded-*, Cf-* and Tailscale-*; Forwarded, Via, X-Real-Ip, True-Client-Ip, X-Client-Ip and X-Original-Forwarded-For. nativeHeaderDropped, copyHeaders and the MCP proxy's header loop all skip them. The caller's other headers still go on. Checked and left as they are: a provider's PassHeaders (names the user chose), Codex's allow-listed codexHeader, the Codex websocket's headers and passOnCaller. Tests: TestNativeAnyDropsProxyIdentity (native route, under MAGPIE_TRUST_PROXY) and TestPassthroughDropsProxyIdentity (Codex relay through copyHeaders, and /mcp/<server>). Each sends twelve identity headers and checks that none arrive and that X-Custom still does. Broken by hand: with native.go, codex_backend.go and mcp.go at their parent, both tests are red. The native vendor was told True-Client-IP and the three Tailscale-User-* headers. The ChatGPT backend and the MCP server were told all twelve. Run on mote at the pushed head 883690a0b (this commit and the one before, on origin/main |
||
|
|
ff415f39cb |
gateway: a compaction refused for an input kind it doesn't take is asked again as text (#5181, #5259)
Command Code's /responses takes messages, function calls, their outputs and reasoning only. A Codex subagent's compaction carries agent_message, custom_tool_call and compaction_trigger items, and Command Code answered 400 unsupported_input_item (param input). codexCompact didn't count that as a reason to ask again with the conversation as text, so the 400 went back to Codex three times and compactFails held the conversation for 5 minutes. inputKindRefused now asks again as text on unsupported_input_item or "unknown item type" (Grok's 422) in a 400, 422 or 502 (another magpie in front wraps it), or in a stream's error / response.failed event. A 401, 403 or 429 with the same words still goes back as it came. itemText reads an agent_message as the user's turn, so the subagent's task and follow-ups are in the text summary and in the local one. No plugin change: the Command Code plugin passes /responses through, and the fallback covers it direct, through a remote magpie and in a stream. Run (mote): - go test -run 'TestCodexCompact|TestCodexCompacts|AgentMessage' ./internal/gateway: ok - go test -timeout 45m -count=1 ./internal/gateway: ok (809.6s) - gofmt -l clean; go vet ./internal/gateway native, GOOS=linux -tags nogui and GOOS=windows: ok Broken by hand: - origin/main's codex_backend.go: every AsksAgainAsText subtest red (400 / 502 back to Codex). - agent_message case removed: the text lacks the subagent's task. - status guard loosened: the 401/403/429 test red. Not tried: a real Command Code account (the keys on this machine are answered 401), the reporters' own sessions; why the compaction reached /responses rather than chat is not confirmed. Reported-by: Mmx233 <36563672+Mmx233@users.noreply.github.com> Reported-by: Edward4226 <Edward4226@users.noreply.github.com> Reported-by: mahiro233 (Discord) Co-authored-by: Mmx233 <36563672+Mmx233@users.noreply.github.com> |
||
|
|
8b70b7d976 |
usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now keeps what each request received back (down_bytes) beside what it sent up (up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the upload (image_files_saved). Shown in Usage → Requests: - a row's details: "Sent upstream", "Received" and "Saved by image files", each only when it is above 0. A row from before has none of them, not 0; - under the Requests card, the period's "↑ up · ↓ down", with "{n} saved by image files" when there is a saving. Its title gives the exact bytes. A period with no counted bytes shows no line. What is counted: - Down bytes are counted as the reply body is read, after Go's transport has undone gzip, so a gzipped reply counts its plain size, not wire bytes. A plugin's row counts the local hop to the plugin host. A 101 body is not wrapped. Every try counts, so a refused try plus the answering one add up (TestLedgerKeepsDownBytes). - Image files saved, per try: the body before the swap minus the body sent, minus the upload bytes this request itself paid (len(b64)/4*3). It can be negative on the turn that uploads; the GUI shows only a saving above 0. Gaps: an upload that finishes after the wait timeout or ctx-done is not subtracted (as with up_bytes); a joined upload flight is paid by the request that started it; multipart overhead is approximate. - packedRow grows by three int32 (152 bytes, still within the test's bound), clamped to the int32 range. Totals sum all three. - settledCountVersion goes 1 → 2, because Totals now count bytes. The settled page, heat and effort caches recount once, on the first start after the update. The heat key hash includes the new fields. Run on mote at |
||
|
|
1100ed6494 |
gateway: an overlong item id goes left out on every kind that may go without one, and under its kind's own prefix on the rest (echo_ts, web_search_call)
echo_ts (Discord, Codex on GitHub Copilot, after |
||
|
|
125fd93ecd |
gateway: an overlong message or call id goes left out, and any other is bound under its kind's prefix, which Copilot checks (echo_ts, #5266, #4972)
echo_ts (Discord #feedback, v0.1.3058): after Codex's native compaction, a tool call on GitHub Copilot failed with an empty 400 "invalid_request_body". Copilot had handed the call a 452-character opaque id (Base64, + and / in it, no fc_ prefix). plainItemIDs, on every relay that checks ids (validatesItemIDs, Copilot among them), sent any id over 64 as boundItemID's sha256. That kept an id's own prefix only when it had one, so an opaque id went as a bare 64-hex digest. Copilot refuses that. By hand, the reporter got 200 with the original id and 200 with the id left out (call_id kept). isnine found the same thing for a message on #4525/#5266: left out 200, bare digest 400, msg_+hash 200. The bare digest dates from |
||
|
|
9a51d644d6 |
gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275)
hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a ~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB summary request was still being written to Ark at 299s (TryNet Send ~299s, no first byte), Codex gave up at 300s (499), and only then did magpie log "the reply ended before it was complete; compacting locally". That local summary went to a request nobody was reading, and compactFails.done cleared the conversation's count as if it had worked. Codex sent the same history again, three times, 300s each, and the conversation never got shorter. - codexCompact gives the summary compactWithin (4 minutes, a minute short of Codex's 300s stream idle timeout, as agentQuietMost). Past it the vendor is no longer waited on (the ask's context ends with a sideTimedOut cause, so the usage log says "magpie stopped waiting: its compaction summary had no answer in 4m0s", not the agent canceling), and magpie's own summary (localSummary, saying "no summary came in 4m0s") goes to Codex while it still waits. Checked after the first ask, the ask as plain text, and the as-text ask after tool calls, so a late first ask is never followed by another ask of the same body. - A compaction Codex left before it was answered is counted a failure (499, "Codex left before the summary reached it") and nothing is written; done() is no longer called for it. After compactFailsMost in a row, the next is held with a 400 at once instead of another 300s. Why the upload was slow: not shown to be magpie's. From here a 3.1MB whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s (HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB control not finishing in 40s by any route, point at the uplink or the Shadowrocket TUN in their path. Not tried through a TUN. Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix; both red on the old code (the first: no answer before the client's 10s; the second: a completed compaction written to a Codex that left, and the next not held). go test -run Compact ./internal/gateway ok; go vet of internal/gateway for darwin, linux and windows ok; gofmt clean. Full suite: run after the push (go test -timeout 45m ./... on mote, log teed), result on #5275. Not tried: a real Codex Desktop session against a slow uplink; a reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex still leaves first, and the count holds the conversation after 3). |
||
|
|
34116ec012 |
gateway: Codex signed in to one account lists another account's models
bigfisheatsmall on X: Codex was kept signed in to ChatGPT account A, on the Free plan. Account B (Team) was the only account on in magpie. dsh listed B's models and Codex didn't. codexMerged added CodexListed(), which leaves out every ChatGPT account's own models because it assumes the backend lists them. But the backend list is fetched with Codex's own sign-in (A, Free), so B's plan-only models were listed nowhere. Routing already sent codex/<model> to B (codexAccounts). - provider.CodexListedBeside(backend) lists an account's own model by magpie's id (codex/<slug>) when the sign-in's backend list lacks it. codexMerged uses it, and FitOwn keeps those entries. - spawnChoices (spawn_agent's models) had the same gap. It now uses the same rule with the slugs in Codex's models cache. - buildCodexListTag covers the accounts' own models, so another account gaining or losing one has Codex ask for the list again. Every Codex asks once after the update. - TestSyncCatalogAgesCodexCache built its "current" tag by hand from CodexListed(). It now uses provider.CodexListTag(), the tag SyncCatalog compares against. Tests (sandbox HOME, fake backend with per-plan lists): TestCodexListHasAnotherAccountsModels covers the list, routing of codex/gpt-6.1-sol to the Pro account, and spawn_agent's choices. TestCodexListOneAccountNoneTwice checks that a single account gets no codex/ duplicates. Run on mote at this tree: go vet (darwin, windows, linux) on gateway, provider and agent: ok. go test -count=1 on provider, agent and codexcat: ok. go test -run 'Codex|Spawn' on gateway and gui: ok. Run at the tree before the sync_test change and the buildCodexListTag tidy: the full gateway package was ok (1224s). Agent was red only in TestSyncCatalogAgesCodexCache, fixed above. Broken by hand: on the old codexMerged, the new test fails with "Codex's list lacks codex/gpt-6.1-sol: [gpt-6-luna gpt-5.6-terra gpt-5.6-luna]". With only codex_spawn_models.go reverted, it fails with "spawn_agent's models lack codex/gpt-6.1-sol". Not tried: real accounts or a real Codex. Not a full go test ./... run. Not tried: models the backend marks hidden. A Codex here for failover alone (codexOwnOnly) is unchanged. |
||
|
|
1e1068c86c |
codex: "Same as the lead" holds every subagent to the lead's model (cleverpigo on X)
cleverpigo (Windows, Codex App 26.1027.6604.0) had Codex's lead on WorkBuddy's DeepSeek-V4.1-Flash, the subagent model on what the GUI called "Same as the lead", and the Routing page still showed a subagent on gpt-5.6-sol through Codex's own sign-in. Cause: that setting, unset, never held a subagent to anything. Since |
||
|
|
78667e9b77 |
gateway: a request in flight shows its model's context window
packinggoods on Discord: Routing's context window card said "the model's
window isn't known" for a request on remote-magpie/claude/claude-opus-5-5
that was still answering, though the remote magpie's list gives that
model's window. The window was put on a route's prompt only when the
request ended (calibrate at the route's end). A live request always
showed it as unknown, on every provider.
Now the window of the model a try goes to is read as the try goes out.
That is windowOf(c.p, c.model), the same call the route's end makes. It
is kept on the route (Route.window, unexported), and the prompt shows it
while the request is under way (livePrompt). This holds whether the
prompt is read before or after the try starts. A fallback to another
model updates it. At the end the answering model's window still comes
first, as before. Codex turns through magpie's Codex backend now work out
Codex's own window (CodexWindow, else models.dev) when the turn begins,
not when it ends, so they show it live too.
Run at this head (rebased on
|
||
|
|
b59e4b747f |
gateway: a conversation on a new account leaves out the old one's seals (#3887)
hheei (#3887): a Codex conversation with a web search in it (OpenAI's own web_search, a web_search_call in its history) failed on every turn with "HTTP 400: Codex: Encrypted content could not be decrypted or parsed. (code: invalid_encrypted_content)" once magpie had moved it to another ChatGPT account of the same routing group: after its affinity went cold ("why": "cold", over two hours on), or after the account it was on was used up or rate limited. What an account's turn wrote comes back sealed for that account (encrypted_content): its reasoning, a web search, and with Codex's output token replay on (codex-rs core/src/client.rs: only for a provider named "OpenAI", which Codex signed in reaches magpie as) each message and call. Codex hands it all back on every turn, and between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as it came (forVendor, |
||
|
|
694f4a6d65 |
gateway: a Codex turn of its own reads past 512 MB, to a sixteenth of the machine's memory (dallascao)
dallascao on Discord: generating images in Codex and revising them again
and again, magpie answered 413 "request body is over magpie's gateway
limit of 512 MB (decoded); the provider was not asked" on
127.0.0.1:3425/backend-api/codex/responses, while Codex signed in to
OpenAI directly went on. The count was right: Codex keeps each image it
generated in the conversation (a function_call_output input_image, a
~3 MB PNG as ~4 MB base64; codex-rs ext/image-generation to_response_item,
and history keeps image_generation_call results), and over HTTP sends the
conversation whole every turn, so ~130 images is 512 MB decoded. To
OpenAI directly Codex uses its WebSocket and sends a delta.
- Codex's own path (codexBackend, the Codex relay, the Responses
WebSocket's read limit, keyLimited on CodexPath) reads to
codexBodyLimit: a sixteenth of the machine's memory (memLimit, else
proc.MemTotal), 512 MB at least, 2 GB at most. 16 GB: 1024 MB,
24 GB: 1536 MB, 32 GB+: 2048 MB, 8 GB or unknown: 512 MB as before.
It is still the bomb guard: nothing decodes past it, and the zstd
decoder keeps its window bound.
- A turn for a magpie model ("provider/model") on that path is held to
the 512 MB of every other route once its model is read: it is
translated, at several times its size. Its 413 says one of Codex's own
models takes up to codexBodyLimit; writeError's /compact hint stays.
- provider.codexNamesBad read tools/input/tool_choice with
GetManyBytes, which copied the whole input (the body's size: 300 MB of
a 300 MB turn in the alloc profile). It reads in place now.
Cost at the largest input (mote, a relayed gpt-5.5 turn of random
~3 MB images, heap objects sampled every 5ms, load ~350): 300 MB took
4.7s, 600 MB 7.7s, 1000 MB 11.9s, peak heap 1.5 to 2.1 GB past the
body's own bytes. The rest of the cost is io.ReadAll growing the decoded
body and fillJSONIn/exchangeOf; bodyRoom still runs a body bigger than
its room alone.
Run at the pushed head (mote): gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/gateway ./internal/provider ok;
go test -timeout 45m ./internal/provider ok, ./internal/gateway ok but
TestCompactionOverByteCapEveryTime, red in the full package run only
(#4862, filed before this; passes alone 3 of 3 here).
TestRequestBodyTooLarge/codex now sends codexBodyLimit+1.
- TestCodexGeneratedImagesPastOldLimit (16 GB machine fixture, a 516 MB
turn of generated images in Codex's shape): reaches the fake ChatGPT
backend whole in ~6s; the same turn for x/gpt-5 is 413 naming
"one of Codex's own models takes up to 1024 MB".
- TestCodexBodyLimitFromMemory: 2/8/16/24/64 GiB and unknown memory.
Broken by hand: codexBackend reading with limit 0 (the old code) makes
TestCodexGeneratedImagesPastOldLimit red with the reporter's 413; the
magpie-model check turned off makes it red (404 from routing, not 413).
Not tried: the reporter's own session or a real Codex image-generation
run through magpie; a turn past 1 GB on a 16 GB machine; the WebSocket's
raised read limit has no test of its own.
|
||
|
|
affa979d56 |
gateway: Codex's one account used up goes on to the Codex subscription's fallbacks
adorable_piglet on Discord: once the ChatGPT (Plus) account's quota ran
out, the Codex app couldn't send at all, and magpie never moved the turn
to the fallback they had set (their own API key, another provider).
Cause: with one ChatGPT account and nothing to route, a turn on Codex's
own sign-in is relayed as it came (codexUpstreamOn). The relay handed an
overload on to the subscription's fallbacks (codexFallBack), but a
quota, credit or rate refusal went to Codex as the backend said it, the
429 usage_limit_reached with its x-codex headers. Codex then stops.
Change: codexAccountOut names the refusals that are the account's, not
the request's: failure() quota, credit or rate, as a status or as a
stream's failure before any reply (response.failed, an error event, a
stream without Content-Type), and a 403 usage_not_included. Never a 401:
Codex renews its own sign-in on it. When the subscription has fallbacks
(codexFallsBack, never a compaction), such a refusal now goes on to them
once the credits retry and the automatic reset have been looked at, as
an overload does; the trace keeps the try's real failure kind. With no
fallback set, Codex still gets the backend's refusal.
What Codex's own client does: it greys Send from its own /wham usage
read. magpie already gets past that once the usage reading says used up
(codex.out with the app-server restart, #540,
|
||
|
|
8819beeb0e |
gateway: a display reads routing as it happens at /v1/magpie/route-events (#3387)
joe21_eee (sywyyhykkk on GitHub) wrote this for an ESP32 screen that shows each agent's requests live: started, each try, the first content, fallback, done. Ported from their route-events branch (42e1fa43f) with the changes below. What a display gets (route_events.go): - GET /v1/magpie/route-events/snapshot: cursor, active, routes (every request the trace has that is still going). - GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID): SSE, one "route" event a change, id = cursor, from a 512-change ring under trace.mu, so a short request is told step by step. 409 snapshot_required for a cursor not this process's or too old, "event: reset" for a reader that fell behind, a heartbeat every 15s, a 10s write deadline. - A route is routeActivity, an allow list: trace id (base 36), time, agent label, the provider of the seat the last try went to (never the seat id, which names an account or a key fingerprint), model, attempt, fallback, phase, status, failed, ms, ttft_ms. No session, account, key, folder, prompt, reply or error text. - firstToken.onFirst tells the first content as it comes (serve and the ChatGPT backend's reads), written to an unexported Try.firstMs so the full trace's TTFT is unchanged. Changed from the branch: - No new key type. The branch added an "sk-magpie-route-" key, its CLI flag and its own Authenticate path through access, identifyCaller and corsGuard. main has read-only keys now (readOnlyGuard), and the feed is answered as /v1/magpie/usage is: this computer, and another machine with an enabled key while shared; a held key is refused (refuseHeld). Both GETs are in readOnlyRoutes, so the display gets `magpie gateway-key add Screen --read-only`. A full key already reads more than this (every call's usage). access, cli, cors.go and lan.go are untouched. - A route the trace drops unfinished (drop: an unrouted request's stand-in once its own route begins; trim past twice traceKeep) is told request_dropped and marked offFeed. The branch kept its own active map that only "done" cleared, so a stand-in stayed going forever. The snapshot is read from t.routes, no second map. - A stream ends when the gateway stops serving (Server.streamsEnding, closed first thing in ListenAndServe's drain). Before, an open stream held srv.Shutdown for its whole drain, 15 minutes on a handover. - Revocation is access.On(KeyID) (identifyCaller swaps the secret out before handlers see it), asked at most once a second when there are changes and at every heartbeat, and remoteKeyed for a remote reader. A rotated key keeps its id, so its open stream goes on until it reconnects (said in the docs). Docs: gateway-routing.md "Route events for a display" and the read-only key's route list; reference.md beside the usage API. Run at the pushed head on mote (Go 1.26.8): - At daaafeb6e (rebased on |
||
|
|
c86fa2a341 |
gateway: a relayed citation without the offsets OpenAI's schema wants is dropped, the thread healed (#4921)
A thread a routing group served once on Volcengine Ark (or another vendor whose Responses endpoint writes its url_citations with no start_index/end_index) never worked on a codex member again: magpie relayed the reply's annotations as they came, Codex stored them, and the ChatGPT backend refused every later replay of the history whole — "Missing required parameter: 'input[221].content[0].annotations[0]. start_index'" — five retries a turn, on any codex member, through any upgrade (#4921, the reporter's routing log and rollout). This is #2855's defect with a different field: what magpie hands a client must be something magpie could send again. Such an annotation goes, at both seams, as the reasoning-item fix did: - a whole reply streamed as the vendor's own events (responsesWholeEvents) drops it in every place a client reads a citation: its annotation events, the content part, the item and the reply the client keeps (dropOffsetlessCitations); - the history Codex replays loses it on its way to the ChatGPT backend (withoutOffsetlessCitations, the same leaving-out as a reasoning item's text, #1411): to the backend by its own sign-in and compaction relay (codexUpstreamOn), to it as a group member or an openai.com or Azure upstream (the provider loop, beside withoutReasoningText), and asked again without it where a relay in front of it names the parameter (refusesCitationOffsets), marked so it is never sent one again — a thread already poisoned heals on its next turn, no new thread needed. The text, and a citation that carries its offsets, go as the vendor wrote them; a turn with no "annotations" in it is not decoded (anyInputItem scan, itemCitesWithoutOffsets; the undecoded-turn test holds, allocations and all). Run: the three new tests fail on the base with the reporter's exact 400 and pass here (ablation: the tidy call and the rewrite's body neutralized, tests kept); TestCodexRewritesAsBefore, TestCodexRewritesLeaveTurnUndecoded and the fuzz hold the rewrite to its scan; the citation/whole/reasoning neighborhood ok (23s); gofmt, go vet (linux, windows) and go build -tags nogui clean. Review: this is skygunner's version of the fix (fcea11649), not ggbdpq's 57dc7b420. ggbdpq's stripped citations only for a request that wasn't for a magpie model, so the reporter's own path (a routing group's codex member, the history passed through) kept the bad annotation. ggbdpq's parity table and verification of the report were used to check this one. Changed in review: annotationLacksOffsets looks only at url_citation and container_file_citation, the two types OpenAI's schema gives start_index and end_index. file_citation and file_path carry a single index, so the patch dropped every one of them as "offsetless". TestCitationsWithOneIndexKept (added in review) holds both kinds and checks that a history with only file_citations is sent byte for byte. Broken by hand at the reviewed head: annotationLacksOffsets made to return false, all four citation tests red; the type check removed, TestCitationsWithOneIndexKept red. Restored, green. Run at the pushed tree (this stack of nine on origin/main |
||
|
|
4bac5eed26 |
usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted ~900 MB up in 45 minutes, and no ledger row said what a request sent. A row now has up_bytes, the bytes that went on the wire, every try and every second ask summed (zstd's size for a ChatGPT turn), and plain_bytes, the last try's body before compression. They are summed in the request's context on its own goroutine, set in serve and, for Codex's own turns that come from the mux and not through serve, in codexUpstreamOn. Handed-on rows carry neither; rows from before carry neither. From ggbdpq's patch (via gua2100), two changes: - the patch counted in codexUpstreamOn but set the context only in serve, so a Codex turn on its ChatGPT sign-in, the zstd case the issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes); - a second request inside one try (RetryOneAuth, RetryZhipuCoding, RetryOpenCodeFreeOnZen) went up uncounted; it counts now (TestLedgerCountsATrysSecondAsk). Request bodies to other vendors stay as their client sent them; zstd stays Codex's (the owner's call, on the issue). Run at this tree on mote: go test ./internal/gateway -run 'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok; go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean. Broken by hand: no context in serve: TestLedgerKeepsUpBytes and TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn: TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444); the second ask not counted: TestLedgerCountsATrysSecondAsk red. Not tried: a real session's numbers against a proxy's; the GUI shows neither field yet. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
f822689ada |
gateway: a relay's "referenced reasoning item" refusal is read as an unreadable item (#3062)
What changed: unreadableItem, the matcher that reads a 400 as "this input
item can't be read", now also takes the wording a Responses passthrough
relay answers in — "Referenced reasoning item 'rs_…' was not found or has
expired" — beside OpenAI's own ("Item with id 'rs_…' not found",
"encrypted content for item"). The refusal is recognized wherever the
matcher is read: the passthrough turn is asked again without the bare
reasoning (and the provider's model isn't sent them again), the ChatGPT
backend drops the named item and asks the rest again, and a compaction
refused so is asked again as text.
Why: a Codex thread behind such a relay (opencode.ai's OpenCode Go)
collects reasoning ids the relay can't resolve, two ways — a turn failed
over to a provider magpie translates leaves Codex reasoning items magpie
minted (an rs_ id and a summary, nothing sealed), which never existed on
the relay's store; and the relay seals its own reasoning only briefly, so
after a resume gap ids from its earlier replies read as expired. Codex
replays the whole history every turn, and the relay's 400, worded by the
relay and naming no input param, passed refusesInput unread — so the
thread 400s on every later turn. The reporter's repro now strips the
named bare item, asks again, and answers 200.
Run: TestRelayRefusedReasoningItemReadAsUnreadable and a TestRefusesInput
row for the reporter's exact body are red before the change and green
after; the bare-reasoning, foreign-seal and item-not-found families stay
green (also with -race, and under an ablation and a mutation of the new
wording, where the old wordings' tests stay green); gofmt clean; go vet
on darwin, linux and windows; builds with -tags nogui on the three. Full
./internal/gateway/ is green on the third run (511s); a first run hit go
test's default 10m timeout and a second failed only
TestAsyncGatewayResponseDoesNotHoldStream — a fixed-10s-guard streaming
hook test unrelated to this change, which passes 3/3 alone.
Generated-by: GLM-5.3-Flash (ZCode)
Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id
checked against the issue) by yetone, rebased on origin/main 2026-11-03.
Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of
internal/gateway with -run over this batch's tests and their families
(PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay,
Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of
the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway
and gofmt -l clean. The full gateway-and-importers run, started at an
earlier base, was still running at the push; its reds get issues.
Broken by hand: the regexp change reverted, test kept:
TestRelayRefusedReasoningItemReadAsUnreadable red; restored, green.
Not tried against the reporter's relay; the fixture is its literal body.
|
||
|
|
5ec2375688 |
gateway: a call's HTTP headers both ways, masked, folded under its bodies
usrname1833 on Discord asked to see the raw request and response HTTP headers (查看原始请求和原始响应的http头), to debug as with a capture. magpie kept the client's request headers and its own response headers only in the request archive, and nothing of what went upstream. Now a call keeps its headers both ways (internal/gateway/wire_headers.go): - the client's, as they reached magpie: headerLogged in Handler() clones them for every request that isn't a GET, HEAD or OPTIONS; - each request magpie sent upstream for the call: method, address, headers, and the answer's status, protocol, headers and time, or the error. rpmTransport (under s.client) records it as it is sent; provider.SendsThroughPlugin records a plugin account's hand-off, shown as handed to the plugin, since the plugin's own request to its vendor is made in Bun and magpie doesn't see it (the view says so). The first 8 tries are kept, the rest counted. Recording copies each header map; nothing is masked or sorted as a request goes. Secrets are taken out when the headers are read (Call.Headers): by what each header is (new redact.SecretHeader, now behind redact.ScrubHeader: Authorization, cookies, x-api-key, api-key, any *-Key, *-Token, *-Secret, *-Auth, *-Signature, but Idempotency-Key and a count of tokens such as anthropic-ratelimit-tokens-remaining), any Bearer or Basic value, and redact.Scrub on the rest; an address loses its password, a secret-named query value (?key=) and its fragment. They live with the call in the 40-call ring; /api/gateway/call gives them as "headers". The request archive keeps the upstream ones as "upstream" beside the request's and response's headers, masked the same way. No body is stored that wasn't before. GUI: under a recent call's bodies on Gateway and a request's on Routing, "HTTP headers" folds open the client's headers, then each upstream request beside its answer (wireHeadersView, plugins/usage/page.js); the archive's copy shows its upstream requests too. Strings in all four languages. docs/subsystems/gui-shell.md describes it. Also changed by SecretHeader: the request archive no longer masks a rate-limit count header (…-tokens-remaining), which the old name rule took for a token. (provider.SecretHeader, which backups use, is another function and unchanged.) Tests: TestRecentCallHeadersBothWays (a fake vendor; the client's key and cookie, magpie's upstream key and the vendor's Set-Cookie all masked; status, protocol and response headers kept), TestRecentCallHeadersEachTry (a 429 then the next key, both kept in order), TestPluginHandOffHeaders, TestScrubURL, TestSecretHeaderRealNames (real header names both ways), TestArchiveOnThisComputer and TestRecentCallBodiesOnDemand extended, call-headers.test.cjs (Gateway, Routing and the archive's copy; chromium and webkit; en at 1100px, zh, zh-TW, ja, de at 380px and Routing at 440; nothing out of the box, no left-border accent). Run (on mote, macOS 27.2, through mote-run, unless named): - Full suite at ebd22b1b4 (the same change on |
||
|
|
07f4d46c52 |
gateway: a Codex reply that ends early, and any failed call, is written to app.log
wjh66 (Discord, Windows, v0.1.2696) saw Codex on a ChatGPT sign-in with
gpt-6.1-sol show "reconnecting 5/5" and then `error decoding response
body`, and app.log around 15:27 held nothing about it. That text is
reqwest's for any read error in a body (a reset, a chunk cut short, a
timeout), so it says the connection broke mid-reply, not which side broke
it. The cause is not found; this change only makes the next report carry
evidence.
- record logs a failed call (status >= 400 or an error) when debug is off,
once a minute per agent/provider/model/status/error, counting repeats.
- codexUpstream logs a reply that ended before its last event (or a
non-SSE body cut by a read or write error): bytes passed on, whether
OpenAI's stream failed or ended, and whether Codex went away, a write
to it failed, or it was told response.failed.
- Shutdown with requests in flight says they are cut (Windows has no
handover, so a quit or update cuts streams after shortDrain).
Run at this head (rebased on 4bd0d6f38; the new and stream-cut tests and vet run again after the rebase on mote and Windows, the full gateway run on Linux was at
|
||
|
|
58541e5b8c |
gateway: a turn that ended failed, cut or canceled says no task done (#4866)
emo172 (mochi) reported that "<agent> 已完成" was shown for Codex turns
that never finished. On Codex signed in with ChatGPT
(/backend-api/codex), three cases were recorded as a clean 200 and
ended the turn: Esc or a closed window mid-reply, a response.failed
under the backend's 200, and a response.incomplete. codexUpstreamOn
looked only at the status and codexStreamCut. codexStreamCut says ""
when sniff.failed is set, when the stream is whole, or when the
context is done. trace.go:790 then ended the turn with final true.
The fix is in the one place both turn paths share, the reply scan
(toolScan) every byte to the agent goes through, and turnFinal, which
now decides `final` at trace.go:790:
- A cut mark makes a reply unfinished: an error event in each wire
format (Anthropic/Responses "type":"error", Chat/Gemini "error":{…}),
a Responses reply failed, incomplete or cancelled, and a reply cut
at its length (stop_reason max_tokens or
model_context_window_exceeded, finish_reason length, finishReason
MAX_TOKENS). Keys are matched with their quotes, so text or tool
arguments that mention them escaped never match. "error":null on a
success doesn't match.
- The agent's request being done before the reply's last event
(response.completed, message_stop, a stop reason, [DONE]) makes it
unfinished too. A client that hangs up after the last event, as
Codex does, still ends its turn.
- A Responses tool_search_call that Codex runs itself
("execution":"client") counts as a tool call. It was missing from
toolValues.
Codex direct also records what it saw, as the routed path does: 499
canceled when Codex went away mid-reply, and the backend's
response.failed as the row's error. Covered: the Codex HTTP and
upstream-socket paths, Codex's own socket to magpie
(response.interrupt), and routed Chat, Responses and Anthropic relays,
plugins included, since they go through captureResponseWriter.
Scene A, a model ending its turn with a question for the user: no
change. Nothing in the bytes tells "asks the user" from "done" without
reading the text, and a turn's end with the agent waiting on the user
is what the alert is for. Structured asks are tool calls and don't
alert already.
Tests (turndone_unfinished_test.go), from real event shapes:
- TestReplyScanUnfinished: 14 replies, each split at six points.
- TestTurnDoneCodexBackendUnfinished: failed, incomplete and canceled
(the agent hangs up on its first write). No end, the route says
error or 499, and a whole reply after each ends the turn.
- TestTurnDoneCodexSocketInterrupt.
- TestTurnDoneRoutedUnfinished: Chat error and length, Responses
failed and incomplete, Anthropic error and max_tokens.
Run on mote:
- go test -timeout 45m ./internal/gateway at c08d02adf (this change
on
|
||
|
|
b4a9cd8db5 |
codex: a tool name the ChatGPT backend refuses goes as one it takes, and comes back as the agent's
wing3556 on Discord (11-02): a compaction through a Codex account failed 400 "Codex: Invalid response.create payload: Invalid 'input[83].name': string does not match pattern. Expected a string that matches the pattern '^[a-zA-Z0-9_.-]+\z'." The ChatGPT backend checks every tool name in a request, a call's in input as well as a tool's in tools, and refuses the whole request when one fails. A conversation can hold a call by such a name: a model another provider served wrote one with a space, a colon or non-ASCII in it, and the agent kept it beside its "no such tool" answer. Every request that replayed it, the compaction above all, then failed on Codex. Nothing on the way checked: buildResponses copies a call's name as it is, and redaction keeps names as written. What changed: - provider.CodexToolName: a valid name stays as it is. Otherwise each refused byte becomes "_", the result is cut to 55 and gets "_" plus 8 hex of its sha256, so it is the same on every request and two names never meet. CodexToolNames applies it to tools (namespace children too), function_call/custom_tool_call items, additional_tools and tool_search_output items, and tool_choice. A body with no bad name goes byte for byte. - It runs where every request to the ChatGPT backend passes: codexBody (an account's, translated or relayed) and codexUpstreamOn (Codex's own sign-in, /responses and /responses/compact), beside DeclareSearch. - A tool the agent declared under such a name is called back by its own name: translated replies through decoderFor (now given the request's tools; codexNamesBack), relayed Responses replies through nsTidy's new back map (codexRenamedIn). - docs/subsystems/gateway-routing.md says so beside #1270's paragraph. Not covered: namespaces, the OpenAI API (whose pattern has no "." and a 64 limit), Azure and Copilot Responses, filed as #4875. Run on mote at this head: - TestCodexToolNamesTheBackendTakes and TestCodexToolNamesKeepValid pass. The fake backend refuses a bad name with the reporter's 400 word for word; the test covers Claude Code's compaction on /v1/messages with four bad history names (sent twice, byte-equal), Chat with a declared "search:web" called back by that name, Responses relayed the same, and Codex's own /backend-api/codex/responses. - go test ./internal/provider ./internal/gateway (-timeout 45m): provider ok; gateway ok but TestCodexPoolSaysTheClientsVersion, the red already filed as #4807 (full package run only, another test's Codex identity reaches it); it passes alone at this head. - go vet ./... (darwin) and GOOS=linux/windows CGO_ENABLED=0 go vet -tags nogui ./...: ok. gofmt -l: clean. Broken by hand: - codexBody hook off: compaction red with the reporter's 400. - codexUpstreamOn hook off, decoder restore off, passthrough restore off (together): the codex, chat and responses cases each red. Not tried: wing3556's real conversation (we don't have its bytes, and the agent is unknown; Claude Code is likely). No real ChatGPT account was asked with a bad name, so whether the real backend also limits length is unknown. |
||
|
|
dd809ea60f |
gateway: an input item's id longer than the 64 an upstream that checks ids takes goes shorter, as its kind's prefix and the sha256 of the whole of it (#4525, #4527)
Codex carries every id an earlier turn came back with, and Copilot gives its items ids hundreds of characters long: 420 as isnine's sessions each showed (#4525), 444 as ghjkllasdf-fake's approval session and its guardian review did (#4527), all of the characters OpenAI takes an id of. plainItemIDs checked the characters only, so every later turn went to Copilot as it came and was turned away 400 "Invalid 'input[N].id': string too long. Expected a string with maximum length 64, but got a string with length 420 instead." — the conversation stuck, a tool call never answered, Codex's automatic approval review failing over it. An id longer than the 64 goes as its kind's prefix ("msg_", "rs_") and the sha256 of the whole of it, cut to fit: the same id to the same shorter one every turn, and no two ids land on one, where a plain cut could (ids of a vendor can begin alike). Copilot's own reasoning, overlong but of the right characters, keeps its place with its seal — an upstream that checks ids made that one, its encrypted_content is its to read, unlike another vendor's, which still goes as it did. A call's call_id was bound already (BoundCallID); one shorter than 65 goes as it came. What changed - gateway: itemIDCap (64) and boundItemID, and plainItemIDs bounds an input item's id at them, on every relay that checks ids as OpenAI does — Copilot's /responses among them (validatesItemIDs) - tests: an id checker that turns an overlong id away word for word as isnine got it; Codex's turn over a Copilot conversation of overlong ids asked twice, the same bound each turn; the 64/65 boundary, determinism, idempotence, two ids that begin alike going to two; the parity harness holding plainItemIDs to it beside what it was Generated-by: GLM-5.3-Flash (ZCode) |
||
|
|
cbfbcb383b |
usage: a lead's answers are looked up in the blocks that name its conversation (#4370)
loggedAnswers, which leadFirst falls back to when affinity has lost a Codex subagent's lead, read thirty days of the log into a Record a row and kept the rows of one conversation. usage.VisitSessions reads only those rows: a block whose Session and NativeSession strings don't name the conversation is skipped, a row of another session is passed over by its shape's string ids without becoming a Record, and a matched row's strings are cloned out of the lent decode buffer. Each packed block's sessions are kept once it is decoded (blockSessions, by weak pointer, so no block the log let go is held), so a lookup decodes only the blocks the conversation is in and the open tail. A page's copy with Codex identities (which rewrite Session as a row is read) is read whole and filtered on its records. Run on mote (macOS 27.2), at load ~70: - BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300): visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and 12KB. - A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions, 18 blocks): every session looked up both ways gives the same records; 6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for a conversation that isn't there. - TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions, red with the known-sessions skip taken out. - GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean. - go test -race of the new tests and the gateway tests of a lead's answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s). - go test ./internal/usage ./internal/gateway (whole packages) was still running on mote at load ~190 when this was pushed; its result goes on #4370. Not tried: a real Codex subagent whose lead lost affinity; the lookup's callers and filters are as they were, and the gateway's loggedAnswers tests cover them. |
||
|
|
2be5d206e1 |
gateway: a Codex summary request too large for the vendor is asked again as text, then compacted locally (celestial_eagle_99230 on Discord)
celestial_eagle_99230 (Discord #general, v0.1.2403) runs Codex on official DeepSeek (DeepSeek-V4.1-Flash, 1M window) and gets "413 Request Entity Too Large: Failed to buffer the request body: length limit exceeded". The turn path was fixed by |
||
|
|
e4384fc3cd |
gateway: a Codex stream cut inside a line still has its failure read (#3377)
#3377's patch writes response.failed when the upstream cuts a Codex stream mid-reply. When the cut lands inside a line, the half line was still open, so the events streamError writes were read as more of that line's data and the client never parsed the failure. A blank line now goes first, ending the half event (as #2446 and #2580 do on the other relays). TestCodexStreamCutMidLineFailureParses cuts the stream inside a delta's data and checks every event the client reads parses, apart from the half line itself, and that response.failed is among them. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
cbefb65987 |
gateway: a compaction summary answered 502 for ending short compacts locally too (#3526)
#3526's patch compacts locally when the summary ask ends short with an error. The same cut can come back as a recorded 502 whose error says it ended short (errEndedShort), with no error returned, and that still went to the client as a 5xx. The local fallback now runs before the status check, for both shapes (summaryEndedShort), and says why from the recorded error. A 502 that says anything else still goes to the client as it did. Edward4226 pointed at the 502 shape in the thread. TestCodexCompactCutShapesCompactLocally covers a stream error, a 502 saying it ended short (compacts locally) and a 502 saying more (stays 502). Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
5b63dfd1a8 |
gateway: a Codex stream the upstream cut mid-reply is told to the client as its failure, and the row says why (#3377, Azir-11)
The ChatGPT backend cut every relayed stream about two minutes into the reply (121-125s, deltas flowing to the end): no response.completed, no error event, no usage, and Codex read a bare EOF, "stream disconnected before completion". Nothing in magpie bounds a stream that way — the gateway's client sets no Timeout, the upstream transport's only waits are ResponseHeaderTimeout (10 minutes, to the headers) and IdleConnTimeout (idle connections alone), the server sets no WriteTimeout, and the body's read deadline is dropped once the body is read — so the relay passed the cut on as it came, and was silent about it: the client's stream just ended, and the usage row recorded a clean 200 with nothing of why. Now a relayed stream that ends mid-reply — SSE, no failure said, no last event reached, the client still there — is answered with the stream's response.failed saying how long it had gone and that the reply is lost, and the row records the 502 with it. What magpie cannot do is keep the upstream talking past its cut: the wall itself stands on the magpie-to-chatgpt.com leg (the reporter's direct Codex ran 480s and 719s on the same machine and network), and telling it apart is what the honest failure is for. TestCodexStreamCutToldTheClient fails without the change: the fake upstream ends its stream after one delta, and the client heard no failure and the row said 200. go vet clean; go test -tags nogui ./internal/gateway/ passes in full. Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
6f041c292c |
gateway: a Codex compaction relayed to a vendor that isn't OpenAI's asks as system, not developer (#2955)
forVendor, the fitting a relayed Responses request gets before it goes to a provider that isn't OpenAI's, now turns the developer messages of a summary ask magpie made itself (codexCompact) into system ones, where they stand (developerItemsAsSystem). Codex's own turns keep the role the client sent, which a relay may be checking them by (#350, #1758), and OpenAI's own API and the ChatGPT backend, which take developer as Codex sends it, get the compaction as it came too. Why: on a provider whose Responses endpoint fronts a chat-only vendor (a relay of one; DeepSeek's preset names one base for chat and responses alike), every Codex compaction failed there with 400 "developer is not one of ['system', 'assistant', 'user', 'tool', 'function']", retried five times, while the turns around it passed: the summary request is relayed as Codex sent it (tools: [], #378), and the compaction carries a developer message its turns don't. The translated route already lifts such messages into the system prompt; the summary ask now says them as system on the relayed route too, in place, so a thread's cached prefix keeps its shape (#502) — what Zed's cloud is already given (ZedBody) and what a Chat Completions upstream is given (developerAsSystem). Run: TestCodexCompactDeveloperAsSystemOnAVendorRelay (red before, green after; ablated and mutated), the compaction families (TestCodexCompact*, TestLocalCompaction*, TestNativeCompaction*, TestVendorRelay*, TestAdditionalTools*, TestCodexOpenAIFields*), the full gateway package, -race over the families, go vet and go build of the package on darwin, linux and windows. Refs #2955 Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
78632d4b84 |
gateway: a Codex compaction cut short with no candidate left compacts locally (#3526, Edward4226)
A summary wanted whole whose stream every candidate broke off reached codexCompact as an error none of its fallback conditions name: not a 404, not an unreadable item, not "Upstream request failed", not "response protection is unavailable". The relay ends such a stream with a response.failed event saying "the reply ended before it was complete" (#2274), and with nobody left to fail over to, that error fell out of the 404/protection family and went to Codex as a 502. Codex asked the same huge summary over, three times, each paying for the whole conversation, until compactFails answered 400 and held it: the conversation could neither compact nor go on. That is the no-candidate case #2274 left, after it made a cut summary fail over where there was someone to fail over to. The summary is magpie's own then, as when no model can be asked at all (#866, #1008, #1270 end so). The summary as text isn't tried either: the cut was in what the model wrote, not in what it was asked, and that would be another ask of the same huge prompt. The words before the cut are never taken: the local summary is built from the request's own items. A summary that failed halfway, or ended incomplete — the output limit's own event — is still told to Codex as it came and still counts the guard; only the bare break-off turns local. 401, 403, 429 and request-shape refusals are untouched. Run: TestCodexCompactCutAloneCompactsLocally (new) is red on the parent with the issue's 502 ("the reply ended before it was complete, so there is no summary") and green here — 200, one magpie compaction holding the local handoff, the cut stream's words in none of it, the last ask the fake saw still the original summary request (no plain-text retry). The #2274 tests keep their shape: TestCodexCompactCutSummaryFailsOver (a whole fallback summary still wins) green unchanged; TestCodexCompactCutSummaryIsNoSummary now covers the halfway and incomplete shapes alone (the cut one moved to the new test); TestCodexCompactKeepsFailingIsHeld holds on the incomplete shape, which still fails and rests nobody. Ablation: only codex_backend.go put back to the parent, tests kept — the new test is red again, restored, green. go test -tags nogui -p 2 -count=1 ./internal/gateway: ok (350.8s). Targeted TestCodexCompact with -race -count=2: ok. ./internal/usage: ok. gofmt -l clean; go vet -tags nogui on darwin, linux and windows clean; CGO_ENABLED=0 go build -tags nogui on all three ok. docs/subsystems/gateway-routing.md says the new terminal state. Refs #3526 Landing record (yetone): Run at the pushed batch head (tree a6b084d0b, on origin/main |
||
|
|
bb50f4ad94 |
gateway: a Codex passthrough member OpenAI doesn't know is left out and asked again
xuanwo on X: every new conversation in the Codex app (two agents) ended
at once with the ChatGPT backend's 400 "[ObjectParam]
[input[55].internal_chat_message_metadata_passthrough.content_token_count]
[unknown_parameter]". The member is new in the Codex app's bundled
build; no open-source Codex sends it (main 67f0994, npm 0.166.0), and
openai/codex#52313 was the same refusal of content_item_metadata in
0.163.0-alpha.1. magpie sends the passthrough as Codex wrote it to
OpenAI hosts and ChatGPT accounts (forVendor), so the refusal reached
the app. The reporter's own look at magpie's routing log: the main
conversation failed at input[49] and input[55], and a conversation
with no subagent failed the same way, so subagents aren't the cause.
The member is Codex's own attribution, not the conversation. A turn
turned away over one passthrough member, or the passthrough as a whole,
is asked once more without it on every item, with the other members
and every other byte kept as written. The provider isn't sent that
member again (unfit, as for a tool's strict). The signed-in Codex
relay's retry (withoutUnreadable) takes the same refusal.
Run (mote, go1.26.8):
- TestPassthroughMemberLeftOutWhereRefused, TestPassthroughRefusalWordings,
TestWithoutPassthrough: ok.
- Broken by hand: with the retry turned off, TestPassthroughMemberLeftOut
WhereRefused gets the reporter's exact 400 back.
- At
|
||
|
|
9551fadcb4 |
gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at base |
||
|
|
0956ca49d7 |
gateway: Codex's own sign-in asks again after a connection dropped with no reply
aetrox333 on Discord: on Codex, bare gpt-6-luna and gpt-6.1-terra
failed with 502 "OpenAI can't be reached (Post …: EOF)" after 43ms
every time, through a fake-IP proxy (chatgpt.com at 198.18.0.12),
while auto/gpt-6-luna and auto/gpt-6.1-terra answered 200 every time.
Cause: a bare Codex model goes to ChatGPT on Codex's own sign-in
(codexUpstreamOn), which ended the turn with 502 at the first transport
error. Go's transport sends a POST again by itself only on a reused
connection (replayable, #2136), so an EOF on a fresh one, a proxy
closing it before a byte of a reply, came straight back to Codex.
auto/ and codex/ go through the accounts loop, which takes the same
502 as passing and asks again after a pause on a new connection, or
asks the group's next member. Both routes share one client, transport,
proxy choice and HTTP/1.1; a recorded diff of the two requests showed
no difference that would change how a proxy treats them (the routed
one adds instructions, Openai-Beta, Session-Id and its own token).
Now a dropped or reset connection with no reply on the own sign-in's
/responses is asked again, retryPause<<n apart, up to lastRetries, as
an overload is (askAgain: the trace shows each try, Codex is kept
alive). The caller gone and a wait that ran out are not asked again.
After the last try Codex is told OpenAI can't be reached, as before.
Run (mote, at this head rebased on
|
||
|
|
b62fa332f3 |
provider: Send requests unmasked for subscriptions and plugin providers too (isee1_1)
isee1_1 on Discord uses a community translation plugin as a provider and asked why "Send requests unmasked" (请求不脱敏) isn't offered for it. |
||
|
|
dafe4af822 |
gateway: the ChatGPT backend's "auto"/"default" tier is recorded as unknown (jjt on Discord)
The ChatGPT Codex backend says service_tier "auto" in response.created and "default" in response.completed whether priority ran or not. jjt's measurements on gpt-6.1-sol with a Plus account: Fast decodes at about 200 tok/s, without it about 110, and the reply says "default" both times (real-priority.sse, speed-plus.txt). magpie copied that into tier_served, so the usage log, its CSV and /v1/magpie/route said served = default for requests that ran Fast. servedTierAt (tier_record.go) leaves those two words empty when the reply came from CodexBase's host. It is applied once per routed try, in attempt (gateway.go, a defer, so every return path and the route's tries see it), and on the relay of Codex's own sign-in (codexUpstreamOn). OpenAI's API, where service_tier means what it says, keeps it as given: a provider at api.openai.com and Codex with an sk- key relayed to it. "priority" or "ultrafast" said by the ChatGPT backend is still kept. Display: tier_served is shown by the CSV (an empty cell), the JSON log and /v1/magpie/route (omitempty). No GUI page or TUI shows a tier (grep of internal/gui/assets and internal/tui for tier_served, tier_asked, tierServed: none), so no strings changed. docs/reference.md and docs/subsystems/gateway-routing.md say it. Tests: - TestChatGPTBackendTierUnknown (new): the backend says auto, then default (jjt's events, cut to the fields read); a routed try asked priority and one asked nothing, and Codex's own sign-in relayed, all record "" in usage and the route. - TestOpenAIAPITierKept (new): api.openai.com's "priority" and "default" kept, routed and through the sk- relay. - TestTierRecordedPerTry: its "none asked" case on the ChatGPT backend now expects "" where it expected "default". Run on mote (mote-run; the wider run at base |
||
|
|
7632e1be1d |
redact: a text sent on a route goes on it as it went, the model's late finds too (vvrfxyz on X)
vvrfxyz on X: "脱敏功能是不是会降低缓存命中率 我开了脱敏后 dsh命中率暴跌".
Cause: the local model (AstrLink Guard, on by default) is waited for
2s a request (masking's defaultWait). A tool's output it hasn't read
by then goes with the rules' masking alone (pii.Partial). On the next
turn the model has read it, finds the names in it, and the same history
text now goes with {{PERSON_…}} in it. Everything from that message on
is a new prompt to the vendor, so its prefix cache misses.
|
||
|
|
ffa07395eb |
gateway: Codex talks Responses to magpie over a WebSocket, turns after the first as a delta (#4058)
Codex names previous_response_id and sends only the new input on its WebSocket path alone; magpie answered the upgrade 426 ( |
||
|
|
442897f414 |
gateway: masking time is kept when magpie's own time is unknown
A masked request's "Masking" part on the Routing page comes from
Route.Masking, which maskingMs capped at Own, magpie's own time before
the request went out. Own is known only when magpie's client wrote the
request and a first token came back, so a request that was masked but
went through a plugin, through Claude Code for a Claude subscription,
failed, or had no first token had its masking time dropped to 0, and
the page showed nothing for it (Discord, lute: some requests show the
masking and model time and some don't). The Codex backend path never
set it at all.
maskingMs now keeps all of the masking time when Own is unknown, and
still caps it at Own when Own is known. The Codex backend path sets it
on its route and its usage record. The usage page still shows Masking
only beside a known Own, as before.
Run (mote, go1.26.8):
- TestMaskingTimeKeptWhenOwnIsUnknown (a masked request the vendor
refuses): red on the old redact_phase.go ("masking 0 ms, held
120ms"), green with it.
- TestCodexOwnSignInKeepsItsMaskingTime: red without the codex
backend lines ("route's masking 0 ms, held 120ms"), green with them.
- TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime: ok.
- go test ./internal/gateway ./internal/usage -count=1 -timeout 45m with
this and the next commit: ok (gateway 502s, usage 16s).
- go vet ./internal/gateway ./internal/usage for darwin, linux
(-tags nogui), windows: ok. gofmt -l: clean.
|
||
|
|
5dc908f764 |
gateway: a turn on Codex's own sign-in says where its time went
The Routing page's "Where the time went" (magpie, network, vendor) is
drawn from a try's TryNet, which only the routed path (gateway.go)
recorded. A turn Codex sends on its own sign-in or its API key goes
through the Codex backend path (codex_backend.go), out through the same
Go client, and its try never had one, so those requests showed no time
split while routed ones did (Discord, lute: some requests show magpie's
and the model's time and some don't).
Each Codex backend try now traces its requests (netTrace) and records
its TryNet when it ends or is handed on for an overload; a request asked
again within the try (a reset spent, a dropped large one, an item taken
out) counts as its Before. A turn asked again for an overload gets a
fresh trace, and its TTFT/FirstText are now from its own Start, as
Try.TTFT is documented, so its "First token" part isn't inflated by the
tries before it.
Run (mote, go1.26.8):
- TestCodexOwnSignInTellsWhereItsTimeWent: red on the old
codex_backend.go ("no timing for a turn on Codex's own sign-in"),
green with the change.
- go test ./internal/gateway -run 'TestCodex|TestTryTellsWhereItsTimeWent|TestTryNet|Overload': ok.
- go test ./internal/gateway -count=1 -timeout 45m at this change
(base
|
||
|
|
fb2e11e288 |
agent: a Codex sign-in OpenAI refused to refresh for good counts as none (#4308)
jjt on Discord: Codex's ChatGPT sign-in was revoked, and magpie's
models were gone from Codex until they signed in again.
Cause: Codex keeps a revoked sign-in's auth.json as it was and remembers
the permanent refresh failure in memory alone (codex-rs
login/src/auth/manager.rs). magpie read auth.json alone
(codexChatGPTKnown), counted the sign-in and wired Codex beside it
(openai_base_url, requires_openai_auth). There, Codex's /models went to
the gateway, which passed OpenAI's 401 token_revoked through, so the
picker had no magpie model; and every turn, magpie's models too, failed
at Codex 0.162.1's workspace routing discovery
(/backend-api/wham/accounts/check, 401).
Change:
- provider: codexRefresh tells a refusal Codex takes as permanent
(request_chatgpt_token_refresh: refresh_token_expired, _reused or
_invalidated, a 400 invalid_grant, or a 401 - here only a 401 that
carries an error code, read as oauth/error.rs reads it). When magpie's
own refresh of Codex's sign-in (codexTokenRenewing, from the usage read
that KeepOnAnAccountWithRoom runs) is refused that way, and the store
still holds that refresh token, codex-signin-gone.json keeps the Codex
home -> sha256 of the refused refresh token (no token stored). A
successful refresh forgets it. Writes Touch the catalog so the agents
resync; the loop's noteCodexGoneNow notices a sign-in made again
elsewhere within minutes.
- agent: codexChatGPTKnown reads such a sign-in as none
(provider.CodexSignInGone), as v0.1.2087 did for forced_login_method =
"api": magpie is Codex's provider without requires_openai_auth, the
user's auth.json stays. A record that can't be read is unknown (as
magpie last wired it). Signing in again gives another refresh token,
which the record doesn't name: Sync writes requires_openai_auth back.
- gateway: codexModels doesn't pass a revoked /models answer
(provider.SignInRevoked) through: it lists Codex's cached models and
magpie's. The desk file does the same while the live list says revoked
(CodexListRevoked). Any other refusal (token_expired, 5xx) is as before.
- docs: agent-wiring and gateway-routing.
Run:
- real codex 0.162.1 (app-server over stdio, and exec) on mote, sandbox
HOME/CODEX_HOME, fake OpenAI (chatgpt_base_url,
CODEX_REFRESH_TOKEN_URL_OVERRIDE, provider.CodexBase) answering 401
token_revoked and refresh_token_invalidated; no real network.
- Old wiring beside the dead sign-in, old gateway: model/list had no
magpie model (jjt's case). With the gateway change: fake/m1 listed,
but exec -m fake/m1 fails at workspace routing discovery (401), and
account/read errors too - why the wiring change is needed.
- Uncommitted e2e in the agent package with magpie's own written
config: Set("fake/m1") wrote it beside the sign-in; magpie's
LoginUsage("codex") then heard the refresh refused, Sync rewrote it
to model_provider = "magpie", model_catalog_json, no
requires_openai_auth. account/read: {"account":null,
"requiresOpenaiAuth":false}; model/list: fake/m1 plus Codex's
models; exec -m fake/m1 answered "hi from magpie"; auth.json byte
for byte the same.
- Red on the old code (broken by hand): without the codexChatGPTKnown
check TestCodexGoneSignInIsNoChatGPT is red; without the
noteCodexSignInGone call TestCodexSignInGoneWhenRefusedForGood is red;
with codexRefreshGone true for every failure TestCodexRefreshGoneRule
is red; TestCodexModelListRevokedSignIn and
TestCodexDesktopCatalogRevokedSignIn are red on the old gateway.
Taking out the store re-check in noteCodexSignInGone leaves the tests
green: a token Codex rotated meanwhile is already held by the hash
comparison, and the re-check only saves a needless record, log line
and resync. Not guarded on its own.
- via mote-run, at this commit rebased on origin/main
|
||
|
|
9101bb8879 |
privacy: a request masking would change can go as written to a model you picked
jessyoungyu on X: when a masking rule hits, send the request to a self-hosted model instead, so a prompt like 「百度这家公司怎么样」 gets an answer about Baidu, not about a placeholder. Settings › Privacy › Instead of masking, send to (settings redactRouteTo). It is Off by default, and nothing changes for a user who leaves it Off. It is picked in the app menu, and only models whose every route is unmasked can be chosen: the provider is set to Send requests unmasked, it is on this computer or the network, it has no account, and any fallback or group member is unmasked too (gateway.MaskRoute, the same rule as provider.SkipsRedaction). The setting is saved on its own with POST /api/settings/redact-route, which checks it with MaskRoute. The general settings save keeps the value. Decisions: - When a value would actually be masked on an agent's turn (maskHits.n > 0), serve sends the request to the chosen model unmasked. Warn-only hits don't count, and Block still answers 400. - If that model fails, the request fails. It is never masked and re-sent to the model the agent asked for, and never goes to a cloud model with the unmasked text. Falling back to a masked cloud request would answer a different question in the background. The user picked this route because masking breaks the answer. - Streaming works the same as on any route. - The route is checked again on every request. A model that is gone or no longer unmasked, or that the caller's gateway key may not use, means the request is masked as before. - Covered: agents' Messages, Chat, Responses and Gemini turns (serve, marked by serveAgent), count_tokens, Codex magpie-model turns, and Codex own-sign-in /responses (codexMaskRoute). - Not covered: magpie's own asks (ownAsk clears the mark), embeddings, audio, images and video. These stay masked. GUI: redactRouteRow lives in plugins/redact/settings.js and wraps renderRedact, so app.js is byte-for-byte unchanged and the core budget is not raised. Strings are added in zh, zh-TW, ja and de. Docs: gateway-routing.md, gui-shell.md, and site/public/docs masking (en, zh, ja). Tests: internal/gateway/mask_route_test.go (TestMaskedRequestGoesToTheModelSet: unset, set, streamed, nothing to mask, local fails, falls back to a vendor, no longer unmasked, count_tokens; TestCodexSigninTurnGoesToTheModelSet; TestMaskRouteTakesOnlyUnmaskedRoutes; TestMaskRouteOnlyForTheAgentsTurn); internal/gui/redact_route_test.go; settings_keep_test.go; internal/gui/tests/redact-route.test.cjs (every language, chromium and webkit, 1100 and 640 wide). Broken by hand, each red: - serveAgent without the agent mark; - MaskRoute taking any route (TestMaskedRequestGoesToTheModelSet, TestMaskRouteTakesOnlyUnmaskedRoutes; at the pushed head); - the codex hook removed; - count_tokens without the mark; - ownAsk not clearing it; - no key check; - no reroute in serve; - the GUI: no keep in the general save, no MaskRoute check on save, and the picker listing every model; - the plugin script left out of index.html (redact-route.test.cjs 22 of 24 red; at the pushed head). Run on mote: - at 221ede767's tree, this change on |
||
|
|
2768f04f9b |
gateway: a thread switched off a used-up Codex model compacts locally (hiwise_aigc)
hiwise_aigc on X (2115741641017565304): with Codex's allowance used up,
an existing thread switched to a magpie model failed every turn and
"还会走gpt模型", restarts or not; a new thread worked.
Cause, from codex-rs: before a turn on a model with a smaller window
(or a changed comp_hash), core/src/session/turn.rs
maybe_run_previous_model_inline_compact compacts the thread on the
PREVIOUS model (gpt-5.5) through the current provider, turn metadata
compaction.reason "model_downshift" / "comp_hash_changed", phase
pre_turn. compact_model_fallback.rs retries with the turn's model only
when the provider is_openai() (name "OpenAI"). Under the takeover
provider "magpie" there is no fallback: /v1/responses resolved bare
gpt-5.5 to the used-up codex account, codexCompact returned its 429,
and that was the turn's error, every turn. A new thread has no previous
model, so no compaction.
Fix: codexCompact, off CodexPath only, reads the compaction reason from
x-codex-turn-metadata (header, else client_metadata in the body). For
model_downshift / comp_hash_changed, a failed, errored or empty
compaction on the old model is answered with localSummary (magpie's own
magpie1 summary, no model), so the thread goes on on the model it was
switched to. The held-account check doesn't short-circuit it either.
context_limit (the thread's own model out of room) still says the
refusal, and CodexPath is left alone: Codex's "OpenAI" provider falls
back to the turn's model itself and gets a better summary there.
Prompts and base_instructions are not touched.
Run:
- TestCodexLeavingModelCompactsLocally: red on the old code (429 at
codex_leaving_model_test.go:84), green now.
- Broken by hand: without the body client_metadata fallback the
header-less case goes red; without the CodexPath scope the CodexPath
case goes red (got 200).
- Sandbox repro (sandbox HOME + CODEX_HOME, fake upstream, live ~/.codex
untouched): codex 0.162.1, takeover-like config with
remote_compaction v2 and a model catalog (gpt-5.5 400k, magpie-x
128k), a gpt-5.5 thread relabelled to provider magpie, resumed on
magpie-x: POST /v1/responses model gpt-5.5 + compaction_trigger,
reason model_downshift; a 429 failed the turn ("Error running remote
compact task: You've hit your usage limit"); answered with a
compaction item, as the gateway now does, the turn went on to
magpie-x and completed. ChatGPT.app's bundled codex has the same
model_downshift / comp_hash_changed path (strings).
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux
-tags nogui and GOOS=windows (mote).
- go test -timeout 45m -count=1 ./internal/gateway ./internal/codexsummary
on mote at this tree (parent
|
||
|
|
fc43c69e53 |
gateway: a Codex thread switched to another effort is shown and sent at it
zzzkl3994 (Discord #feedback): Codex switched from medium to xhigh
mid-session, and Routing still showed medium. Their rollout had
{"type":"configuration_update","reasoning":{"effort":"xhigh"}}.
What Codex sends, captured from the real codex 0.162.1 TUI in a sandbox
CODEX_HOME against a local Responses server (built-in openai provider
via openai_base_url, /model -> Extra high -> "s"):
- reasoning_effort_override off (the default): reasoning.effort at the
top goes xhigh; no item.
- reasoning_effort_override on: the top stays at the thread's first
(medium), and every turn carries a configuration_update after its user
message, the last one {"effort":"xhigh"}. This is the reporter's case.
magpie read only the top, so for such a thread:
- Routing's route and try showed medium (requestEffort/bodyEffort);
- a Responses vendor not OpenAI's got the items taken out (forVendor)
and was asked at medium;
- a translated request (parseResponses) was asked at medium;
- magpie's own pick (withEffort, a fixed member) set the top, which an
upstream reading the items overrode.
Now the effort of a Responses request is its last configuration_update's
when it has one (effortUpdated):
- bodyEffort/requestEffort read it, so Routing, tries and usage say xhigh;
- parseResponses takes it as the request's effort;
- forVendor puts it at the top where it takes the items out;
- withBodyEffort and withFixedEffort rewrite the last update (the top
stays, so the thread's prefix does too);
- withoutAnyReasoning drops the items with the reasoning ask.
OpenAI's API and the ChatGPT backend still get the body as Codex sent it.
No Codex prompt or base_instructions is touched.
Tests (codex_effort_change_test.go), built from the captured request:
- TestCodexEffortChangeShownAndSent: route and try at xhigh, a Responses
relay asked xhigh with no item;
- TestCodexEffortChangeReachesChatVendor: Chat vendor asked xhigh;
- TestCodexEffortChangeReaders: readers, magpie's pick, a fixed effort,
reasonless, and OpenAI/ChatGPT bodies byte for byte.
Red on the old code (fix files stashed, two stub funcs): all three fail,
route at "medium", sent medium.
Run at this head (rebased on
|
||
|
|
34b2dd9b70 |
gateway: a used-up Codex sign-in, the one account, is heard on its relayed turns and served without a restart
unsplashz on Discord: Codex beside its ChatGPT sign-in, one Codex account in magpie. When the account ran out, Codex couldn't send until it was restarted, after which its turns went through magpie. Cause. With Codex's sign-in the only account on, an own-model turn is relayed to ChatGPT as Codex sent it (codexUpstreamOn, no account). That path never kept the reply's x-codex-* / codex.rate_limits windows (heardCodexLimits) and never asked for the account to be read again on a usage_limit_reached refusal (codexMayBeUsedUp). Only turns served through magpie's accounts did. So magpie learned the account was out at the next look, one to five minutes on, and until then wrote no codex.out and left the Codex app's app-server alone, its Send greyed. A Codex started before codex.out also kept sending own-model turns to its built-in provider, each relayed to the same refusal, until it was restarted. Fix. - codexUpstreamOn: for a /responses relay on magpie's ChatGPT account (codexRelayedAccount: the account signed with, or Codex's sign-in when the request's chatgpt-account-id names it), the reply's windows are heard, and a quota refusal calls codexMayBeUsedUp. codexServed now uses the same lookup. - codexAccounts: while the sign-in is known out (CodexUsedUpKnown, the cached reading only) and the request signs as it, an own-model turn goes through routing as codex/<model>, as a restarted Codex's does. Another sign-in (a Codex in WSL) still goes as it came. Run: - go test ./internal/gateway -run 'TestCodexUsedUp|TestCodexRelayedWindowsHeard|TestCodexHeldSignInServedWithoutRestart|TestCodexOwnModel|TestCodexPaused|OneAccount' (mote): ok. - GOOS=darwin/linux/windows go vet ./internal/gateway (mote): clean. gofmt -l: clean. - go test ./... -timeout 45m -count=1 at 25fbbd03e on the Linux VM (wsl-run, mote had another session's full suite): 73 ok, internal/gateway ok (738s). Reds: ., internal/cli and internal/gui don't build there (no gtk4/webkitgtk-6.0 dev packages); internal/agent TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir, TestZedAppPath, all #4033 (and #3548). The first three are red the same on origin/main |
||
|
|
0e2739743b |
codex: a reset set to go when the week runs out is spent before the credits
tongzhenbao on X: a Codex Pro account with "when its week runs out" on,
its week at 0% left, one reset held until 11-06 (after the week's own
reset on 11-03) and Use credits on. Overnight ~10k credits went and the
reset stayed; the card said "not auto-used" beside the switch on.
Cause: the week's auto-use ran only on a vendor refusal. autoReset in
routing needs a 429 usage_limit_reached on the last candidate, and the
relay's autoResetSignedIn the same on its 429. An account let spend its
credits is never refused for its week: ChatGPT answers on the credits,
and routing never benches it (full() and onCredits). So the week's reset
could only ever be spent with credits off.
Decision (product call delegated): a reset is free, credits cost money,
so a reset the user set to go when the week runs out goes before any
credits. resetBeforeCredits runs before a try is sent to a Codex account
on its credits whose last reading has its week used up, with the week's
switch on; AutoUseCodexReset reads the week again and keeps one a week
at most, so a second time in the same week goes on the credits. Hooked
in the routing loop and in codexUpstreamOn (the relay, signed-in or an
account). With no reset held, or the week's switch off, nothing changes.
The card's summary: with only the week's switch on it now says "auto-used
when the week runs out" (zh 周额度用完时自动使用), not "not auto-used",
with its title in all five languages. CLI help and auto-reset messages
say "or before its credits are spent". gateway-routing.md names it.
Siblings: the expiring switch already spends regardless of credits
(usedUp ignores them); the credits-off path (planned.held) is unchanged.
Run (mote, through mote-run, at this tree):
- go test ./internal/gateway -run 'TestCodexResetBeforeCredits|TestCodexAutoReset|TestCodexCredits|TestCodexNoCredits': ok
- broken by hand: gateway.go and codex_backend.go at origin/main:
TestCodexResetBeforeCredits/relayed and /routed red (200, spent ""),
the two negative cases green
- node --test codex-auto-reset, i18n-keys, codex-auto-reset-settings,
codex-resets-used, panel-options-fold, quota-curve: 96/96 (chromium +
webkit, en/zh/zh-TW/ja/de); codex-auto-reset red with origin/main's
app.js ("· not auto-used")
- full suite, before the rebase onto
|
||
|
|
b4267de595 |
gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:
- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
the group as routed, Live) hands its members to planLevel
(planFallbackGroup): the group's own routing, its sink and asides, and
its pause rules (serve passes provider.PausedOut for the agent's folder).
Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
a model named earlier, or another fallback group's member is left out
where it comes second. Groups have no fallbacks of their own and a
member's fallbacks are not followed, so nothing leads back. A group that
is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
provider.FallbackModels: redaction (unredactedRoute: an unmasked
provider with a fallback group holding a remote model is masked),
careful accounts (carefulOf), native compaction, Codex's own turns
(codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
moves from provider.Resolve to ResolveRoute, as the gateway reads
fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
groups); its usage and error now say so. Pinned by
TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
(providers.gateway.groups) beside the models as chips with the Routing
fan and a muted "routing group" tell; a picked group's row has the same
fan and tell, and a gone one says "No routing group {id} now; it is
skipped". A filter matches a group's name, id and its members'
providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.
Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.
Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
(TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
…) killed at their 30s bars while four other sessions' GUI suites held
mote at load 70-110. Run alone, all ten
pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
red at base
|
||
|
|
25bf394a72 |
gateway: a resumed Codex subagent goes back on the model it was spawned on
HoGee_xxl on X: a Codex subagent brought back with resume_agent ran on
the lead's model, not the one the lead spawned it on.
Codex's multi-agent V1 (the one magpie's own models ask for) builds the
resumed subagent's config from the lead's current turn:
codex-rs core/src/agent/child_config.rs build_agent_resume_config ->
build_agent_shared_config sets config.model to turn.model_info().slug,
and core/src/agent/control/spawn.rs resume_single_agent_from_rollout
starts the thread on that config without reading back the thread's
stored model. Neither the spawn_agent model nor [agents]
default_subagent_model is asked again. V2's ensure_v2_agent_loaded does
put a thread back on its stored model, so this follows Codex's own rule.
The gateway now notes the model each Codex subagent thread (thread_id in
x-codex-turn-metadata / client_metadata; session_id only on a Codex old
enough not to share it) first asked for, and puts a later request of
that thread asking for another back on it. Kept in codex-subagents.json
beside providers.json (0600, temp file and rename, the 512 latest, 30
days), so a resume after a restart is known. A model set for every
subagent (codexSubagentPick) still wins. No prompt or base_instructions
is touched.
Run (mote-run): go test ./internal/gateway -run 'TestCodexResumed|
TestCodexSubagentThreadOf|TestCodexSubagent|TestCodexFollow|
SessionMetadata|TestCodexSide' -count=1: ok.
Broken by hand: skipping the restore in codex_backend.go turns
TestCodexResumedSubagentKeepsItsSpawnModel red ("worker-1 asking gpt-5.5
went on gpt-5.5, want gpt-6-astra"); skipping the save turns its
after-restart step red.
Not tried: a real Codex resume_agent run against a real ChatGPT account.
|