diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index e24b03cc2..95aa01aa3 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -87,6 +87,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - 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)). - A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `{…}`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters), DeepSeek's half-Hermes `` form (#917) and GLM's ``/`` (#906), read by `parseTextCalls`. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A reply whose model made a call itself is left alone. Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`. - Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. +- A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat and Qoder put them in a user message right after the results, and the result says they follow. Command Code puts them in the user's turn after the results, Gemini and Code Assist after the function's response, and Devin in its tool message. Kiro's results hold text alone, so Kiro (the built-in, and its plugin from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin`, `TestCodexToolImageKiro`, and the plugin's `tool-images.test.mjs`. - Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). - An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 or 422 whose error names `extra_body`, `include_thoughts` or thinking at all (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, its least, or at the model's lowest level where it has no `minimal` (`geminiLevels`: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (`geminiRefusedLevel`): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (`levelRefused`), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own `none` or `minimal` that Gemini turns away this way is asked again at the model's lowest level (`onEffort`), and that level goes at the lowest from then on (`turnedAway`); the other still goes as sent, as AI Studio takes `none` from gemini-3.8-flash. A refusal that names the levels the model takes (`effortLevelsNamed`, Command Code's for Qoder's `none`) marks reasoning off as a whole (`offRefused`): both go at the lowest from then on; one that lists the other among the levels taken (`otherOffNamed`, quoted, OpenAI's for gpt-5.1's `minimal`) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking. diff --git a/internal/gateway/tool_images_1861_test.go b/internal/gateway/tool_images_1861_test.go new file mode 100644 index 000000000..be3cc6984 --- /dev/null +++ b/internal/gateway/tool_images_1861_test.go @@ -0,0 +1,73 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// codexViewImage is a Codex turn whose view_image call came back with an +// image, as codex-rs 0.162 sends it (FunctionCallOutputContentItem in +// protocol/src/models.rs; view_image.rs answers with the image alone, its +// detail "high"): the function_call_output's output is a list holding one +// input_image, a data: URL (#1861). +const codexViewImage = `{"model":"m","stream":true,"input":[ +{"type":"message","role":"user","content":[{"type":"input_text","text":"使用computer use截图当前屏幕看下"}]}, +{"type":"function_call","name":"view_image","arguments":"{\"path\":\"/tmp/magpie_icon.png\"}","call_id":"call_view1"}, +{"type":"function_call_output","call_id":"call_view1","output":[{"type":"input_image","image_url":"data:image/png;base64,` + viewedPNG + `","detail":"high"}]} +]}` + +// a 1x1 PNG +const viewedPNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==" + +func codexViewImageRequest(t *testing.T) *Request { + t.Helper() + r, err := parse(provider.Responses, []byte(codexViewImage)) + if err != nil { + t.Fatal(err) + } + return r +} + +// What a plugin on Anthropic's Messages (Kiro's) is handed: the image in +// the tool_result, as an image block of base64 bytes. Kiro's plugin reads it +// there (magpie-community/plugins kiro 0.1.9). +func TestCodexToolImageReachesAnthropicPlugin(t *testing.T) { + var body struct { + Messages []struct { + Content []struct { + Type string `json:"type"` + ToolUseID string `json:"tool_use_id"` + Content []struct { + Type string `json:"type"` + } `json:"content"` + } `json:"content"` + } `json:"messages"` + } + b := buildAnthropic(codexViewImageRequest(t), "claude-sonnet-4.5") + if err := json.Unmarshal(b, &body); err != nil { + t.Fatal(err) + } + last := body.Messages[len(body.Messages)-1].Content + if len(last) != 1 || last[0].Type != "tool_result" || len(last[0].Content) != 1 || last[0].Content[0].Type != "image" { + t.Fatalf("tool_result = %s", b) + } + if !strings.Contains(string(b), `"source":{"type":"base64","media_type":"image/png","data":"`+viewedPNG+`"}`) { + t.Fatalf("the image's bytes aren't in the tool_result: %s", b) + } +} + +// Kiro's built-in sends the image with the message answering the call, as +// #369 made it for Claude Code's. +func TestCodexToolImageKiro(t *testing.T) { + b := buildKiroBody(t, codexViewImageRequest(t), false) + cur := b.ConversationState.CurrentMessage.UserInputMessage + if len(cur.Images) != 1 || cur.Images[0].Format != "png" || cur.Images[0].Source.Bytes != viewedPNG { + t.Fatalf("images = %+v", cur.Images) + } + if rs := cur.Context.ToolResults; len(rs) != 1 || rs[0].ToolUseID != "call_view1" { + t.Fatalf("results = %+v", rs) + } +} diff --git a/internal/provider/migrate_kiro.go b/internal/provider/migrate_kiro.go index 0f17df5ea..5d7cd06ca 100644 --- a/internal/provider/migrate_kiro.go +++ b/internal/provider/migrate_kiro.go @@ -21,7 +21,7 @@ import ( func init() { movers["kiro"] = &mover{ pkg: "@magpie-community/opencode-kiro-auth", - min: "0.1.8", // a tool named past 64 characters sent under a short name, as the built-in (#1393) + min: "0.1.9", // a tool's images reach the model, as the built-in sends them (#1861) agents: []string{"kiro"}, out: func() ([]Moving, error) { var out []Moving