Commit Graph
6 Commits
Author SHA1 Message Date
yetone 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
dd809ea60 (v0.1.2652, 11-01). Before it, + and / were already turned into
"_" since d75ea9282 (10-10).

The id doesn't go back unchanged, because Copilot doesn't always take its
own long ids: isnine's 420-character ones were refused "string too long …
maximum length 64" (#4525). Leaving the id out was 200 in both reports. So:

- a message (typed or not) or function_call whose id is over 64 goes
  without its id (idOptional). OpenAI's schema makes both optional, and
  the call keeps its call_id, so its output still pairs with it.
- any other kind keeps an id, bound under the prefix its type says
  (rs_ for reasoning, openaiItemPrefix's ctc_/tsc_). Only a kind with no
  known prefix takes one from its id, and a bare digest is left only for an
  unknown kind whose id has no prefix.

Every route takes the same function: the relay's prepare (streaming,
non-streaming, compaction through serve, and Responses over a WebSocket,
whose frames are served as the POST), the ask-again after a refusal, the
Codex relay and the ChatGPT backend. OpenAI, Azure and the ChatGPT backend
issue ids of 64 at most, so an id over that is always another vendor's.
Those upstreams also take a message or call without an id, and they check
an id's kind prefix too ("Expected an ID that begins with 'tsc'"), so the
typed prefix fits them as well.

Tests:
- TestCopilotTakesItsOwnOpaqueCallID: a fake Copilot that takes its own
  ids or none, and answers any other id that is over 64 or lacks its kind's
  prefix with its empty 400, word for word. A 452-character Base64 call id
  goes through streaming and non-streaming, paired by call_id.
- TestPlainItemIDsBindsOtherKinds: another vendor's overlong reasoning,
  tool_search_call, custom_tool_call and unknown-kind ids are still bound to
  64 (rs_, tsc_, ctc_, own prefix), and foreign-character reasoning is still
  left out.
- TestPlainItemIDsBoundItemIDs is changed to match: the overlong message
  id is left out, and the "two ids alike go to two" check is on
  custom_tool_call. The parity reference (wasPlainItemIDs) follows the same
  rule.

Run (mote, -tags nogui): -run 'ItemID|CodexRewrites|OpaqueCallID|
BindsOtherKinds' ./internal/gateway ok, 13 tests listed as PASS. Broken by
hand (old plainItemIDs/boundItemID, new tests kept): both new tests red,
the call test with Copilot's empty 400 verbatim. Whole internal/gateway
package: ok (791s). go vet darwin/linux/windows on internal/gateway:
clean. gofmt -l: nothing.

Not tried: a real Copilot account (both reporters' by-hand results are
the evidence that a left-out id is taken). fc_+hash was not tried live.
A Copilot reasoning item whose own id has + or / is still left out as
another vendor's (as before this change). Its seal goes with it, and the
turn still goes through.
2026-11-06 00:07:18 +08:00
vincent 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 3c2dceb34),
on mote (macOS arm64, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/catalog/...
  ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...:
  catalog, plugin and davsync ok; gateway red on one test only,
  TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's
  Codex identity reaches it in a full package run). It passes run
  alone at this tree, 3 of 3.
- go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: ok. gofmt -l on every tracked .go file: clean.
- The hand breaks above ran on this stack before its rebase onto
  3c2dceb34. That commit changed member.go only, nothing these tests
  reach.
Not tried: the GUI suite, since no GUI file changed. Windows and Linux
test runs (the Claude bridge tests use a shell fake and skip on
Windows). No real vendor, Claude Code or network was used; every
case runs against fakes.
2026-11-03 07:43:18 +08:00
ggbdpq 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)
2026-11-02 05:38:10 +08:00
ggbdpq 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 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: developerItemsAsSystem made to return the body
unchanged: TestCodexCompactDeveloperAsSystemOnAVendorRelay goes red with
the fake vendor's 400 "developer is not one of"; restored, green.
Not tried: the reporter's vendor relay itself; the refusal is the fake
vendor's copy of its words.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 06:38:00 +08:00
yetone 2a19245cec gateway: Codex's output token replay goes to OpenAI only (Copilot refused it)
echo_ts on Discord (#feedback): a Codex conversation begun on gpt-6-astra
and carried on on a Copilot model failed with "Copilot: Invalid value:
'output.encrypted_content'. Supported values are: ...".

Cause: Codex with output token replay on (codex-rs core/src/client.rs)
adds "output.encrypted_content" to include, and keeps each message's and
call's sealed copy (encrypted_content) in its history, only for a
provider named "OpenAI". Signed in, Codex reaches magpie as that
provider, so a magpie model got both as they came: the passthrough to
Copilot's /responses (forVendor) and the rebuilt request (buildResponses)
both kept the include, and Copilot refuses it.

Now magpie does what Codex does under any other provider name
(!is_openai): forVendor drops output.encrypted_content from include and
encrypted_content from every input item but reasoning and compactions
(ResponseItem::clear_encrypted_content keeps those). buildResponses asks
for it only of api.openai.com and chatgpt.com. OpenAI's API and the
ChatGPT backend get the request as before. Astra's sealed reasoning
still goes along; one Copilot can't read is taken out once refused, as
before (foreignReasoning).

Tests: TestCodexOutputReplayStaysWithOpenAI (the fake refuses with the
reporter's literal error; signed-in and /v1/responses routes) and
TestResponsesOutputReplayOnlyToOpenAI. The rewrite equivalence test's
reference copy (wasForVendor) gets the same rule, with new marks.

Run: go test ./internal/gateway -count=1 -timeout 45m: every test ok but TestHandedOverGatewayFinishesItsStream
("request 0 during the handover: ... EOF"), which this change doesn't
reach; it passes 5 of 5 alone (-count=5) and is open as #3568.
gofmt -l clean; go vet, GOOS=windows and GOOS=linux go vet of
internal/gateway clean.
Broken by hand: with codex_backend.go and responses.go as on main, both
new tests are red (400 with the reporter's error; include kept for
api.githubcopilot.com, relay.example and api.x.ai).
Not tried: a real Codex with output token replay against a real Copilot
account, nor Copilot's answer to a message's encrypted_content alone
(left out because Codex leaves it out for any provider not OpenAI's).
2026-10-27 23:38:47 +08:00
yetone 58cfca2f77 gateway: a Codex turn's rewrites look at its items in place and decode it only when one has something to change (#1532, #2354)
A long Codex session grew slower each turn through magpie because every
request went through up to eight rewrites (callItemIDs, plainItemIDs,
boundCallIDs, codexInputAs, forVendor, withoutBareReasoning,
withoutReasoningText, withModel), and each one json.Unmarshal'ed the
whole conversation into maps, even though on most turns none of them had
anything to change. When one did change something, encoding/json
re-scanned every raw item one byte per call to write the body back. In
the live heap, withModel's json.Marshal held 28.8 MB, and checkValid and
stateInString were ~25% of CPU.

- Before decoding anything, each rewrite now asks whether any input item
  is one it changes (anyInputItem, over longBody's remembered split). It
  reads the item's members where they lie, matching keys as the old
  decode did: exact and last-wins for map reads, EqualFold for struct
  reads (reasoningOf). An escaped key, or a null in a field, falls back
  to decodeJSON. The change path is still the old code.
- forVendor and withModel split the body with rawObject/rawArray. When a
  rewrite writes the body back, marshalRaw is used (marshalPlain without
  HTML escaping, marshalJSON with it). It copies each raw value with its
  strings whole, into one buffer sized up front, and its bytes are
  encoding/json's own. Where encoding/json would refuse a value, the call
  falls back to encoding/json and gets its error.
- withModel now passes a body of null through unchanged. It used to panic
  writing into a nil map.

Measured with a sandbox gateway and a fake upstream. The bodies were
shaped from local Codex rollouts and never leave the machine. The machine
was at load ~160-180, so wall times are noisy; the CPU profiles are the
steadier number.
  5 MB body, CPU per mode (17 requests, pprof):
    relay    4.36s -> 1.38s  (~256 -> ~81 ms a request)
    accounts 10.29s -> 3.78s (~605 -> ~222 ms)
    magpie   7.00s -> 3.40s  (~412 -> ~200 ms)
  wall time to upstream, medians before -> after:
    relay    100k 8.1 -> 7.2ms, 1m 66.7 -> 47.9ms, 5m 1069 -> 280-661ms
    accounts 100k 32.3 -> 17.3ms, 1m 1016 -> 373ms, 5m 4852 -> 2118-2567ms
    magpie   100k 13.3 -> 10.1ms, 1m 345 -> 139ms, 5m 2713 -> 960-1805ms
  The remaining cost at 5 MB is parse/promptOf/codexBody decoding the
  body for their own needs (decodeJSON, longBody), not these rewrites.
  SSE: the relay flushes each read and the masking writer passes Flush
  on; TTFB stayed within ~1-10ms of to-upstream before and after.

Tests:
- TestCodexRewritesAsBefore compares each rewrite's output byte for byte
  against its old code, which is kept in the test. It covers marked items
  (bad ids, magpie compactions, triggers, reasoning with text or nothing
  sealed, configuration_update, Codex metadata), duplicate and escaped
  keys, non-object items, an input that is null or an object, and 300
  random mixes.
- FuzzCodexRewritesAsBefore ran 150s: 22,796 execs, PASS.
- TestMarshalRawIsEncodingJSON and FuzzMarshalRaw (90s, 46,537 execs,
  PASS) check marshalRaw against encoding/json, with and without HTML
  escaping.
- Broken by hand to see the new tests fail:
  - With anyInputItem always true, TestCodexRewritesLeaveTurnUndecoded
    went red: "callItemIDs: 11086 allocations for a turn it leaves as it
    came (243 KB)", and every rewrite, forVendor 9172.
  - With marshalPlain's marshalRaw path off, TestMarshalRawAllocatesOnce
    went red: "marshalPlain of 420 items: 4 allocations".
- gofmt -l and go vet -tags nogui ./internal/gateway are clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./... are clean.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m:
  ok  github.com/yetone/magpie/internal/gateway 2579.125s
2026-10-20 20:23:52 +08:00