diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 13b0c557d..b5b5d5196 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -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 diff --git a/internal/gateway/item_ids_test.go b/internal/gateway/item_ids_test.go index f0d6de63c..e0a892be7 100644 --- a/internal/gateway/item_ids_test.go +++ b/internal/gateway/item_ids_test.go @@ -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) + } } }