copilot: a Responses turn goes as its delta over Copilot's WebSocket
yuushabu_buyinn on X asked whether Copilot's Responses route can send
the delta too: their Usage page has Copilot at 70.4K requests, up 129 GB
for 31 GB down, since each turn went whole over HTTP. Copilot's HTTP
/responses answers previous_response_id with 400, but its Responses
WebSocket at <api>/responses takes previous_response_id (store false)
on the same connection, as Copilot Chat sends it for a model whose
supported_endpoints list "ws:/responses".
- provider: the model list remembers which models list ws:/responses
(copilotSee); SocketTurn gives a Copilot turn its socket at the API's
/responses with Copilot's own headers (CopilotSocketTurn).
- gateway: overSocket takes such a Copilot turn; the message is
{type:"response.create", initiator, ...body} without stream; the
handshake has no OpenAI-Beta or X-Initiator; the keep key adds the
Copilot session token. A status-less error frame and a refused
handshake have the turn over HTTP, as before.
- keep: Copilot's reasoning ids are Base64 (+ and /), and plainItemIDs
leaves such reasoning out of the next turn, so the real account's
second turn never matched what it kept and went whole. A Copilot turn
without its kept reasoning still carries on: Copilot keeps that
reasoning with the response.
Tests (fake Copilot, no network): TestCopilotSocketSendsTheDelta,
OnlyForItsModels, RefusedGoesOverHTTP, ErrorFrameGoesOverHTTP,
DeltaWithoutItsReasoning. Each of the first four is red on origin/main;
DeltaWithoutItsReasoning is red with the sealed skip turned off (whole
input, no previous_response_id).
Real account (owner's Copilot, sandbox HOME, wsl-run magpie-desktop):
gpt-5.3-codex over the socket, turn 2 on the kept socket with
previous_response_id and only its new input, answer right ("apple
banana"). gpt-5.5 and gpt-5.4 answer 400 "not available for integrator
vscode-chat" on that account, so weren't tried.
Run at this tree (wsl-run, magpie-desktop): gofmt -l internal/ clean; go vet
of gateway and provider for GOOS linux, windows and darwin; go test
-run "Socket|Copilot" ./internal/gateway ./internal/provider ok. The full
`go test -count=1 -timeout 45m ./...` is queued on mote behind another
session's suite and was not finished at push.
This commit is contained in:
@@ -171,12 +171,26 @@ func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, e
|
||||
return t.next.RoundTrip(req)
|
||||
}
|
||||
body, ok := codexSocketMessage(req)
|
||||
if !ok {
|
||||
copilot := provider.CopilotSocketTurn(req)
|
||||
if !ok || (copilot && !provider.CopilotSocketModel(gjson.GetBytes(body, "model").String())) {
|
||||
return viaHTTP()
|
||||
}
|
||||
msg := codexCreate(body)
|
||||
create := codexCreate
|
||||
if copilot {
|
||||
initiator := "agent"
|
||||
if strings.EqualFold(req.Header.Get("X-Initiator"), "user") {
|
||||
initiator = "user"
|
||||
}
|
||||
create = func(body []byte) []byte { return copilotCreate(body, initiator) }
|
||||
}
|
||||
msg := create(body)
|
||||
var shape *codexTurnShape
|
||||
key := codexKeepKey(req, body)
|
||||
if key == "" && copilot {
|
||||
// Copilot is sent no conversation's id: the conversation is how
|
||||
// it opens, as a delta goes only after the turn it carries on
|
||||
key = codexKeepKeyOf(req, conversationID(req.Header, body), "")
|
||||
}
|
||||
if key != "" {
|
||||
if s, ok := codexShape(body); ok {
|
||||
shape = s
|
||||
@@ -187,7 +201,7 @@ func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, e
|
||||
if k := codexKeepTake(key); k != nil {
|
||||
send := msg
|
||||
if d, ok := k.delta(body, shape); ok {
|
||||
send = codexCreate(d)
|
||||
send = create(d)
|
||||
}
|
||||
if codexMessageTooBig(req.URL.Host, len(send)) {
|
||||
k.close()
|
||||
@@ -201,7 +215,7 @@ func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, e
|
||||
if codexMessageTooBig(req.URL.Host, len(msg)) {
|
||||
return viaHTTP()
|
||||
}
|
||||
res, err := t.socket(req, msg, key, shape, shun)
|
||||
res, err := t.socket(req, msg, key, shape, shun, copilot)
|
||||
if errors.Is(err, errCodexSocketFallBack) {
|
||||
return viaHTTP()
|
||||
}
|
||||
@@ -272,6 +286,29 @@ func codexCreate(body []byte) []byte {
|
||||
return append(out, rest...)
|
||||
}
|
||||
|
||||
// copilotCreate is body, a JSON object, as Copilot's response.create
|
||||
// message: without stream, and with whether the user or the agent asked
|
||||
// the turn (initiator, said in X-Initiator over HTTP), as Copilot Chat
|
||||
// sends it (chatWebSocketManager.ts sendRequest).
|
||||
func copilotCreate(body []byte, initiator string) []byte {
|
||||
who, _ := json.Marshal(initiator)
|
||||
out := make([]byte, 0, len(body)+48)
|
||||
out = append(out, `{"type":"response.create","initiator":`...)
|
||||
out = append(out, who...)
|
||||
gjson.ParseBytes(body).ForEach(func(k, v gjson.Result) bool {
|
||||
switch k.String() {
|
||||
case "stream", "type", "initiator":
|
||||
return true
|
||||
}
|
||||
out = append(out, ',')
|
||||
out = append(out, k.Raw...)
|
||||
out = append(out, ':')
|
||||
out = append(out, v.Raw...)
|
||||
return true
|
||||
})
|
||||
return append(out, '}')
|
||||
}
|
||||
|
||||
// withoutClientMetadata is body with key gone from its client_metadata,
|
||||
// every other byte as it was, and body itself when it has no such key.
|
||||
func withoutClientMetadata(body []byte, key string) []byte {
|
||||
@@ -331,7 +368,10 @@ func withClientMetadata(body []byte, meta map[string]string) ([]byte, bool) {
|
||||
}
|
||||
|
||||
// codexSocketHeaders are req's headers as the handshake carries them.
|
||||
func codexSocketHeaders(req *http.Request) http.Header {
|
||||
// Copilot's carries no OpenAI-Beta, as Copilot Chat's
|
||||
// (createResponsesWebSocket in @vscode/copilot-api), and no X-Initiator,
|
||||
// which each turn's message says.
|
||||
func codexSocketHeaders(req *http.Request, copilot bool) http.Header {
|
||||
h := http.Header{}
|
||||
for k, vs := range req.Header {
|
||||
switch http.CanonicalHeaderKey(k) {
|
||||
@@ -343,9 +383,14 @@ func codexSocketHeaders(req *http.Request) http.Header {
|
||||
if hopHeader(k) || strings.HasPrefix(http.CanonicalHeaderKey(k), "Sec-Websocket-") {
|
||||
continue
|
||||
}
|
||||
if copilot && http.CanonicalHeaderKey(k) == "X-Initiator" {
|
||||
continue
|
||||
}
|
||||
h[k] = vs
|
||||
}
|
||||
h.Set("OpenAI-Beta", codexSocketBeta)
|
||||
if !copilot {
|
||||
h.Set("OpenAI-Beta", codexSocketBeta)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -353,7 +398,7 @@ func codexSocketHeaders(req *http.Request) http.Header {
|
||||
// carries on with key's conversation is kept for its next turn. A host
|
||||
// that refuses the handshake is left to HTTP for a while when shun says
|
||||
// so (a provider's Socket "on" never is).
|
||||
func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *codexTurnShape, shun bool) (*http.Response, error) {
|
||||
func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *codexTurnShape, shun, copilot bool) (*http.Response, error) {
|
||||
// the socket may outlive the request, kept for the next turn: only
|
||||
// the handshake ends with it
|
||||
ctx, cancel := context.WithCancel(context.WithoutCancel(req.Context()))
|
||||
@@ -362,7 +407,7 @@ func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *co
|
||||
u := *req.URL
|
||||
c, hs, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{
|
||||
HTTPClient: &http.Client{Transport: t.next, CheckRedirect: provider.KeepsCredentials},
|
||||
HTTPHeader: codexSocketHeaders(req),
|
||||
HTTPHeader: codexSocketHeaders(req, copilot),
|
||||
CompressionMode: websocket.CompressionNoContextTakeover,
|
||||
})
|
||||
stopped := timer.Stop()
|
||||
@@ -405,7 +450,7 @@ func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *co
|
||||
}
|
||||
header[k] = vs
|
||||
}
|
||||
k := &codexKept{c: c, cancel: cancel, key: key, host: u.Host, header: header, opened: time.Now()}
|
||||
k := &codexKept{c: c, cancel: cancel, key: key, host: u.Host, header: header, opened: time.Now(), copilot: copilot}
|
||||
return t.turn(req, k, msg, shape, false)
|
||||
}
|
||||
|
||||
@@ -466,7 +511,7 @@ func (t codexSocket) turn(req *http.Request, k *codexKept, msg []byte, shape *co
|
||||
return nil, errCodexSocketAgain
|
||||
}
|
||||
// ahead of the reply: it stands for the HTTP route's status
|
||||
if res, fall := codexSocketError(req, header, frame); fall || res != nil {
|
||||
if res, fall := codexSocketError(req, header, frame, k.copilot); fall || res != nil {
|
||||
body.Close()
|
||||
if fall {
|
||||
return nil, errCodexSocketFallBack
|
||||
@@ -536,7 +581,7 @@ func codexSocketEnded(host string, size int, err error) error {
|
||||
// codexSocketError is the HTTP reply an error frame that comes ahead of
|
||||
// the reply stands for, and true when the turn is to go over HTTP
|
||||
// instead; neither for one the stream carries on with.
|
||||
func codexSocketError(req *http.Request, header http.Header, frame []byte) (*http.Response, bool) {
|
||||
func codexSocketError(req *http.Request, header http.Header, frame []byte, copilot bool) (*http.Response, bool) {
|
||||
code := gjson.GetBytes(frame, "error.code").String()
|
||||
if code == "websocket_connection_limit_reached" {
|
||||
return nil, true
|
||||
@@ -546,7 +591,11 @@ func codexSocketError(req *http.Request, header http.Header, frame []byte) (*htt
|
||||
status = int(gjson.GetBytes(frame, "status_code").Int())
|
||||
}
|
||||
if status < 400 || status > 599 {
|
||||
return nil, false
|
||||
// Copilot's error frames name no status
|
||||
// ({"type":"error","error":{"code":"bad_request",...}}): the
|
||||
// turn is asked over HTTP, whose reply has the status the
|
||||
// account's resting and retries read
|
||||
return nil, copilot
|
||||
}
|
||||
h := header.Clone()
|
||||
for _, path := range []string{"headers", "error.headers"} {
|
||||
@@ -652,11 +701,13 @@ func sseEvent(kind string, frame []byte) []byte {
|
||||
|
||||
// codexSocketBody is the socket's frames read as server-sent events.
|
||||
type codexSocketBody struct {
|
||||
c *websocket.Conn
|
||||
ctx context.Context
|
||||
k *codexKept
|
||||
shape *codexTurnShape // nil: the socket isn't kept after the turn
|
||||
output []itemSum
|
||||
c *websocket.Conn
|
||||
ctx context.Context
|
||||
k *codexKept
|
||||
shape *codexTurnShape // nil: the socket isn't kept after the turn
|
||||
output []itemSum
|
||||
// sealed: which of output are reasoning items (codexKept.sealed)
|
||||
sealed []bool
|
||||
pending []byte
|
||||
done bool
|
||||
err error
|
||||
@@ -691,6 +742,7 @@ func (b *codexSocketBody) frame() ([]byte, error) {
|
||||
if b.shape != nil {
|
||||
if sum, ok := codexReplyItem(data); ok {
|
||||
b.output = append(b.output, sum)
|
||||
b.sealed = append(b.sealed, gjson.GetBytes(data, "item.type").String() == "reasoning")
|
||||
} else {
|
||||
b.shape = nil
|
||||
}
|
||||
@@ -701,7 +753,7 @@ func (b *codexSocketBody) frame() ([]byte, error) {
|
||||
// kept for the conversation's next turn, which may carry on
|
||||
// from this one
|
||||
b.k.fields, b.k.input = b.shape.fields, b.shape.sums
|
||||
b.k.output, b.k.replyID = b.output, id
|
||||
b.k.output, b.k.sealed, b.k.replyID = b.output, b.sealed, id
|
||||
codexKeepPut(b.k)
|
||||
} else {
|
||||
b.k.closeNormally()
|
||||
|
||||
@@ -64,19 +64,26 @@ var (
|
||||
// codexKept is a socket to the backend and what its last turn sent and
|
||||
// got back.
|
||||
type codexKept struct {
|
||||
c *websocket.Conn
|
||||
cancel context.CancelFunc
|
||||
key string // "" for a turn that names no conversation
|
||||
host string
|
||||
header http.Header // the handshake's, as each reply carries them
|
||||
opened time.Time
|
||||
used time.Time
|
||||
once sync.Once
|
||||
timer *time.Timer
|
||||
fields map[string]string
|
||||
input []itemSum
|
||||
output []itemSum
|
||||
c *websocket.Conn
|
||||
cancel context.CancelFunc
|
||||
key string // "" for a turn that names no conversation
|
||||
host string
|
||||
header http.Header // the handshake's, as each reply carries them
|
||||
opened time.Time
|
||||
used time.Time
|
||||
once sync.Once
|
||||
timer *time.Timer
|
||||
fields map[string]string
|
||||
input []itemSum
|
||||
output []itemSum
|
||||
// sealed says which of output are reasoning items, which a Copilot
|
||||
// turn may come back without: Copilot's reasoning ids are Base64,
|
||||
// + and / in them, and plainItemIDs leaves such reasoning out of the
|
||||
// next turn. Copilot keeps the response's reasoning itself, so a
|
||||
// turn that carries on from it without that item is still a delta.
|
||||
sealed []bool
|
||||
replyID string
|
||||
copilot bool // Copilot's socket (copilotCreate)
|
||||
}
|
||||
|
||||
// close ends the socket at once.
|
||||
@@ -107,12 +114,22 @@ func codexKeepKey(req *http.Request, body []byte) string {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return codexKeepKeyOf(req, sid, tid)
|
||||
}
|
||||
|
||||
// codexKeepKeyOf is the key of req's conversation named sid and tid.
|
||||
func codexKeepKeyOf(req *http.Request, sid, tid string) string {
|
||||
if sid == "" && tid == "" {
|
||||
return ""
|
||||
}
|
||||
h := sha256.New()
|
||||
for _, v := range []string{
|
||||
req.URL.Scheme, req.URL.Host, req.URL.Path, req.Header.Get("Authorization"), req.Header.Get("Chatgpt-Account-Id"),
|
||||
// a Responses provider's key may be said in either (#5781)
|
||||
req.Header.Get("X-Api-Key"), req.Header.Get("Api-Key"),
|
||||
sid, tid, req.Header.Get("X-Openai-Subagent"), req.Header.Get("X-Codex-Parent-Thread-Id"),
|
||||
// Copilot Auto's session, which the handshake carries
|
||||
req.Header.Get("Copilot-Session-Token"),
|
||||
} {
|
||||
h.Write([]byte(v))
|
||||
h.Write([]byte{0})
|
||||
@@ -306,8 +323,7 @@ func (k *codexKept) delta(body []byte, s *codexTurnShape) ([]byte, bool) {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
n := len(k.input) + len(k.output)
|
||||
if len(s.sums) < n {
|
||||
if len(s.sums) < len(k.input) {
|
||||
return nil, false
|
||||
}
|
||||
for i, sum := range k.input {
|
||||
@@ -315,10 +331,16 @@ func (k *codexKept) delta(body []byte, s *codexTurnShape) ([]byte, bool) {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
n := len(k.input)
|
||||
for i, sum := range k.output {
|
||||
if s.sums[len(k.input)+i] != sum {
|
||||
return nil, false
|
||||
if n < len(s.sums) && s.sums[n] == sum {
|
||||
n++
|
||||
continue
|
||||
}
|
||||
if k.copilot && i < len(k.sealed) && k.sealed[i] {
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
in := gjson.GetBytes(body, "input")
|
||||
if !in.IsArray() || in.Index <= 0 {
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// copilotWSModels is Copilot's model list as the owner's account has it:
|
||||
// gpt-5.5 served over the Responses WebSocket too, gpt-5.3-codex over
|
||||
// HTTP only.
|
||||
const copilotWSModels = `{"data":[
|
||||
{"id":"gpt-5.5","name":"GPT-5.5","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses","ws:/responses"],"capabilities":{"type":"chat"}},
|
||||
{"id":"gpt-5.3-codex","name":"GPT-5.3-Codex","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat"}}]}`
|
||||
|
||||
// copilotSocketFake signs a Copilot account in to a fake Copilot API whose
|
||||
// /responses is f, over HTTP and over its WebSocket.
|
||||
func copilotSocketFake(t *testing.T, f *fakeSocketBackend) {
|
||||
t.Helper()
|
||||
socketOn(t)
|
||||
provider.ForgetCopilotForTest()
|
||||
t.Cleanup(provider.ForgetCopilotForTest)
|
||||
f.path = "/responses"
|
||||
f.whole = true
|
||||
copilotFake(t, "gho_copilot_ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/models":
|
||||
io.WriteString(w, copilotWSModels)
|
||||
case "/responses":
|
||||
f.ServeHTTP(w, r)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func copilotTurn(model string, items ...string) string {
|
||||
return `{"model":"copilot/` + model + `","stream":true,"instructions":"be brief","input":[` + strings.Join(items, ",") + `]}`
|
||||
}
|
||||
|
||||
func copilotPost(t *testing.T, s *Server, body string) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") ||
|
||||
!strings.Contains(rec.Body.String(), "event: response.completed\n") {
|
||||
t.Fatalf("%d, a reply without its end: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// yuushabu_buyinn on X: magpie sent each Copilot Responses turn whole over
|
||||
// HTTP (129 GB up for 31 GB down), where Copilot answers
|
||||
// previous_response_id 400 "previous_response_id is not supported". Over
|
||||
// its Responses WebSocket, as Copilot Chat sends a model that lists
|
||||
// "ws:/responses", a conversation's next turn goes on the same socket as
|
||||
// its new input after previous_response_id.
|
||||
func TestCopilotSocketSendsTheDelta(t *testing.T) {
|
||||
f := &fakeSocketBackend{keep: true}
|
||||
f.frames = keptReply(f)
|
||||
copilotSocketFake(t, f)
|
||||
s := New()
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing))
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing, asstPong, userAgain))
|
||||
|
||||
posts, sockets := f.counts()
|
||||
if posts != 0 || sockets != 2 || f.opened() != 1 {
|
||||
t.Fatalf("%d over HTTP, %d turns on %d sockets; want both turns on one socket", posts, sockets, f.opened())
|
||||
}
|
||||
first, next := f.turn(0), f.turn(1)
|
||||
for i, turn := range []socketTurn{first, next} {
|
||||
m := gjson.ParseBytes(turn.msg)
|
||||
if m.Get("type").String() != "response.create" || m.Get("stream").Exists() || m.Get("model").String() != "gpt-5.5" {
|
||||
t.Errorf("turn %d's message: %s", i, turn.msg)
|
||||
}
|
||||
if m.Get("initiator").String() == "" {
|
||||
t.Errorf("turn %d's message says no initiator: %s", i, turn.msg)
|
||||
}
|
||||
}
|
||||
if gjson.GetBytes(first.msg, "previous_response_id").Exists() || len(gjson.GetBytes(first.msg, "input").Array()) != 1 {
|
||||
t.Errorf("the first turn: %s", first.msg)
|
||||
}
|
||||
if id := gjson.GetBytes(next.msg, "previous_response_id").String(); id != "resp-1" {
|
||||
t.Errorf("the next turn carries on from %q: %s", id, next.msg)
|
||||
}
|
||||
if in := gjson.GetBytes(next.msg, "input").Array(); len(in) != 1 || in[0].Get("content.0.text").String() != "again" {
|
||||
t.Errorf("the next turn is not its new input alone: %s", next.msg)
|
||||
}
|
||||
if h := first.header; h.Get("OpenAI-Beta") != "" || h.Get("X-Initiator") != "" ||
|
||||
h.Get("Authorization") != "Bearer sess" || h.Get("Copilot-Integration-Id") == "" {
|
||||
t.Errorf("the handshake's headers: %v", h)
|
||||
}
|
||||
}
|
||||
|
||||
// A model Copilot's list doesn't name for "ws:/responses" goes over HTTP,
|
||||
// as Copilot Chat sends it.
|
||||
func TestCopilotSocketOnlyForItsModels(t *testing.T) {
|
||||
f := &fakeSocketBackend{keep: true}
|
||||
f.frames = keptReply(f)
|
||||
copilotSocketFake(t, f)
|
||||
s := New()
|
||||
copilotPost(t, s, copilotTurn("gpt-5.3-codex", userPing))
|
||||
copilotPost(t, s, copilotTurn("gpt-5.3-codex", userPing, asstPong, userAgain))
|
||||
if posts, sockets := f.counts(); posts != 2 || sockets != 0 || f.opened() != 0 {
|
||||
t.Fatalf("%d over HTTP, %d on a socket (%d opened); want both over HTTP", posts, sockets, f.opened())
|
||||
}
|
||||
}
|
||||
|
||||
// A Copilot that refuses the handshake has the turn over HTTP.
|
||||
func TestCopilotSocketRefusedGoesOverHTTP(t *testing.T) {
|
||||
f := &fakeSocketBackend{keep: true, refuse: http.StatusNotFound}
|
||||
f.frames = keptReply(f)
|
||||
copilotSocketFake(t, f)
|
||||
s := New()
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing))
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing, asstPong, userAgain))
|
||||
if posts, sockets := f.counts(); posts != 2 || sockets != 0 {
|
||||
t.Fatalf("%d over HTTP, %d on a socket; want both over HTTP", posts, sockets)
|
||||
}
|
||||
}
|
||||
|
||||
// Copilot's error frame names no status ({"type":"error","error":
|
||||
// {"code":"bad_request",...}}, the real account's answer to a
|
||||
// previous_response_id from another socket): the turn is asked over HTTP,
|
||||
// whose reply has the status resting and retries read.
|
||||
func TestCopilotSocketErrorFrameGoesOverHTTP(t *testing.T) {
|
||||
f := &fakeSocketBackend{keep: true}
|
||||
f.frames = func(socketTurn) []string {
|
||||
return []string{`{"type":"error","error":{"type":"invalid_request_error","code":"bad_request","message":"previous_response_id is not supported"}}`}
|
||||
}
|
||||
copilotSocketFake(t, f)
|
||||
copilotPost(t, New(), copilotTurn("gpt-5.5", userPing))
|
||||
if posts, sockets := f.counts(); posts != 1 || sockets != 1 {
|
||||
t.Fatalf("%d over HTTP, %d on a socket; want the socket's refusal asked again over HTTP", posts, sockets)
|
||||
}
|
||||
}
|
||||
|
||||
// Copilot's reasoning ids are Base64 ("+" and "/" in them), and such
|
||||
// reasoning is left out of the next turn (plainItemIDs): the real
|
||||
// account's gpt-5.3-codex turn came back reasoning then message, and the
|
||||
// next went whole until a turn without its reasoning counted as carrying
|
||||
// on. Copilot keeps that reasoning itself, with the response.
|
||||
func TestCopilotSocketDeltaWithoutItsReasoning(t *testing.T) {
|
||||
const sealed = `{"type":"reasoning","id":"Y9Jw8X3JbNrD+gvjyaVn/JJSBK==","summary":[],"encrypted_content":"tInH0RH7w5ID5F7p"}`
|
||||
f := &fakeSocketBackend{keep: true}
|
||||
reply := keptReply(f)
|
||||
f.frames = func(turn socketTurn) []string {
|
||||
frames := reply(turn)
|
||||
return append([]string{frames[0], `{"type":"response.output_item.done","output_index":0,"item":` + sealed + `}`}, frames[1:]...)
|
||||
}
|
||||
copilotSocketFake(t, f)
|
||||
s := New()
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing))
|
||||
copilotPost(t, s, copilotTurn("gpt-5.5", userPing, sealed, asstPong, userAgain))
|
||||
if posts, sockets := f.counts(); posts != 0 || sockets != 2 || f.opened() != 1 {
|
||||
t.Fatalf("%d over HTTP, %d turns on %d sockets; want both turns on one socket", posts, sockets, f.opened())
|
||||
}
|
||||
next := f.turn(1).msg
|
||||
if id := gjson.GetBytes(next, "previous_response_id").String(); id != "resp-1" {
|
||||
t.Errorf("the next turn carries on from %q: %s", id, next)
|
||||
}
|
||||
if in := gjson.GetBytes(next, "input").Array(); len(in) != 1 || in[0].Get("content.0.text").String() != "again" {
|
||||
t.Errorf("the next turn is not its new input alone: %s", next)
|
||||
}
|
||||
}
|
||||
@@ -1883,7 +1883,7 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
|
||||
copilotSeenMu.Lock()
|
||||
for _, m := range v.Data {
|
||||
if m.Capabilities.Type == "chat" {
|
||||
copilotSeen[m.ID] = copilotAPIs(m.Endpoints)
|
||||
copilotSee(m.ID, m.Endpoints)
|
||||
}
|
||||
}
|
||||
copilotSeenMu.Unlock()
|
||||
|
||||
@@ -312,7 +312,7 @@ func copilotAutoRoute(ctx context.Context, app copilotApp, s copilotSession, bas
|
||||
// the pick's endpoints, which the account's list may not give
|
||||
copilotSeenMu.Lock()
|
||||
if _, ok := copilotSeen[v.Selected.ID]; !ok || len(v.Selected.Endpoints) > 0 {
|
||||
copilotSeen[v.Selected.ID] = copilotAPIs(v.Selected.Endpoints)
|
||||
copilotSee(v.Selected.ID, v.Selected.Endpoints)
|
||||
}
|
||||
copilotSeenMu.Unlock()
|
||||
exp := time.Now().Add(copilotAutoReuse).Unix()
|
||||
@@ -438,8 +438,17 @@ func copilotAutoHeld(token string, a *copilotAutoSession) bool {
|
||||
var (
|
||||
copilotSeenMu sync.Mutex
|
||||
copilotSeen = map[string][]string{}
|
||||
// copilotSeenWS: the models served over the Responses WebSocket
|
||||
copilotSeenWS = map[string]bool{}
|
||||
)
|
||||
|
||||
// copilotSee keeps what Copilot said model is served on; under
|
||||
// copilotSeenMu.
|
||||
func copilotSee(model string, endpoints []string) {
|
||||
copilotSeen[model] = copilotAPIs(endpoints)
|
||||
copilotSeenWS[model] = slices.Contains(endpoints, "ws:/responses")
|
||||
}
|
||||
|
||||
func copilotSeenAPIs(model string) []Protocol {
|
||||
copilotSeenMu.Lock()
|
||||
defer copilotSeenMu.Unlock()
|
||||
@@ -465,7 +474,7 @@ func ForgetCopilotForTest() {
|
||||
copilotTerms, copilotPicks = map[string]map[string]bool{}, map[string][]string{}
|
||||
copilotTermsMu.Unlock()
|
||||
copilotSeenMu.Lock()
|
||||
copilotSeen = map[string][]string{}
|
||||
copilotSeen, copilotSeenWS = map[string][]string{}, map[string]bool{}
|
||||
copilotSeenMu.Unlock()
|
||||
copilotRefusedMu.Lock()
|
||||
copilotRefusedAt = map[string]map[string]time.Time{}
|
||||
|
||||
@@ -79,6 +79,9 @@ type socketKey struct{}
|
||||
type socketAt struct {
|
||||
host, path string
|
||||
shun bool
|
||||
// copilot: a Copilot account's turns, at whatever API host its
|
||||
// session names (CopilotSocketTurn)
|
||||
copilot bool
|
||||
}
|
||||
|
||||
// withSocket is ctx carrying where p's turns may go over the Responses
|
||||
@@ -96,6 +99,9 @@ func withSocket(ctx context.Context, p Provider) context.Context {
|
||||
}
|
||||
|
||||
func (p Provider) socketAt() (socketAt, bool) {
|
||||
if p.copilotSocket() {
|
||||
return socketAt{copilot: true, shun: true}, true
|
||||
}
|
||||
mode := p.SocketMode()
|
||||
if mode == "" || !p.TakesSocket() {
|
||||
return socketAt{}, false
|
||||
@@ -119,8 +125,44 @@ func SocketTurn(req *http.Request) (ok, shun bool) {
|
||||
return true, true
|
||||
}
|
||||
at, _ := req.Context().Value(socketKey{}).(socketAt)
|
||||
if at.copilot {
|
||||
return req.URL.Path == "/responses", true
|
||||
}
|
||||
if at.host == "" || !strings.EqualFold(req.URL.Host, at.host) || req.URL.Path != at.path {
|
||||
return false, false
|
||||
}
|
||||
return true, at.shun
|
||||
}
|
||||
|
||||
// A Copilot account's Responses turn goes over Copilot's Responses
|
||||
// WebSocket, at the same /responses address, for a model whose
|
||||
// supported_endpoints list "ws:/responses", as Copilot Chat sends it
|
||||
// (microsoft/vscode extensions/copilot chatEndpoint.ts: useWebSocket,
|
||||
// ModelSupportedEndpoint.WebSocketResponses). There a conversation's next
|
||||
// turn goes on the same socket as its new input after
|
||||
// previous_response_id with store false, where over HTTP Copilot answers
|
||||
// previous_response_id 400 "previous_response_id is not supported" and
|
||||
// every turn goes whole (yuushabu_buyinn on X: 129 GB up for 31 GB down).
|
||||
// Socket "off" keeps an account's turns on HTTP.
|
||||
func (p Provider) copilotSocket() bool {
|
||||
return p.Account != nil && p.Account.Agent == "copilot" && p.Socket != SocketOff
|
||||
}
|
||||
|
||||
// CopilotSocketTurn says req is a Copilot account's Responses turn that
|
||||
// may go over Copilot's WebSocket (SocketTurn), its model aside
|
||||
// (CopilotSocketModel).
|
||||
func CopilotSocketTurn(req *http.Request) bool {
|
||||
if req == nil || req.URL == nil {
|
||||
return false
|
||||
}
|
||||
at, _ := req.Context().Value(socketKey{}).(socketAt)
|
||||
return at.copilot && req.URL.Path == "/responses"
|
||||
}
|
||||
|
||||
// CopilotSocketModel says Copilot's list named model served over its
|
||||
// Responses WebSocket ("ws:/responses" in its supported_endpoints).
|
||||
func CopilotSocketModel(model string) bool {
|
||||
copilotSeenMu.Lock()
|
||||
defer copilotSeenMu.Unlock()
|
||||
return copilotSeenWS[model]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user