Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions core/schemas/useragents.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package schemas
import (
"regexp"
"strings"
"unicode/utf8"
)

// UserAgentIdentifiers lists substrings that may appear in User-Agent for a given integration.
Expand Down Expand Up @@ -40,6 +41,54 @@ var (
QwenCodeCLI = UserAgentIdentifiers{"qwen-code", "qwencode", "qwen"}
)

// MaxSessionIDLength caps every caller-asserted session identifier Bifrost
// ingests, counted in runes rather than bytes so the limit means the same thing
// for a non-ASCII identifier as for an ASCII one.
//
// Session IDs become KV lookup keys and exported trace attributes, and the
// OpenTelemetry attribute value length limit defaults to unlimited
// (https://opentelemetry.io/docs/specs/otel/common/#attribute-limits), so
// nothing downstream bounds a caller-controlled value for us. Every ingestion
// path (x-bf-session-id, the baggage session-id member, x-bf-mcp-session-id, and
// the harness headers below) goes through NormalizeSessionID.
const MaxSessionIDLength = 255
Comment thread
akshaydeo marked this conversation as resolved.
Resolved

// NormalizeSessionID trims a caller-asserted session identifier and reports
// whether it is usable: non-empty and no longer than MaxSessionIDLength runes.
// Every session ingestion path shares it so one rule governs what can become a
// KV lookup key or an exported trace attribute.
func NormalizeSessionID(value string) (string, bool) {
value = strings.TrimSpace(value)
if value == "" || utf8.RuneCountInString(value) > MaxSessionIDLength {
return "", false
}
return value, true
}

// HarnessSessionHeaders lists the headers coding harnesses use to carry their
// own session identifier, in priority order. Bifrost falls back to these when
// x-bf-session-id is absent, so harness traffic gets provider key stickiness and
// OTEL session grouping without the caller renaming anything.
//
// Claude Code documents x-claude-code-session-id for exactly this purpose and
// classifies it as a header a gateway may consume rather than forward:
// https://code.claude.com/docs/en/llm-gateway-protocol#request-headers
// That reference also treats x-claude-code-* as an open list that grows with
// releases, so revisit this table when Claude Code ships new attribution headers.
//
// Only headers a harness verifiably sends belong here. Deliberately absent:
// x-parent-session-id (OpenCode) would collapse every sub-agent onto its
// parent's key, and x-qwen-code-session-id was designed but never shipped.
var HarnessSessionHeaders = []string{
"x-claude-code-session-id", // Claude Code, and wrappers that spawn it (e.g. Conductor)
"x-session-affinity", // OpenCode
"x-session-id", // OpenCode sends this alongside the above; also the generic convention
"session-id", // Codex CLI
"session_id", // Codex CLI, builds predating the dashed rename
"thread-id", // Codex CLI thread: coarser, only when no session header is sent
"conversation_id", // Codex CLI, builds predating the dashed rename
}

// UserAgentAppMatcher maps a detected application label to User-Agent identifiers.
type UserAgentAppMatcher struct {
App string
Expand Down
2 changes: 2 additions & 0 deletions docs/features/observability/otel.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ Because all requests in a session share one trace, very long-lived sessions prod

To send a session ID, pass the [`x-bf-session-id`](/providers/request-options) header on each request you want grouped together.

Requests from a coding harness need no Bifrost-specific header: when `x-bf-session-id` is absent, Bifrost adopts the harness's own session header (Claude Code, Codex CLI, and OpenCode are recognized). That populates `session.id` on every request in the run; enable `group_traces_by_session` to collapse the run into a single trace. See [Coding Harness Headers](/providers/request-options#session-stickiness-session-id) for the full list.
Comment thread
akshaydeo marked this conversation as resolved.
Resolved

---

## Setup
Expand Down
22 changes: 21 additions & 1 deletion docs/providers/request-options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Bifrost provides request options that control behavior, enable features, and pas
| `BifrostContextKeyAPIKeyName` | `x-bf-api-key` | `string` | Explicit API key name selection |
| `BifrostContextKeyAPIKeyID` | `x-bf-api-key-id` | `string` | Explicit API key ID selection (takes priority over name) |
| `BifrostContextKeyDirectKey` | `x-bf-direct-key` (+ `Authorization` / `x-api-key` / `x-goog-api-key`) | `schemas.Key` | Use a caller-supplied raw provider key directly, bypassing the registered key pool. On the gateway, requires `allow_direct_keys` server-side |
| `BifrostContextKeySessionID` | `x-bf-session-id` | `string` | Session ID for key stickiness (requires KV store) |
| `BifrostContextKeySessionID` | `x-bf-session-id` (falls back to coding-harness session headers) | `string` | Session ID for key stickiness (requires KV store) |
| `BifrostContextKeySessionTTL` | `x-bf-session-ttl` | `time.Duration` | Session-to-key cache TTL (duration string or seconds) |
| `BifrostContextKeyRequestID` | `x-request-id` | `string` | Custom request ID for tracking |
| `BifrostContextKeySendBackRawRequest` | `x-bf-send-back-raw-request` | `bool` | Include raw provider request in the response |
Expand Down Expand Up @@ -236,6 +236,26 @@ On the first request for a session ID, Bifrost selects a key and caches the bind
- **Retries**: Session stickiness persists across retry attempts. If a request fails and is retried, the same sticky key is used.
- **Fallbacks**: When falling back to a different provider (e.g., from OpenAI to Anthropic), session stickiness is disabled and a new key is selected for the fallback provider. This ensures availability when the primary provider's keys are exhausted or failing.

**Coding Harness Headers:**

Coding harnesses already send a session identifier on every request under their own header name. When `x-bf-session-id` is absent, Bifrost adopts the first of these it finds, so pointing a harness at Bifrost gives you session stickiness and session-grouped traces with no configuration:

| Header | Sent by |
| --------------------------- | ---------------------------------------------------------------- |
| `x-claude-code-session-id` | Claude Code, and tools that run it (for example Conductor) |
| `x-session-affinity` | OpenCode |
| `x-session-id` | OpenCode (alongside the above), and clients using the generic convention |
| `session-id` | Codex CLI |
| `session_id` | Codex CLI, builds predating its dashed-header rename |
| `thread-id` | Codex CLI thread, used only when no session header is sent |
| `conversation_id` | Codex CLI, builds predating its dashed-header rename |

The list is ordered: the first non-empty header whose value is at most 255 runes wins, so a blank or over-long header is skipped and the next one is tried.

An explicit `x-bf-session-id` always overrides all of them, so you can group requests your own way regardless of what the client sends. It also decides the outcome when it is unusable: a request that sends an `x-bf-session-id` longer than 255 runes gets no session at all rather than falling back to a harness header, because silently grouping it under a session you did not ask for is worse than leaving it ungrouped.

Claude Code documents `x-claude-code-session-id` in its [gateway protocol reference](https://code.claude.com/docs/en/llm-gateway-protocol#request-headers), where it is listed as a header a gateway may consume for attribution rather than forward upstream. Subagent requests carry the same session ID as their parent, so an agent run with parallel subagents stays on one key.

<Tabs>
<Tab title="Gateway (cURL)">
```bash
Expand Down
6 changes: 5 additions & 1 deletion transports/bifrost-http/handlers/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -1344,7 +1344,11 @@ func (m *TracingMiddleware) Middleware() schemas.BifrostHTTPMiddleware {
// asynchronously and must never observe later mutations.
tracer.SetTraceAttribute(traceID, schemas.TraceAttrDimensions, maps.Clone(dimensions))
}
if sessionID := strings.TrimSpace(string(ctx.Request.Header.Peek("x-bf-session-id"))); sessionID != "" {
// Resolved rather than peeked: this middleware runs before context
// conversion, so it repeats the same x-bf-session-id-then-harness-header
// lookup ConvertToBifrostContext does. Both read the same headers with
// the same priority list, so key stickiness and session.id agree.
if sessionID := lib.ResolveSessionIDFromRequest(&ctx.Request.Header); sessionID != "" {
tracer.SetTraceAttribute(traceID, schemas.TraceAttrSessionID, sessionID)
}
// Only trace ID goes into context (lightweight, no bloat)
Expand Down
123 changes: 109 additions & 14 deletions transports/bifrost-http/lib/ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"

"github.com/google/uuid"
"github.com/maximhq/bifrost/core/schemas"
Expand Down Expand Up @@ -87,17 +88,93 @@ func ParseSessionIDFromBaggage(header string) string {
if key != "session-id" || value == "" {
continue
}
if len(value) > 255 {
sessionID, ok := schemas.NormalizeSessionID(value)
if !ok {
if logger != nil {
logger.Warn("session-id exceeds 255 chars, ignoring: length=%d, prefix=%s", len(value), value[:255])
// Length only, never the value: baggage is caller-controlled.
logger.Warn("baggage session-id exceeds %d runes, ignoring: length=%d", schemas.MaxSessionIDLength, utf8.RuneCountInString(value))
}
continue
}
return value
return sessionID
}
return ""
}

// ResolveHarnessSessionID returns the first non-empty header from
// schemas.HarnessSessionHeaders, in that list's priority order. Coding harnesses
// (Claude Code, Codex CLI, OpenCode) already send a session identifier on every
// request under their own header name; honoring it means their traffic gets key
// stickiness and OTEL session grouping without the caller setting x-bf-session-id.
//
// headers must be keyed by lowercased header name. Values are trimmed and
// rejected past schemas.MaxSessionIDLength so no ingestion path can plant an
// oversized KV lookup key or trace attribute. Callers are responsible for
// preferring an explicit x-bf-session-id over this result.
func ResolveHarnessSessionID(headers map[string]string) string {
if len(headers) == 0 {
return ""
}
for _, name := range schemas.HarnessSessionHeaders {
raw := headers[name]
if strings.TrimSpace(raw) == "" {
continue
}
sessionID, ok := schemas.NormalizeSessionID(raw)
if !ok {
if logger != nil {
// Don't echo the value: harness session headers are caller-controlled.
logger.Warn("%s exceeds %d runes, ignoring: length=%d", name, schemas.MaxSessionIDLength, utf8.RuneCountInString(strings.TrimSpace(raw)))
}
continue
}
return sessionID
}
return ""
}

// ResolveSessionIDFromHeaders returns the session ID for a request from a
// lowercased header map. An explicit x-bf-session-id decides the outcome
// whenever the caller sends one: if it is valid it wins, and if it is oversized
// the request gets no session at all rather than silently adopting a harness
// header, because substituting a different session identity for the one the
// caller asked for is worse than having none. Only when no explicit header is
// present do the harness headers apply.
func ResolveSessionIDFromHeaders(headers map[string]string) string {
if raw := headers["x-bf-session-id"]; strings.TrimSpace(raw) != "" {
sessionID, ok := schemas.NormalizeSessionID(raw)
if !ok {
if logger != nil {
// Length only, never the value: x-bf-session-id is caller-controlled.
logger.Warn("x-bf-session-id exceeds %d runes, ignoring: length=%d", schemas.MaxSessionIDLength, utf8.RuneCountInString(strings.TrimSpace(raw)))
}
return ""
}
return sessionID
}
return ResolveHarnessSessionID(headers)
}

// ResolveSessionIDFromRequest is ResolveSessionIDFromHeaders for callers that
// hold a fasthttp header rather than the lowercased header map
// ConvertToBifrostContext builds, notably the tracing middleware, which runs
// before context conversion.
//
// Keys are lowercased during iteration rather than read with Peek so the result
// never depends on fasthttp header-name normalization, which does not fold the
// underscore forms Codex CLI still sends.
func ResolveSessionIDFromRequest(h *fasthttp.RequestHeader) string {
if h == nil {
return ""
}
headers := make(map[string]string, h.Len())
h.All()(func(key, value []byte) bool {
headers[strings.ToLower(string(key))] = string(value)
return true
})
return ResolveSessionIDFromHeaders(headers)
}

// ConvertToBifrostContext converts a FastHTTP RequestCtx to a Bifrost context,
// preserving important header values for monitoring and tracing purposes.
//
Expand Down Expand Up @@ -144,7 +221,9 @@ func ParseSessionIDFromBaggage(header string) string {
// - This allows callers to send arbitrary context metadata without needing to extend the public schema
//
// 8. Session Stickiness Headers:
// - x-bf-session-id: Session identifier for key binding (reuse same key across requests)
// - x-bf-session-id: Session identifier for key binding (reuse same key across requests).
// When absent, falls back to the coding-harness session headers listed in
// schemas.HarnessSessionHeaders (Claude Code, Codex CLI, OpenCode).
// - x-bf-session-ttl: Per-request TTL override (duration string e.g. "30m" or seconds integer)
//
// 9. Raw Capture Headers (per-request override of provider config; accepts "true" or "false"):
Expand Down Expand Up @@ -336,16 +415,17 @@ func ConvertToBifrostContext(ctx *fasthttp.RequestCtx, store HandlerStore) (*sch
// Handle MCP session ID header (x-bf-mcp-session-id): a client-issued
// opaque identifier used for session-mode per-user OAuth flows. Any
// non-empty string the caller can re-present on subsequent /mcp calls.
// 255-char cap matches ParseSessionIDFromBaggage so both ingestion
// paths reject oversized lookup keys consistently.
// schemas.NormalizeSessionID applies the same cap as every other session
// ingestion path, so none of them can accept a lookup key the others reject.
if keyStr == "x-bf-mcp-session-id" {
if v := strings.TrimSpace(string(value)); v != "" {
if len(v) > 255 {
// Don't echo any of the value — x-bf-mcp-session-id is a
if raw := strings.TrimSpace(string(value)); raw != "" {
v, ok := schemas.NormalizeSessionID(raw)
if !ok {
// Don't echo any of the value: x-bf-mcp-session-id is a
// re-presentable lookup key for session-mode OAuth; the
// length alone is enough for debugging.
if logger != nil {
logger.Warn("x-bf-mcp-session-id exceeds 255 chars, ignoring: length=%d (skipped last %d chars)", len(v), len(v)-255)
logger.Warn("x-bf-mcp-session-id exceeds %d runes, ignoring: length=%d", schemas.MaxSessionIDLength, utf8.RuneCountInString(raw))
}
return true
}
Expand Down Expand Up @@ -446,11 +526,11 @@ func ConvertToBifrostContext(ctx *fasthttp.RequestCtx, store HandlerStore) (*sch
}
return true
}
// Session stickiness: session ID for key binding
// Session stickiness: session ID for key binding. Consumed here so the
// header is not forwarded to the provider by the direct-forwarding path
// below; the value itself is resolved once after this loop, by the same
// function the tracing middleware calls, so the two cannot disagree.
if keyStr == "x-bf-session-id" {
if valueStr := strings.TrimSpace(string(value)); valueStr != "" {
bifrostCtx.SetValue(schemas.BifrostContextKeySessionID, valueStr)
}
return true
}
// Session stickiness: per-request TTL override (duration string or seconds integer)
Expand Down Expand Up @@ -643,6 +723,21 @@ func ConvertToBifrostContext(ctx *fasthttp.RequestCtx, store HandlerStore) (*sch
})
bifrostCtx.SetValue(schemas.BifrostContextKeyRequestHeaders, allHeaders)

// Session stickiness: an explicit x-bf-session-id wins, otherwise the
// harness's own session header applies, so Claude Code / Codex CLI /
// OpenCode traffic gets key stickiness without the caller renaming anything.
//
// This deliberately runs after the header loop rather than inside it: that
// loop is a single pass with early returns, and header order is not
// guaranteed, so a harness header arriving first would otherwise beat
// x-bf-session-id. allHeaders is already built and already lowercased, so
// this costs no extra header iteration, and routing both the explicit and
// the harness case through one resolver keeps stickiness and the OTEL
// session.id trace attribute in agreement.
if sessionID := ResolveSessionIDFromHeaders(allHeaders); sessionID != "" {
bifrostCtx.SetValue(schemas.BifrostContextKeySessionID, sessionID)
}

// Collect all request query params for downstream use (e.g., governance routing CEL rules
// that read params["..."]). Keys are lowercased for case-insensitive lookup.
queryArgs := ctx.Request.URI().QueryArgs()
Expand Down
Loading
Loading