Files
magpie/internal/gateway/custom_tool.go
T
yetone ec7f474323 gateway: Codex on Copilot is relayed with its web_search, and a translated call's arguments stream (echo_ts)
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.
2026-10-19 00:33:29 +08:00

210 lines
6.0 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"regexp"
"strconv"
"unicode/utf8"
)
// Codex offers custom tools on Responses (exec in code mode, apply_patch):
// a tool of type custom whose call carries free-form input. A vendor's
// Responses API may take none of them, or only some: DeepSeek's answers
// 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported."
// to a request that only offers exec (#2656). A relay sends the tools as
// they came, so such a request is translated instead, on the same API:
// the translation offers each custom tool as a function taking its input
// (customSchema) and gives a call to one back as the custom_tool_call
// Codex runs. Once the model has turned them away it is translated from
// the start.
// customToolRefusal is an upstream turning a custom tool away: DeepSeek's
// "Unsupported custom tool: 'exec'", or the type named unsupported. A
// refusal of anything else about a tool doesn't match.
var customToolRefusal = regexp.MustCompile(`(?i)unsupported custom tool|custom tools? (?:is |are )?not (?:supported|allowed)|(?:unsupported|unknown|invalid) tool type[^\n{}]{0,20}?['"\x60]custom['"\x60]|tool type ['"\x60]custom['"\x60] (?:is )?(?:not supported|unsupported)`)
// customToolRefused is how unfit remembers model turning custom tools
// away.
func customToolRefused(model string) string { return "custom tools\x00" + model }
// hasCustomTool reports whether a Responses body offers a custom tool:
// among its tools, in a namespace there, or in an input item that carries
// tools (Responses Lite's additional_tools, a tool search's output).
func hasCustomTool(body []byte) bool {
if !bytes.Contains(body, []byte(`"custom"`)) {
return false
}
var m map[string]any
if json.Unmarshal(body, &m) != nil {
return false
}
if customIn(m["tools"]) {
return true
}
items, _ := m["input"].([]any)
for _, it := range items {
if im, _ := it.(map[string]any); im != nil && customIn(im["tools"]) {
return true
}
}
return false
}
// customIn reports whether a list of tools has a custom one, a namespace's
// included.
func customIn(v any) bool {
tools, _ := v.([]any)
for _, t := range tools {
tm, _ := t.(map[string]any)
if tm == nil {
continue
}
if tm["type"] == "custom" || tm["type"] == "namespace" && customIn(tm["tools"]) {
return true
}
}
return false
}
// customStream gives a custom tool's input as its call's arguments come,
// a piece at a time: the text of the input string in {"input":"…"} (or of
// a lone JSON string), unescaped, as the custom_tool_call_input deltas a
// client reads while the model writes a patch. What can't be read yet (an
// escape or a character cut off) waits for the next piece. The finished
// item's input is still customInput's of the whole arguments; arguments
// of another shape stream nothing.
type customStream struct {
pend []byte // of the input string, read and not given yet
depth int
str bool // in a string that isn't the input
esc bool // after its backslash
key []byte // the depth-1 key being read, raw
inKey bool // the string being read is that key
want bool // a key is next, at depth 1
last string // the last depth-1 key
value bool // the depth-1 value next is the input's
in bool // in the input string
over bool // the input is given, or there is none
}
// feed reads the next piece of the arguments and gives what it adds to
// the input.
func (c *customStream) feed(s string) string {
if c.over {
return ""
}
if c.in {
c.pend = append(c.pend, s...)
return c.take()
}
for i := 0; i < len(s); i++ {
b := s[i]
switch {
case c.str:
if c.inKey {
c.key = append(c.key, b)
}
switch {
case c.esc:
c.esc = false
case b == '\\':
c.esc = true
case b == '"':
c.str = false
if c.inKey {
c.inKey = false
c.last = ""
json.Unmarshal(append([]byte{'"'}, c.key...), &c.last)
}
}
case b == '"' && (c.depth == 0 || c.depth == 1 && c.value):
c.in = true
c.pend = append(c.pend, s[i+1:]...)
return c.take()
case b == '"':
c.str = true
if c.depth == 1 && c.want {
c.inKey, c.key, c.want = true, c.key[:0], false
}
case b == '{' || b == '[':
c.depth++
if c.depth == 1 && b == '{' {
c.want = true
}
case b == '}' || b == ']':
if c.depth--; c.depth <= 0 {
c.over = true
return ""
}
case b == ':' && c.depth == 1:
c.value = c.last == "input"
case b == ',' && c.depth == 1:
c.want, c.value = true, false
case b == ' ' || b == '\t' || b == '\n' || b == '\r':
case c.depth == 0:
c.over = true // not JSON this reads
return ""
case c.depth == 1:
c.value = false // the input isn't a string
}
}
return ""
}
// take unescapes what can be read of the input string so far, up to its
// closing quote.
func (c *customStream) take() string {
n, end := 0, false
scan:
for n < len(c.pend) {
switch c.pend[n] {
case '"':
end = true
break scan
case '\\':
switch {
case n+1 >= len(c.pend):
break scan
case c.pend[n+1] != 'u':
n += 2
case n+6 > len(c.pend):
break scan
case !highSurrogate(c.pend[n+2 : n+6]):
n += 6
case n+8 > len(c.pend):
break scan
case c.pend[n+6] != '\\' || c.pend[n+7] != 'u':
n += 6 // a lone half, read as JSON reads it
case n+12 > len(c.pend):
break scan // the low half is cut off
default:
n += 12
}
default:
n++
}
}
// a character cut off waits too
for k := 0; k < utf8.UTFMax-1 && n > 0 && !end && !utf8.Valid(c.pend[:n]); k++ {
n--
}
var text string
if json.Unmarshal(append(append([]byte{'"'}, c.pend[:n]...), '"'), &text) != nil {
c.over = true // not a string JSON reads: the finished item says it
return ""
}
c.pend = c.pend[n:]
if end {
c.over, c.pend = true, nil
}
return text
}
// highSurrogate is whether the four hex digits of a \u escape are the
// first half of a pair.
func highSurrogate(hex []byte) bool {
r, err := strconv.ParseUint(string(hex), 16, 16)
return err == nil && r >= 0xD800 && r < 0xDC00
}