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 125fd93ec / v0.1.3060):
with native web search on, the turn after a search failed with Copilot's
empty 400 {"error":{"message":"","code":"invalid_request_body"}}. Copilot
gives a web_search_call an id of ~450 characters of Base64 with no ws_ at
the front. plainItemIDs left out only a message's or function_call's
overlong id and bound the rest with boundItemID, which knew a kind prefix
for reasoning, tool_search_call and custom_tool_call only. So the search
call went as a bare 64-hex digest, the shape Copilot refuses (#5266). The
bare digest dates from dd809ea60 (v0.1.2652, #4525/#4527).

The fix covers every kind of input item, not only this one. Which kinds
need an id comes from OpenAI's own SDK, openai-go v3.42.0's
ResponseInputItemUnionParam, where each kind's id is either param.Opt or
required:

- id optional, so an overlong one is left out (idOptional): message
  (typed or not), function_call(_output), custom_tool_call(_output),
  tool_search_call/_output, computer_call_output, shell_call(_output),
  apply_patch_call(_output), mcp_approval_response, additional_tools,
  compaction. Each call and output keeps its call_id, which pairs them.
  Leaving the id out is the case both reporters saw Copilot answer 200.
- id required, so an overlong one is bound under the prefix OpenAI gives
  that kind (itemKindPrefix): reasoning rs_, web_search_call ws_,
  file_search_call fs_, computer_call cu_, image_generation_call ig_,
  code_interpreter_call ci_, mcp_call mcp_, mcp_list_tools mcpl_,
  mcp_approval_request mcpr_. A message bound as msg_+hash was 200 on
  Copilot (isnine, #4525).
- Kinds left as before, keeping their id's own prefix or else a bare
  digest: local_shell_call(_output), item_reference and
  program/program_output. Codex doesn't send these and Copilot isn't known
  to make them. An item_reference's id names a stored item, so hashing it
  can't keep it working anyway.

The 64-character bound (#4525/#4527) stays the same for every kind. An id
of 64 or fewer stays as it was, other characters as "_" (d75ea9282).
custom_tool_call and tool_search_call used to be bound as ctc_/tsc_ and are
now left out. Their schema makes the id optional, and callItemIDs still
re-prefixes a fitting fc_ id.

Tests (internal/gateway/item_ids_test.go):
- TestCopilotTakesItsOwnOpaqueSearchCallID: the reporter's shape, a
  452-character Base64 id with + and / and no prefix on a web_search_call
  between two turns, with tools [web_search], streamed and not, against
  the fake Copilot (opaqueCopilot, which now also checks ws_ on a search
  call). The fake answers the empty 400 word for word.
- TestPlainItemIDsBindsOtherKinds now lists every kind above, each with
  the prefix it gets or "without", and checks that every call kind keeps
  its call_id.
- TestPlainItemIDsBoundItemIDs: the "two ids that begin alike go to two"
  check moved from custom_tool_call to web_search_call (ws_).
- The fake Copilot's setup moved into onOpaqueCopilot, which both Copilot
  tests use.

Run (mote, -tags nogui): -run 'ItemID|CodexRewrites|OpaqueCallID|
OpaqueSearchCallID|BindsOtherKinds' ./internal/gateway: ok, 14 PASS
(including the CodexRewritesAsBefore parity test and its fuzz seed).
Broken by hand (codex_backend.go at origin/main, new tests kept): all
three red. The search-call test failed with Copilot's empty 400 verbatim
("stream true: 400 … invalid_request_body"), BoundItemIDs got msg_ for the
search calls, and BindsOtherKinds got the old ids.
Whole internal/gateway package (go test -tags nogui -timeout 45m): ok (700s).
go vet -tags nogui ./internal/gateway for GOOS darwin, linux and windows:
clean. gofmt -l: nothing.

Not tried: a real Copilot account; this session has none it can use
safely. ws_+hash on Copilot has not been tried live. The evidence is
msg_+hash 200 and bare digest 400 for a message (#4525) and the same 400
in echo_ts's report. The other required kinds' prefixes come from OpenAI's
documented id shapes, and none of them was sent to OpenAI or Copilot.
This commit is contained in:
yetone
2026-11-06 01:13:42 +08:00
parent 1d704f8190
commit 1100ed6494
2 changed files with 169 additions and 43 deletions
+41 -8
View File
@@ -3095,8 +3095,8 @@ const itemIDCap = 64
// boundItemID is id, of at most itemIDCap characters, as an upstream that
// checks item ids takes it: one longer goes as its kind's prefix and the
// sha256 of the whole of it, cut to fit. The kind comes from typ ("rs_" for
// reasoning, openaiItemPrefix's for a call), and only an item of another
// sha256 of the whole of it, cut to fit. The kind comes from typ
// (itemKindPrefix, openaiItemPrefix's for a call), and only an item of another
// kind takes a prefix from its id: Copilot's own ids can be opaque, + and
// / in them and no prefix at the front, and a bare digest passed the
// length and the characters and still had the whole request turned away
@@ -3107,8 +3107,8 @@ func boundItemID(id, typ string) string {
sum := sha256.Sum256([]byte(id))
digest := hex.EncodeToString(sum[:])
prefix := openaiItemPrefix[typ]
if typ == "reasoning" {
prefix = "rs_"
if prefix == "" {
prefix = itemKindPrefix[typ]
}
if prefix == "" {
if i := strings.IndexByte(id, '_'); i > 0 && i <= 4 && safeID([]byte(id[:i])) {
@@ -3119,13 +3119,46 @@ func boundItemID(id, typ string) string {
}
// idOptional are the kinds of input item whose id OpenAI's /responses
// takes left out ("" is a message given with no type). One of these with an
// takes left out ("" is a message given with no type), as OpenAI's own SDK
// has them (openai-go v3.42.0's ResponseInputItemUnionParam: the id is
// param.Opt on each of these, required on the rest). One of these with an
// id too long goes without it, which every upstream that checks ids takes:
// Copilot answered a message's and a call's overlong id left out with 200,
// and the same id as a bare digest with an empty 400 "invalid_request_body"
// (isnine on #4525, echo_ts after Codex's compaction). A call keeps its
// call_id, which its output names it by.
var idOptional = map[string]bool{"": true, "message": true, "function_call": true}
// (isnine on #4525, echo_ts after Codex's compaction). A call and its
// output keep their call_id, which pairs them.
var idOptional = map[string]bool{
"": true, "message": true,
"function_call": true, "function_call_output": true,
"custom_tool_call": true, "custom_tool_call_output": true,
"tool_search_call": true, "tool_search_output": true,
"computer_call_output": true,
"shell_call": true, "shell_call_output": true,
"apply_patch_call": true, "apply_patch_call_output": true,
"mcp_approval_response": true,
"additional_tools": true,
"compaction": true,
}
// itemKindPrefix is the prefix OpenAI gives the id of each kind of input
// item that can't go without one (openai-go's id "required"), which
// boundItemID binds an overlong id under. Copilot hands these out opaque
// too: a web_search_call's id ~450 characters of Base64 with no ws_ at the
// front, which as a bare digest had the whole request turned away with the
// same empty 400 "invalid_request_body" (echo_ts, native web search on
// Copilot). A kind not here (local_shell_call, item_reference, program)
// keeps the prefix its own id has.
var itemKindPrefix = map[string]string{
"reasoning": "rs_",
"web_search_call": "ws_",
"file_search_call": "fs_",
"computer_call": "cu_",
"image_generation_call": "ig_",
"code_interpreter_call": "ci_",
"mcp_call": "mcp_",
"mcp_list_tools": "mcpl_",
"mcp_approval_request": "mcpr_",
}
// plainItemIDs is a Responses request whose input items' ids are of
// [A-Za-z0-9_-] only and of itemIDCap characters at most, as OpenAI takes
+128 -35
View File
@@ -385,8 +385,8 @@ func TestPlainItemIDsBoundItemIDs(t *testing.T) {
{"type":"message","role":"assistant","id":"` + long + `","status":"completed","content":[{"type":"output_text","text":"OK"}]},
{"type":"reasoning","id":"` + rs + `","summary":[],"encrypted_content":"gAAAA"},
{"type":"reasoning","id":"` + museReasoningID + `","summary":[],"encrypted_content":"muse-sealed"},
{"type":"custom_tool_call","id":"` + like + `","call_id":"call_1","name":"apply_patch","input":"x"},
{"type":"custom_tool_call","id":"` + other + `","call_id":"call_2","name":"apply_patch","input":"y"}]}`)
{"type":"web_search_call","id":"` + like + `","status":"completed","action":{"type":"search","query":"a"}},
{"type":"web_search_call","id":"` + other + `","status":"completed","action":{"type":"search","query":"b"}}]}`)
got := plainItemIDs(body)
var q struct {
Input []map[string]any `json:"input"`
@@ -410,7 +410,7 @@ func TestPlainItemIDsBoundItemIDs(t *testing.T) {
bound = id
}
}
if got := strings.Join(types, ","); got != "message,message,reasoning,custom_tool_call,custom_tool_call" {
if got := strings.Join(types, ","); got != "message,message,reasoning,web_search_call,web_search_call" {
t.Fatalf("items: %s", got)
}
if q.Input[0]["id"] != "msg_keep" {
@@ -435,10 +435,10 @@ func TestPlainItemIDsBoundItemIDs(t *testing.T) {
// its first 440, so these two would land on one)
var callIDs []string
for _, it := range q.Input {
if it["type"] == "custom_tool_call" {
if it["type"] == "web_search_call" {
id, _ := it["id"].(string)
if !strings.HasPrefix(id, "ctc_") {
t.Errorf("a custom tool call's id not bound under its kind's prefix: %q", id)
if !strings.HasPrefix(id, "ws_") {
t.Errorf("a web search call's id not bound under its kind's prefix: %q", id)
}
callIDs = append(callIDs, id)
}
@@ -499,7 +499,7 @@ func (u *opaqueCopilot) ServeHTTP(w http.ResponseWriter, r *http.Request) {
continue
}
typ, _ := it["type"].(string)
prefix := map[string]string{"message": "msg_", "function_call": "fc_", "reasoning": "rs_"}[typ]
prefix := map[string]string{"message": "msg_", "function_call": "fc_", "reasoning": "rs_", "web_search_call": "ws_"}[typ]
if len(id) > 64 || !openaiItemID.MatchString(id) || prefix != "" && !strings.HasPrefix(id, prefix) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
@@ -526,23 +526,16 @@ func (u *opaqueCopilot) asked() []map[string]any {
return append([]map[string]any(nil), u.bodies...)
}
// echo_ts, in Codex on GitHub Copilot: after Codex's native compaction,
// the turn that carried Copilot's tool call back was turned away with an
// empty 400 "invalid_request_body". The call's 452-character id had gone
// as a bare sha256 digest, which Copilot refuses, where its own id, or
// none, goes. The call goes without its id, paired with its output by
// call_id, streamed or not.
func TestCopilotTakesItsOwnOpaqueCallID(t *testing.T) {
if len(copilotOpaqueCallID) != 452 || !strings.ContainsAny(copilotOpaqueCallID, "+/") {
t.Fatalf("fixture not of Copilot's shape: %d %q", len(copilotOpaqueCallID), copilotOpaqueCallID[:20])
}
// onOpaqueCopilot signs a fresh HOME in to a Copilot whose /responses is
// up, with one GPT model on /responses.
func onOpaqueCopilot(t *testing.T, up *opaqueCopilot) {
t.Helper()
fresh(t)
cfg := os.Getenv("XDG_CONFIG_HOME")
os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755)
os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{
"github.com:Iv1.x": map[string]any{"user": "echo", "oauth_token": "gho_echo"},
}), 0o600)
up := &opaqueCopilot{own: map[string]bool{copilotOpaqueCallID: true}}
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/models":
@@ -553,7 +546,7 @@ func TestCopilotTakesItsOwnOpaqueCallID(t *testing.T) {
w.WriteHeader(404)
}
}))
defer api.Close()
t.Cleanup(api.Close)
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/token") {
json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}})
@@ -561,10 +554,24 @@ func TestCopilotTakesItsOwnOpaqueCallID(t *testing.T) {
}
io.WriteString(w, `{"copilot_plan":"individual"}`)
}))
defer gh.Close()
t.Cleanup(gh.Close)
oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL
provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user"
defer func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }()
t.Cleanup(func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser })
}
// echo_ts, in Codex on GitHub Copilot: after Codex's native compaction,
// the turn that carried Copilot's tool call back was turned away with an
// empty 400 "invalid_request_body". The call's 452-character id had gone
// as a bare sha256 digest, which Copilot refuses, where its own id, or
// none, goes. The call goes without its id, paired with its output by
// call_id, streamed or not.
func TestCopilotTakesItsOwnOpaqueCallID(t *testing.T) {
if len(copilotOpaqueCallID) != 452 || !strings.ContainsAny(copilotOpaqueCallID, "+/") {
t.Fatalf("fixture not of Copilot's shape: %d %q", len(copilotOpaqueCallID), copilotOpaqueCallID[:20])
}
up := &opaqueCopilot{own: map[string]bool{copilotOpaqueCallID: true}}
onOpaqueCopilot(t, up)
input := `[{"type":"message","role":"user","content":[{"type":"input_text","text":"list the files"}]},
{"type":"function_call","id":"` + copilotOpaqueCallID + `","call_id":"call_Xq7","name":"shell","arguments":"{\"cmd\":\"ls\"}"},
@@ -606,19 +613,38 @@ func TestCopilotTakesItsOwnOpaqueCallID(t *testing.T) {
}
}
// An overlong id of a kind that can't go without one, another vendor's on
// a conversation switched to an upstream that checks ids, is still bound:
// under its kind's prefix when its type says one, else under its own, and
// another vendor's reasoning of other characters still goes.
// An overlong id of a kind that can't go without one (OpenAI's schema has
// it required), another vendor's or Copilot's opaque one, is bound under the
// prefix OpenAI gives that kind, else under its own; one of a kind that may
// go without its id goes without it, its call_id kept; and another vendor's
// reasoning of other characters still goes.
func TestPlainItemIDsBindsOtherKinds(t *testing.T) {
long := strings.Repeat("Z", 300)
body := []byte(`{"model":"gpt-6.1","store":false,"input":[
{"type":"reasoning","id":"` + long + `","summary":[],"encrypted_content":"gAAAA"},
{"type":"reasoning","id":"` + museReasoningID + `","summary":[],"encrypted_content":"muse-sealed"},
{"type":"tool_search_call","id":"` + long + `","call_id":"ts_1","execution":"client","arguments":{}},
{"type":"custom_tool_call","id":"fc_` + long + `","call_id":"cc_1","name":"apply_patch","input":"x"},
{"type":"web_search_call","id":"` + long + `","status":"completed","action":{"type":"search","query":"q"}},
{"type":"file_search_call","id":"` + long + `","status":"completed","queries":["q"]},
{"type":"computer_call","id":"` + long + `","call_id":"cu_call","action":{"type":"screenshot"},"pending_safety_checks":[],"status":"completed"},
{"type":"image_generation_call","id":"` + long + `","status":"completed","result":"iVBOR"},
{"type":"code_interpreter_call","id":"` + long + `","status":"completed","code":"1","container_id":"cntr_1","outputs":[]},
{"type":"mcp_list_tools","id":"` + long + `","server_label":"s","tools":[]},
{"type":"mcp_approval_request","id":"` + long + `","server_label":"s","name":"n","arguments":"{}"},
{"type":"mcp_call","id":"` + long + `","server_label":"s","name":"n","arguments":"{}"},
{"type":"item_kind_x","id":"xk_` + long + `"},
{"type":"item_kind_y","id":"` + long + `"}]}`)
{"type":"item_kind_y","id":"` + long + `"},
{"type":"tool_search_call","id":"` + long + `","call_id":"ts_1","execution":"client","arguments":{}},
{"type":"tool_search_output","id":"` + long + `","call_id":"ts_1","execution":"client","tools":[]},
{"type":"custom_tool_call","id":"fc_` + long + `","call_id":"cc_1","name":"apply_patch","input":"x"},
{"type":"custom_tool_call_output","id":"` + long + `","call_id":"cc_1","output":"ok"},
{"type":"function_call_output","id":"` + long + `","call_id":"fn_1","output":"ok"},
{"type":"computer_call_output","id":"` + long + `","call_id":"cu_call","output":{"type":"computer_screenshot","image_url":"data:,"}},
{"type":"shell_call","id":"` + long + `","call_id":"sh_1","action":{"commands":["ls"]}},
{"type":"shell_call_output","id":"` + long + `","call_id":"sh_1","output":[]},
{"type":"apply_patch_call","id":"` + long + `","call_id":"ap_1","status":"completed","operation":{"type":"delete_file","path":"x"}},
{"type":"apply_patch_call_output","id":"` + long + `","call_id":"ap_1","status":"completed"},
{"type":"mcp_approval_response","id":"` + long + `","approval_request_id":"mcpr_1","approve":true},
{"type":"compaction","id":"` + long + `","encrypted_content":"gAAAB"}]}`)
var q struct {
Input []map[string]any `json:"input"`
}
@@ -627,19 +653,86 @@ func TestPlainItemIDsBindsOtherKinds(t *testing.T) {
}
var ids []string
for _, it := range q.Input {
id, _ := it["id"].(string)
typ := it["type"].(string)
id, has := it["id"].(string)
if !has {
ids = append(ids, typ+" without")
if it["call_id"] == nil && strings.Contains(typ, "_call") {
t.Errorf("%s sent without its call_id: %v", typ, it)
}
continue
}
if len(id) != 64 || !openaiItemID.MatchString(id) {
t.Errorf("id %q not bound to 64 of the characters OpenAI takes", id)
}
ids = append(ids, it["type"].(string)+"="+id[:4])
prefix := ""
if i := strings.IndexByte(id, '_'); i >= 0 {
prefix = id[:i+1]
}
ids = append(ids, typ+"="+prefix)
}
got := strings.Join(ids, ",")
for _, w := range []string{"reasoning=rs_", "tool_search_call=tsc_", "custom_tool_call=ctc_", "item_kind_x=xk_"} {
if !strings.Contains(got, w) {
t.Errorf("ids %s lack %s", got, w)
want := "reasoning=rs_,web_search_call=ws_,file_search_call=fs_,computer_call=cu_," +
"image_generation_call=ig_,code_interpreter_call=ci_,mcp_list_tools=mcpl_," +
"mcp_approval_request=mcpr_,mcp_call=mcp_,item_kind_x=xk_,item_kind_y=," +
"tool_search_call without,tool_search_output without,custom_tool_call without," +
"custom_tool_call_output without,function_call_output without,computer_call_output without," +
"shell_call without,shell_call_output without,apply_patch_call without," +
"apply_patch_call_output without,mcp_approval_response without,compaction without"
if got != want {
t.Errorf("ids\n got %s\nwant %s", got, want)
}
}
// echo_ts, in Codex on GitHub Copilot with native web search: Copilot
// hands a web_search_call an id of ~450 characters of Base64, no ws_ at
// the front, and Codex carries it back on the next turn. It went as a bare
// sha256 digest and Copilot turned the whole request away with its empty
// 400 "invalid_request_body". A web search call can't go without its id
// (OpenAI's schema has it required), so it goes bound under ws_, and the
// turn goes through, streamed or not.
func TestCopilotTakesItsOwnOpaqueSearchCallID(t *testing.T) {
b := make([]byte, 339)
for i := range b {
b[i] = byte(i*197 + 3)
}
searchID := base64.StdEncoding.EncodeToString(b)
if len(searchID) != 452 || strings.HasPrefix(searchID, "ws_") || !strings.ContainsAny(searchID, "+/") {
t.Fatalf("fixture not of Copilot's shape: %d %q", len(searchID), searchID[:20])
}
up := &opaqueCopilot{}
onOpaqueCopilot(t, up)
input := `[{"type":"message","role":"user","content":[{"type":"input_text","text":"what's new in Go 1.26?"}]},
{"type":"web_search_call","id":"` + searchID + `","status":"completed","action":{"type":"search","query":"Go 1.26 release notes"}},
{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Go 1.26 adds new(expr)."}]},
{"type":"message","role":"user","content":[{"type":"input_text","text":"and 1.25?"}]}]`
s := New()
for _, stream := range []bool{true, false} {
body := `{"model":"copilot/gpt-6.1","stream":` + strconv.FormatBool(stream) + `,"store":false,"tools":[{"type":"web_search"}],"input":` + input + `}`
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "DONE") {
t.Fatalf("stream %v: %d %s", stream, rec.Code, rec.Body.String())
}
}
asked := up.asked()
if len(asked) != 2 {
t.Fatalf("asked Copilot %d times", len(asked))
}
if len(q.Input) != 5 {
t.Errorf("another vendor's reasoning of other characters not left out: %s", got)
for _, q := range asked {
items, _ := q["input"].([]any)
var search map[string]any
for _, raw := range items {
if it, _ := raw.(map[string]any); it["type"] == "web_search_call" {
search = it
}
}
if search == nil {
t.Fatalf("the web search call not sent: %v", items)
}
id, _ := search["id"].(string)
if !strings.HasPrefix(id, "ws_") || len(id) != 64 {
t.Errorf("the web search call sent under %q", id)
}
}
}