diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 43fe3920b..ff7e6f2f2 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -9,6 +9,12 @@ origins can read this header through CORS. magpie never makes up an id for a request without one, so such a request has no session and its text is not recorded: text kept under an id nothing lists couldn't be opened. Prompt text, caller keys and network addresses are never used to guess conversation ownership. +So the configs magpie writes have each agent name its session: Pi's provider +block sets `compat.sendSessionAffinityHeaders` (`x-session-affinity` on Chat and +Messages; Responses sends `session_id` anyway), and omp 16.0.6 and later gets +`compat.promptCacheSessionHeader: x-session-affinity`. A user's own +`sendSessionAffinityHeaders` is kept (`piBlockKept`). Verification: +`TestPiNamesItsSessionToTheGateway`, `TestOmpNamesItsSessionToTheGateway`. Older ledger records without `Session` remain excluded. The projection is computed from the usage ledger and is not persisted. Window projections and routing summaries reuse versioned log snapshots; appends and rewrites invalidate diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 1dac8d9b6..bb2c7e0ea 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -392,11 +392,40 @@ func magpieProviderJSONAt(shape, catalog, gw string) any { if ms == nil { ms = []map[string]any{} } - return map[string]any{"name": "magpie", "baseUrl": gw + "/v1", "api": "openai-completions", "apiKey": keyAt(gw), "models": ms} + // Pi names its session to a provider only when asked to: + // sendSessionAffinityHeaders has it send it on Chat + // (x-session-affinity, session_id) and Anthropic's Messages API + // (x-session-affinity). On Responses it sends session_id anyway. + // Without it a turn of Pi's on Chat or Messages reached the gateway + // with no session: its usage had none and "Record gateway + // conversations" kept none of it (akic404 on Discord). + return map[string]any{"name": "magpie", "baseUrl": gw + "/v1", "api": "openai-completions", "apiKey": keyAt(gw), + "compat": map[string]any{"sendSessionAffinityHeaders": true}, "models": ms} } return nil } +// piBlockKept is theirsKept for magpie's provider in a Pi models.json at +// path, where a sendSessionAffinityHeaders the file already has, the +// user's own or pi-cache-optimizer's (#1103), stays as it is. +func piBlockKept(path string, value func() any) func() any { + return theirsKept(path, "providers."+magpieID, func() any { + v := value() + if _, set := edit.GetJSON(path, "providers."+magpieID+".compat.sendSessionAffinityHeaders"); !set { + return v + } + if m, ok := v.(map[string]any); ok { + if c, ok := m["compat"].(map[string]any); ok { + delete(c, "sendSessionAffinityHeaders") + if len(c) == 0 { + delete(m, "compat") + } + } + } + return v + }, "models") +} + // piModelJSON is one of magpie's models as an entry of Pi's models.json. // native asks it on the API its provider speaks natively (a model's own // api and baseUrl); without it the model is left on the provider's @@ -817,7 +846,7 @@ func piLike(at place, id, name, dir string) *Agent { pair := pairSet(set, "defaultProvider", "defaultModel") // the model a new session starts on, as the model field shows it startup := func() string { return piStartup(path, pairGet(get, "defaultProvider", "defaultModel")()) } - block := theirsKept(modelsPath, "providers."+magpieID, func() any { return magpieProviderJSONAt("pi", id, at.gw()) }, "models") + block := piBlockKept(modelsPath, func() any { return magpieProviderJSONAt("pi", id, at.gw()) }) writeMagpie := func() error { return edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: block()}) } diff --git a/internal/agent/aside_native.go b/internal/agent/aside_native.go index 499ebd5cf..5fd66d4b9 100644 --- a/internal/agent/aside_native.go +++ b/internal/agent/aside_native.go @@ -360,7 +360,7 @@ func (c *asideConnection) sync() error { // kept is the block with what else Aside's providers.magpie holds kept // (theirsKept). func (c *asideConnection) kept() func() any { - return theirsKept(c.models, "providers.magpie", c.block, "models") + return piBlockKept(c.models, c.block) } func (c *asideConnection) state() NativeState { diff --git a/internal/agent/omp.go b/internal/agent/omp.go index 8401dd82f..a001c6371 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -527,9 +527,20 @@ type ompProviderEntry struct { // and only a later one with its own (omp/18.4.4), so its requests went // to "Bun" in usage and past omp's own rules and stand-ins Headers map[string]string `yaml:"headers,omitempty"` - Models []ompModel `yaml:"models"` + // Compat names the header omp sends its session in. omp names the + // conversation on Anthropic's Messages API (X-Claude-Code-Session-Id), + // and on Chat and Responses only to OpenAI itself, so a turn of omp's on + // Chat or Responses reached the gateway with no session: its usage had + // none and "Record gateway conversations" kept none of it (akic404 on + // Discord). promptCacheSessionHeader has omp send its session id in it. + Compat map[string]string `yaml:"compat,omitempty"` + Models []ompModel `yaml:"models"` } +// ompSessionSince is the first omp whose compat takes +// promptCacheSessionHeader (pi-catalog 16.0.6). +const ompSessionSince = "16.0.6" + // ompMaxSince is the first omp whose models.yml takes max as a thinking // effort (pi-ai 16.4.0); 16.3.5's schema stops at xhigh and turns the whole // file away over a max. @@ -609,6 +620,9 @@ func ompProviderAt(gw, version string) ompProviderEntry { } e := ompProviderEntry{BaseURL: gw + "/v1", API: "openai-completions", Auth: "none", Headers: map[string]string{"User-Agent": "omp"}, Models: ms} + if version != "" && !Newer(ompSessionSince, version) { + e.Compat = map[string]string{"promptCacheSessionHeader": "x-session-affinity"} + } // whqtian on Discord: a WSL omp under NAT asks Windows' address, where // the gateway turns a request without a named key away if key := keyAt(gw); key != gateway.Token { diff --git a/internal/agent/session_header_test.go b/internal/agent/session_header_test.go new file mode 100644 index 000000000..e392606df --- /dev/null +++ b/internal/agent/session_header_test.go @@ -0,0 +1,57 @@ +package agent + +import ( + "path/filepath" + "testing" +) + +// akic404 on Discord: with "Record gateway conversations" on, OpenCode's +// turns were kept and Pi's and omp's weren't. The gateway records a turn +// only under the session the agent names, and Pi (1.1.0) names it on Chat +// and Anthropic's Messages API only when its provider's compat says +// sendSessionAffinityHeaders, omp (18.6.1) on Chat and Responses only to +// OpenAI itself. Both were run against a header dump: with the provider +// block magpie writes, Pi sends x-session-affinity on Chat and Messages +// and session_id on Responses, omp x-session-affinity on Chat and +// Responses (and X-Claude-Code-Session-Id on Messages, as before). +func TestPiNamesItsSessionToTheGateway(t *testing.T) { + home := syncHome(t) + piModels := filepath.Join(home, ".pi", "agent", "models.json") + if err := pi(home).Fields[0].Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + compat, _ := providerAt(t, piModels, "providers")["compat"].(map[string]any) + if compat["sendSessionAffinityHeaders"] != true { + t.Fatalf("Pi isn't told to name its session:\n%s", readFile(piModels)) + } + + // one the user turned off stays off, through a sync and a pick + writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","baseUrl":"http://127.0.0.1:3425/v1","api":"openai-completions","apiKey":"magpie","compat":{"sendSessionAffinityHeaders":false,"supportsStore":false},"models":[]}}}`) + SyncCatalog() + if err := pi(home).Fields[0].Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + compat, _ = providerAt(t, piModels, "providers")["compat"].(map[string]any) + if compat["sendSessionAffinityHeaders"] != false || compat["supportsStore"] != false { + t.Fatalf("the user's own compat was written over:\n%s", readFile(piModels)) + } +} + +func TestOmpNamesItsSessionToTheGateway(t *testing.T) { + syncHome(t) + for _, c := range []struct { + version string + want string + }{ + {"18.6.1", "x-session-affinity"}, + {"16.0.6", "x-session-affinity"}, + // before 16.0.6 omp had no promptCacheSessionHeader; an omp whose + // version isn't known is taken for an older one + {"16.0.5", ""}, + {"", ""}, + } { + if got := ompProviderAt("http://127.0.0.1:3425", c.version).Compat["promptCacheSessionHeader"]; got != c.want { + t.Errorf("omp %q: promptCacheSessionHeader %q, want %q", c.version, got, c.want) + } + } +}