diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 90a5d5091..916dda465 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -268,7 +268,7 @@ recorded as a prediction failure (`noPrediction`). - A Responses request's top-level `access_programs`, the Cyber program Codex asks the model under (`{"cyber":"standard"}` on a subagent it inherits, OpenAI's Daybreak programs, magpie-releases#18), goes only where Codex itself would send it: codex-rs sends it with a ChatGPT sign-in, or an API key on its provider named `openai`, and to no other provider (`cyber_access_program.rs`, `for_auth`, `for_provider`). In `forwardOnce`, relayed or built (from Chat too), it goes as it came to a ChatGPT (Codex) account, a host ending in `openai.com`, another magpie (`IsRemoteMagpie`, whose own upstream decides) and a relay set `codexAsSent` when Codex sent the request; every other Responses upstream is sent the request without it (`keepsAccessPrograms`, `withoutTopMember`, the rest byte for byte). OpenCode Go answered it, for DeepSeek and GLM, with 503 "Upstream request failed: Endpoint is unavailable." and 200 without it or with null; its Haiku took it (#3172, three reporters' real A/B runs). It is taken out before the user's extraBody is merged, so an `access_programs` written there still goes. Chat and Messages builds never carry it; a Chat request relayed as it came keeps whatever its client wrote. `TestAccessProgramsGoToOpenAIAlone`, `TestWithoutTopMember`, `TestCodexAccessProgramsReachBackend`. - 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 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 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 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`), for a ChatGPT (Codex) account, and for a provider set `additionalTools` (`magpie provider set additional-tools=on`); `additional-tools=off` (`additionalToolsOff`) turns it off even where it is the default, and `default` goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into `tools`, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) 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`, `TestCodexAccountLoadsInPlace`. - 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 thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`. - Every thinking block a Messages client gets says a `signature`, a string, as Anthropic's own do (its stream starts each block with `"signature": ""`): Grok Build reads `ContentBlock::Thinking` as `{thinking, signature}`, both required, and turned a whole reply away, "missing field `signature`" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (`anthropicEncoder.thinking`), `renderAnthropic` and `whole_stream.go` write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (`sigFieldTidy` in [`thinking_signature.go`](../../internal/gateway/thinking_signature.go), in `passthrough`); a block already signed goes byte for byte, and `redacted_thinking` is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (`anthropicBody` leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block. `TestMessagesThinkingIsSigned`, `TestSignedThinkingRelayedAsItCame`. diff --git a/internal/cli/additional_tools_cli_test.go b/internal/cli/additional_tools_cli_test.go index 576ed13e8..f57f0039a 100644 --- a/internal/cli/additional_tools_cli_test.go +++ b/internal/cli/additional_tools_cli_test.go @@ -14,8 +14,15 @@ func TestAdditionalToolsPair(t *testing.T) { 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) + // off turns magpie's own default off too (a ChatGPT account's, #4738) + if err := applyPairs(&p, []string{"additional-tools=off"}); err != nil || p.AdditionalTools || !p.AdditionalToolsOff { + t.Fatalf("off: %v %v %v", err, p.AdditionalTools, p.AdditionalToolsOff) + } + if err := applyPairs(&p, []string{"additional-tools=on"}); err != nil || !p.AdditionalTools || p.AdditionalToolsOff { + t.Fatalf("on after off: %v %v %v", err, p.AdditionalTools, p.AdditionalToolsOff) + } + if err := applyPairs(&p, []string{"additional-tools=default"}); err != nil || p.AdditionalTools || p.AdditionalToolsOff { + t.Fatalf("default: %v %v %v", err, p.AdditionalTools, p.AdditionalToolsOff) } 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.go index d35855637..9839bdd00 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -50,7 +50,9 @@ const providerUsage = `usage: false 429 (Codex's, Claude Code's, Hermes' old persona) with a zero-width space 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 tools + keeps the cache); OpenAI's API and a ChatGPT (Codex) account do so by + default; additional-tools=off puts it with the other tools, + additional-tools=default is magpie's patience=2m keeps a request to it alone (not through a group) that long while it is busy or briefly rate limited, asking again after a pause (at most 4m); patience=off hands the agent the error at once; @@ -1148,14 +1150,18 @@ func applyPairs(p *provider.Provider, pairs []string) error { 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) + // where it was loaded, which keeps the cached prefix (#2660); + // off: in the tools, where magpie's default sends the item + // (OpenAI's API, a ChatGPT account, #4738); default: magpie's switch strings.ToLower(v) { case "on", "yes": - p.AdditionalTools = true - case "default", "no", "off": - p.AdditionalTools = false + p.AdditionalTools, p.AdditionalToolsOff = true, false + case "off", "no": + p.AdditionalTools, p.AdditionalToolsOff = false, true + case "default": + p.AdditionalTools, p.AdditionalToolsOff = false, false default: - return fmt.Errorf("additional-tools=on|default, not %q", v) + return fmt.Errorf("additional-tools=on|off|default, not %q", v) } case "patience": // how long a request to the provider alone is kept while it diff --git a/internal/gateway/codex_access_programs_test.go b/internal/gateway/codex_access_programs_test.go index d0e2bb6ce..bdec8fbd4 100644 --- a/internal/gateway/codex_access_programs_test.go +++ b/internal/gateway/codex_access_programs_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "slices" "strings" "sync" "testing" @@ -265,3 +266,45 @@ func TestAccessProgramsNullKept(t *testing.T) { t.Fatalf("built %s", m["access_programs"]) } } + +// TestCodexAccountLoadsInPlace (#4738, infinitex233): Claude Code's tool +// search through a ChatGPT account sends the tool it loaded to the backend +// in an additional_tools item where the search loaded it, so the tools +// and every earlier item stay as the request before sent them; set +// additional-tools=off, the tool goes in the tools as before. +func TestCodexAccountLoadsInPlace(t *testing.T) { + codexSignedIn(t) + d := daybreak(t) + body := func(i int) string { + return strings.Replace(tsRequests[i], `"model":"m1"`, `"model":"codex/gpt-daybreak-blue-latest"`, 1) + } + ask := func(i int) gjson.Result { + t.Helper() + if code, out := post(t, "/v1/messages", body(i)); code != 200 { + t.Fatalf("request %d: %d %s", i+1, code, out) + } + return gjson.ParseBytes(d.last(t)) + } + first, second := ask(0), ask(1) + if got := tsNames(second.Get("tools")); strings.Join(got, ",") != strings.Join(tsNames(first.Get("tools")), ",") { + t.Fatalf("the loaded tool changed the tools: %v, before %v", got, tsNames(first.Get("tools"))) + } + var item gjson.Result + second.Get("input").ForEach(func(_, it gjson.Result) bool { + if it.Get("type").String() == "additional_tools" { + item = it + } + return true + }) + if strings.Join(tsNames(item.Get("tools")), ",") != "mcp__probe__read_a" { + t.Fatalf("no additional_tools item with read_a: %s", second.Get("input").Raw) + } + + os.MkdirAll(filepath.Dir(provider.Path()), 0o755) + os.WriteFile(provider.Path(), mustJSON(map[string]any{"providers": []any{map[string]any{"id": "codex", "additionalToolsOff": true}}}), 0o600) + provider.ForgetAccounts() + off := ask(1) + if strings.Contains(off.Get("input").Raw, "additional_tools") || !slices.Contains(tsNames(off.Get("tools")), "mcp__probe__read_a") { + t.Fatalf("off, the tool goes in the tools: %s", off.Raw) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c6afc1f31..830e95b6a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6814,16 +6814,26 @@ const additionalToolsItem = "additional_tools" // 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. +// (provider.Provider.AdditionalTools), and a ChatGPT (Codex) account: +// the ChatGPT backend takes the item where it was loaded, the model calls +// the tools in it, and the cached prefix is kept (#4738: 7680 tokens read +// from cache on each load where it read none with the tools moved up). +// Nothing else is, unless the user says so: xAI's Responses API answers +// 422 "unknown item type" (#350), and a relay, another vendor's sign-in +// or a plugin's vendor hasn't been tried. additional-tools=off +// (AdditionalToolsOff) turns the default off. func loadsInPlace(p provider.Provider) bool { + if p.AdditionalToolsOff { + return false + } if p.AdditionalTools { return true } + if p.Account != nil { + return p.Account.Agent == "codex" + } h := p.Host() - return p.Account == nil && !p.IsPlugin() && !p.IsAzure() && (h == "api.openai.com" || strings.HasSuffix(h, ".api.openai.com")) + return !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 diff --git a/internal/gateway/loaded_in_place_test.go b/internal/gateway/loaded_in_place_test.go index 2c6f9643d..3cb5012e7 100644 --- a/internal/gateway/loaded_in_place_test.go +++ b/internal/gateway/loaded_in_place_test.go @@ -185,9 +185,10 @@ func TestLoadedToolsWhereNotTaken(t *testing.T) { } } -// 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. +// TestLoadsInPlaceScope: OpenAI's own API and a ChatGPT (Codex) account +// are sent the item (#4738), and a provider the user said takes it; xAI, a +// relay, another vendor's sign-in, Azure and a plugin aren't, nor one the +// user turned it off for. func TestLoadsInPlaceScope(t *testing.T) { for _, c := range []struct { p provider.Provider @@ -199,7 +200,11 @@ func TestLoadsInPlaceScope(t *testing.T) { {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: "codex", Responses: "https://chatgpt.com/backend-api/codex", Account: &provider.Account{Agent: "codex"}}, true}, + {provider.Provider{ID: "codex", Responses: "https://chatgpt.com/backend-api/codex", Account: &provider.Account{Agent: "codex"}, AdditionalToolsOff: true}, false}, + {provider.Provider{ID: "openai", Responses: "https://api.openai.com/v1", AdditionalToolsOff: true}, false}, + {provider.Provider{ID: "copilot", Responses: "https://api.githubcopilot.com", Account: &provider.Account{Agent: "copilot"}}, false}, + {provider.Provider{ID: "copilot", Responses: "https://api.githubcopilot.com", Account: &provider.Account{Agent: "copilot"}, AdditionalTools: true}, true}, {provider.Provider{ID: "az", Responses: "https://x.openai.azure.com/openai/v1"}, false}, } { if got := loadsInPlace(c.p); got != c.want { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index ebe5407fd..15952429d 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1798,6 +1798,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if !in.AdditionalTools && old != nil { in.AdditionalTools = old.AdditionalTools } + if !in.AdditionalToolsOff && old != nil { + in.AdditionalToolsOff = old.AdditionalToolsOff + } // and how long a request to it alone is kept while it is // busy, set with `magpie provider set patience=` if in.Patience == 0 && old != nil { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 9fa801ac0..9e9d8eb19 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -301,10 +301,15 @@ type Provider struct { // 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). + // the prompt's cached prefix (#2660). OpenAI's own API and a ChatGPT + // (Codex) account are sent one without it (#4738: the ChatGPT backend + // takes the item where it was loaded, and its cache is kept); another + // vendor isn't unless this is set, since xAI's turns the item away + // (#350). AdditionalTools bool `json:"additionalTools,omitempty"` + // AdditionalToolsOff, `additional-tools=off`, sends a loaded tool in + // the top-level tools even where magpie's default would send the item. + AdditionalToolsOff bool `json:"additionalToolsOff,omitempty"` // Patience is how many seconds more a request to this provider alone, // not through a group, may be kept once it has failed in a way that @@ -861,7 +866,7 @@ func accountSettings(a, pk Provider) Provider { a.PromptAsWritten = pk.PromptAsWritten // a deferred tool a tool search loaded goes where it was loaded, set // with `magpie provider set additional-tools=on` (#2660, #4738) - a.AdditionalTools = pk.AdditionalTools + a.AdditionalTools, a.AdditionalToolsOff = pk.AdditionalTools, pk.AdditionalToolsOff // Send requests unmasked, the user's for a subscription and a // plugin's provider too (isee1_1 on Discord) a.Unredacted = pk.Unredacted