:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): send session attribution to the ai gateway (#108422)
Ben White65ccc2ee8aec
diff --git a/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts b/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.tsindex eecb1dfc15ce..0e13a16d013d 100644--- a/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts+++ b/packages/agent/packages/agent-contracts/src/posthog-property-headers.test.ts@@ -9,6 +9,8 @@ import {buildPosthogPropertyHeaderRecord,buildPosthogScopedPropertyHeaderLines,buildPosthogScopedPropertyHeaderRecord,+ buildPosthogSessionHeaderLines,+ buildPosthogSessionHeaderRecord,collapsePropertyHeadersForAiGateway,} from "./posthog-property-headers";@@ -33,6 +35,24 @@ describe("PostHog project headers", () => {});});+describe("PostHog session headers", () => {+ it("builds record and line forms with sanitized values", () => {+ expect(+ buildPosthogSessionHeaderRecord("session-1\r\nmalicious: true"),+ ).toEqual({+ "X-PostHog-Session-Id": "session-1 malicious: true",+ });+ expect(buildPosthogSessionHeaderLines("session-1")).toBe(+ "X-PostHog-Session-Id: session-1",+ );+ });++ it.each([undefined, null, ""])("omits the header for %s", (sessionId) => {+ expect(buildPosthogSessionHeaderRecord(sessionId)).toEqual({});+ expect(buildPosthogSessionHeaderLines(sessionId)).toBe("");+ });+});+describe("task run headers", () => {it("uses task_run_id instead of task_id in record and line formats", () => {const properties = { task_id: "task-1", task_run_id: "run-1" };diff --git a/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts b/packages/agent/packages/agent-contracts/src/posthog-property-headers.tsindex 4ece01873a17..e6d84802a6e7 100644--- a/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts+++ b/packages/agent/packages/agent-contracts/src/posthog-property-headers.ts@@ -228,6 +228,22 @@ export function buildPosthogPropertiesHeaderLines(*/export const POSTHOG_SESSION_ID_HEADER = "X-PostHog-Session-Id";+export function buildPosthogSessionHeaderRecord(+ sessionId: string | null | undefined,+): Record<string, string> {+ return sessionId+ ? { [POSTHOG_SESSION_ID_HEADER]: sanitizeHeaderValue(sessionId) }+ : {};+}++export function buildPosthogSessionHeaderLines(+ sessionId: string | null | undefined,+): string {+ return Object.entries(buildPosthogSessionHeaderRecord(sessionId))+ .map(([key, value]) => `${key}: ${value}`)+ .join("\n");+}+const PROPERTY_HEADER_PREFIX = "x-posthog-property-";function parsePropertiesBlob(raw: string): PosthogProperties {diff --git a/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts b/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.tsindex e7f9f81e0bdf..207a77f7d975 100644--- a/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts+++ b/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts@@ -614,6 +614,24 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {expect(properties).not.toHaveProperty("task_run_span_id");});+ it("sends the task id as the Go gateway session header", () => {+ const env = buildServer().configureEnvironment({+ originProduct: "signal_report",+ aiStage: "scout",+ taskId: "task-1",+ });++ expect(env.anthropicCustomHeaders).toContain(+ "X-PostHog-Session-Id: task-1",+ );+ expect(env.openaiCustomHeaders).toMatchObject({+ "X-PostHog-Session-Id": "task-1",+ });+ expect(parseBlob(env.anthropicCustomHeaders ?? "")).not.toHaveProperty(+ "$ai_session_id",+ );+ });+// The gateway writes the tier into the OpenAI body from this header, so a// run that loses it silently runs on the standard queue and a flex trial// measures nothing. Codex-only: the Claude header lines never carry it.diff --git a/packages/agent/packages/agent/src/server/gateway-env.ts b/packages/agent/packages/agent/src/server/gateway-env.tsindex 93988c6f390a..5ecc9aa43b6f 100644--- a/packages/agent/packages/agent/src/server/gateway-env.ts+++ b/packages/agent/packages/agent/src/server/gateway-env.ts@@ -4,6 +4,8 @@ import {buildPosthogPropertiesHeaderRecord,buildPosthogScopedPropertyHeaderLines,buildPosthogScopedPropertyHeaderRecord,+ buildPosthogSessionHeaderLines,+ buildPosthogSessionHeaderRecord,} from "@posthog/agent-contracts/posthog-property-headers";import type { GatewayEnv } from "../adapters/claude/session/options";import type { Task } from "../types";@@ -136,8 +138,16 @@ export function buildGatewayEnv(ai_product: aiProduct,team_id: projectId,};- customHeaders = buildPosthogPropertiesHeaderLines(properties);- openaiCustomHeaders = buildPosthogPropertiesHeaderRecord(properties);+ customHeaders = [+ buildPosthogPropertiesHeaderLines(properties),+ buildPosthogSessionHeaderLines(taskId),+ ]+ .filter(Boolean)+ .join("\n");+ openaiCustomHeaders = {+ ...buildPosthogPropertiesHeaderRecord(properties),+ ...buildPosthogSessionHeaderRecord(taskId),+ };// The Go gateway writes this into the OpenAI body's `service_tier`, which// is the only way a Codex run reaches the flex or priority queue: Codex// itself omits a tier its model catalogue does not advertise. Codex-only,@@ -160,8 +170,8 @@ export function buildGatewayEnv(gatewayProperties,projectId,);- // No $ai_session_id on the Go-gateway path above: it strips $-prefixed- // blob keys, so the session id would be silently dropped there.+ // Only the legacy gateway reads the session id from a property. The Go+ // path above sends it as a header, because its blob drops $-prefixed keys.openaiCustomHeaders = buildPosthogScopedPropertyHeaderRecord({...gatewayProperties,