Grok's models (grok-4.6, grok-4.7) write a whole number in a tool call's
arguments with a fraction of zeros. Codex reads exec_command's
yield_time_ms and max_output_tokens as u64/usize and write_stdin's
session_id as i32, though their schemas say "number", and serde turned the
whole call away ("failed to parse function arguments: invalid type:
floating point `2500.0`, expected u64 at line 1 column 77"; `17277.0`,
expected i32), so the turn stopped at its first command. Reported 11 of 11
turns through a sub2api relay in front of grok-4.6 and grok-4.7.
What changed (grok_integral.go):
- grokModel/grokServed: a Grok model is one whose id, as magpie names it
or as it is sent upstream, has a last `/` segment beginning "grok"
(relay/grok-4.6, x-ai/grok-4, the plugin's grok-4.7).
- wholeNums: a streaming scanner over the arguments' JSON text. A number
written with a fraction of zeros and no exponent loses the fraction
(2500.0 -> 2500, -3.00 -> -3, [1.0,2.0] -> [1,2]). Strings, keys, other
fractions (2.5, 2.50) and exponents (1.0e3) stay as written. It holds
only a run of ".0…" until the next byte, so arguments cut into deltas
anywhere come out the same as whole, and the deltas add up to what the
done events say.
- Relayed (passthrough): intTidy, beside nsTidy and built like it, on
Responses (function_call items, argument deltas and done, the completed
response, a whole reply), Chat (tool_calls deltas and messages) and
Messages (tool_use input and input_json_delta), streamed or whole. A
line that carries no call passes as it came. Plugin-served Grok and the
built-in subscription go through the same passthrough.
- Translated: translate sets Request.Grok; encoder() wraps the client's
encoder in wholeEncoder (outside usageEncoder) and render() rewrites the
Result's calls (wholeResult), so every client protocol is covered at
those two choke points.
- Any other model's reply is relayed byte for byte, as before.
- gateway-routing.md says so, and lists the tests.
Scope, against the reporter's 9fd6855b: that commit rewrote only fields a
tool schema typed "integer" or a fixed list of Codex's (codexInts), only
on Responses, and left deltas as they came, so the deltas disagreed with
the done events, and the list missed Codex's other integers (shell's
timeout_ms, sleep's duration_ms, tool_search's limit, the multi-agent
tools' timeout_ms). Codex's own schemas say "number", and JSON has one number type, so 2500 is the same value as
2500.0 for every client; this drops the zero fraction everywhere in a
Grok model's call arguments instead. Its rollout fixtures are kept
verbatim (testdata/grok_integral_args) and its test helpers adapted.
Tests: TestWholeNumsAnyCut (every split point and byte by byte),
TestGrokCallsGiveCodexIntegers (relayed Responses, streamed with deltas
cut whole, byte by byte and at every '.'/zero, and whole),
TestGrokCallsGiveCodexIntegersTranslated (Chat upstream -> Codex),
TestGrokCallsGiveIntegersOnEveryProtocol (Chat relayed, Messages relayed,
Messages translated from Chat), TestGrokCallsByUpstreamName,
TestGrokPluginCallsGiveCodexIntegers (fake plugin, $FAKE_GROK),
TestOnlyGrokCallsGetIntegers (gpt-5.5 byte for byte on Responses, Chat
and Messages relayed; translated keeps 2500.0), TestGrokModel. Each
recorded case checks that the field Codex's own error names is now an
integer of the Rust type it named, wherever Codex reads the call.
With grokModel forced false, every Grok test fails; with the delta
rewriting turned off (intTidy and wholeEncoder), every streamed case
fails on deltas != done.
Run: gofmt -l (clean); go vet -tags nogui ./... on darwin, GOOS=linux
and GOOS=windows; go build ./... and GOOS=linux/windows -tags nogui
builds; go test -tags nogui ./... under a temp HOME; -race -count=3 on
the new tests. End to end: the built binary (`serve`, sandbox HOME, port
47812) in front of a fake upstream streaming 2500.0 a byte per delta on
Responses and Chat; a client reading /v1/responses and
/v1/chat/completions, streamed and whole, got integers in deltas,
arguments.done, output_item.done, completed and output for grok-4.6
(relayed) and grok-4.7 (translated from Chat), and 2500.0 unchanged for
gpt-5.5. The same client against a binary of the parent commit failed
all 12 Grok checks.
Not verified: a real Grok model or a real Codex turn; Messages and Chat
Grok replies have not been seen in the field; a relayed Messages
tool_use input that is rewritten has its keys re-marshalled in sorted
order; exponent forms (2.5e3) are left as written.
Co-authored-by: timonwong <timon86.wang@gmail.com>
229 lines
9.0 KiB
Go
229 lines
9.0 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// besideFake installs the fake plugin as the plugin of the built-in id,
|
|
// not moved onto it (id-plugin beside the built-in), signed in with a
|
|
// key, its requests going to up; it gives the provider's id.
|
|
func besideFake(t *testing.T, id string, up http.Handler) string {
|
|
t.Helper()
|
|
bun, err := exec.LookPath("bun")
|
|
if err != nil {
|
|
t.Skip("no bun on PATH")
|
|
}
|
|
fresh(t)
|
|
t.Setenv("MAGPIE_BUN", bun)
|
|
t.Setenv("FAKE_ID", id)
|
|
t.Setenv("FAKE_RESPONSES", "1")
|
|
t.Cleanup(plugin.Settle)
|
|
srv := httptest.NewServer(up)
|
|
t.Cleanup(srv.Close)
|
|
t.Setenv("FAKE_BASE", srv.URL+"/v1")
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
defer cancel()
|
|
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
|
|
if _, err := plugin.Add(ctx, abs); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := plugin.Providers(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := plugin.APIKey(ctx, id, 0, nil, "k1", plugin.NewAccount); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pid := provider.PluginID(id)
|
|
if p, err := provider.Find(pid); err != nil || !p.IsPlugin() || p.PluginProvider() != id {
|
|
t.Fatalf("Find(%s) = %+v, %v", pid, p, err)
|
|
}
|
|
return pid
|
|
}
|
|
|
|
// The Grok plugin draws at Grok's Imagine API as the built-in does
|
|
// (TestGrokAccountDraws): the same models, the same request, sent through
|
|
// the plugin, which signs it.
|
|
func TestGrokPluginDraws(t *testing.T) {
|
|
var mu sync.Mutex
|
|
var paths, bodies []string
|
|
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
b, _ := io.ReadAll(r.Body)
|
|
mu.Lock()
|
|
paths, bodies = append(paths, r.URL.Path), append(bodies, string(b))
|
|
mu.Unlock()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, `{"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`)
|
|
}))
|
|
p, err := provider.Find(pid)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if ds := Drawers(*p); len(ds) != 2 || ds[0].ID != "grok-imagine-image" || ds[0].Provider != pid {
|
|
t.Fatalf("drawers %v", ds)
|
|
}
|
|
if vs := Videomakers(*p); len(vs) == 0 {
|
|
t.Fatal("the Grok plugin makes no videos")
|
|
}
|
|
code, a, raw := postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"`+pid+`/grok-imagine-image","prompt":"a magpie","size":"1792x1024"}`)
|
|
if code != 200 || len(a.Data) != 1 {
|
|
t.Fatalf("%d %s", code, raw)
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if len(paths) != 1 || paths[0] != "/v1/images/generations" || !strings.Contains(bodies[0], `"model":"grok-imagine-image"`) || !strings.Contains(bodies[0], `"aspect_ratio":"16:9"`) {
|
|
t.Fatalf("asked %v %v", paths, bodies)
|
|
}
|
|
}
|
|
|
|
// Codex's namespaced tools reach the Grok plugin flat, and its call comes
|
|
// back under the namespace, as with the built-in (TestGrokGetsNamespacedTools).
|
|
func TestGrokPluginGetsNamespacedTools(t *testing.T) {
|
|
var mu sync.Mutex
|
|
var sent []map[string]any
|
|
call := `{"type":"function_call","id":"fc_1","call_id":"c9","name":"collaboration__spawn_agent","arguments":"{\"message\":\"go\"}","status":"completed"}`
|
|
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
b, _ := io.ReadAll(r.Body)
|
|
var q map[string]any
|
|
json.Unmarshal(b, &q)
|
|
mu.Lock()
|
|
sent = append(sent, q)
|
|
mu.Unlock()
|
|
done := `{"id":"r1","object":"response","status":"completed","output":[` + call + `],"usage":{"input_tokens":5,"output_tokens":3}}`
|
|
if q["stream"] != true {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, done)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, sse(
|
|
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
|
|
`event: response.output_item.added`+"\n"+`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"c9","name":"collaboration__spawn_agent","arguments":""}}`,
|
|
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`,
|
|
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`))
|
|
}))
|
|
body := `{"model":"` + pid + `/fake-resp","stream":false,` + namespacedTools + `,"input":[
|
|
{"type":"message","role":"user","content":"go"},
|
|
{"type":"function_call","call_id":"c1","name":"spawn_agent","namespace":"collaboration","arguments":"{}"},
|
|
{"type":"function_call_output","call_id":"c1","output":"ok"}]}`
|
|
rec := httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
mu.Lock()
|
|
if len(sent) != 1 {
|
|
t.Fatalf("asked %d times", len(sent))
|
|
}
|
|
q := sent[0]
|
|
mu.Unlock()
|
|
var names []string
|
|
for _, tl := range q["tools"].([]any) {
|
|
tm := tl.(map[string]any)
|
|
names = append(names, tm["type"].(string)+":"+tm["name"].(string))
|
|
}
|
|
if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent,function:collaboration__freeform" {
|
|
t.Fatalf("Grok was offered %s", got)
|
|
}
|
|
if c := q["input"].([]any)[1].(map[string]any); c["name"] != "collaboration__spawn_agent" || c["namespace"] != nil {
|
|
t.Fatalf("the call handed back went as %v", c)
|
|
}
|
|
var res struct {
|
|
Output []map[string]any `json:"output"`
|
|
}
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil || len(res.Output) != 1 {
|
|
t.Fatalf("%v: %s", err, rec.Body)
|
|
}
|
|
if it := res.Output[0]; it["name"] != "spawn_agent" || it["namespace"] != "collaboration" {
|
|
t.Fatalf("Codex was given %v", it)
|
|
}
|
|
}
|
|
|
|
// Kiro's plugin beside the built-in (kiro-plugin) counts by estimate, as
|
|
// the built-in and the moved plugin do: the vendor isn't asked.
|
|
func TestPluginBesideBuiltinCountsByEstimate(t *testing.T) {
|
|
up := &countAsked{}
|
|
pid := besideFake(t, "kiro", up)
|
|
rec := httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages/count_tokens",
|
|
strings.NewReader(`{"model":"`+pid+`/fake-claude","messages":[{"role":"user","content":"hello there"}]}`)))
|
|
if n := estimated(t, rec); n == 999 || len(up.asked()) > 0 {
|
|
t.Fatalf("the vendor was asked to count: %v, %d", up.asked(), n)
|
|
}
|
|
}
|
|
|
|
// Grok's plugin beside the built-in Grok (grok-plugin) searches by itself
|
|
// as the built-in does, on Responses only.
|
|
func TestGrokPluginSearchesItself(t *testing.T) {
|
|
pid := besideFake(t, "grok", http.NotFoundHandler())
|
|
p, err := provider.Find(pid)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if pid != "grok-plugin" || !searchesItself(*p, provider.Responses) || searchesItself(*p, provider.Chat) {
|
|
t.Fatalf("%s searches by itself: %v on Responses, %v on Chat", pid, searchesItself(*p, provider.Responses), searchesItself(*p, provider.Chat))
|
|
}
|
|
}
|
|
|
|
// A Codex subagent's plain agent_message reaches the Grok plugin as the
|
|
// user's message, as with the built-in (TestGrokGetsAgentMessageAsUser):
|
|
// streamed, as Codex asks, the request is relayed, not translated.
|
|
func TestGrokPluginGetsAgentMessageAsUser(t *testing.T) {
|
|
var mu sync.Mutex
|
|
var sent []map[string]any
|
|
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
b, _ := io.ReadAll(r.Body)
|
|
var q map[string]any
|
|
json.Unmarshal(b, &q)
|
|
mu.Lock()
|
|
sent = append(sent, q)
|
|
mu.Unlock()
|
|
done := `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}],"usage":{"input_tokens":5,"output_tokens":1}}`
|
|
if q["stream"] != true {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, done)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, sse(
|
|
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
|
|
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`))
|
|
}))
|
|
rec := httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"`+pid+`/fake-resp","stream":true,`+agentMessageTurn+`}`)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if len(sent) != 1 {
|
|
t.Fatalf("asked %d times", len(sent))
|
|
}
|
|
checkAgentMessageSent(t, sent[0])
|
|
}
|
|
|
|
// A Grok model the Grok plugin serves writes Codex's integers as floats
|
|
// too; Codex reads them as integers, as from a relay
|
|
// (TestGrokCallsGiveCodexIntegers), streamed in deltas or whole.
|
|
func TestGrokPluginCallsGiveCodexIntegers(t *testing.T) {
|
|
c := integralCases(t)[0]
|
|
t.Setenv("FAKE_GROK", "1")
|
|
pid := besideFake(t, "grok", responsesCall(c.tool, c.args, someCuts(c.args)["by byte"]))
|
|
for _, stream := range []bool{true, false} {
|
|
checkResponses(t, c, askGrok(t, "/v1/responses", codexShellTurn(pid+"/grok-4.7", stream)), stream)
|
|
}
|
|
}
|