diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7949a6a68..3ac584ddb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -11,6 +11,17 @@ This page covers how a request is routed. Plugins that change requests and replies are in [Gateway middleware](gateway-middleware.md). Subscriptions served by a plugin are in [Provider and plugin ownership](provider-plugins.md). +WorkBuddy and CodeBuddy Code's `X-Conversation-ID` is a native session header +in `sessionHeaders` (`sessionOf`, `nativeSessionOf`, `conversationID` in +[`gateway.go`](../../internal/gateway/gateway.go)). It keeps their requests +apart even when two chats have the same first message. The same identity is +used for affinity, usage and the Routing page, and is preserved when passed +to a remote magpie, not copied to an ordinary vendor. Existing header +precedence is unchanged. Affinity previously kept under an inferred first +message digest is not migrated to a newly recognised native id, so the first +request after upgrading can choose an account anew. Historical usage is not +backfilled; see [Gateway Session Aggregation](gateway-sessions.md). + ## Responsibilities and sources of truth | Part | Responsibility | Source | diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 4064ed0de..11cf14cb2 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -21,6 +21,16 @@ routing summaries reuse versioned log snapshots; appends and rewrites invalidate them, and price/provider changes also invalidate priced projections. Single-session lookups use the cached identity index. Native exclusions are applied per caller. +WorkBuddy and CodeBuddy Code name their conversation in `X-Conversation-ID`. +The gateway reads it as a native session header, after the existing native +headers; `X-Magpie-Session` still overrides the recorded session without +changing its native identity. The per-turn `X-Conversation-Request-ID`, +per-message `X-Conversation-Message-ID` and `X-Parent-Conversation-ID` do not +identify the current session. This lets Routing group requests by the same id +the native WorkBuddy session reader already knows; old requests without a +recorded session remain unnamed. See `TestWorkBuddySessionHeader`, +`TestWorkBuddySessionThroughGateway` and `TestRemoteMagpieKeepsTheSession`. + When the same identity is present in a native session, the native session wins and the gateway projection is omitted. Gateway projections have no path, resume command or terminal action: the agent's own files of them are not on diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index bf3c388e6..68a146c4b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5662,10 +5662,12 @@ func developerAsSystem(body []byte) []byte { } // sessionHeaders are where agents already name their conversation: OpenCode -// (to its own gateway, and to everyone else), Pi, Codex and Claude Code. +// (to its own gateway, and to everyone else), Pi, Codex, Claude Code and +// WorkBuddy / CodeBuddy (X-Conversation-ID). var sessionHeaders = []string{ "x-opencode-session", "x-session-affinity", "x-session-id", "session_id", "session-id", "x-claude-code-session-id", + "x-conversation-id", } // SessionHeader names the session a call is part of, for the usage log to diff --git a/internal/gateway/remote_magpie_session_test.go b/internal/gateway/remote_magpie_session_test.go index 89d8bdb56..5c01b6760 100644 --- a/internal/gateway/remote_magpie_session_test.go +++ b/internal/gateway/remote_magpie_session_test.go @@ -71,14 +71,17 @@ func TestRemoteMagpieKeepsTheSession(t *testing.T) { t.Fatalf("no record %d of the remote's", n) return usage.Record{} } - for i, tc := range []struct{ path, body string }{ - {"/v1/chat/completions", `{"model":"office/fake/m1","messages":[{"role":"user","content":"hi"}]}`}, - {"/v1/responses", `{"model":"office/fake/m1","input":[{"role":"user","content":"hi"}],"prompt_cache_key":"cache-A"}`}, + for i, tc := range []struct{ path, body, ua, agent, header, native string }{ + {"/v1/chat/completions", `{"model":"office/fake/m1","messages":[{"role":"user","content":"hi"}]}`, "pi/1.0", "pi", "session_id", "native-A"}, + {"/v1/responses", `{"model":"office/fake/m1","input":[{"role":"user","content":"hi"}],"prompt_cache_key":"cache-A"}`, "pi/1.0", "pi", "session_id", "native-A"}, + {"/v1/chat/completions", `{"model":"office/fake/m1","messages":[{"role":"user","content":"hi"}]}`, "CLI/2.161.0 WorkBuddy/2.161.0", "workbuddy", "X-Conversation-ID", "workbuddy-A"}, + {"/v1/responses", `{"model":"office/fake/m1","input":[{"role":"user","content":"hi"}]}`, "CLI/2.161.0 WorkBuddy/2.161.0", "workbuddy", "X-Conversation-ID", "workbuddy-A"}, } { req := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)) - req.Header.Set("User-Agent", "pi/1.0") + req.Header.Set("User-Agent", tc.ua) + req.Header.Set("Authorization", "Bearer "+TokenFor(tc.agent)) req.Header.Set(SessionHeader, "trace-A") - req.Header.Set("session_id", "native-A") + req.Header.Set(tc.header, tc.native) rec := httptest.NewRecorder() New().Handler().ServeHTTP(rec, req) if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello") { @@ -87,18 +90,18 @@ func TestRemoteMagpieKeepsTheSession(t *testing.T) { mu.Lock() got := arrived[len(arrived)-1] mu.Unlock() - if got.Get(SessionHeader) != "trace-A" || got.Get("session_id") != "native-A" { - t.Errorf("%s: the remote magpie was sent %s=%q session_id=%q; want trace-A, native-A", tc.path, SessionHeader, got.Get(SessionHeader), got.Get("session_id")) + if got.Get(SessionHeader) != "trace-A" || got.Get(tc.header) != tc.native { + t.Errorf("%s: the remote magpie was sent %s=%q %s=%q; want trace-A, %s", tc.path, SessionHeader, got.Get(SessionHeader), tc.header, got.Get(tc.header), tc.native) } - if r := there(i + 1); r.Session != "trace-A" || r.NativeSession != "native-A" || r.Agent != "pi" { - t.Errorf("%s: the remote recorded agent %q session %q native %q; want pi, trace-A, native-A", tc.path, r.Agent, r.Session, r.NativeSession) + if r := there(i + 1); r.Session != "trace-A" || r.NativeSession != tc.native || r.Agent != tc.agent { + t.Errorf("%s: the remote recorded agent %q session %q native %q; want %s, trace-A, %s", tc.path, r.Agent, r.Session, r.NativeSession, tc.agent, tc.native) } } mu.Lock() defer mu.Unlock() for _, v := range vendor { for k := range v { - if lk := strings.ToLower(k); strings.HasPrefix(lk, "x-magpie-") || lk == "session_id" { + if lk := strings.ToLower(k); strings.HasPrefix(lk, "x-magpie-") || lk == "session_id" || lk == "x-conversation-id" { t.Errorf("the vendor was sent %s", k) } } diff --git a/internal/gateway/workbuddy_session_test.go b/internal/gateway/workbuddy_session_test.go new file mode 100644 index 000000000..138a81ee3 --- /dev/null +++ b/internal/gateway/workbuddy_session_test.go @@ -0,0 +1,160 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" +) + +// WorkBuddy 5.8.2's bundled ModelProvider sends the session as +// X-Conversation-ID, not its per-turn request or per-message id. +func TestWorkBuddySessionHeader(t *testing.T) { + const body = `{"messages":[{"role":"user","content":"hello"}]}` + h := http.Header{} + h.Set("X-Conversation-ID", "workbuddy-session") + h.Set("X-Conversation-Request-ID", "turn-1") + h.Set("X-Conversation-Message-ID", "message-1") + for name, got := range map[string]string{ + "session": sessionOf(h), "native": nativeSessionOf(h), + "conversation": conversationID(h, []byte(body)), "otel": otelSessionOf(h), + } { + if got != "workbuddy-session" { + t.Errorf("%s = %q, want WorkBuddy's actual session", name, got) + } + } + if got := convOf(h, []byte(body)); got != "" { + t.Errorf("an explicit WorkBuddy session still has an inferred conversation %q", got) + } + h.Set(SessionHeader, "override") + if sessionOf(h) != "override" || nativeSessionOf(h) != "workbuddy-session" || otelSessionOf(h) != "workbuddy-session" || conversationID(h, []byte(body)) != "workbuddy-session" { + t.Fatal("the explicit override lost WorkBuddy's native session") + } + for _, header := range []string{"x-opencode-session", "x-session-affinity", "x-session-id", "session_id", "session-id", "x-claude-code-session-id"} { + t.Run(header, func(t *testing.T) { + h := http.Header{} + h.Set(header, "existing-session") + h.Set("X-Conversation-ID", "workbuddy-session") + if sessionOf(h) != "existing-session" || nativeSessionOf(h) != "existing-session" || conversationID(h, []byte(body)) != "existing-session" { + t.Fatal("WorkBuddy's fallback header overrode an existing session header") + } + }) + } + h = http.Header{} + h.Set("X-Conversation-Request-ID", "turn-only") + h.Set("X-Conversation-Message-ID", "message-only") + h.Set("X-Parent-Conversation-ID", "parent-only") + if sessionOf(h) != "" || nativeSessionOf(h) != "" || conversationID(h, []byte(body)) != conversationID(http.Header{}, []byte(body)) { + t.Fatal("a turn, message or parent id became the current session") + } + h.Set("x-conversation-id", " ") + if sessionOf(h) != "" || nativeSessionOf(h) != "" { + t.Fatal("an empty conversation header became a session") + } + h.Set("x-conversation-id", " "+strings.Repeat("s", 140)+" ") + if sessionOf(h) != strings.Repeat("s", 128) || nativeSessionOf(h) != strings.Repeat("s", 128) { + t.Fatal("the new header bypassed the existing session bounds") + } +} + +func TestWorkBuddySessionThroughGateway(t *testing.T) { + fresh(t) + var mu sync.Mutex + var seen []http.Header + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + seen = append(seen, r.Header.Clone()) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"chatcmpl-test","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3000,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":2500}}}`) + })) + t.Cleanup(up.Close) + for _, id := range []string{"first", "second"} { + if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "test-key", Keys: []provider.KeyAccount{{Key: "other-test-key"}}, Models: []string{"m"}, Chat: up.URL + "/v1", Affinity: provider.AffinitySession}); err != nil { + t.Fatal(err) + } + } + if err := sessions.SetGatewayRecording(true, false); err != nil { + t.Fatal(err) + } + s := New() + handler := lanGuard(s.Handler()) + send := func(model, session, turn, message string) Route { + t.Helper() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hello"}]}`)) + req.RemoteAddr = "127.0.0.1:5000" + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "CLI/2.161.0 WorkBuddy/2.161.0") + req.Header.Set("Authorization", "Bearer "+TokenFor("workbuddy")) + req.Header.Set("X-Conversation-ID", session) + req.Header.Set("X-Conversation-Request-ID", turn) + req.Header.Set("X-Conversation-Message-ID", message) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || rec.Header().Get(SessionHeader) != session { + t.Fatalf("reply status=%d session=%q body=%s", rec.Code, rec.Header().Get(SessionHeader), rec.Body) + } + rows := s.Trace(context.Background(), 0, 0).Routes + last := rows[len(rows)-1] + if last.Agent != "workbuddy" || last.Session != session || last.Conv != "" { + t.Fatalf("request was not attributed to its real WorkBuddy session: agent=%q session=%q conv=%q", last.Agent, last.Session, last.Conv) + } + return last + } + first := send("first/m", "chat-a", "turn-1", "message-1") + again := send("first/m", "chat-a", "turn-1", "message-2") + other := send("first/m", "chat-b", "turn-1", "message-3") + send("second/m", "chat-a", "turn-2", "message-4") + if first.Affinity == nil || first.Affinity.Why != "first" || again.Affinity == nil || !again.Affinity.Kept || other.Affinity == nil || other.Affinity.Why != "first" { + t.Fatalf("sessions with the same first message shared affinity: first=%+v again=%+v other=%+v", first.Affinity, again.Affinity, other.Affinity) + } + counts := map[string]int{} + for _, record := range usage.Load(time.Time{}) { + if record.Agent == "workbuddy" { + if record.NativeSession != record.Session { + t.Errorf("usage lost the native session: %+v", record) + } + counts[record.Session]++ + } + } + if counts["chat-a"] != 3 || counts["chat-b"] != 1 { + t.Fatalf("usage grouped requests incorrectly: %v", counts) + } + for id, want := range map[string]int{"chat-a": 3, "chat-b": 1} { + transcript, err := sessions.GatewayTranscript("workbuddy", id) + if err != nil || transcript.Captured != want { + t.Errorf("session %s captured %d turns, want %d: %v", id, transcript.Captured, want, err) + } + } + get := httptest.NewRequest("GET", "/v1/magpie/route", nil) + get.RemoteAddr = "127.0.0.1:5000" + get.Header.Set("X-Conversation-ID", "chat-a") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, get) + var latest struct { + Session string `json:"session"` + Route *SessionRoute `json:"route"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &latest); err != nil || rec.Code != http.StatusOK || latest.Session != "chat-a" || latest.Route == nil || latest.Route.Asked != "second/m" { + t.Fatalf("session lookup missed WorkBuddy's latest model: %d %s (%v)", rec.Code, rec.Body, err) + } + mu.Lock() + defer mu.Unlock() + for _, headers := range seen { + for _, name := range []string{SessionHeader, "X-Conversation-ID", "X-Conversation-Request-ID", "X-Conversation-Message-ID"} { + if headers.Get(name) != "" { + t.Errorf("private client identity leaked to the vendor in %s", name) + } + } + } +}