: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
feat(tasks): route posthog_code cloud pi runs through the go gateway (#116535)
Brandon29f2860c8014
diff --git a/packages/agent/packages/agent/src/server/gateway-env.pi.test.ts b/packages/agent/packages/agent/src/server/gateway-env.pi.test.tsnew file mode 100644index 000000000000..5d9d588ad8d8--- /dev/null+++ b/packages/agent/packages/agent/src/server/gateway-env.pi.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Logger } from "../utils/logger";+import { buildPiProviderRoute } from "./gateway-env";++const ENV_KEYS = [+ "LLM_GATEWAY_URL",+ "AI_GATEWAY_URL",+ "AI_GATEWAY_PRODUCTS",+ "AI_GATEWAY_PRODUCT",+ "AI_GATEWAY_AI_STAGE",+ "AI_GATEWAY_TOKEN",+];++const config = {+ apiKey: "oauth-token",+ apiUrl: "https://us.posthog.com",+ projectId: 7,+};++const properties = { task_id: "task-1", task_run_id: "run-1", ai_stage: null };++function logger(): Logger & { warn: ReturnType<typeof vi.fn> } {+ return {+ warn: vi.fn(),+ debug: vi.fn(),+ info: vi.fn(),+ error: vi.fn(),+ } as never;+}++describe("buildPiProviderRoute", () => {+ const saved: Record<string, string | undefined> = {};++ beforeEach(() => {+ for (const key of ENV_KEYS) {+ saved[key] = process.env[key];+ delete process.env[key];+ }+ });++ afterEach(() => {+ for (const key of ENV_KEYS) {+ if (saved[key] === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = saved[key];+ }+ }+ });++ function routeToGo(): void {+ process.env.AI_GATEWAY_URL = "https://ai-gateway.us.posthog.com/v1";+ process.env.AI_GATEWAY_PRODUCTS = "posthog_code";+ process.env.AI_GATEWAY_PRODUCT = "posthog_code";+ }++ it("uses the Go gateway with the scoped token when the worker minted one", () => {+ routeToGo();+ process.env.AI_GATEWAY_TOKEN = "phe_run";+ const route = buildPiProviderRoute(+ config,+ { taskId: "task-1", model: "claude-opus-5-5", properties },+ logger(),+ );++ expect(route.isAiGateway).toBe(true);+ expect(route.apiKey).toBe("phe_run");+ expect(route.baseUrl).toBe("https://ai-gateway.us.posthog.com");+ expect(route.model).toBe("claude-opus-5-5");+ expect(route.headers["X-PostHog-Session-Id"]).toBe("task-1");+ expect(JSON.parse(route.headers["X-PostHog-Properties"])).toMatchObject({+ task_id: "task-1",+ ai_product: "posthog_code",+ team_id: 7,+ });+ expect(+ Object.keys(route.headers).some((key) =>+ key.toLowerCase().startsWith("x-posthog-property-"),+ ),+ ).toBe(false);+ });++ it("sends GLM under the bare id on the Go gateway", () => {+ routeToGo();+ process.env.AI_GATEWAY_TOKEN = "phe_run";+ const route = buildPiProviderRoute(+ config,+ { model: "@cf/zai-org/glm-5.2", properties },+ logger(),+ );+ expect(route.model).toBe("zai-org/glm-5.2");+ });++ it("stays on the Python gateway with the run credential when no token was minted", () => {+ routeToGo();+ const log = logger();+ const route = buildPiProviderRoute(+ config,+ { model: "@cf/zai-org/glm-5.2", properties },+ log,+ );++ expect(route.isAiGateway).toBe(false);+ expect(route.apiKey).toBe("oauth-token");+ expect(route.baseUrl).toMatch(/\/posthog_code$/);+ expect(route.model).toBe("@cf/zai-org/glm-5.2");+ expect(route.headers["X-PostHog-Properties"]).toBeUndefined();+ expect(log.warn).toHaveBeenCalledOnce();+ });++ it("keeps the legacy route unchanged when the product is not routed", () => {+ process.env.LLM_GATEWAY_URL = "https://gateway.us.posthog.com";+ process.env.AI_GATEWAY_TOKEN = "phe_run";+ const route = buildPiProviderRoute(config, { properties }, logger());++ expect(route.isAiGateway).toBe(false);+ expect(route.apiKey).toBe("oauth-token");+ expect(route.baseUrl).toBe("https://gateway.us.posthog.com/posthog_code");+ });+});diff --git a/packages/agent/packages/agent/src/server/gateway-env.ts b/packages/agent/packages/agent/src/server/gateway-env.tsindex 1393c11e9434..188325db91e3 100644--- a/packages/agent/packages/agent/src/server/gateway-env.ts+++ b/packages/agent/packages/agent/src/server/gateway-env.ts@@ -2,6 +2,7 @@ import type { SpanContext } from "@opentelemetry/api";import {buildPosthogPropertiesHeaderLines,buildPosthogPropertiesHeaderRecord,+ buildPosthogPropertyHeaderRecord,buildPosthogScopedPropertyHeaderLines,buildPosthogScopedPropertyHeaderRecord,buildPosthogSessionHeaderLines,@@ -9,7 +10,11 @@ import {} from "@posthog/agent-contracts/posthog-property-headers";import type { GatewayEnv } from "../adapters/claude/session/options";import type { Task } from "../types";-import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";+import {+ resolveGatewayProduct,+ resolveGatewayTarget,+ resolveLlmGatewayUrl,+} from "../utils/gateway";import type { Logger } from "../utils/logger";import type { AgentServerConfig } from "./types";@@ -200,6 +205,77 @@ export function buildGatewayEnv(};}+// Go serves GLM under its bare id and has no `@cf/` alias.+export function piModelIdForRoute<T extends string | undefined>(+ model: T,+ isAiGateway: boolean,+): T {+ return (isAiGateway ? model?.replace(/^@cf\//, "") : model) as T;+}++export interface PiProviderRoute {+ apiKey: string;+ baseUrl: string;+ headers: Record<string, string>;+ model: string | undefined;+ isAiGateway: boolean;+}++/** Go with the run's scoped token when the worker minted one, else the Python gateway. */+export function buildPiProviderRoute(+ config: Pick<AgentServerConfig, "apiKey" | "apiUrl" | "projectId">,+ {+ originProduct,+ aiStage,+ taskId,+ model,+ properties,+ }: {+ originProduct?: Task["origin_product"] | null;+ aiStage?: string | null;+ taskId?: string | null;+ model?: string;+ properties: Record<string, string | number | boolean | null | undefined>;+ },+ logger: Logger,+): PiProviderRoute {+ const gatewayToken = process.env.AI_GATEWAY_TOKEN?.trim() || undefined;+ const target = resolveGatewayTarget({+ product: resolveGatewayProduct({ originProduct }),+ aiStage,+ posthogHost: config.apiUrl,+ });+ if (target.isAiGateway && gatewayToken) {+ return {+ apiKey: gatewayToken,+ baseUrl: target.baseUrl,+ // Go reads one properties blob and strips `$` keys, so the session id has its own header.+ headers: {+ ...buildPosthogPropertiesHeaderRecord({+ ...properties,+ ai_product: target.aiProduct,+ team_id: config.projectId,+ }),+ ...buildPosthogSessionHeaderRecord(taskId),+ },+ model: piModelIdForRoute(model, true),+ isAiGateway: true,+ };+ }+ if (target.isAiGateway) {+ logger.warn(+ `AI_GATEWAY_TOKEN missing for routed product ${target.aiProduct}; falling back to the Python gateway`,+ );+ }+ return {+ apiKey: config.apiKey,+ baseUrl: resolveLlmGatewayUrl(process.env.LLM_GATEWAY_URL, config.apiUrl),+ headers: buildPosthogPropertyHeaderRecord(properties),+ model,+ isAiGateway: false,+ };+}+/*** The codex session's LLM auth, from the resolved gateway env. Codex must never* read the raw run credential: on the Go-gateway path the bearer is the per-rundiff --git a/packages/agent/packages/agent/src/server/pi-agent-server.test.ts b/packages/agent/packages/agent/src/server/pi-agent-server.test.tsindex 3d7a79b7717f..c792d7aab3be 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.test.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.test.ts@@ -620,6 +620,7 @@ describe("PiAgentServer", () => {};server.session = {runtime: { sendCommand, client: { getState: vi.fn(async () => ({})) } },+ providerRoute: { isAiGateway: false },};await server.executeCommand("set_config_option", { configId, value });@@ -628,6 +629,38 @@ describe("PiAgentServer", () => {},);+ it.each([+ { isAiGateway: true, modelId: "zai-org/glm-5.2" },+ { isAiGateway: false, modelId: "@cf/zai-org/glm-5.2" },+ ])(+ "switches to GLM under the route's spelling (Go: $isAiGateway)",+ async ({ isAiGateway, modelId }) => {+ const sendCommand = vi.fn(async () => ({ success: true }));+ const server = new PiAgentServer(config()) as unknown as {+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.session = {+ runtime: { sendCommand, client: { getState: vi.fn(async () => ({})) } },+ providerRoute: { isAiGateway },+ };++ await server.executeCommand("set_config_option", {+ configId: "model",+ value: "@cf/zai-org/glm-5.2",+ });++ expect(sendCommand).toHaveBeenCalledWith({+ type: "set_model",+ provider: "posthog",+ modelId,+ });+ },+ );+it("bounds events retained while no SSE client is connected", () => {const server = new PiAgentServer(config()) as unknown as {broadcast(event: Record<string, unknown>): void;diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.tsindex 80a928871ff4..0025476e5e46 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts@@ -18,7 +18,6 @@ import {serializeError,type TaskRunArtifact,} from "@posthog/agent-contracts";-import { buildPosthogPropertyHeaderRecord } from "@posthog/agent-contracts/posthog-property-headers";import type { TaskContext } from "@posthog/agent-contracts/task-context";import { AgentInstructionFiles } from "@posthog/harness/extensions/agent-instructions";import { resolveContextWikiPath } from "@posthog/harness/extensions/context-wiki";@@ -59,9 +58,13 @@ import {import { PostHogAPIClient } from "../posthog-api";import { attachmentFilePath } from "../utils/attachments";import { createEventIdSource } from "../utils/event-id";-import { resolveLlmGatewayUrl } from "../utils/gateway";import { Logger } from "../utils/logger";import { TaskRunEventStreamSender } from "./event-stream-sender";+import {+ buildPiProviderRoute,+ type PiProviderRoute,+ piModelIdForRoute,+} from "./gateway-env";import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";@@ -91,6 +94,7 @@ interface PiCloudSession {runtime: PiRuntime;sseController: SseController | null;unsubscribe: () => void;+ providerRoute: PiProviderRoute;}const emptySchema = z.object({});@@ -699,30 +703,41 @@ export class PiAgentServer {channelMode,additionalInstructions,};- const attributionHeaders = buildPosthogPropertyHeaderRecord({- task_id: payload.task_id,- task_run_id: payload.run_id,- task_origin_product: task?.origin_product ?? null,- task_repositories: task?.repositories?.length- ? JSON.stringify(task.repositories)- : task?.repository- ? JSON.stringify([task.repository])- : null,- task_runtime_adapter: "pi",- task_sandbox_environment_id:- typeof runState?.sandbox_environment_id === "string"- ? runState.sandbox_environment_id- : null,- task_snapshot_kind: taskSnapshotKind,- task_prewarmed: taskRun ? runState?.prewarmed === true : null,- ai_stage:- typeof runState?.ai_stage === "string" ? runState.ai_stage : null,- ai_agent_name:- typeof runState?.ai_agent_name === "string"- ? runState.ai_agent_name- : null,- task_execution_environment: "cloud",- });+ const aiStage =+ typeof runState?.ai_stage === "string" ? runState.ai_stage : null;+ const providerRoute = buildPiProviderRoute(+ this.config,+ {+ originProduct: task?.origin_product ?? null,+ aiStage,+ taskId: payload.task_id,+ model: this.config.model,+ properties: {+ task_id: payload.task_id,+ task_run_id: payload.run_id,+ task_origin_product: task?.origin_product ?? null,+ task_repositories: task?.repositories?.length+ ? JSON.stringify(task.repositories)+ : task?.repository+ ? JSON.stringify([task.repository])+ : null,+ task_runtime_adapter: "pi",+ task_sandbox_environment_id:+ typeof runState?.sandbox_environment_id === "string"+ ? runState.sandbox_environment_id+ : null,+ task_snapshot_kind: taskSnapshotKind,+ task_prewarmed: taskRun ? runState?.prewarmed === true : null,+ ai_stage: aiStage,+ ai_agent_name:+ typeof runState?.ai_agent_name === "string"+ ? runState.ai_agent_name+ : null,+ task_execution_environment: "cloud",+ },+ },+ this.logger,+ );const extensions: PiRuntimeExtension[] = ["context-wiki"];if (channelMode) {@@ -733,7 +748,7 @@ export class PiAgentServer {}const client = createPiRpcClient({cliPath: this.config.piRpcHostPath,- model: this.config.model,+ model: providerRoute.model,sessionFile: restoredSessionFile,enrichment: {apiUrl: this.config.apiUrl,@@ -748,12 +763,9 @@ export class PiAgentServer {mcpToolPolicies: mcpConfiguration.policies,taskContext,providerOptions: {- apiKey: this.config.apiKey,- baseUrl: resolveLlmGatewayUrl(- process.env.LLM_GATEWAY_URL,- this.config.apiUrl,- ),- headers: attributionHeaders,+ apiKey: providerRoute.apiKey,+ baseUrl: providerRoute.baseUrl,+ headers: providerRoute.headers,},extensions,contextWikiPath: resolveContextWikiPath(),@@ -799,7 +811,13 @@ export class PiAgentServer {unsubscribeMcpPermissions();};- this.session = { payload, runtime, sseController: null, unsubscribe };+ this.session = {+ payload,+ runtime,+ sseController: null,+ unsubscribe,+ providerRoute,+ };this.sessionReadyBootMs = Math.round(process.uptime() * 1000);this.sessionInitMs = Date.now() - startedAt;await this.posthogAPI.updateTaskRun(payload.task_id, payload.run_id, {@@ -1107,13 +1125,21 @@ export class PiAgentServer {configId: "model" | "effort",value: string,): Promise<Record<string, never>> {- const runtime = this.session?.runtime;- if (!runtime) {+ const session = this.session;+ if (!session) {throw new Error("No active Pi runtime");}+ const runtime = session.runtime;const response = await runtime.sendCommand(configId === "model"- ? { type: "set_model", provider: "posthog", modelId: value }+ ? {+ type: "set_model",+ provider: "posthog",+ modelId: piModelIdForRoute(+ value,+ session.providerRoute.isAiGateway,+ ),+ }: { type: "set_thinking_level", level: value as PiThinkingLevel },);if (!response.success) {diff --git a/packages/agent/packages/harness/src/extensions/posthog-provider/models.test.ts b/packages/agent/packages/harness/src/extensions/posthog-provider/models.test.tsindex ce1419c34cba..d4809d3a136d 100644--- a/packages/agent/packages/harness/src/extensions/posthog-provider/models.test.ts+++ b/packages/agent/packages/harness/src/extensions/posthog-provider/models.test.ts@@ -63,6 +63,15 @@ describe("resolveModelConfigs", () => {vi.restoreAllMocks();});+ it("lists the Go spelling of every @cf fallback model", () => {+ const ids = new Set(fallbackModelConfigs("us").map((model) => model.id));+ const cf = [...ids].filter((id) => id.startsWith("@cf/"));+ expect(cf.length).toBeGreaterThan(0);+ for (const id of cf) {+ expect(ids).toContain(id.replace(/^@cf\//, ""));+ }+ });+it("returns fallback models when PI_OFFLINE is set", async () => {process.env.PI_OFFLINE = "1";const fetchSpy = vi.fn();diff --git a/packages/agent/packages/harness/src/extensions/posthog-provider/models.ts b/packages/agent/packages/harness/src/extensions/posthog-provider/models.tsindex a46458189886..638c748b3db0 100644--- a/packages/agent/packages/harness/src/extensions/posthog-provider/models.ts+++ b/packages/agent/packages/harness/src/extensions/posthog-provider/models.ts@@ -321,6 +321,13 @@ const FALLBACK_GATEWAY_MODELS: GatewayModel[] = [context_window: 128000,supports_vision: false,},+ // The Go gateway's spelling of the entry above; it has no `@cf/` alias.+ {+ id: "zai-org/glm-5.2",+ owned_by: "baseten",+ context_window: 128000,+ supports_vision: false,+ },{id: "moonshotai/kimi-k3",owned_by: "modal",diff --git a/products/tasks/backend/logic/services/gateway_model_pin.py b/products/tasks/backend/logic/services/gateway_model_pin.pyindex b9dec5107674..2d5b5468c59e 100644--- a/products/tasks/backend/logic/services/gateway_model_pin.py+++ b/products/tasks/backend/logic/services/gateway_model_pin.py@@ -31,9 +31,12 @@ def _first_party_pin(product: str) -> list[str]:# Ids the legacy gateway serves to PostHog Desktop that the catalog lacks; older app builds call them._DESKTOP_LEGACY_MODELS: tuple[str, ...] = ("gpt-5.4", "gpt-5.3-codex", "gpt-5.2", "gpt-5-mini")+# Go has no `@cf/` alias, so a run stored on `@cf/zai-org/glm-5.2` calls Go under the bare id.+_GO_SPELLINGS: tuple[str, ...] = ("zai-org/glm-5.2",)+# Every model a PostHog Desktop session or cloud run may call, slash ids included. Go picks the provider.DESKTOP_AGENT_MODELS: list[str] = list(- dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS), *_DESKTOP_LEGACY_MODELS])+ dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS), *_DESKTOP_LEGACY_MODELS, *_GO_SPELLINGS]))# The Go gateway refuses a pin longer than this at mint.MAX_GATEWAY_PIN_LENGTH = 32diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex ab82f9637909..b7f4ce24ddfb 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -252,8 +252,8 @@ def mint_refusal(refusal = _posthog_code_refusal(team_id, model, distinct_id)if refusal:return refusal- # The Pi harness reads only LLM_GATEWAY_URL.- if runtime == "pi":+ # Pi reaches Go only for posthog_code.+ elif runtime == "pi":return "pi_runtime"# The gateway denies an off-pin model with no fallback.if not model_allowed_by_product_pin(ai_product, model):diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.pyindex 1040f9c2aae6..494c19634044 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -1266,8 +1266,8 @@ class TestMintRefusalScope:with patch(_CREDIT_LOOKUP, return_value=None):assert mint_refusal(product, team_id=2, state=None, model=None, runtime="acp") is None- @pytest.mark.parametrize("product", ["workflows", "review_hog", "signals_scout"])- def test_pi_runs_never_mint(self, product):+ @pytest.mark.parametrize("product", ["workflows", "review_hog", "signals_scout", "posthog_ai"])+ def test_pi_runs_of_other_products_never_mint(self, product):assert mint_refusal(product, team_id=2, state=None, model=None, runtime="pi") == "pi_runtime"@pytest.mark.parametrize("product", ["posthog_ai", "workflows", "review_hog"])@@ -1472,6 +1472,10 @@ class TestPosthogCodeSandboxMint:assert {entry.id for entry in model_catalog.MODELS} <= set(pin)assert set(SDK_IMPLICIT_MODELS) <= set(pin)assert {"gpt-5.4", "gpt-5.3-codex", "gpt-5.2", "gpt-5-mini"} <= set(pin)++ def test_pin_carries_the_go_spelling_of_every_cf_id(self):+ pin = set(_PRODUCT_ALLOWED_MODELS["posthog_code"])+ assert {entry.removeprefix("@cf/") for entry in pin if entry.startswith("@cf/")} <= pinassert any("/" in model for model in pin)def test_free_pin_is_the_legacy_free_tier_in_both_glm_spellings(self):@@ -1578,6 +1582,18 @@ class TestPosthogCodeSandboxMint:"not_rolled_out")+ @pytest.mark.django_db+ def test_a_rolled_out_pi_run_mints(self):+ team = self._team(paid=True)+ with (+ patch(+ "products.tasks.backend.logic.services.desktop_gateway_token.feature_enabled_or_false",+ return_value=True,+ ),+ patch(_CREDIT_LOOKUP, return_value=None),+ ):+ assert mint_refusal("posthog_code", team_id=team.id, state=None, model=None, runtime="pi") is None+@pytest.mark.django_dbdef test_flag_is_evaluated_for_the_team_org(self):team = self._team(paid=True)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex b2a4d7176547..35662dfa1013 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -1501,7 +1501,7 @@ def run_gateway_env_vars(ctx: TaskProcessingContext, task: Task) -> dict[str, strecord_gateway_routing(run_id=ctx.run_id,team_id=ctx.team_id,- uses_gateway=bool(env_vars.get("AI_GATEWAY_TOKEN")) and ctx.task_runtime != "pi",+ uses_gateway=bool(env_vars.get("AI_GATEWAY_TOKEN")),)return env_vars