Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a tool Claude Code's tool search loads goes to OpenAI's Responses API where it was loaded (#2660)
yetonef5b0157420a4
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 935f4e46e..e9e11d170 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -156,6 +156,7 @@ recorded as a prediction failure (`noPrediction`).- 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`).- Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put blocks of their own in a message: a `tool_addition` (`tool` a `tool_reference` naming the tool, or a `tool_definition`), a `tool_removal`, and a `tool_reference`. Kimi's Anthropic endpoint refuses any of them with a whole-request 400 "Invalid request Error" that names nothing, so once a session had loaded a tool every turn failed (#2042); DeepSeek's takes a `tool_addition` naming a tool but refuses one defining it, a `tool_removal` and a message's `tool_reference` with 422 "unknown variant `tool_removal`" (both checked against the real endpoints on 2026-10-14). OpenCode Go also rejects DeepSeek inline definitions with a generic 422 "Upstream request failed: Endpoint is unavailable." (checked on 2026-10-15). Kimi and DeepSeek models on OpenCode are never sent these blocks (`forwardOnce`); a provider that refuses one in those words is asked again at once without them and not sent them again while magpie runs (`refuseShapes`, `shapeDeferred`; the retry loop reads a 422 as well as a 400). `withoutDeferredTools` drops the blocks and a message they leave empty; definitions present only in a `tool_addition.tool.definition` join the request's `tools` once by name (an existing top-level definition wins), and a `tool_reference` inside a `tool_result` (ToolSearch's answer, which both take) stays. Any other provider is sent them as Claude Code wrote them ([`anthropic_shapes.go`](../../internal/gateway/anthropic_shapes.go), `TestKimiIsSentNoDeferredToolBlocks`, `TestDeferredToolBlocksRefusedOnceLeftOut`, `TestOpenCodeDeepSeekInlineTools`, `TestDeferredInlineDefinitionPreserved`).- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).+- A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`) and for a provider set `additionalTools` (`magpie provider set <id> additional-tools=on`); nothing else, since xAI answers the item 422 (#350), the ChatGPT backend has been seen to take it only for Codex's Responses Lite, and no relay or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`.- A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte.- A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message.- A Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)).diff --git a/internal/cli/additional_tools_cli_test.go b/internal/cli/additional_tools_cli_test.gonew file mode 100644index 000000000..576ed13e8--- /dev/null+++ b/internal/cli/additional_tools_cli_test.go@@ -0,0 +1,23 @@+package cli++import (+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// additional-tools=on has a provider's Responses API sent a tool Claude+// Code's tool search loads where it was loaded (#2660); default takes it+// back, and another value is refused.+func TestAdditionalToolsPair(t *testing.T) {+ var p provider.Provider+ if err := applyPairs(&p, []string{"additional-tools=on"}); err != nil || !p.AdditionalTools {+ t.Fatalf("on: %v %v", err, p.AdditionalTools)+ }+ if err := applyPairs(&p, []string{"additional-tools=default"}); err != nil || p.AdditionalTools {+ t.Fatalf("default: %v %v", err, p.AdditionalTools)+ }+ if err := applyPairs(&p, []string{"additional-tools=maybe"}); err == nil {+ t.Fatal("maybe taken")+ }+}diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.goindex 0c9f6c0cf..47d28f7f2 100644--- a/internal/cli/providers_cli.go+++ b/internal/cli/providers_cli.go@@ -42,6 +42,9 @@ const providerUsage = `usage:compaction=native asks the provider Codex's own compaction and handsCodex its sealed item as it came (a Responses API, a ChatGPT account,Copilot), compaction=magpie, the default, has magpie summarise+ additional-tools=on sends a tool Claude Code's tool search loads to its+ Responses API where it was loaded (an additional_tools item, which+ keeps the cache); additional-tools=default puts it with the other toolsmagpie provider key <id> <key> change the API keymagpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in iconmagpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)@@ -1048,6 +1051,18 @@ func applyPairs(p *provider.Provider, pairs []string) error {default:return fmt.Errorf("codex=as-sent|default, not %q", v)}+ case "additional-tools":+ // on: a tool an Anthropic client's tool search loads goes to+ // the provider's Responses API in an additional_tools item+ // where it was loaded, which keeps the cached prefix (#2660)+ switch strings.ToLower(v) {+ case "on", "yes":+ p.AdditionalTools = true+ case "default", "no", "off":+ p.AdditionalTools = false+ default:+ return fmt.Errorf("additional-tools=on|default, not %q", v)+ }case "user-agent", "ua":// agent: a request goes with the User-Agent the agent that// sent it gave, for a coding plan that serves only agents itdiff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.goindex dfe818b44..3d0f242ad 100644--- a/internal/gateway/anthropic.go+++ b/internal/gateway/anthropic.go@@ -86,6 +86,7 @@ type aRequest struct {Description string `json:"description,omitempty"`InputSchema json.RawMessage `json:"input_schema,omitempty"`CacheControl json.RawMessage `json:"cache_control,omitempty"`+ DeferLoading bool `json:"defer_loading,omitempty"`} `json:"tools,omitempty"`ToolChoice *struct {Type string `json:"type"`@@ -167,7 +168,7 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) {msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: anthropicInID(b.ID), Name: b.Name, Args: b.Input})case "tool_result":out, images := toolOutput(b.Content)- msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError})+ msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError, Loads: toolRefs(b.Content)})case "thinking":msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature})case "redacted_thinking":@@ -218,7 +219,7 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) {// only keeps Anthropic's deferred loading on; never to be calledcontinue}- r.Tools = append(r.Tools, Tool{Name: t.Name, Description: t.Description, Schema: t.InputSchema})+ r.Tools = append(r.Tools, Tool{Name: t.Name, Description: t.Description, Schema: t.InputSchema, Deferred: t.DeferLoading})}if tc := a.ToolChoice; tc != nil {switch tc.Type {diff --git a/internal/gateway/anthropic_shapes.go b/internal/gateway/anthropic_shapes.goindex 928aa2215..4d55ba0d8 100644--- a/internal/gateway/anthropic_shapes.go+++ b/internal/gateway/anthropic_shapes.go@@ -409,6 +409,22 @@ func toolLoadedText(name string) string {return "Tool " + name + " is loaded and can be called now."}+// toolRefs are the tools a tool_result's content names in tool_reference+// blocks, as Claude Code's ToolSearch answers, in their order.+func toolRefs(content json.RawMessage) []string {+ if !bytes.Contains(content, []byte(`"tool_reference"`)) {+ return nil+ }+ var names []string+ gjson.ParseBytes(content).ForEach(func(_, b gjson.Result) bool {+ if n := b.Get("tool_name").String(); b.Get("type").String() == "tool_reference" && n != "" {+ names = append(names, n)+ }+ return true+ })+ return names+}+// refsOnly is a tool_result's content that is tool_reference blocks and// nothing else, as ToolSearch answers.func refsOnly(c gjson.Result) bool {diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex c05a0a1b7..f315b8191 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -5075,6 +5075,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, tor := *reqr.CacheKey, req = "", &r}+ if want := to == provider.Responses && loadsInPlace(p) && s.fits(p.ID, additionalToolsItem, to); want != req.LoadedInPlace {+ r := *req+ r.LoadedInPlace, req = want, &r+ }if offEffort(req.Effort) && !s.fits(p.ID, offRefused(model), to) {r := *reqr.Effort, req = onEffort(p, model), &r@@ -5236,6 +5240,17 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, tob, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))res.Body.Close()res.Body = io.NopCloser(bytes.NewReader(b))+ if req.LoadedInPlace && refusesField(res.StatusCode, b, additionalToolsItem) && bytes.Contains(body, []byte(`"`+additionalToolsItem+`"`)) {+ // an upstream that turns the item away is asked again with the+ // loaded tools among the others, and not sent it again: the+ // prompt's prefix changes from here, as before #2660, and the+ // log says so rather than the cache seeming kept+ log.Printf("gateway: %s turned away additional_tools (%d); loaded tools go in tools from now on", p.ID, res.StatusCode)+ s.markUnfit(p.ID, additionalToolsItem, to)+ r := *req+ r.LoadedInPlace, req = false, &r+ continue+ }if to == provider.Anthropic && res.StatusCode == http.StatusBadRequest &&samplingDeprecated.Match(b) && (req.Temp != nil || req.TopP != nil) {// a Claude by a name samplingAsTaken can't read refuses the@@ -5435,6 +5450,28 @@ func (s *Server) servesElsewhere(p provider.Provider, model string, proto providreturn slices.ContainsFunc(s.usable(p, model), func(x provider.Protocol) bool { return x != proto })}+// additionalToolsItem is the Responses input item a deferred tool goes to+// the upstream in where a result loaded it (Request.LoadedInPlace); a+// provider that refused it is remembered under it in unfit.+const additionalToolsItem = "additional_tools"++// loadsInPlace is whether p's Responses API is sent a tool an Anthropic+// client's tool search loaded in an additional_tools item at the place it+// was loaded (#2660): OpenAI's own API with a key, whose tool search guide+// documents the item and that its tools load at the end of the context+// so the cached prefix is kept, and a provider the user said takes it+// (provider.Provider.AdditionalTools). Nothing else is: xAI's Responses+// API answers 422 "unknown item type" (#350), the ChatGPT backend has+// been seen to take it only for Codex's Responses Lite, and a relay or+// plugin's vendor hasn't been tried.+func loadsInPlace(p provider.Provider) bool {+ if p.AdditionalTools {+ return true+ }+ h := p.Host()+ return p.Account == nil && !p.IsPlugin() && !p.IsAzure() && (h == "api.openai.com" || strings.HasSuffix(h, ".api.openai.com"))+}+// cacheKeyField is the client's prompt cache key as a request carries it// upstream; a provider that refused it is remembered under it in unfit.const cacheKeyField = "prompt_cache_key"diff --git a/internal/gateway/ir.go b/internal/gateway/ir.goindex 348523f1d..2426c2ed1 100644--- a/internal/gateway/ir.go+++ b/internal/gateway/ir.go@@ -50,6 +50,10 @@ type Part struct {IsError boolImages []Part // the images the tool returned beside its textStandalone map[string]any // native Responses notification with no call ID+ // Loads are the tools a tool's result loads, by name: Claude Code's+ // ToolSearch answers with tool_reference blocks naming the deferred+ // tools it found (#2660)+ Loads []string// thinking: its signature (Anthropic's, or a Gemini thought's). On a// tool call, and on text, Gemini's thoughtSignature: a tool call's@@ -140,6 +144,10 @@ type Tool struct {Description stringSchema json.RawMessage // JSON schema of the argumentsStrict bool // the client asked for its arguments held to the schema+ // Deferred is a tool the client marked defer_loading: Claude Code's+ // tools that ToolSearch loads, offered from where they were loaded+ // (Part.Loads), not from the start (#2660)+ Deferred bool}// Request is a call to a model, whichever API it arrived in.@@ -244,6 +252,12 @@ type Request struct {// Namespaced are the tools a Responses client offered inside a// namespace, by the flat name the model is offered them under.Namespaced map[string]nsTool+ // LoadedInPlace has a Responses upstream that takes an additional_tools+ // item (loadsInPlace) given a deferred tool a result loaded in such an+ // item right after that result, not in the top-level tools: the tools+ // and the conversation sent before stay as they were, so its prompt+ // cache does (#2660). Every other upstream gets them in tools.+ LoadedInPlace bool// Grok is set when the model asked is one of Grok's, whose calls'// arguments reach the client with their zero fractions dropped// (grok_integral.go).diff --git a/internal/gateway/loaded_in_place_test.go b/internal/gateway/loaded_in_place_test.gonew file mode 100644index 000000000..2c6f9643d--- /dev/null+++ b/internal/gateway/loaded_in_place_test.go@@ -0,0 +1,264 @@+package gateway++import (+ "fmt"+ "net/http"+ "reflect"+ "strings"+ "testing"++ "github.com/tidwall/gjson"++ "github.com/yetone/magpie/internal/provider"+)++// Claude Code's tool search as maximia's probe recorded it (#2660, 2.1.302):+// the first request offers ToolSearch and the placeholder that keeps+// deferred loading on; once ToolSearch answers with a tool_reference, the+// next request offers the loaded MCP tool too, defer_loading true, and the+// one after that loads a second tool the same way.+const tsTools0 = `{"name":"Bash","description":"Run a command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},+ {"name":"ToolSearch","description":"Fetches full schema definitions for deferred tools","input_schema":{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}}`++const tsPlaceholder = `{"name":"DeferredToolPlaceholder","description":"","input_schema":{"type":"object"},"defer_loading":true}`++const tsReadA = `{"name":"mcp__probe__read_a","description":"Read A","input_schema":{"type":"object","properties":{"path":{"type":"string"}}},"defer_loading":true}`+const tsReadB = `{"name":"mcp__probe__read_b","description":"Read B","input_schema":{"type":"object","properties":{"path":{"type":"string"}}},"defer_loading":true}`++const tsSystem = `[{"type":"text","text":"You are Claude Code."}]`++const tsTurn1 = `{"role":"user","content":[{"type":"text","text":"load read_a with ToolSearch, call it, then load read_b and call it"}]}`+const tsSearchA = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"ToolSearch","input":{"query":"select:mcp__probe__read_a","max_results":1}}]},+ {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":[{"type":"tool_reference","tool_name":"mcp__probe__read_a"}]}]}`+const tsCallA = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_02","name":"mcp__probe__read_a","input":{"path":"a"}}]},+ {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_02","content":"A"}]}`+const tsSearchB = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_03","name":"ToolSearch","input":{"query":"select:mcp__probe__read_b","max_results":1}}]},+ {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_03","content":[{"type":"tool_reference","tool_name":"mcp__probe__read_b"}]}]}`++func tsRequest(tools []string, msgs ...string) string {+ return fmt.Sprintf(`{"model":"m1","max_tokens":1000,"stream":true,"system":%s,"tools":[%s],"messages":[%s]}`,+ tsSystem, strings.Join(tools, ","), strings.Join(msgs, ","))+}++// the three requests of maximia's probe+var tsRequests = []string{+ tsRequest([]string{tsTools0, tsPlaceholder}, tsTurn1),+ tsRequest([]string{tsTools0, tsReadA, tsPlaceholder}, tsTurn1, tsSearchA),+ tsRequest([]string{tsTools0, tsReadA, tsReadB, tsPlaceholder}, tsTurn1, tsSearchA, tsCallA, tsSearchB),+}++func tsBuild(t *testing.T, body string, inPlace bool) gjson.Result {+ t.Helper()+ r, err := parseAnthropic([]byte(body))+ if err != nil {+ t.Fatal(err)+ }+ r.LoadedInPlace = inPlace+ return gjson.ParseBytes(buildResponses(r, "m1", "api.openai.com", false))+}++func tsNames(v gjson.Result) []string {+ var out []string+ v.ForEach(func(_, t gjson.Result) bool {+ out = append(out, t.Get("name").String())+ return true+ })+ return out+}++// TestLoadedToolsKeepThePrefix: a tool Claude Code's tool search loads goes+// to a Responses upstream that takes additional_tools in such an item after+// the result that loaded it, so the top-level tools, the instructions and+// every earlier input item stay as they were sent (#2660).+func TestLoadedToolsKeepThePrefix(t *testing.T) {+ var outs []gjson.Result+ for _, body := range tsRequests {+ outs = append(outs, tsBuild(t, body, true))+ }+ first := outs[0]+ for i, o := range outs {+ if got, want := o.Get("tools").Raw, first.Get("tools").Raw; got != want {+ t.Fatalf("request %d's tools changed:\n%s\nwant\n%s", i+1, got, want)+ }+ if o.Get("instructions").Raw != first.Get("instructions").Raw {+ t.Fatalf("request %d's instructions changed", i+1)+ }+ if i == 0 {+ continue+ }+ prev, cur := outs[i-1].Get("input").Array(), o.Get("input").Array()+ if len(cur) <= len(prev) {+ t.Fatalf("request %d's input is no longer than the one before", i+1)+ }+ for j := range prev {+ if prev[j].Raw != cur[j].Raw {+ t.Fatalf("request %d's input item %d changed:\n%s\nwas\n%s", i+1, j, cur[j].Raw, prev[j].Raw)+ }+ }+ }+ if got := tsNames(first.Get("tools")); strings.Join(got, ",") != "Bash,ToolSearch" {+ t.Fatalf("tools = %v", got)+ }++ // read_a right after the result that loaded it, read_b after its own+ in := outs[2].Get("input").Array()+ var kinds []string+ for _, it := range in {+ k := it.Get("type").String()+ if k == "additional_tools" {+ k += ":" + strings.Join(tsNames(it.Get("tools")), "+")+ if it.Get("role").String() != "developer" {+ t.Fatalf("item without the developer role: %s", it.Raw)+ }+ }+ kinds = append(kinds, k)+ }+ want := "message,function_call,function_call_output,additional_tools:mcp__probe__read_a,function_call,function_call_output,function_call,function_call_output,additional_tools:mcp__probe__read_b"+ if strings.Join(kinds, ",") != want {+ t.Fatalf("input = %s\nwant %s", strings.Join(kinds, ","), want)+ }+ loaded := in[3].Get("tools.0")+ if loaded.Get("type").String() != "function" || loaded.Get("parameters.properties.path.type").String() != "string" || loaded.Get("description").String() != "Read A" {+ t.Fatalf("loaded tool = %s", loaded.Raw)+ }+ // what the client is told of the load is as before+ if got := in[2].Get("output").String(); !strings.Contains(got, "mcp__probe__read_a is loaded") {+ t.Fatalf("output = %q", got)+ }+}++// TestLoadedToolsInOneItem: tools loaded by results answered together, by+// one result naming several, or named again by a later search go in one+// item after the last of those results, once each.+func TestLoadedToolsInOneItem(t *testing.T) {+ body := tsRequest([]string{tsTools0, tsReadA, tsReadB, tsPlaceholder}, tsTurn1,+ `{"role":"assistant","content":[+ {"type":"tool_use","id":"toolu_01","name":"ToolSearch","input":{"query":"select:mcp__probe__read_a,mcp__probe__read_b","max_results":5}},+ {"type":"tool_use","id":"toolu_02","name":"ToolSearch","input":{"query":"read b","max_results":5}}]}`,+ `{"role":"user","content":[+ {"type":"tool_result","tool_use_id":"toolu_01","content":[{"type":"tool_reference","tool_name":"mcp__probe__read_a"},{"type":"tool_reference","tool_name":"mcp__probe__read_b"}]},+ {"type":"tool_result","tool_use_id":"toolu_02","content":[{"type":"tool_reference","tool_name":"mcp__probe__read_b"}]}]}`,+ `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_03","name":"ToolSearch","input":{"query":"select:mcp__probe__read_a","max_results":1}}]}`,+ `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_03","content":[{"type":"tool_reference","tool_name":"mcp__probe__read_a"}]},{"type":"text","text":"go on"}]}`)+ o := tsBuild(t, body, true)+ var kinds []string+ for _, it := range o.Get("input").Array() {+ k := it.Get("type").String()+ if k == "additional_tools" {+ k += ":" + strings.Join(tsNames(it.Get("tools")), "+")+ }+ kinds = append(kinds, k)+ }+ want := "message,function_call,function_call,function_call_output,function_call_output,additional_tools:mcp__probe__read_a+mcp__probe__read_b,function_call,function_call_output,message"+ if strings.Join(kinds, ",") != want {+ t.Fatalf("input = %s\nwant %s", strings.Join(kinds, ","), want)+ }+ if got := tsNames(o.Get("tools")); strings.Join(got, ",") != "Bash,ToolSearch" {+ t.Fatalf("tools = %v", got)+ }+}++// TestLoadedToolsWhereNotTaken: where the item isn't taken the request is+// built as before #2660: every tool top-level, no additional_tools. So is a+// deferred tool no result in the history loaded (a compacted history), and+// a tool a reference names that wasn't deferred.+func TestLoadedToolsWhereNotTaken(t *testing.T) {+ for i, body := range tsRequests {+ o := tsBuild(t, body, false)+ if strings.Contains(o.Raw, "additional_tools") {+ t.Fatalf("request %d: %s", i+1, o.Raw)+ }+ want := []string{"Bash", "ToolSearch", "mcp__probe__read_a", "mcp__probe__read_b"}[:2+i]+ if got := tsNames(o.Get("tools")); !reflect.DeepEqual(got, want) {+ t.Fatalf("request %d's tools = %v, want %v", i+1, got, want)+ }+ }+ compacted := tsRequest([]string{tsTools0, tsReadA, tsPlaceholder}, `{"role":"user","content":"summary of what was done"}`)+ o := tsBuild(t, compacted, true)+ if strings.Contains(o.Raw, "additional_tools") || strings.Join(tsNames(o.Get("tools")), ",") != "Bash,ToolSearch,mcp__probe__read_a" {+ t.Fatalf("compacted: %s", o.Raw)+ }+ notDeferred := tsRequest([]string{tsTools0, `{"name":"mcp__probe__read_a","input_schema":{"type":"object"}}`}, tsTurn1, tsSearchA)+ o = tsBuild(t, notDeferred, true)+ if strings.Contains(o.Raw, "additional_tools") || len(o.Get("tools").Array()) != 3 {+ t.Fatalf("not deferred: %s", o.Raw)+ }+}++// TestLoadsInPlaceScope: OpenAI's own API is sent the item, and a provider+// the user said takes it; xAI, a relay, the ChatGPT backend, Azure and a+// plugin aren't.+func TestLoadsInPlaceScope(t *testing.T) {+ for _, c := range []struct {+ p provider.Provider+ want bool+ }{+ {provider.Provider{ID: "openai", Responses: "https://api.openai.com/v1"}, true},+ {provider.Provider{ID: "openai-eu", Responses: "https://eu.api.openai.com/v1"}, true},+ {provider.Provider{ID: "lookalike", Responses: "https://api.openai.com.example.net/v1"}, false},+ {provider.Provider{ID: "xai", Responses: "https://api.x.ai/v1"}, false},+ {provider.Provider{ID: "relay", Responses: "https://relay.example.com/v1"}, false},+ {provider.Provider{ID: "relay", Responses: "https://relay.example.com/v1", AdditionalTools: true}, true},+ {provider.Provider{ID: "codex", Responses: "https://api.openai.com/v1", Account: &provider.Account{Agent: "codex"}}, false},+ {provider.Provider{ID: "az", Responses: "https://x.openai.azure.com/openai/v1"}, false},+ } {+ if got := loadsInPlace(c.p); got != c.want {+ t.Errorf("%s %s: %v, want %v", c.p.ID, c.p.Responses, got, c.want)+ }+ }+}++// TestLoadedToolsThroughTheGateway: a provider set to take the item gets+// it from /v1/messages; one that isn't gets the request as before; one+// that turns the item away is asked again with every tool top-level and+// isn't sent it again.+func TestLoadedToolsThroughTheGateway(t *testing.T) {+ f := &fake{t: t, reply: sse(+ `data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`,+ `data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)}+ setup(t, provider.Responses, f)+ ask := func() gjson.Result {+ t.Helper()+ if code, out := post(t, "/v1/messages", tsRequests[1]); code != 200 {+ t.Fatalf("status %d: %s", code, out)+ }+ return gjson.ParseBytes(f.got)+ }+ if got := ask(); strings.Contains(got.Raw, "additional_tools") || len(got.Get("tools").Array()) != 3 {+ t.Fatalf("not set, the request is as before: %s", got.Raw)+ }++ p, err := provider.Find("fake")+ if err != nil {+ t.Fatal(err)+ }+ p.AdditionalTools = true+ if err := provider.Save(*p); err != nil {+ t.Fatal(err)+ }+ got := ask()+ if !strings.Contains(got.Raw, `"additional_tools"`) || strings.Join(tsNames(got.Get("tools")), ",") != "Bash,ToolSearch" {+ t.Fatalf("set, the loaded tool goes where it was loaded: %s", got.Raw)+ }++ f.calls = 0+ f.refuse = func(b []byte) (int, string) {+ if strings.Contains(string(b), `"additional_tools"`) {+ return http.StatusBadRequest, `{"error":{"message":"Invalid value: 'additional_tools'. Supported values are: 'message', 'function_call'.","type":"invalid_request_error","param":"input[3].type"}}`+ }+ return 0, ""+ }+ srv := New()+ for i := range 2 {+ if code, out := postTo(t, srv, "/v1/messages", tsRequests[1]); code != 200 {+ t.Fatalf("try %d: status %d: %s", i, code, out)+ }+ got := gjson.ParseBytes(f.got)+ if strings.Contains(got.Raw, "additional_tools") || len(got.Get("tools").Array()) != 3 {+ t.Fatalf("refused, asked again as before: %s", got.Raw)+ }+ }+ if f.calls != 3 {+ t.Fatalf("calls = %d, want the refused one, its retry, and the next without the item", f.calls)+ }+}diff --git a/internal/gateway/responses.go b/internal/gateway/responses.goindex 714bd51ee..1dab20b84 100644--- a/internal/gateway/responses.go+++ b/internal/gateway/responses.go@@ -1094,6 +1094,25 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {// sealed reasoning, and may refuse an item without it.replay := replaysReasoning(model, host)var input []any+ // a deferred tool a result loaded goes in an additional_tools item+ // after that result and the results beside it, once, where the+ // upstream takes one (Request.LoadedInPlace, #2660)+ deferred := map[string]Tool{}+ placed := map[string]bool{}+ if r.LoadedInPlace {+ for _, t := range r.Tools {+ if t.Deferred {+ deferred[t.Name] = t+ }+ }+ }+ var loaded []any+ flushLoaded := func() {+ if len(loaded) > 0 {+ input = append(input, map[string]any{"type": "additional_tools", "role": "developer", "tools": loaded})+ loaded = nil+ }+ }// a second answer to one call is left out, as the Chat and Messages// builds leave it (dropSecondAnswers)for _, m := range dropSecondAnswers(r.Messages) {@@ -1102,6 +1121,7 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {if len(content) == 0 {return}+ flushLoaded()input = append(input, map[string]any{"type": "message", "role": m.Role, "content": content})content = nil}@@ -1131,14 +1151,17 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {// a Responses API's own sealed reasoning goes back as// it came: id, summary and encrypted_content (#1445)flushMsg()+ flushLoaded()input = append(input, p.Sealed)} else if replay && p.Text != "" {flushMsg()+ flushLoaded()input = append(input, map[string]any{"type": "reasoning", "summary": []any{},"content": []map[string]any{{"type": "reasoning_text", "text": p.Text}}})}case ToolCall:flushMsg()+ flushLoaded()id := p.IDif id == "" {id = "call_" + newID()@@ -1163,10 +1186,17 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {output = items}input = append(input, map[string]any{"type": "function_call_output", "call_id": p.CallID, "output": output})+ for _, name := range p.Loads {+ if t, ok := deferred[name]; ok && !placed[name] {+ placed[name] = true+ loaded = append(loaded, responsesTool(t))+ }+ }}}flushMsg()}+ flushLoaded()if replay {// each step that makes a call, or follows a tool output, leads with// its reasoning, or with a space's (#1592, #1822)@@ -1255,14 +1285,10 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {if len(r.Tools) > 0 || r.WebSearch {var tools []map[string]anyfor _, t := range r.Tools {- // strict is said, as Codex says it: left out, the ChatGPT- // backend holds the schema to strict mode's rules and refuses a- // pattern with a lookaround (MiniMax Code's path, #383)- tool := map[string]any{"type": "function", "name": t.Name, "description": t.Description, "strict": t.Strict}- if len(t.Schema) > 0 {- tool["parameters"] = t.Schema+ if placed[t.Name] {+ continue // offered where it was loaded}- tools = append(tools, tool)+ tools = append(tools, responsesTool(t))}if r.WebSearch {tools = append(tools, map[string]any{"type": "web_search"})@@ -1272,7 +1298,9 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {include = append(include, "web_search_call.action.sources")}}- out["tools"] = tools+ if len(tools) > 0 {+ out["tools"] = tools+ }switch {case r.ToolChoice == "auto" || r.ToolChoice == "none" || r.ToolChoice == "required":out["tool_choice"] = r.ToolChoice@@ -1303,6 +1331,18 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {return pairToolItems(b)}+// responsesTool is t as a Responses function tool. strict is said, as+// Codex says it: left out, the ChatGPT backend holds the schema to strict+// mode's rules and refuses a pattern with a lookaround (MiniMax Code's+// path, #383).+func responsesTool(t Tool) map[string]any {+ tool := map[string]any{"type": "function", "name": t.Name, "description": t.Description, "strict": t.Strict}+ if len(t.Schema) > 0 {+ tool["parameters"] = t.Schema+ }+ return tool+}+type rUsage struct {InputTokens int `json:"input_tokens"`OutputTokens int `json:"output_tokens"`diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex aa40c7955..940867663 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -1540,6 +1540,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {if !in.CodexAsSent && old != nil {in.CodexAsSent = old.CodexAsSent}+ // and additional_tools taken, set with `magpie provider+ // set <id> additional-tools=on` (#2660)+ if !in.AdditionalTools && old != nil {+ in.AdditionalTools = old.AdditionalTools+ }// each account's own proxy likewise: {} clears themif in.AccountProxies == nil && old != nil {in.AccountProxies = old.AccountProxiesdiff --git a/internal/provider/provider.go b/internal/provider/provider.goindex 5fd0acd16..a36e7df0f 100644--- a/internal/provider/provider.go+++ b/internal/provider/provider.go@@ -228,6 +228,15 @@ type Provider struct {// fitting, which a backend that isn't OpenAI's needs (#350).CodexAsSent bool `json:"codexAsSent,omitempty"`+ // AdditionalTools says the provider's Responses API takes an+ // additional_tools input item, as OpenAI's does: a deferred tool an+ // Anthropic client's tool search loaded goes to it in such an item+ // where the search loaded it, not in the top-level tools, which keeps+ // the prompt's cached prefix (#2660). OpenAI's own API is sent one+ // without it; another vendor isn't unless this is set, since xAI's+ // turns the item away (#350).+ AdditionalTools bool `json:"additionalTools,omitempty"`+// NativeCompaction has Codex's compaction_trigger go to the provider// as Codex sent it, and the compaction the provider writes back go to// Codex as it came (#1099), where magpie otherwise asks the model for