diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 407456242..d16e9db0d 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -141,6 +141,7 @@ recorded as a prediction failure (`noPrediction`). - Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); with the writer gone from the candidates (switched off, resting, removed), magpie answers 400 `checkpointError` naming why, and never sends it to another key, drops it, or summarises it in its place. With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`. - A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`. - A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge. +- A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`. - Every request to a key+URL provider goes with magpie's User-Agent (`magpie/`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's ` magpie-image/1`, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`. - A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before. - Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`). diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 8b508b045..81081a2c6 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -72,6 +72,7 @@ type cRequest struct { func parseChat(body []byte) (*Request, error) { body = liftMessageTools(body) // a request handle didn't see (#2322) + body = shapeChatTools(body) // and its tools in another API's shape (#2622) var c cRequest if err := decodeJSON(body, &c); err != nil { return nil, fmt.Errorf("invalid request: %v", err) diff --git a/internal/gateway/chat_tool_shape.go b/internal/gateway/chat_tool_shape.go new file mode 100644 index 000000000..5964fa5c3 --- /dev/null +++ b/internal/gateway/chat_tool_shape.go @@ -0,0 +1,94 @@ +package gateway + +import ( + "bytes" + "encoding/json" + + "github.com/tidwall/gjson" +) + +// A Chat Completions tool is {"type":"function","function":{name, +// description, parameters, strict}}. Some clients send theirs in another +// API's shape on the Chat route: MCP's {"name","description","inputSchema"} +// (ZCode, #2622), Anthropic's input_schema, a bare {"name","parameters"}, +// or Responses' flat {"type":"function","name",…}. OpenAI and the strict +// Chat APIs turn every one of those away (SenseNova: "field Tools[0].Type +// invalid, should be set", "function cannot be empty"), and parseChat read +// no name from them, so a translated request offered a tool with none. + +// shapeChatTools is a Chat request with each such tool in the Chat shape. +// A tool that already has its function object, a hosted tool (any other +// type), one with no name, and a request that doesn't parse are as they +// came; a tool's other fields stay beside its function. +func shapeChatTools(body []byte) []byte { + if !bytes.Contains(body, []byte(`"tools"`)) { + return body + } + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + need := false + for _, t := range tools.Array() { + if unshapedChatTool(t) { + need = true + break + } + } + if !need { + return body + } + var raw []json.RawMessage + if json.Unmarshal([]byte(tools.Raw), &raw) != nil { + return body + } + for i, t := range raw { + if !unshapedChatTool(gjson.ParseBytes(t)) { + continue + } + var m map[string]json.RawMessage + if json.Unmarshal(t, &m) != nil { + continue + } + fn := map[string]json.RawMessage{} + for _, k := range []string{"name", "description", "strict"} { + if v, ok := m[k]; ok { + fn[k] = v + delete(m, k) + } + } + for _, k := range []string{"parameters", "inputSchema", "input_schema"} { + if v, ok := m[k]; ok { + if _, set := fn["parameters"]; !set { + fn["parameters"] = v + } + delete(m, k) + } + } + f, err := marshalPlain(fn) + if err != nil { + continue + } + m["type"] = json.RawMessage(`"function"`) + m["function"] = f + out, err := marshalPlain(m) + if err != nil { + continue + } + raw[i] = out + } + return withFields(body, map[string]any{"tools": raw}) +} + +// unshapedChatTool is whether t is a function tool with its name at the +// top rather than in a function object. +func unshapedChatTool(t gjson.Result) bool { + if !t.IsObject() || t.Get("function").Exists() { + return false + } + if typ := t.Get("type").String(); typ != "" && typ != "function" { + return false + } + n := t.Get("name") + return n.Type == gjson.String && n.String() != "" +} diff --git a/internal/gateway/chat_tool_shape_test.go b/internal/gateway/chat_tool_shape_test.go new file mode 100644 index 000000000..49f023cd3 --- /dev/null +++ b/internal/gateway/chat_tool_shape_test.go @@ -0,0 +1,108 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// zcodeAsking is jinyue806's reproduction of #2622 as they sent it to +// magpie, with tool standing in for its tools[0]. The tools are the +// shapes the report tried, each of which SenseNova turned away. +const zcodeAsking = `{ + "model": "sensenova/kimi-k3", + "messages": [{"role":"user","content":"hi"}], + "max_tokens": 8, + "tools": [TOOL] + }` + +var zcodeTools = map[string]string{ + "name and parameters": `{"name":"f","parameters":{"type":"object","properties":{}}}`, + "mcp inputSchema": `{"name":"f","inputSchema":{"type":"object","properties":{}}}`, + "with description": `{"name":"f","description":"d","parameters":{"type":"object","properties":{}}}`, + "flat function": `{"type":"function","name":"f","parameters":{"type":"object","properties":{}}}`, +} + +// A tool a Chat client sends in MCP's or another API's shape reaches the +// upstream as a Chat function tool when relayed, and as the named tool +// when translated (#2622). +func TestChatToolInAnotherShapeIsShaped(t *testing.T) { + srv, seen := relayOfEvery(t) + for _, route := range []struct { + name, model, path string + p provider.Provider + check func(t *testing.T, body string) + }{ + {"chat relayed", "kimi-k3", "/v1/chat/completions", provider.Provider{Chat: srv.URL + "/v1"}, func(t *testing.T, body string) { + tool := gjson.Get(body, "tools.0") + if tool.Get("type").String() != "function" || tool.Get("function.name").String() != "f" || + tool.Get("function.parameters.type").String() != "object" { + t.Errorf("tool relayed as %s", tool.Raw) + } + for _, k := range []string{"name", "parameters", "inputSchema", "description"} { + if tool.Get(k).Exists() { + t.Errorf("%s left beside the function: %s", k, tool.Raw) + } + } + }}, + {"messages", "claude-opus-5-5", "/v1/messages", provider.Provider{Anthropic: srv.URL}, func(t *testing.T, body string) { + if tool := gjson.Get(body, "tools.0"); tool.Get("name").String() != "f" || tool.Get("input_schema.type").String() != "object" { + t.Errorf("tool sent as %s", tool.Raw) + } + }}, + {"responses", "kimi-k3", "/v1/responses", provider.Provider{Responses: srv.URL + "/v1"}, func(t *testing.T, body string) { + if tool := gjson.Get(body, "tools.0"); tool.Get("name").String() != "f" || tool.Get("parameters.type").String() != "object" { + t.Errorf("tool sent as %s", tool.Raw) + } + }}, + } { + for shape, tool := range zcodeTools { + t.Run(route.name+"/"+shape, func(t *testing.T) { + fresh(t) + p := route.p + p.ID, p.Name, p.Key, p.Models = "sensenova", "SenseNova", "k", []string{route.model} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + seen() + body := strings.Replace(strings.Replace(zcodeAsking, "TOOL", tool, 1), "kimi-k3", route.model, 1) + if code, b := post(t, "/v1/chat/completions", body); code != 200 { + t.Fatalf("%d %s", code, b) + } + paths, bodies := seen() + if len(paths) != 1 || paths[0] != route.path { + t.Fatalf("went to %v, want %s", paths, route.path) + } + route.check(t, bodies[0]) + }) + } + } +} + +// A request whose tools are all in the Chat shape, or hosted, is relayed +// byte for byte; only a tool in another shape is rewritten, and its other +// fields stay. +func TestShapeChatToolsLeavesChatShape(t *testing.T) { + for _, body := range []string{ + `{"model":"m","messages":[],"tools":[{"type":"function","function":{"name":"f","parameters":{"type":"object"}}}]}`, + `{"model":"m","messages":[],"tools":[{"type":"web_search_preview"},{"type":"function","function":{"name":"g"}}]}`, + `{"model":"m","messages":[],"tools":[{"type":"custom","name":"apply_patch"}]}`, + `{"model":"m","messages":[],"tools":[{"description":"no name"}]}`, + `{"model":"m","messages":[{"role":"user","content":"tools"}]}`, + } { + if got := string(shapeChatTools([]byte(body))); got != body { + t.Errorf("%s\nbecame %s", body, got) + } + } + got := shapeChatTools([]byte(`{"model":"m","tools":[{"type":"function","function":{"name":"a"}},{"name":"b","input_schema":{"type":"object"},"strict":true,"cache_control":{"type":"ephemeral"}}]}`)) + if a := gjson.GetBytes(got, "tools.0").Raw; a != `{"type":"function","function":{"name":"a"}}` { + t.Errorf("a Chat tool changed: %s", a) + } + b := gjson.GetBytes(got, "tools.1") + if b.Get("function.name").String() != "b" || !b.Get("function.strict").Bool() || + b.Get("function.parameters.type").String() != "object" || b.Get("cache_control.type").String() != "ephemeral" { + t.Errorf("tool shaped as %s", b.Raw) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d9a5adc11..0ee523507 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1374,6 +1374,9 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc { // own: in the request's tools for every route, the relay's // and every check that reads them (#2322) body = liftMessageTools(body) + // a tool in MCP's, Anthropic's or Responses' shape, which + // no Chat API takes, in the Chat shape for every route (#2622) + body = shapeChatTools(body) } // Claude Code's headers, for a test asked as Claude Code to ask // with (provider.TestAs), whatever serves this model: a