diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 0b096be9d..2df06abf6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1768,9 +1768,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. body = s.withoutRefused(p.ID, proto, body) } // a Grok subscription is given Codex's namespaced functions flat - // (grokBody); a call to one goes back under its namespace (#404) + // (grokBody), and Zed's plugin likewise (ZedBody); a call to one goes + // back under its namespace (#404) var named map[string]nsTool - if proto == provider.Responses && p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok") { + if proto == provider.Responses && p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok" || p.PluginProvider() == "zed") { named = namespacedIn(body) } res, err := s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header) diff --git a/internal/gateway/plugin_zed_test.go b/internal/gateway/plugin_zed_test.go new file mode 100644 index 000000000..689d8bb5e --- /dev/null +++ b/internal/gateway/plugin_zed_test.go @@ -0,0 +1,161 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// zedParses is what Zed's cloud asks of an OpenAI Responses request +// (zed-industries/zed, crates/open_ai/src/responses.rs) before it goes on, +// "" when it would take it. +func zedParses(q map[string]any) string { + items, _ := q["input"].([]any) + for _, it := range items { + im, _ := it.(map[string]any) + switch ty, _ := im["type"].(string); ty { + case "message": + switch im["role"] { + case "user", "assistant", "system", "tool": + default: + return "unknown variant `" + im["role"].(string) + "`, expected one of `user`, `assistant`, `system`, `tool`" + } + if _, ok := im["content"].([]any); !ok { + return "invalid type: expected a sequence" + } + case "reasoning": + if c, ok := im["content"]; ok && c == nil { + return "invalid type: null, expected a sequence" + } + case "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "compaction", "compaction_trigger": + default: + return "unknown variant `" + ty + "`" + } + } + tools, _ := q["tools"].([]any) + for _, t := range tools { + if ty := t.(map[string]any)["type"]; ty != "function" && ty != "custom" { + return "unknown variant `" + ty.(string) + "`, expected `function` or `custom`" + } + } + inc, _ := q["include"].([]any) + for _, v := range inc { + if v != "reasoning.encrypted_content" { + return "unknown variant `" + v.(string) + "`" + } + } + return "" +} + +// A Codex request on an OpenAI model of Zed's plugin reaches Zed as its +// cloud reads it: the developer messages Codex sends at the start and +// mid-conversation (a model switched) as system ones where they stand, +// reasoning with a null content without it, a web search an OpenAI model +// ran left out, and the namespaced tools flat (nico on Discord: "failed to +// parse OpenAI Responses API request: unknown variant `developer`"). +func TestZedPluginGetsNoDeveloperRole(t *testing.T) { + var mu sync.Mutex + var sent []map[string]any + pid := besideFake(t, "zed", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + sent = append(sent, q) + mu.Unlock() + if why := zedParses(q); why != "" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"failed to parse OpenAI Responses API request: `+why+`"}}`) + return + } + done := `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":5,"output_tokens":1}}` + if q["stream"] != true { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, done) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","item_id":"m1","output_index":0,"delta":"ok"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`)) + })) + body := `{"model":"` + pid + `/fake-resp","stream":true,"instructions":"You are Codex.",` + namespacedTools + `, + "include":["reasoning.encrypted_content"],"reasoning":{"effort":"medium","summary":"auto"},"input":[ + {"type":"message","role":"developer","content":[{"type":"input_text","text":"sandboxed"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}, + {"type":"reasoning","summary":[{"type":"summary_text","text":"thinking"}],"content":null,"encrypted_content":"gAAAAAx"}, + {"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"magpie"}}, + {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}, + {"type":"message","role":"developer","content":[{"type":"input_text","text":"now another model"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}]}` + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + mu.Lock() + defer mu.Unlock() + if len(sent) != 1 { + t.Fatalf("asked %d times", len(sent)) + } + q := sent[0] + var roles []string + for _, it := range q["input"].([]any) { + im := it.(map[string]any) + if im["type"] == "message" { + roles = append(roles, im["role"].(string)) + } + } + if got := strings.Join(roles, ","); got != "system,user,assistant,system,user" { + t.Fatalf("roles %s", got) + } + in := q["input"].([]any) + if len(in) != 6 { + t.Fatalf("input %v", in) + } + if s := in[4].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]; s != "now another model" { + t.Fatalf("the model switch went as %v", in[4]) + } + if r := in[2].(map[string]any); r["type"] != "reasoning" || r["encrypted_content"] != "gAAAAAx" { + t.Fatalf("reasoning went as %v", r) + } + if q["instructions"] != "You are Codex." { + t.Fatalf("instructions %v", q["instructions"]) + } + var names []string + for _, tl := range q["tools"].([]any) { + tm := tl.(map[string]any) + names = append(names, tm["type"].(string)+":"+tm["name"].(string)) + } + if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent" { + t.Fatalf("Zed was offered %s", got) + } +} + +// The built-in Zed account's OpenAI request is fitted the same way: a web +// search offered (no search API set up) leaves no web_search tool, nor +// include's web_search_call.action.sources, for Zed's cloud to turn away. +func TestZedBuiltInResponsesParse(t *testing.T) { + req, err := parseResponses([]byte(`{"model":"m","stream":true,"include":["reasoning.encrypted_content"],"reasoning":{"effort":"high"}, + "tools":[{"type":"function","name":"exec_command","parameters":{"type":"object"}},{"type":"web_search"}],"input":[ + {"type":"message","role":"developer","content":[{"type":"input_text","text":"rules"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`)) + if err != nil { + t.Fatal(err) + } + raw, _, err := zedRequest(req, "open_ai", "gpt-5.5") + if err != nil { + t.Fatal(err) + } + var q map[string]any + json.Unmarshal(raw, &q) + if why := zedParses(q); why != "" { + t.Fatalf("%s: %s", why, raw) + } +} diff --git a/internal/gateway/zed.go b/internal/gateway/zed.go index 3b41c3a00..23b59b65e 100644 --- a/internal/gateway/zed.go +++ b/internal/gateway/zed.go @@ -77,7 +77,10 @@ func zedRequest(req *Request, vendor, model string) (json.RawMessage, provider.P b, err := json.Marshal(m) return b, provider.Anthropic, err case "responses": - return buildResponses(&q, model, "api.openai.com", false), provider.Responses, nil + // fitted to the Responses types Zed's cloud reads (a web_search + // tool, or include's web_search_call.action.sources, would have it + // turn the request away) + return provider.ZedBody(buildResponses(&q, model, "api.openai.com", false)), provider.Responses, nil case "chat": var m map[string]json.RawMessage if err := json.Unmarshal(buildChat(&q, model, "api.x.ai", false), &m); err != nil { diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 575d36c32..551c2f02c 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -232,6 +232,11 @@ func pluginProvider(pp plugin.Provider, l pluginLogin) Provider { // them (#404): the plugin's own rewrite would leave them out a.body = grokBody } + if pp.ID == "zed" { + // an OpenAI model's request as Zed's cloud reads it: Codex's + // developer messages as system ones, its namespaced tools flat + a.body = ZedBody + } a.models = func() []catalog.Model { if cur, ok := PluginOf(id); ok { return pluginAccountCatalog(cur, acct.Key) diff --git a/internal/provider/zed_body.go b/internal/provider/zed_body.go new file mode 100644 index 000000000..ddaa0d160 --- /dev/null +++ b/internal/provider/zed_body.go @@ -0,0 +1,161 @@ +package provider + +import ( + "bytes" + "encoding/json" +) + +// Zed's cloud reads an OpenAI model's request into its own Responses types +// (zed-industries/zed, crates/open_ai/src/responses.rs) before it goes on to +// OpenAI, and turns the whole request away over anything they don't name: +// "failed to parse OpenAI Responses API request: unknown variant +// `developer`, expected one of `user`, `assistant`, `system`, `tool`" on +// Codex's developer messages. What they take: +// +// - input items tagged by type: message, function_call, +// function_call_output, custom_tool_call, custom_tool_call_output, +// reasoning, compaction, compaction_trigger; +// - a message's role: user, assistant, system, tool; its content a list; +// - a reasoning item's content a list, if there (serde's default is for +// a missing field, not a null one); +// - tools of type function or custom; +// - include: reasoning.encrypted_content alone; +// - reasoning.summary: auto, concise, detailed. +// +// ZedBody is a Responses request fitted to those, Codex's above all; a +// request in another API (one with no input list) goes as it came. +func ZedBody(body []byte) []byte { + if !bytes.Contains(body, []byte(`"input"`)) { + return body + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var m map[string]any + if dec.Decode(&m) != nil || m == nil { + return body + } + input, ok := m["input"].([]any) + if !ok { + return body + } + if _, chat := m["messages"]; chat { + return body + } + dirty := false + kept := input[:0:0] + for _, it := range input { + im, ok := it.(map[string]any) + if !ok { + kept = append(kept, it) + continue + } + ty, _ := im["type"].(string) + if ty == "" { + if _, ok := im["role"]; ok { + // the shorthand message, {role, content}: Zed's items are + // tagged + im["type"], ty, dirty = "message", "message", true + } + } + if flatCall(im) { + dirty = true + } + switch ty { + case "message": + // Codex's developer messages (its permissions, the model + // switched, the context changed) say what a system message + // says, and stay where they stand + if im["role"] == "developer" { + im["role"], dirty = "system", true + } + if s, ok := im["content"].(string); ok { + part := "input_text" + if im["role"] == "assistant" { + part = "output_text" + } + im["content"], dirty = []any{map[string]any{"type": part, "text": s}}, true + } + case "agent_message": + // a task handed to a subagent, or one agent's message to + // another: the user's turn for the agent that receives it + im = map[string]any{"type": "message", "role": "user", "content": im["content"]} + dirty = true + case "reasoning": + if c, ok := im["content"]; ok && c == nil { + delete(im, "content") + dirty = true + } + case "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "compaction", "compaction_trigger": + default: + // an item Zed has no type for (a web search an OpenAI model + // ran, an item_reference) goes; it would take the request with it + dirty = true + continue + } + kept = append(kept, im) + } + m["input"] = kept + if tools, ok := m["tools"].([]any); ok { + var out []any + for _, t := range tools { + tm, _ := t.(map[string]any) + switch ty, _ := tm["type"].(string); ty { + case "function", "custom": + out = append(out, t) + case "namespace": + dirty = true + // its functions flat, as Grok's backend is given them; a + // call back to one is named for Codex again + out = append(out, grokFlat(tm)...) + default: + dirty = true + } + } + if len(out) == 0 { + delete(m, "tools") + delete(m, "tool_choice") + } else { + m["tools"] = out + } + } + if tc, ok := m["tool_choice"].(map[string]any); ok { + // Zed's tool_choice names a function as Chat Completions does + // ({type, function: {name}}) and turns the Responses one away: a + // tool is still called, the model picking which + m["tool_choice"], dirty = "auto", true + if tc["type"] == "function" || tc["type"] == "custom" { + m["tool_choice"] = "required" + } + } + if inc, ok := m["include"].([]any); ok { + var out []any + for _, v := range inc { + if v == "reasoning.encrypted_content" { + out = append(out, v) + } else { + dirty = true + } + } + if len(out) == 0 { + delete(m, "include") + } else { + m["include"] = out + } + } + if r, ok := m["reasoning"].(map[string]any); ok { + if s, ok := r["summary"]; ok && s != "auto" && s != "concise" && s != "detailed" { + delete(r, "summary") + dirty = true + } + } + if !dirty { + return body + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + if enc.Encode(m) != nil { + return body + } + return bytes.TrimRight(b.Bytes(), "\n") +}