gateway: a relayed Responses item keeps the id it was added with, so Codex on Copilot shows a message once (echo_ts on Discord)

echo_ts (v0.1.1293, Codex desktop, a GPT model on GitHub Copilot): each
commentary paragraph was shown twice; fine around v0.1.1280.

Cause: since ec7f47432 (v0.1.1287) a Codex turn on Copilot offering
web_search is relayed, not translated. Copilot's /responses gives an item
a new id in every event: output_item.added, each delta, output_item.done
and response.completed's output all differ (checked 2026-10-19 on the
owner's account, gpt-5.5 with web_search, in a sandbox HOME). Codex starts
an item by the added's id and ends one by the done's, so the streamed
message and the finished one were two messages. Translated, magpie's
encoder had given each item one id of its own, so it didn't show before.

Fix: idTidy (itemids.go), in passthrough before phaseTidy for every
relayed Responses stream: each later event's item_id / item.id, and
response.completed/incomplete/failed's output[i].id, take the id the
item was added with. An upstream whose ids agree goes through byte for
byte. docs/subsystems/gateway-routing.md says so.

Tests:
- TestCopilotItemKeepsItsID: a real Copilot reply (testdata, encrypted
  parts cut short) relayed through the handler from a fake Copilot
  (copilotSol now takes a reply); each output item goes by one id.
- TestItemIDsThatAgreeGoAsTheyCame: OpenAI-shaped ids, fed in 7-byte
  pieces, come out unchanged.
Broken by hand (idTidy off in passthrough): TestCopilotItemKeepsItsID
FAIL "item 0 went by 3 ids", items 1-3 by 6, 8, 5. Restored: ok.

Real use: built magpie serve in a sandbox HOME (port 3478, only the
Copilot sign-in copied), the real codex-cli 0.162.1 exec --json with
web_search on copilot/gpt-5.5:
- before: web_search item.started and item.completed under different ids;
- after: same id for each, and the follow-up requests carrying the kept
  ids back to Copilot were answered. A raw stream gave one id per item.
Not tried in the Codex desktop app itself.

Sibling found, not changed: on the translated path a reasoning item with
a non-rs_ id and a summary reaches the client twice (filed #2974; Copilot
gave summary [] in every capture).

Run at b9d1cd36f plus this change: gofmt -l clean; go vet ./... for
darwin, linux (-tags nogui) and windows ok; go test -timeout 45m ./...:
64 packages ok (internal/gateway 2023s), exit 0.
This commit is contained in:
yetone
2026-10-20 00:33:40 +08:00
parent 2c3c903974
commit d155ab1619
6 changed files with 318 additions and 1 deletions
+1
View File
@@ -174,6 +174,7 @@ recorded as a prediction failure (`noPrediction`).
- A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`.
- A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (`customToolRefusal` in [`custom_tool.go`](../../internal/gateway/custom_tool.go): DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656) ends the relay: `passthrough` marks the model (`customToolRefused`) and returns not done, and `attempt` translates the request on the same API (`ownAPI`), where each custom tool is offered as a function taking its `input` and a call comes back as the `custom_tool_call` Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (`keepsCompaction`) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (`shapeRefused`): the next member is asked. `TestCustomToolTranslatedWhereRefused`, `TestCustomToolRefusalInGroup`, `TestCustomToolRefusalWordings`.
- A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`.
- A relayed Responses stream gives each output item the one id its `response.output_item.added` gave it, in every event after that carries an `item_id` or an `item`, and in the `output` of `response.completed`, `response.incomplete` or `response.failed` (`idTidy` in [`itemids.go`](../../internal/gateway/itemids.go), applied in `passthrough` before `phaseTidy`). GitHub Copilot's `/responses` gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, `TestCopilotItemKeepsItsID`). An upstream whose ids agree goes through byte for byte (`TestItemIDsThatAgreeGoAsTheyCame`); a translated reply's ids are magpie's own.
- A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale.
- A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`).
+7
View File
@@ -25,6 +25,7 @@ import (
type copilotUp struct {
mu sync.Mutex
bodies []map[string]any
reply string // a stream to answer with, in place of the made one
}
func (c *copilotUp) last(t *testing.T) map[string]any {
@@ -59,7 +60,13 @@ func copilotSol(t *testing.T) *copilotUp {
json.Unmarshal(b, &body)
c.mu.Lock()
c.bodies = append(c.bodies, body)
reply := c.reply
c.mu.Unlock()
if reply != "" {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, reply)
return
}
message := "Find the release date of Codex 0.159 and report it."
if strings.Contains(string(b), `"encrypted"`) {
message = "gAAAAAsealed=="
+20 -1
View File
@@ -4651,8 +4651,17 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if proto == provider.Responses {
phases = &phaseTidy{sse: sse}
}
// out is what a filter let through, through phases
// each item keeps the id it was added with (itemids.go): Copilot gives
// it another in every event
var ids *idTidy
if proto == provider.Responses && sse {
ids = &idTidy{}
}
// out is what a filter let through, through ids and phases
out := func(b []byte) []byte {
if ids != nil {
b = ids.write(b)
}
if phases != nil {
return phases.write(b)
}
@@ -4707,6 +4716,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if sigs != nil {
out = sigs.write(out)
}
if ids != nil {
out = ids.write(out)
}
if phases != nil {
out = phases.write(out)
}
@@ -4769,6 +4781,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if sigs != nil {
write(out(sigs.flush()))
}
if ids != nil {
b := ids.flush()
if phases != nil {
b = phases.write(b)
}
write(b)
}
if phases != nil {
write(phases.flush())
}
+123
View File
@@ -0,0 +1,123 @@
package gateway
import (
"github.com/tidwall/gjson"
)
// idTidy keeps each output item of a relayed Responses stream under the
// one id its output_item.added gave it. GitHub Copilot's /responses gives
// an item a new id in every event: the added, each delta, the done and
// response.completed's output each carry another (2026-10-19, a real
// account, gpt-5.5 with web_search). Codex starts an item by the added's
// id and finishes one by the done's, so with two ids a message was shown
// twice, once as it streamed and once finished, and a web search stayed
// started (echo_ts on Discord, once ec7f47432 relayed Codex on Copilot
// instead of translating it). An upstream whose ids already agree goes
// through as it came.
type idTidy struct {
buf []byte
ids map[int64]idOf // output_index → the item's id and type, as added
}
type idOf struct{ id, typ string }
func (t *idTidy) write(b []byte) []byte {
t.buf = append(t.buf, b...)
var out []byte
for {
n := eventEnd(t.buf)
if n < 0 {
return out
}
out = append(out, t.event(t.buf[:n])...)
t.buf = t.buf[n:]
}
}
func (t *idTidy) flush() []byte {
b := t.buf
t.buf = nil
return b
}
func (t *idTidy) event(ev []byte) []byte {
data := eventData(ev)
if len(data) == 0 || !gjson.ValidBytes(data) {
return append([]byte(nil), ev...)
}
e := gjson.ParseBytes(data)
at := e.Get("output_index")
switch typ := e.Get("type").String(); {
case typ == "response.output_item.added":
if id := e.Get("item.id").String(); id != "" && at.Exists() {
if t.ids == nil {
t.ids = map[int64]idOf{}
}
t.ids[at.Int()] = idOf{id, e.Get("item.type").String()}
}
return append([]byte(nil), ev...)
case typ == "response.completed" || typ == "response.incomplete" || typ == "response.failed":
return t.ended(ev, data, e)
case !at.Exists():
return append([]byte(nil), ev...)
}
was, ok := t.ids[at.Int()]
if !ok {
return append([]byte(nil), ev...)
}
itemID, itemIn := e.Get("item_id"), e.Get("item.id")
if (!itemID.Exists() || itemID.String() == was.id) && (!itemIn.Exists() || itemIn.String() == was.id) {
return append([]byte(nil), ev...)
}
var m map[string]any
if decodeNumbers(data, &m) != nil {
return append([]byte(nil), ev...)
}
if itemID.Exists() {
m["item_id"] = was.id
}
if it, _ := m["item"].(map[string]any); it != nil && itemIn.Exists() && (was.typ == "" || it["type"] == was.typ) {
it["id"] = was.id
}
nb, err := marshalPlain(m)
if err != nil {
return append([]byte(nil), ev...)
}
return withData(ev, nb)
}
// ended is the reply's last event, each item of its output under the id
// it was added with.
func (t *idTidy) ended(ev, data []byte, e gjson.Result) []byte {
differs := false
for i, it := range e.Get("response.output").Array() {
if was, ok := t.ids[int64(i)]; ok && it.Get("id").Exists() && it.Get("id").String() != was.id && (was.typ == "" || it.Get("type").String() == was.typ) {
differs = true
break
}
}
if !differs {
return append([]byte(nil), ev...)
}
var m map[string]any
if decodeNumbers(data, &m) != nil {
return append([]byte(nil), ev...)
}
res, _ := m["response"].(map[string]any)
out, _ := res["output"].([]any)
for i, v := range out {
it, _ := v.(map[string]any)
was, ok := t.ids[int64(i)]
if it == nil || !ok {
continue
}
if _, has := it["id"]; has && (was.typ == "" || it["type"] == was.typ) {
it["id"] = was.id
}
}
nb, err := marshalPlain(m)
if err != nil {
return append([]byte(nil), ev...)
}
return withData(ev, nb)
}
+104
View File
@@ -0,0 +1,104 @@
package gateway
import (
"os"
"strings"
"testing"
"github.com/tidwall/gjson"
)
// Copilot's /responses gives an item a new id in every event (the fixture
// is a real reply, gpt-5.5 offered web_search and a function, its
// encrypted parts cut short). Relayed to Codex, each item keeps the one
// id it was added with, in its events, its done and response.completed,
// so Codex shows the commentary once and ends the search it started
// (echo_ts on Discord).
func TestCopilotItemKeepsItsID(t *testing.T) {
reply, err := os.ReadFile("testdata/copilot_rotating_ids.sse")
if err != nil {
t.Fatal(err)
}
c := copilotSol(t)
c.mu.Lock()
c.reply = string(reply)
c.mu.Unlock()
code, out := postTo(t, New(), "/v1/responses", `{"model":"copilot/gpt-6-luna","stream":true,"probe":"as sent",
"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Search for the latest Go release, then run go version."}]}],
"tools":[{"type":"function","name":"exec_command","description":"Runs a command","strict":false,"parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}},{"type":"web_search"}]}`)
if code != 200 {
t.Fatalf("%d %s", code, out)
}
if c.last(t)["probe"] != "as sent" {
t.Fatal("not relayed: the reply under test is Copilot's own")
}
ids := map[int64]map[string]bool{} // output_index → every id it was given
note := func(at int64, id string) {
if ids[at] == nil {
ids[at] = map[string]bool{}
}
ids[at][id] = true
}
texts := map[string]int{}
completed := false
for _, line := range strings.Split(out, "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
e := gjson.Parse(data)
switch e.Get("type").String() {
case "response.completed":
completed = true
for i, it := range e.Get("response.output").Array() {
note(int64(i), it.Get("id").String())
}
continue
case "response.output_item.done":
if it := e.Get("item"); it.Get("type").String() == "message" {
texts[it.Get("content.0.text").String()]++
}
}
at := e.Get("output_index")
if !at.Exists() {
continue
}
if id := e.Get("item.id"); id.Exists() {
note(at.Int(), id.String())
}
if id := e.Get("item_id"); id.Exists() {
note(at.Int(), id.String())
}
}
if !completed || len(ids) != 4 {
t.Fatalf("completed %v, items %d: %s", completed, len(ids), out)
}
for at, seen := range ids {
if len(seen) != 1 {
t.Errorf("item %d went by %d ids", at, len(seen))
}
}
if len(texts) != 1 {
t.Errorf("messages done: %v", texts)
}
}
// An upstream whose ids agree, as OpenAI's do, goes through byte for byte.
func TestItemIDsThatAgreeGoAsTheyCame(t *testing.T) {
stream := sse(
`data: {"type":"response.created","response":{"id":"r1"}}`,
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`,
`data: {"type":"response.output_text.delta","output_index":0,"item_id":"msg_1","content_index":0,"delta":"a <b> & c"}`,
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"a <b> & c"}]}}`,
`data: {"type":"response.completed","response":{"id":"r1","output":[{"type":"message","id":"msg_1"}],"usage":{"input_tokens":1.0}}}`,
)
var got []byte
tidy := &idTidy{}
for i := 0; i < len(stream); i += 7 {
got = append(got, tidy.write([]byte(stream[i:min(i+7, len(stream))]))...)
}
got = append(got, tidy.flush()...)
if string(got) != stream {
t.Errorf("changed:\n%s\nwant:\n%s", got, stream)
}
}
File diff suppressed because one or more lines are too long