echo_ts (magpie 0.1.1279, macOS): Codex on a GitHub Copilot subscription
through magpie was about 10x slower than Copilot directly. Two causes,
both in the gateway:
- Codex offers web_search on every turn, and magpie counted Copilot as a
provider that can't search, so every Codex turn on Copilot was
translated for magpie's search instead of relayed.
- On that translated path responsesDecoder held a call's argument deltas
until the call was done, so Codex saw nothing while the model wrote a
command or a patch, then all of it at once. A custom tool (apply_patch)
got no custom_tool_call_input deltas at all.
Fixes:
- search.go: searchesItself counts a Copilot account on Responses. Real
check on 2026-10-17 with the owner's account: gpt-5.3-codex,
gpt-5.4-mini, gpt-6-luna, grok-4.7 and mai-code-1.1-flash each answered
a request offering web_search with web_search_call items and cited
pages. searchRank never picks Copilot to search for another provider's
models (its premium requests).
- gateway.go: a Copilot Responses request whose tools mark an argument
"encrypted" (MultiAgentV2's spawn_agent message) is still translated,
marks left out (asksSealing in responses.go). Checked on the real
account: relayed, Copilot seals the message ("UlQC...", no
encrypted_function_args), and the subagent's turn carrying it came back
"Encrypted function output content could not be decrypted or
decoded". This was already broken for a Copilot turn without
web_search; it is fixed for that too. An unsealed agent_message relayed
with web_search answers normally (checked).
- responses.go: responsesDecoder gives argument deltas as they come. It
holds only the deltas that make the arguments whole JSON, until the
done events, so #613's case (deltas that disagree with done) still
ends with the fuller arguments. The encoder sends a custom tool's input
as custom_tool_call_input.delta, read out of the {"input": ...}
arguments as they stream (customStream in custom_tool.go, which waits
for cut escapes, surrogate pairs and UTF-8), and closes it with
custom_tool_call_input.done.
- docs/subsystems/gateway-routing.md says the above.
Not changed: the HTTP/2 connection. Head-of-line blocking from large
uploads on the one connection to Copilot was measured on the real
account with a Go client: a 4MB request and a small one 300ms later,
5 rounds x 2, same connection vs a new one. The small request's first
byte took 0.93-1.68s on the shared connection, 1.26-4.77s on its own
(handshake included), 0.66-1.08s alone. No sign of blocking.
Small requests slower while a long session runs (echo_ts, 42.8s vs
17-29s first text, xhigh): nothing in magpie serializes Copilot requests
by default (lanes need MaxConcurrency, the RPM gate MaxRPM; Go's h2
windows are 1GB per connection, 4MB per stream). Measured: small
requests beside a 412s xhigh stream (16,617 output tokens) were as fast
as idle, via magpie 0.8-1.1s first text, direct 1.3-2.0s, sent_ms
1-10ms. One global lock found: copilotMu is held across the token
refresh's HTTP call, which stalls every Copilot request only around a
refresh, filed as #2762, not changed here. usage.jsonl's own_ms,
queued_ms and sent_ms against ttft_ms tell magpie's time from Copilot's.
Tests:
- TestCallArgsStreamWhenTranslated (function and custom), through the
real handler with an upstream that holds the rest of the call until
the client has the first delta.
- TestResponsesCallArgsStream, TestCustomInputStreams (pieces of 1, 2, 3,
5, 7 bytes and whole).
- TestCopilotRelayedUnlessAskedToSeal; TestCopilotUltraSubagentWithWebSearch
now expects the subagent relayed with the search.
Broken by hand at this tree, each went red:
- decoder holding every delta: TestCallArgsStreamWhenTranslated,
TestResponsesCallArgsStream;
- no custom input delta: TestCallArgsStreamWhenTranslated/custom;
- Copilot out of searchesItself: TestCopilotRelayedUnlessAskedToSeal,
TestCopilotUltraSubagentWithWebSearch;
- the asksSealing check off: the same two.
Real use: a built magpie serve in a sandbox HOME (port 3461) with the
owner's Copilot account, Codex-shaped requests offering exec_command,
apply_patch and web_search to copilot/gpt-5.3-codex:
- unmarked: relayed (Copilot's own response ids), apply_patch gave 93
custom_tool_call_input deltas from 3.55s to 11.69s;
- with a sealed spawn_agent: translated, apply_patch 117 deltas from
1.45s to 11.73s, exec_command 92 function_call_arguments deltas from
1.55s to 8.16s.
Not tried with the Codex binary itself.
Run at d783df46c plus this change (load 160-330 from other sessions): gofmt -l clean; go vet ./... for darwin,
linux (-tags nogui) and windows ok; go test -timeout 45m ./...:
60 packages ok; internal/agent, internal/gateway and internal/library
timed out at 45m (#2544/#2723, #2108, filed #2853), internal/gui's
TestSetAnswersWhileDevinAndProvidersHang (#1375) and TestMainWindowCorners
(#2645) red. Rerun alone: internal/library ok 1184s; the two gui tests
ok; internal/gateway timed out at 45m again (load ~300), then at
-timeout 3h ran 2887s with one red, TestClaudeAccountsSpentFallBackToCodex
"stream=true: no answer" at its 30s wall wait (filed #2858; -count=3
alone ok). The tests above, after the rebase: ok.
218 lines
8.9 KiB
Go
218 lines
8.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// gatedCall is a Responses upstream that streams a call's first argument
|
|
// delta and then waits, before the rest of the call, until the test has
|
|
// seen that delta reach the client (or gives up).
|
|
type gatedCall struct {
|
|
name string // the function the upstream calls
|
|
first string // its first argument delta
|
|
rest string // the rest of its arguments
|
|
seen chan struct{} // closed by the test once the client has the first delta
|
|
wrote chan struct{} // closed by the upstream as it goes on to the rest
|
|
}
|
|
|
|
func (g *gatedCall) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
io.ReadAll(r.Body)
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
f := w.(http.Flusher)
|
|
q := func(s string) string { b, _ := json.Marshal(s); return string(b) }
|
|
write := func(lines ...string) {
|
|
io.WriteString(w, sse(lines...))
|
|
f.Flush()
|
|
}
|
|
write(`data: {"type":"response.created","response":{"id":"r1","model":"m"}}`,
|
|
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":""}}`,
|
|
`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.first)+`}`)
|
|
select {
|
|
case <-g.seen:
|
|
case <-time.After(20 * time.Second):
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
close(g.wrote)
|
|
args := q(g.first + g.rest)
|
|
write(`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.rest)+`}`,
|
|
`data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":`+args+`}`,
|
|
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":`+args+`,"status":"completed"}}`,
|
|
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":5}}}`)
|
|
}
|
|
|
|
// A call's arguments reach Codex as the upstream writes them, on the
|
|
// translated path its web_search sends a request down (echo_ts on Discord:
|
|
// on Copilot, Codex saw nothing for the minutes the model wrote a patch or
|
|
// a command, then all of it at once). A function's arguments come as
|
|
// function_call_arguments deltas, a custom tool's input (apply_patch) as
|
|
// custom_tool_call_input deltas, each before the upstream's call is done;
|
|
// the finished items are what they were.
|
|
func TestCallArgsStreamWhenTranslated(t *testing.T) {
|
|
const patch = "*** Begin Patch\n*** Add File: a.go\n+package a\n+// \"quoted\" \\ é 😀\n*** End Patch\n"
|
|
whole, _ := json.Marshal(map[string]string{"input": patch})
|
|
split := 24 // inside the patch: {"input":"*** Begin Pat
|
|
for _, c := range []struct {
|
|
name, fn string
|
|
first, rest string
|
|
delta string // the event the client is given the call's text by
|
|
wantFirst string // what that event's first delta says
|
|
wantItemType string
|
|
}{
|
|
{"function", "exec_command", `{"cmd":"go test ./...",`, `"yield_time_ms":1000}`,
|
|
"response.function_call_arguments.delta", `{"cmd":"go test ./...",`, "function_call"},
|
|
{"custom", "apply_patch", string(whole[:split]), string(whole[split:]),
|
|
"response.custom_tool_call_input.delta", patch[:split-len(`{"input":"`)], "custom_tool_call"},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
fresh(t)
|
|
up := &gatedCall{name: c.fn, first: c.first, rest: c.rest, seen: make(chan struct{}), wrote: make(chan struct{})}
|
|
vendor := httptest.NewServer(up)
|
|
t.Cleanup(vendor.Close)
|
|
if err := provider.Save(provider.Provider{ID: "rel", Name: "Rel", Key: "k", Responses: vendor.URL + "/v1", Models: []string{"m"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := httptest.NewServer(New().Handler())
|
|
t.Cleanup(srv.Close)
|
|
body := `{"model":"rel/m","stream":true,"input":[{"role":"user","content":"add a.go"}],
|
|
"tools":[{"type":"function","name":"exec_command","description":"Runs a command.","strict":false,
|
|
"parameters":{"type":"object","properties":{"cmd":{"type":"string"},"yield_time_ms":{"type":"number"}},"required":["cmd"]}},
|
|
{"type":"custom","name":"apply_patch","description":"Edits files.","format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}},
|
|
{"type":"web_search"}],"tool_choice":"auto"}`
|
|
res, err := http.Post(srv.URL+"/v1/responses", "application/json", strings.NewReader(body))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != 200 {
|
|
b, _ := io.ReadAll(res.Body)
|
|
t.Fatalf("%d %s", res.StatusCode, b)
|
|
}
|
|
var deltas []string
|
|
var done map[string]any
|
|
early := false
|
|
sc := bufio.NewScanner(res.Body)
|
|
sc.Buffer(make([]byte, 1<<20), 1<<20)
|
|
for sc.Scan() {
|
|
data, ok := strings.CutPrefix(sc.Text(), "data: ")
|
|
if !ok {
|
|
continue
|
|
}
|
|
var ev struct {
|
|
Type string `json:"type"`
|
|
Delta string `json:"delta"`
|
|
Item map[string]any `json:"item"`
|
|
}
|
|
if json.Unmarshal([]byte(data), &ev) != nil {
|
|
continue
|
|
}
|
|
switch {
|
|
case ev.Type == c.delta:
|
|
if len(deltas) == 0 {
|
|
select {
|
|
case <-up.wrote:
|
|
default:
|
|
early = true // the upstream is still holding the rest
|
|
}
|
|
close(up.seen)
|
|
}
|
|
deltas = append(deltas, ev.Delta)
|
|
case ev.Type == "response.output_item.done" && ev.Item["type"] == c.wantItemType:
|
|
done = ev.Item
|
|
case ev.Type == "response.output_item.done" && done == nil:
|
|
// another kind of item: what the call came back as
|
|
done = ev.Item
|
|
}
|
|
}
|
|
if !early {
|
|
t.Fatalf("no %s before the upstream's call was done: deltas %q", c.delta, deltas)
|
|
}
|
|
if deltas[0] != c.wantFirst {
|
|
t.Errorf("first delta %q, want %q", deltas[0], c.wantFirst)
|
|
}
|
|
if done == nil || done["type"] != c.wantItemType {
|
|
t.Fatalf("finished item %v", done)
|
|
}
|
|
if c.wantItemType == "custom_tool_call" {
|
|
if done["input"] != patch || strings.Join(deltas, "") != patch {
|
|
t.Errorf("input %q, deltas %q, want %q", done["input"], strings.Join(deltas, ""), patch)
|
|
}
|
|
} else if done["arguments"] != c.first+c.rest || strings.Join(deltas, "") != c.first+c.rest {
|
|
t.Errorf("arguments %q, deltas %q", done["arguments"], strings.Join(deltas, ""))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A custom tool's input read out of its arguments a piece at a time is
|
|
// the input the whole arguments hold, wherever the pieces are cut: in an
|
|
// escape, between a surrogate pair's halves, inside a character.
|
|
func TestCustomInputStreams(t *testing.T) {
|
|
patch := "*** Begin Patch\n+\"q\" \\ é 😀 <a>&\t\n*** End Patch\n"
|
|
marshalled, _ := json.Marshal(map[string]string{"input": patch})
|
|
for _, c := range []struct{ args, want string }{
|
|
{string(marshalled), patch},
|
|
{`{"input":"\ud83d\ude00 \u00e9\u0041\/\n"}`, "😀 éA/\n"},
|
|
{`{"path":"a.go","input":"x\"y"}`, `x"y`},
|
|
{`{"meta":{"input":"no","list":["input"]},"input":"yes"}`, "yes"},
|
|
{`{ "input" : "spaced" }`, "spaced"},
|
|
{`"a lone string"`, "a lone string"},
|
|
{`{"input":"lone \ud83d half"}`, "lone \ufffd half"},
|
|
{`{"input":5}`, ""},
|
|
{`{"other":"x"}`, ""},
|
|
{`not json`, ""},
|
|
} {
|
|
for _, size := range []int{1, 2, 3, 5, 7, len(c.args)} {
|
|
var s customStream
|
|
var got strings.Builder
|
|
for i := 0; i < len(c.args); i += size {
|
|
got.WriteString(s.feed(c.args[i:min(i+size, len(c.args))]))
|
|
}
|
|
if got.String() != c.want {
|
|
t.Errorf("%s in pieces of %d: %q, want %q", c.args, size, got.String(), c.want)
|
|
}
|
|
if c.want != "" && customInput(c.args) != c.want {
|
|
t.Errorf("%s: customInput %q", c.args, customInput(c.args))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// A Responses upstream's argument deltas are given as they come, except
|
|
// those that make the arguments whole JSON, which wait for the call's done
|
|
// events: what was given and what follows add up to the fuller arguments.
|
|
func TestResponsesCallArgsStream(t *testing.T) {
|
|
var d responsesDecoder
|
|
var got []string
|
|
emit := func(ev Event) {
|
|
if ev.Kind == KToolArgs {
|
|
got = append(got, ev.Text)
|
|
}
|
|
}
|
|
d.decode(`{"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"f"}}`, emit)
|
|
for _, x := range []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`} {
|
|
q, _ := json.Marshal(x)
|
|
d.decode(`{"type":"response.function_call_arguments.delta","delta":`+string(q)+`}`, emit)
|
|
}
|
|
if want := []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`}; strings.Join(got, "|") != strings.Join(want, "|") {
|
|
t.Fatalf("before the end %q, want %q", got, want)
|
|
}
|
|
d.decode(`{"type":"response.function_call_arguments.delta","delta":"}"}`, emit)
|
|
if len(got) != 3 {
|
|
t.Fatalf("the delta that makes it whole was given before the call's done: %q", got)
|
|
}
|
|
d.decode(`{"type":"response.output_item.done","item":{"type":"function_call","call_id":"c1","name":"f","arguments":"{\"cmd\":\"a}\\\"]{\",\"n\":[1,{}],\"more\":true}"}}`, emit)
|
|
if all := strings.Join(got, ""); all != `{"cmd":"a}\"]{","n":[1,{}],"more":true}` {
|
|
t.Fatalf("arguments %s", all)
|
|
}
|
|
}
|