xianfeng-zhu (#3386): Cursor's Private Inference on magpie's /v1/chat/completions, a Gemini model behind it, failed every turn that made a tool call with AI_TypeValidationError at choices[0].delta.tool_calls[0].index ("expected number, received undefined"), then a 499 loop; turns without tools went fine. Gemini's OpenAI-compatible API sends its calls with no index (Linka's frames in gemini_compat_cut_test.go have none either), where the OpenAI contract has one on every fragment, and a relayed stream went on without one. The AI SDK's OpenAI provider, which the report names as what Cursor reads Chat with, checks every chunk and turns that one away, so the call is never made. OpenAI's own node SDK, through its stream helper, keeps no call at all. chatTidy, which already mends a relayed Chat stream's empty ids, empty names and "stop" after calls, now gives a fragment with no index (none, or null) the index of its call (streamCallIndexes.give). A fragment with an id other than the open call's, or after the first in its delta, starts the next call, as chatDecoder reads a new id; any other goes on with the open one. So two calls in chunks of their own are 0 and 1. Given both 0, as their place in the delta would give them, OpenAI's node SDK merged them into one call with both arguments run together. A fragment with an index keeps it, and a stream whose calls have theirs goes as it came. It runs before the ids are mended, so a call with no id either (#3386's chunk) gets both. Not changed: the translations write an index already (chatEncoder, chatWholeEvents), and a whole reply's message needs none. Nor is a call given a type: Gemini's frames have "type": "function". The report's chunk has neither an id nor a type, and is taken as cut short: magpie gives a call with no id one (#2611, v0.1.1277), so the chunk it sent would have had one. What was run (tree e6023c66, ona93190ae, go1.26.8): a real run: magpie built ata93190aeand at this commit (go build -tags nogui), magpie serve in a sandbox HOME, its provider's Chat URL a local server replaying Linka's frames (the call, its signature and the usage in one chunk, then "stop", then [DONE]) under gemini-4-argon, so the Gemini paths run as for Google's host (geminiCompat). Clients on magpie's /v1/chat/completions, with the tool codemode: curl, the chunk magpie sends on: main, the call with no index; this change, index 0 (0 and 1 with the second call below) @ai-sdk/openai 2.0.136 (ai 5.0.281), streamText: main: AI_TypeValidationError, path choices, 0, delta, tool_calls, 0, index, "Invalid input: expected number, received undefined"; no tool-call this change: tool-call codemode {"code":"run()"}, finish tool-calls @ai-sdk/openai 2.0.48 and 2.0.122, older releases that turn away a new call with no id (2.0.48 one with no type too): main, the same validation error; this change, the call openai 5.23.2, chat.completions.stream and finalChatCompletion: main: no tool_calls (finish_reason tool_calls) this change: call_1 codemode {"code":"run()"} @ai-sdk/openai-compatible 1.0.59, which gives a missing index the call's place in its delta: the call, on main and with this change with a second call in a chunk of its own (made up from Linka's frame, id call_2): @ai-sdk/openai 2.0.48, 2.0.122 and 2.0.136: main, the validation error for each; this change, both calls openai: main, no tool_calls; this change, call_1 {"code":"run()"} and call_2 {"code":"two()"} @ai-sdk/openai-compatible: both calls, on main and with this change the replay sending both calls at index 0, as their place in the delta would give them: openai keeps one call, id call_2, arguments {"code":"run()"}{"code":"two()"}, on main and with this change, which keeps an index the upstream sent #3386's chunk as the report shows it, the call with no id and no type: this change sends it on with index 0 and an id (#2611's); @ai-sdk/openai 2.0.122 and 2.0.136 make the call, 2.0.48 throws "Expected 'function' type." and openai "tool call snapshot missing `type`" two such calls, each in a chunk of its own: nothing tells them apart, here as in chatDecoder, so both go with index 0 (the second is given its id after, where its signature is carried); @ai-sdk/openai 2.0.136 makes both calls, 2.0.122 the first only, 2.0.48 and openai throw as above broken by hand, with this change: chatTidy without the give step: TestChatTidyGivesCallsAnIndex: no line's calls have an index ("line 4: indexes [[-1 -1]], want [[1 2]]") TestGeminiCompatRelayedCallsHaveAnIndex: every case, "call 0 went with index <nil>, want 0" go test -race -count=20 -cpu 1,2 of those two, TestChatTidy* and TestStreamedCallGivenAnID: ok gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go vet -tags nogui ./internal/gateway: exit 0; CGO_ENABLED=0 GOOS=darwin and windows go build -tags nogui .: exit 0 full suite, go test -tags nogui -count=1 -timeout 45m ./... (475 s): 63 packages ok. 14 tests red in 7 packages, none in a file this change touches: internal/agent TestHowInstalled, TestOmpDetectedWithPiDir, TestZedAppPath, TestCopilotFolderFromAnIDEPluginIsNotTheCLI and TestQoderSettingsFromAnIDEPluginIsNotTheCLI (qoder-cn): proc.Look keeps "not found" for a tool written in the tick of its folder's last change (#3141). internal/agent TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under /tmp meets a /tmp/.git that isn't a repository of this user's ("error obtaining VCS status: exit status 128"). internal/claudebridge TestCallbackGoesPastTheAgentsProxy, internal/gateway TestClaudeToolCallbackOnANonLoopbackAddress (the package's only red), internal/gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie: the processes this run started had their outgoing connections sent through a proxy (graftcp). internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv TestProgram: umask 077 here; the fixtures' own modes go through it (0444 is written as 0400). internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun 1.3.11 on PATH names port 80 in the request line (#3397). Not tried: Google's own endpoint with a key (the frames are Linka's, as the repo keeps them), Cursor itself, macOS, Windows.
212 lines
10 KiB
Go
212 lines
10 KiB
Go
package gateway
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// Gemini's OpenAI-compatible API, in Linka's frames (Discord): a whole
|
|
// function call, its thought signature and the usage in one chunk, then
|
|
// the finish_reason in the next.
|
|
const (
|
|
compatCall = `data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"extra_content":{"google":{"thought_signature":"c2ln"}},"function":{"arguments":"{\"code\":\"run()\"}","name":"codemode"},"id":"call_1","type":"function"}]},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n"
|
|
compatStop = `data: {"choices":[{"delta":{},"finish_reason":"stop","index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n"
|
|
compatDone = "data: [DONE]\n\n"
|
|
)
|
|
|
|
// compatServer serves reply as a Chat upstream on this machine, where a
|
|
// Gemini model's is taken to be Gemini's OpenAI-compatible API
|
|
// (geminiCompat), and asks it for model at path with body.
|
|
func compatServer(t *testing.T, model, reply, path, body string) (int, string) {
|
|
t.Helper()
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.Copy(io.Discard, r.Body)
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, reply)
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{model}, Chat: up.URL + "/v1"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return post(t, path, strings.ReplaceAll(body, "MODEL", "up/"+model))
|
|
}
|
|
|
|
// compatBare is compatCall without the usage: the generation wasn't
|
|
// counted as done.
|
|
var compatBare = strings.Replace(compatCall, `,"usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}`, "", 1)
|
|
|
|
// The upstream hung up between the call and its finish_reason. Gemini's
|
|
// OpenAI-compatible API counts the usage only once the generation is
|
|
// done, so a call chunk carrying it lost only the finish_reason: the
|
|
// client relayed to gets it, "tool_calls", where Pi threw the call away
|
|
// as "Stream ended without finish_reason". Without the usage the reply
|
|
// was cut, and the client is told so, as a Gemini stream's is (#1644).
|
|
func TestGeminiCompatRelayEndedShort(t *testing.T) {
|
|
const ask = `{"model":"MODEL","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}`
|
|
const cut = `data: {"error":{"message":"UP: the reply ended before it was complete","type":"api_error"}}`
|
|
|
|
code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/chat/completions", ask)
|
|
if code != 200 || !strings.Contains(body, `"codemode"`) || strings.Contains(body, "ended before") {
|
|
t.Fatalf("status %d: %s", code, body)
|
|
}
|
|
if !strings.Contains(body, `"finish_reason":"tool_calls"`) || !strings.HasSuffix(strings.TrimSpace(body), compatDone[:len(compatDone)-2]) {
|
|
t.Errorf("a done Gemini reply that lost its finish_reason didn't end with it: %s", body)
|
|
}
|
|
|
|
// text alone, done, ends with "stop"
|
|
text := `data: {"choices":[{"delta":{"role":"assistant","content":"hi"},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1,"prompt_tokens":2049,"total_tokens":2050}}` + "\n\n"
|
|
if _, body := compatServer(t, "gemini-4-argon", text, "/v1/chat/completions", ask); !strings.Contains(body, `"finish_reason":"stop"`) || strings.Contains(body, "ended before") {
|
|
t.Errorf("done text: %s", body)
|
|
}
|
|
|
|
code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/chat/completions", ask)
|
|
if code != 200 || !strings.Contains(body, `"codemode"`) {
|
|
t.Fatalf("status %d: %s", code, body)
|
|
}
|
|
if !strings.HasSuffix(strings.TrimSpace(body), cut) {
|
|
t.Errorf("a cut Gemini reply ended as if whole: %s", body)
|
|
}
|
|
if strings.Contains(body, `"finish_reason":"`) {
|
|
t.Errorf("a cut reply given a finish_reason: %s", body)
|
|
}
|
|
|
|
// whole, with [DONE] or without it, it goes as it came, its one
|
|
// finish_reason "tool_calls" as it made a call (chatTidy, 喜欢一个人
|
|
// on Discord), never a second one added
|
|
for what, reply := range map[string]string{
|
|
"whole": compatCall + compatStop + compatDone,
|
|
"whole, no [DONE]": compatCall + compatStop,
|
|
} {
|
|
code, body := compatServer(t, "gemini-4-argon", reply, "/v1/chat/completions", ask)
|
|
if code != 200 || strings.Contains(body, "ended before") || strings.Count(body, `"finish_reason":"`) != 1 || !strings.Contains(body, `"finish_reason":"tool_calls"`) {
|
|
t.Errorf("%s: %d %s", what, code, body)
|
|
}
|
|
}
|
|
|
|
// another vendor's Chat stream may end whole with neither: it goes as
|
|
// it came, as it did
|
|
for _, reply := range []string{compatCall, compatBare} {
|
|
other := strings.ReplaceAll(reply, "models/gemini-4-argon", "kimi-k3")
|
|
code, body = compatServer(t, "kimi-k3", other, "/v1/chat/completions", ask)
|
|
if code != 200 || strings.Contains(body, "ended before") || strings.Contains(body, `"finish_reason":"`) {
|
|
t.Errorf("another vendor's stream: %d %s", code, body)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Translated, a call whose generation was done ends the turn with the
|
|
// call, for Claude Code to run; a cut one ends with the error, not with a
|
|
// turn that ended with the call never run.
|
|
func TestGeminiCompatTranslatedEndedShort(t *testing.T) {
|
|
const ask = `{"model":"MODEL","max_tokens":32000,"stream":true,"messages":[{"role":"user","content":"hi"}]}`
|
|
_, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", ask)
|
|
if !strings.Contains(body, `"codemode"`) {
|
|
t.Fatalf("the call didn't reach the client: %s", body)
|
|
}
|
|
if _, stops, errs := messageStops(body); errs != 0 || stops != 1 || !strings.Contains(body, `"stop_reason":"tool_use"`) {
|
|
t.Errorf("a done Gemini call didn't end its turn as one (%d stops, %d errors): %s", stops, errs, body)
|
|
}
|
|
|
|
_, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", ask)
|
|
if !strings.Contains(body, `"codemode"`) {
|
|
t.Fatalf("the call didn't reach the client: %s", body)
|
|
}
|
|
if _, stops, errs := messageStops(body); errs != 1 || stops != 0 {
|
|
t.Errorf("a cut Gemini reply ended as a turn (%d stops, %d errors): %s", stops, errs, body)
|
|
}
|
|
|
|
_, body = compatServer(t, "gemini-4-argon", compatCall+compatStop+compatDone, "/v1/messages", ask)
|
|
if _, stops, errs := messageStops(body); errs != 0 || stops != 1 {
|
|
t.Errorf("a whole Gemini reply (%d stops, %d errors): %s", stops, errs, body)
|
|
}
|
|
|
|
// another vendor's Chat stream ends as it did
|
|
other := strings.ReplaceAll(compatBare, "models/gemini-4-argon", "kimi-k3")
|
|
_, body = compatServer(t, "kimi-k3", other, "/v1/messages", ask)
|
|
if _, _, errs := messageStops(body); errs != 0 {
|
|
t.Errorf("another vendor's stream: %s", body)
|
|
}
|
|
|
|
// unstreamed: a done call is the answer, a cut reply a 502
|
|
unstreamed := strings.Replace(ask, `"stream":true`, `"stream":false`, 1)
|
|
code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", unstreamed)
|
|
if code != 200 || !strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"stop_reason":"tool_use"`) {
|
|
t.Errorf("unstreamed done call: %d %s", code, body)
|
|
}
|
|
code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", unstreamed)
|
|
if code != 502 || !strings.Contains(body, "ended before") {
|
|
t.Errorf("unstreamed cut: %d %s", code, body)
|
|
}
|
|
}
|
|
|
|
// A Gemini reply that ended done but inside a line still gets its
|
|
// finish_reason as an event of its own, not as more of that line (#2446).
|
|
func TestGeminiCompatFinishAfterPartialLine(t *testing.T) {
|
|
const ask = `{"model":"MODEL","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}`
|
|
_, body := compatServer(t, "gemini-4-argon", compatCall+`data: {"choi`, "/v1/chat/completions", ask)
|
|
i := strings.Index(body, `"finish_reason":"tool_calls"`)
|
|
if i < 0 {
|
|
t.Fatalf("no finish_reason filled in: %s", body)
|
|
}
|
|
j := strings.LastIndex(body[:i], "data: ")
|
|
if j < 0 || !strings.HasSuffix(body[:j], "\n\n") {
|
|
t.Errorf("the finish_reason began inside the line still pending: %q", body)
|
|
}
|
|
}
|
|
|
|
// Gemini's OpenAI-compatible API sends a call with no index (Linka's
|
|
// frames), where the OpenAI contract has one on every fragment. The AI
|
|
// SDK's OpenAI provider, which Cursor's Private Inference reads Chat with,
|
|
// turned the chunk away ("expected number, received undefined" at
|
|
// tool_calls[0].index), and the call was never made (#3386). Relayed,
|
|
// every call has its index: Linka's call 0, a second call in a chunk of
|
|
// its own 1, and #3386's chunk, with no id either, 0 and an id.
|
|
func TestGeminiCompatRelayedCallsHaveAnIndex(t *testing.T) {
|
|
const ask = `{"model":"MODEL","stream":true,"messages":[{"role":"user","content":"hi"}]}`
|
|
second := strings.NewReplacer(`"call_1"`, `"call_2"`, `run()`, `two()`).Replace(compatCall)
|
|
reported := `data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"extra_content":{"google":{"thought_signature":"c2ln"}},"function":{"arguments":"{\"code\":\"run()\"}","name":"codemode"}}]},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk"}` + "\n\n"
|
|
for _, c := range []struct {
|
|
name, reply string
|
|
ids []string // how each call's id starts
|
|
}{
|
|
{"Linka's call", compatCall + compatStop + compatDone, []string{"call_1"}},
|
|
{"a second call", compatCall + second + compatStop + compatDone, []string{"call_1", "call_2"}},
|
|
{"#3386's chunk", reported + compatStop + compatDone, []string{"call_"}},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
code, body := compatServer(t, "gemini-4-argon", c.reply, "/v1/chat/completions", ask)
|
|
if code != 200 {
|
|
t.Fatalf("status %d: %s", code, body)
|
|
}
|
|
var calls []map[string]any
|
|
for _, ev := range events(body) {
|
|
chs, _ := ev["choices"].([]any)
|
|
for _, ch := range chs {
|
|
d, _ := ch.(map[string]any)["delta"].(map[string]any)
|
|
tcs, _ := d["tool_calls"].([]any)
|
|
for _, tc := range tcs {
|
|
calls = append(calls, tc.(map[string]any))
|
|
}
|
|
}
|
|
}
|
|
if len(calls) != len(c.ids) {
|
|
t.Fatalf("%d calls, want %d: %s", len(calls), len(c.ids), body)
|
|
}
|
|
for i, call := range calls {
|
|
if n, ok := call["index"].(float64); !ok || n != float64(i) {
|
|
t.Errorf("call %d went with index %v, want %d: %s", i, call["index"], i, body)
|
|
}
|
|
if id, _ := call["id"].(string); !strings.HasPrefix(id, c.ids[i]) {
|
|
t.Errorf("call %d went with id %q, want one starting %q", i, id, c.ids[i])
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|