diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f9d842c43..9bbd56ae3 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -390,6 +390,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - 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 trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (`plannedCarrier`, read from `perKeyBarred` without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, `codexCompact` gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 `carrierError` with no upstream asked (#2725, ggbdpq; `TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt`, `TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt`, `TestNativeCompactionDecisionLeavesTheTurnsAlone`). 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`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Model settings, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). A call Codex makes beside the conversation, on a model of its own choosing with the conversation's history in it (`compactionAside`: the guardian's auto-review, on `codex-auto-review` or the model set for it, a memory, a subagent, a title, description, summary, prediction or suggestion), goes on without the seal when the writer isn't among its candidates (`withoutCompaction`), its instructions, turns since and tool calls kept: it isn't refused, and the conversation's own turns are still held to the writer. Relayed to Codex's own sign-in, a compaction recorded as sealed by a provider other than the Codex subscription (Copilot, an API key's) never goes as it came (`foreignToSignin`): such a side call goes without it, a turn or a `/responses/compact` is refused with `checkpointError` (echo_ts: every auto-review after a Copilot compaction was answered 400 `invalid_encrypted_content` by OpenAI; `TestForeignCompactionLeftOutOfAutoReview`). A seal with no record, or one whose provider can't be read, is the sign-in's to judge, as before. One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). 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 route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). 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 compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON), as Codex keeps places in a rollout by byte. A line the full message makes longer in a paginated rollout (a short summary under Codex's long prefix) is never left with magpie's seal, which OpenAI then refused for good (hey_boyce on X: "The encrypted content for item cmp_magpie_… could not be verified"): `fitShorter` writes the summary under a short heading, then cut to fit, then with no heading, and as a last resort a standalone item as `magpie_compaction`, a type Codex reads as unknown and never sends. Inside `replacement_history` such an item would go (Codex sends it as `other`, and OpenAI refuses "Invalid value: 'other'", codex-cli 0.165.0 and 0.169.1), so a compaction or reasoning item retired there is left out with its metadata entry, and one an earlier pass retired there is taken out (`retiredInList`). A pass state from before this (`codex-portable.json` without `refit`) makes one whole pass again for the rollouts left so. The gateway's last line: a 400 naming a `cmp_magpie_` item asks again with its summary message in its place (`withoutItem`, `TestRefusedMagpieCompactionGoesAsText`): a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way. A longer provider id for a paginated rollout leaves that line as it was and moves the thread by its row in Codex's state database alone, where Codex reads a paginated thread's provider from; before, it was refused ("keeps its history by byte, and \"magpie\" is longer than the provider it names", @xMopf7RF on X). With no row to move, it is refused with nothing changed (`sessions.StuckError`), and the Sessions page says why, that the session stays on its provider, and that Delete clears it into magpie's trash (`TestMoveCodexProviderPagedByRow`, `TestMoveCodexProviderPagedNoRow`, `sessions-codex-provider-stuck.test.cjs`). It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does, and by codex-cli 0.169.1 against OpenAI itself with the reporter's item and an id-less one retired, a retired reasoning item in its replacement_history taken out. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. - The summary ask `codexCompact` sends a provider that isn't OpenAI's or a Codex account carries Codex's developer messages as system ones (`forVendor`, `developerItemsAsSystem`, #2955: a chat-only vendor refuses developer). A relay of a ChatGPT account takes developer alone and refuses system (sub2api, #5067), so a summary refused "System messages are not allowed", or with a relay's bare "Upstream request failed", as a 4xx or as an error event in a 200 stream (`roleRefused`), is asked once more with the roles as Codex sent them (`askAsSent`), then as text, then made by magpie, so such a refusal no longer counts toward the hold (`compactFails`). A summary with no developer message isn't asked the same twice. `TestCodexCompactSystemRefusedAsksAgainDeveloper`, `TestCodexCompactSystemRefusedEverywhereNeverHolds`. +- Open Design's amr-link (its plugin, `opendesign`, or a provider at amr-link.open-design.ai: `openDesign`) answered Codex's compaction on every model with 400 `[code=upstream_error] Provider returned error`, while the turns around it went through (Mugenrikka on X; not tried on a real account). Codex's compaction is its one request with `"tools": []`, and the summary ask adds `tool_choice` and `parallel_tool_calls` for #292's relays; a Responses request relayed to amr-link goes without an empty `tools` and the two beside it (`withoutEmptyTools`, in `passthrough`), and every other upstream is sent them as before. A summary amr-link still refuses in those words counts as `upstreamFailed` (`vendorUnsaidWords`): it is asked as sent, then as text, then made by magpie, never handed to Codex as the 400. `TestOpenDesignCompactionSendsNoEmptyTools`, `TestOpenDesignCompactionRefusedAsksAsText` in [`opendesign_compact_test.go`](../../internal/gateway/opendesign_compact_test.go). - 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 shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, its Lite marker removed from `client_metadata` (`withoutLiteMetadata`), and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A Codex websocket turn repeats the marker in `client_metadata`; leaving it beside a removed `reasoning.context` made a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requires `reasoning.context` to be `all_turns`". A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also 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`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`, `TestFromLiteRemovesOnlyTheWebsocketLiteMarker`, `TestCodexTitleRelayKeepsLiteShapeConsistent`. - 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`. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 6dc0bf5ca..5562c37a9 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -4128,13 +4128,14 @@ func summaryEndedShort(rec *recorder) bool { // upstreamFailed is a relay's own word that the provider behind it turned // the request away, without saying why: "flyapi: Upstream request failed" // came as a 404 (#866), "apex: Upstream request failed" as a 400 -// invalid_request_error (#1511). Codex asking the same relay itself -// compacts, so the summary request is asked again as text, and compacted -// without a model when that fails too. +// invalid_request_error (#1511), Open Design's "[code=upstream_error] +// Provider returned error" as a 400 (vendorUnsaidWords). Codex asking the +// same relay itself compacts, so the summary request is asked again as +// text, and compacted without a model when that fails too. func upstreamFailed(rec *recorder) bool { return rec.status >= 400 && rec.status < 500 && rec.status != http.StatusUnauthorized && rec.status != http.StatusForbidden && rec.status != http.StatusTooManyRequests && - upstreamFailedWords.Match(rec.body.Bytes()) + (upstreamFailedWords.Match(rec.body.Bytes()) || vendorUnsaidWords.Match(rec.body.Bytes())) } var upstreamFailedWords = lazyre.New(`(?i)upstream request failed`) @@ -4152,7 +4153,7 @@ func roleRefused(rec *recorder, err error) bool { if rec.status >= 400 { return upstreamFailed(rec) || rec.status == http.StatusBadRequest && systemRefusedWords.Match(rec.body.Bytes()) } - return err != nil && (systemRefusedWords.MatchString(err.Error()) || upstreamFailedWords.MatchString(err.Error())) + return err != nil && (systemRefusedWords.MatchString(err.Error()) || upstreamFailedWords.MatchString(err.Error()) || vendorUnsaidWords.MatchString(err.Error())) } var systemRefusedWords = lazyre.New(`(?i)system messages are not allowed`) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 85e91f950..219df1d91 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6958,6 +6958,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if refusesLoneToolChoice(p) { body = withoutLoneToolChoice(body) } + // Open Design's amr-link answers Codex's compaction summary, its + // one request with no tools, 400 upstream_error: it is sent no + // empty tools and no choice beside them (opendesign_tools.go) + if openDesign(p) { + body = withoutEmptyTools(body) + } case provider.Chat: if p.RejectsTemperature(model) { // a model whose list refuses them (a plugin's temperature: diff --git a/internal/gateway/opendesign_compact_test.go b/internal/gateway/opendesign_compact_test.go new file mode 100644 index 000000000..b6afd3c13 --- /dev/null +++ b/internal/gateway/opendesign_compact_test.go @@ -0,0 +1,109 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// amrRefusal is how Open Design's amr-link turns a request away for the +// vendor behind it (#5219, #4852): a 400 upstream_error that names no +// field. +const amrRefusal = `{"error":{"message":"[code=upstream_error] Provider returned error","type":"upstream_error","code":"upstream_error"}}` + +var amrSummary = sse( + `data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"OD SUMMARY"}]}}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`) + +// openDesignCompaction posts Codex Desktop 26.1007's real compaction +// (compaction2352) at Open Design's plugin, its model on chat completions +// and served on Responses too, as amr-link serves every model (FAKE_ALSO), +// to a vendor that refuses what refuse says. It gives Codex's answer and +// the bodies the vendor got. +func openDesignCompaction(t *testing.T, refuse func(b []byte) bool) (*httptest.ResponseRecorder, [][]byte) { + t.Helper() + t.Setenv("FAKE_ALSO", "1") + var mu sync.Mutex + var got [][]byte + pid := besideFake(t, "opendesign", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, b) + mu.Unlock() + if !strings.HasSuffix(r.URL.Path, "/responses") { + t.Errorf("asked at %s", r.URL.Path) + } + if refuse(b) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, amrRefusal) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, amrSummary) + })) + body, turn := compaction2352(t) + body = strings.Replace(body, `"model":"fake/m1"`, `"model":"`+pid+`/fake-also"`, 1) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)) + req.Header.Set("User-Agent", "Codex Desktop/26.1007 (Mac OS 26.2.0; arm64)") + req.Header.Set("originator", "Codex Desktop") + req.Header.Set(turnMetadataHeader, turn) + New().Handler().ServeHTTP(rec, req) + mu.Lock() + defer mu.Unlock() + return rec, got +} + +// Mugenrikka on X: Codex compacting on any Open Design model got 400 +// upstream_error, while the turns around it went through. Codex's +// compaction is its one request with no tools ("tools": []), and magpie's +// summary ask added tool_choice and parallel_tool_calls beside them. With +// nothing to call, amr-link is sent none of the three, and the summary +// comes back. +func TestOpenDesignCompactionSendsNoEmptyTools(t *testing.T) { + lone := func(b []byte) bool { + var q map[string]json.RawMessage + json.Unmarshal(b, &q) + var tools []any + json.Unmarshal(q["tools"], &tools) + _, choice := q["tool_choice"] + _, parallel := q["parallel_tool_calls"] + _, listed := q["tools"] + return len(tools) == 0 && (listed || choice || parallel) + } + rec, got := openDesignCompaction(t, lone) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"type":"compaction"`) { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if len(got) != 1 { + t.Errorf("asked %d times, want once", len(got)) + } + if len(got) > 0 && (lone(got[0]) || !bytes.Contains(got[0], []byte("CONTEXT CHECKPOINT COMPACTION"))) { + t.Errorf("amr-link got %.600s", got[0]) + } +} + +// A summary amr-link refuses in its unsaid words anyway (here over the +// history's tool calls, which Anthropic's API refuses with no tools +// declared) is asked again with the conversation as text, as a relay's +// "Upstream request failed" is, and Codex gets the summary, not the 400. +func TestOpenDesignCompactionRefusedAsksAsText(t *testing.T) { + calls := func(b []byte) bool { return bytes.Contains(b, []byte(`"function_call"`)) } + rec, got := openDesignCompaction(t, calls) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"type":"compaction"`) { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if n := len(got); n < 2 || calls(got[n-1]) || !bytes.Contains(got[n-1], []byte("This is the conversation so far")) { + t.Errorf("asked %d times; last %.600s", n, got[len(got)-1]) + } + if strings.Contains(rec.Body.String(), "magpie could not") { + t.Errorf("compacted locally: %s", rec.Body) + } +} diff --git a/internal/gateway/opendesign_tools.go b/internal/gateway/opendesign_tools.go new file mode 100644 index 000000000..381f964b5 --- /dev/null +++ b/internal/gateway/opendesign_tools.go @@ -0,0 +1,55 @@ +package gateway + +import ( + "encoding/json" + + "github.com/yetone/magpie/internal/lazyre" + "github.com/yetone/magpie/internal/provider" +) + +// Open Design Cloud's amr-link answers a request it, or the vendor behind +// it, turns away with a 400 "[code=upstream_error]" and often no more than +// "Provider returned error". Codex's compaction is the one request Codex +// makes with no tools ("tools": [], codex-26.1007-compaction.json), and +// magpie's summary ask for it adds the tool_choice and parallel_tool_calls +// a relay of the ChatGPT backend checks for (#292): every model of the +// plan answered that summary 400 upstream_error while the turns around it, +// tools declared, went through (Mugenrikka on X). With no tools those two +// ask nothing, and a Chat API (OpenAI's own) refuses them, and an empty +// tools list, outright; so none of the three goes to amr-link. + +// openDesign is whether p is Open Design Cloud: its plugin, or a provider +// at amr-link's address. +func openDesign(p provider.Provider) bool { + if p.PluginProvider() == "opendesign" { + return true + } + for _, proto := range []provider.Protocol{provider.Responses, provider.Chat, provider.Anthropic} { + if provider.HostOf(p.Base(proto)) == "amr-link.open-design.ai" { + return true + } + } + return false +} + +// withoutEmptyTools is a Responses or Chat body without an empty tools +// list and the tool_choice and parallel_tool_calls beside it; a body +// that declares a tool goes as it came. +func withoutEmptyTools(body []byte) []byte { + if !bodyHas(body, `"tools"`) && !bodyHas(body, `"tool_choice"`) && !bodyHas(body, `"parallel_tool_calls"`) { + return body + } + var q struct { + Tools []json.RawMessage `json:"tools"` + } + if decodeJSON(body, &q) != nil || len(q.Tools) > 0 { + return body + } + return withoutFields(body, "tools", "tool_choice", "parallel_tool_calls") +} + +// vendorUnsaidWords is amr-link's word for a refusal it passes on from the +// vendor behind it, said or not why: a summary ask so refused is asked +// again with the roles as Codex sent them, then as text, then made +// locally (codexCompact), as for a relay's "Upstream request failed". +var vendorUnsaidWords = lazyre.New(`(?i)\[code=upstream_error\]`)