From a0f8e61494a2c288fc2eac28e41fef97129d021c Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Fri, 4 Dec 2026 15:58:32 +0100
Subject: [PATCH] feat(ai): send W3C trace context on agent model calls
agentClient now wraps its transport in otelhttp.NewTransport with only
the TraceContext propagator. Each provider call becomes an HTTP client
span of the agent's request, and the provider receives traceparent and
tracestate, so a gateway that traces (the llm-serving-pack's AI Gateway)
continues the same trace. baggage never goes out: the transport does not
use the server's TraceContext+Baggage propagators. The guard,
ResponseHeaderTimeout and the absence of a whole-request timeout are
unchanged.
TestAgentCallCarriesOnlyTraceContext drives the real Proxy and agentClient
against a fake provider and asserts the exact header set for six cases:
telemetry on or off, with a valid, missing or malformed incoming
traceparent, streamed and not. Each case gets its own tracer provider
through the handler rather than the global one.
Docs: a contract entry for the headers a model call carries to the
provider, two patterns, and a paragraph in the admin configuration page.
Refs nebari-dev/llm-serving-pack#315, nebari-dev/llm-serving-pack#148
---
docs/architecture/contracts.md | 6 +
docs/architecture/patterns.md | 10 +
internal/ai/aisettings/aisettings.go | 7 +-
internal/ai/aisettings/aisettings_test.go | 208 +++++++++++++++++++
site/src/content/docs/admin/configuration.md | 2 +
5 files changed, 232 insertions(+), 1 deletion(-)
diff --git a/docs/architecture/contracts.md b/docs/architecture/contracts.md
index 0fcba408..c142425f 100644
--- a/docs/architecture/contracts.md
+++ b/docs/architecture/contracts.md
@@ -391,3 +391,9 @@ What each promoted component contract promises today, in the code as it is now.
**Promises:** on a `tool-output-available` chunk, and on the saved `dynamic-tool` part, of a `tapas` server tool whose result holds a plan waiting for approval, `toolMetadata` is `{"tapas": {"kind": "approval", "planId", "approveUrl"?}}`. On a `tool-output-error` chunk or saved part of a policy denial it is `{"tapas": {"kind": "denied", "message"}}`. Every other tool output has no `toolMetadata`. The output and `errorText` are unchanged. Only the `tapas` server's results are read, so another MCP server cannot claim a Tapas plan; the UI acts on `planId` through the plans API, never on `approveUrl`.
**Errors:** a mark with a missing field is not sent.
**Since:** 2026-12-03 (nebari-dev/tapas#79)
+
+### Headers a model call from `agentproxy` carries to the provider
+**Owner:** `internal/ai/agentproxy` (`Proxy.chat`, which sets the headers) and `internal/ai/aisettings` (`agentClient(timeout, guard) *http.Client`, whose transport adds the trace context) ยท **Consumers:** the admin's OpenAI-compatible provider, which may be a third party outside the cluster, and the llm-serving-pack's AI Gateway, which continues the trace (verified: `grep -rn -e 'agentClient(' -e 'req.Header.Set' internal/ai/aisettings/aisettings.go internal/ai/agentproxy/agentproxy.go`)
+**Promises:** a request to `/chat/completions` carries `Content-Type: application/json`, `Authorization: Bearer `, `Accept: text/event-stream` when the request streams, and the W3C trace context of the call's client span (`traceparent`, and `tracestate` when the trace has one), plus what Go's HTTP client adds itself (`User-Agent`, `Accept-Encoding`, `Content-Length`). Nothing else the agent sent goes out: never its token or cookies, and never `baggage`, which may name the caller. The trace context is `agentClient`'s `otelhttp.NewTransport` with only `propagation.TraceContext{}`; the call is a standard HTTP client span whose parent is the gateway's server span from `telemetry.Handler`, so, while `telemetry.Start` exports, an agent's valid `traceparent` is continued with a new span id and a call without one starts a trace of its own. While it exports nothing (no SDK tracer provider), an agent's valid `traceparent` and `tracestate` go on as they came, a malformed one is dropped, and a call without one sends no trace context. `agentClient` keeps its signature, the guard, `ResponseHeaderTimeout` (the longer of `ai.timeout` and five minutes) and no whole-request timeout, so a streamed answer is unchanged. `TestAgentCallCarriesOnlyTraceContext` (`internal/ai/aisettings/aisettings_test.go`) checks the exact header set.
+**Errors:** none of its own; a failed call is the proxy's 502 as before.
+**Since:** 2026-12-04 (nebari-dev/llm-serving-pack#315; traces: nebari-dev/llm-serving-pack#148)
diff --git a/docs/architecture/patterns.md b/docs/architecture/patterns.md
index 444909c7..9eb57bc7 100644
--- a/docs/architecture/patterns.md
+++ b/docs/architecture/patterns.md
@@ -104,6 +104,16 @@ The agent token janitor, `agenttoken.Broker.RunJanitor(ctx, first, every)`, take
**Confirmed:** 2026-11-30 (spec: docs/superpowers/specs/2026-11-30-frames-integration-design.md)
+### The agent model proxy sends the provider a fixed, listed set of headers and never the caller's token or cookies; the only trace headers added are the W3C trace context (`traceparent`, `tracestate`), never `baggage`
+`internal/ai/agentproxy/agentproxy.go:198-203`, `internal/ai/aisettings/aisettings.go:390-397`
+
+**Confirmed:** 2026-12-04 (nebari-dev/llm-serving-pack#315; traces: nebari-dev/llm-serving-pack#148)
+
+### Telemetry is configured only by the standard `OTEL_*` variables and is off when no endpoint is set; incoming W3C trace context is read by `telemetry.Handler` whether or not anything is exported
+`internal/telemetry/telemetry.go:60-66`, `:75-78`
+
+**Confirmed:** 2026-12-04 (nebari-dev/llm-serving-pack#315; traces: nebari-dev/llm-serving-pack#148)
+
### A coding agent's credentials live in the helper sidecar; the agent gets only local helper addresses; the helper drops incoming credentials, adds its own, forwards to fixed destinations, and logs method and path only
`internal/agenthelper/agenthelper.go:1-11` (the package doc, which names the three routes), `:89-133` (`Handler` and `routeOf`: `/api/` and `/frames` to the gateway with the app token, `/model` to the model's base URL with the model key), `internal/controller/workspace/agenthelper.go:33-86` (`addAgentHelper`, which also sets `JAVO_FRAMES_URL` on the agent when `Inputs.Frames`)
diff --git a/internal/ai/aisettings/aisettings.go b/internal/ai/aisettings/aisettings.go
index 54c89426..80233ea5 100644
--- a/internal/ai/aisettings/aisettings.go
+++ b/internal/ai/aisettings/aisettings.go
@@ -28,6 +28,8 @@ import (
"unicode/utf8"
"github.com/tink-crypto/tink-go/v2/tink"
+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
+ "go.opentelemetry.io/otel/propagation"
"github.com/nebari-dev/javo/internal/ai"
"github.com/nebari-dev/javo/internal/ai/agentproxy"
@@ -382,13 +384,16 @@ func guardedTransport() *http.Transport { return httpx.Guard{}.Transport() }
// agentClient waits at most the longer of timeout and five minutes for a
// provider's first answer byte; a streamed answer then takes as long as it
// takes, until the agent hangs up. guard keeps it off blocked addresses.
+// Each call is a client span that sends the provider the W3C trace context
+// (traceparent, tracestate) and nothing else of the trace: never baggage,
+// which may name the caller.
func agentClient(timeout time.Duration, guard bool) *http.Client {
t := http.DefaultTransport.(*http.Transport).Clone()
if guard {
t = guardedTransport()
}
t.ResponseHeaderTimeout = max(timeout, 5*time.Minute)
- return &http.Client{Transport: t}
+ return &http.Client{Transport: otelhttp.NewTransport(t, otelhttp.WithPropagators(propagation.TraceContext{}))}
}
func lastRunes(s string, n int) string {
diff --git a/internal/ai/aisettings/aisettings_test.go b/internal/ai/aisettings/aisettings_test.go
index 7bb3bb39..7c477eca 100644
--- a/internal/ai/aisettings/aisettings_test.go
+++ b/internal/ai/aisettings/aisettings_test.go
@@ -4,11 +4,24 @@ import (
"bytes"
"context"
"errors"
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "slices"
"strings"
"sync"
"testing"
"time"
+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
+ "go.opentelemetry.io/otel/propagation"
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
+ "go.opentelemetry.io/otel/sdk/trace/tracetest"
+ "go.opentelemetry.io/otel/trace"
+ "go.opentelemetry.io/otel/trace/noop"
+
+ "github.com/nebari-dev/javo/internal/ai/agentproxy"
"github.com/nebari-dev/javo/internal/ai/aisettings"
"github.com/nebari-dev/javo/internal/ai/aitest"
"github.com/nebari-dev/javo/internal/ai/provider"
@@ -335,3 +348,198 @@ func TestConcurrentCallsAndSaves(t *testing.T) {
}
wg.Wait()
}
+
+// A model call carries the agent's W3C trace context (traceparent,
+// tracestate) as a client span of the agent's request, and nothing else the
+// agent sent: never its token, cookies, baggage or other headers. Streaming
+// is unchanged.
+//
+// The server side is otelhttp.NewHandler with the same propagators as
+// telemetry.Handler (TraceContext and Baggage) and the subtest's own tracer
+// provider, not telemetry.Handler itself: that uses the global provider, and
+// the first otel.SetTracerProvider permanently sets the default global's
+// delegate, so restoring it would not undo a subtest's provider. The model
+// call's transport takes the provider from the server span in the request
+// context.
+func TestAgentCallCarriesOnlyTraceContext(t *testing.T) {
+ const (
+ traceID = "4bf92f3577b34da6a3ce929d0eaf4736"
+ spanID = "00f067aa0ba902b7"
+ zeroTrace = "00000000000000000000000000000000"
+ stream = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n"
+ plainBody = `{"choices":[{"message":{"content":"hi"}}]}`
+ )
+ // What the provider must get as trace context.
+ const (
+ none = iota // no traceparent, no tracestate
+ continued // the agent's trace, a new span id, its tracestate
+ same // the agent's traceparent and tracestate unchanged
+ fresh // a new trace of the gateway's own, no tracestate
+ )
+ sampled := map[string]string{"traceparent": "00-" + traceID + "-" + spanID + "-01", "tracestate": "vendor=x"}
+ malformed := map[string]string{"traceparent": "ff-zzz"}
+ cases := []struct {
+ name string
+ incoming map[string]string
+ stream bool
+ recorder bool
+ want int
+ }{
+ {name: "sampled trace", incoming: sampled, recorder: true, want: continued},
+ {name: "streamed", incoming: sampled, stream: true, recorder: true, want: continued},
+ {name: "no incoming trace, no tracer", want: none},
+ {name: "malformed incoming traceparent", incoming: malformed, want: none},
+ {name: "telemetry off, valid incoming trace", incoming: sampled, want: same},
+ {name: "telemetry on, malformed incoming traceparent", incoming: malformed, recorder: true, want: fresh},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := tracetest.NewSpanRecorder()
+ var tp trace.TracerProvider = noop.NewTracerProvider()
+ if tc.recorder {
+ sdk := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(rec))
+ t.Cleanup(func() { _ = sdk.Shutdown(context.Background()) })
+ tp = sdk
+ }
+
+ var (
+ mu sync.Mutex
+ seen []http.Header
+ )
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ seen = append(seen, r.Header.Clone())
+ mu.Unlock()
+ if tc.stream {
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = io.WriteString(w, stream)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, plainBody)
+ }))
+ t.Cleanup(srv.Close)
+
+ c := helm()
+ c.BaseURL = srv.URL
+ live, _, _ := newLive(t, c)
+ p := &agentproxy.Proxy{
+ Upstream: live.Upstream,
+ Caller: func(context.Context) (string, bool) { return "p", true },
+ MaxRequestBytes: 1 << 20,
+ }
+ mux := http.NewServeMux()
+ p.Register(mux)
+ h := otelhttp.NewHandler(mux, "javo",
+ otelhttp.WithTracerProvider(tp),
+ otelhttp.WithPropagators(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})))
+
+ body := `{"model":"helm/model","messages":[{"role":"user","content":"hi"}]}`
+ if tc.stream {
+ body = `{"model":"helm/model","stream":true,"messages":[{"role":"user","content":"hi"}]}`
+ }
+ req := httptest.NewRequest(http.MethodPost, agentproxy.Route+"/chat/completions", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer agent-token")
+ req.Header.Set("Cookie", "s=1")
+ req.Header.Set("baggage", "user=alice")
+ req.Header.Set("X-Custom", "1")
+ for k, v := range tc.incoming {
+ req.Header.Set(k, v)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status %d: %s", w.Code, w.Body.String())
+ }
+ want := plainBody
+ if tc.stream {
+ want = stream
+ }
+ if got := w.Body.String(); got != want {
+ t.Fatalf("answer %q, want %q", got, want)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(seen) != 1 {
+ t.Fatalf("provider saw %d requests", len(seen))
+ }
+ got := seen[0]
+
+ names := map[string]bool{}
+ for k := range got {
+ switch k := strings.ToLower(k); k {
+ case "user-agent", "accept-encoding", "content-length":
+ default:
+ names[k] = true
+ }
+ }
+ wantNames := map[string]bool{"content-type": true, "authorization": true}
+ if tc.stream {
+ wantNames["accept"] = true
+ }
+ if tc.want != none {
+ wantNames["traceparent"] = true
+ }
+ if tc.want == continued || tc.want == same {
+ wantNames["tracestate"] = true
+ }
+ if !maps.Equal(names, wantNames) {
+ t.Fatalf("provider headers %v, want %v", slices.Sorted(maps.Keys(names)), slices.Sorted(maps.Keys(wantNames)))
+ }
+ if a := got.Get("Authorization"); a != "Bearer "+configKey {
+ t.Fatalf("authorization %q, want the upstream key", a)
+ }
+ if tc.want == none {
+ if tparent := got.Get("traceparent"); tparent != "" {
+ t.Fatalf("traceparent %q sent without a trace", tparent)
+ }
+ return
+ }
+ if tc.want == continued || tc.want == same {
+ if ts := got.Get("tracestate"); ts != "vendor=x" {
+ t.Fatalf("tracestate %q", ts)
+ }
+ }
+ if tc.want == same {
+ if tparent := got.Get("traceparent"); tparent != sampled["traceparent"] {
+ t.Fatalf("traceparent %q, want the agent's %q unchanged", tparent, sampled["traceparent"])
+ }
+ return
+ }
+ parts := strings.Split(got.Get("traceparent"), "-")
+ if len(parts) != 4 {
+ t.Fatalf("traceparent %q", got.Get("traceparent"))
+ }
+ var server, client []sdktrace.ReadOnlySpan
+ for _, s := range rec.Ended() {
+ switch s.SpanKind() {
+ case trace.SpanKindServer:
+ server = append(server, s)
+ case trace.SpanKindClient:
+ client = append(client, s)
+ }
+ }
+ if len(server) != 1 || len(client) != 1 {
+ t.Fatalf("%d server and %d client spans recorded, want one each", len(server), len(client))
+ }
+ if client[0].Parent().SpanID() != server[0].SpanContext().SpanID() {
+ t.Fatalf("client span's parent %s is not the server span %s", client[0].Parent().SpanID(), server[0].SpanContext().SpanID())
+ }
+ if client[0].SpanContext().SpanID().String() != parts[2] {
+ t.Fatalf("traceparent span %s is not the client span %s", parts[2], client[0].SpanContext().SpanID())
+ }
+ switch tc.want {
+ case continued:
+ if parts[1] != traceID || parts[2] == spanID {
+ t.Fatalf("traceparent %q: want trace %s, a new span", got.Get("traceparent"), traceID)
+ }
+ case fresh:
+ if parts[1] == zeroTrace || parts[1] != server[0].SpanContext().TraceID().String() {
+ t.Fatalf("traceparent %q: want the server span's trace %s", got.Get("traceparent"), server[0].SpanContext().TraceID())
+ }
+ }
+ })
+ }
+}
diff --git a/site/src/content/docs/admin/configuration.md b/site/src/content/docs/admin/configuration.md
index fb10767b..36598166 100644
--- a/site/src/content/docs/admin/configuration.md
+++ b/site/src/content/docs/admin/configuration.md
@@ -60,6 +60,8 @@ Values fall in two groups:
Each value is a flag of `javo server`, `javo gateway` and `javo controller` (`--log-format`, `--log-level`); the collector is the standard `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable, and the other `OTEL_EXPORTER_OTLP_*` variables (headers, protocol details, a separate `_TRACES_` or `_METRICS_` endpoint), `OTEL_SERVICE_NAME`, `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_SDK_DISABLED` work as the OpenTelemetry specification says. `javo local` writes text.
+With a collector set, a coding agent's model call through the gateway is a client span of the agent's request, and the call to the AI provider carries that span's W3C trace context (`traceparent`, and `tracestate` when the agent sent one), continuing the agent's trace when it sent one, so a provider or gateway that traces (such as the Nebari LLM serving pack's AI Gateway) joins the same trace. With no collector set, a valid `traceparent` and its `tracestate` from the agent go to the provider as they came, and without one no trace context is sent. Nothing else the agent sent goes to the provider: never its token or cookies, and never `baggage`.
+
## Request limits
`config.api.limits` bounds what requests may hold in the gateway, so one person or a slow client cannot use up its connections or memory. The defaults suit most installs.