: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(signals): mint per-run scoped gateway tokens for routed sandboxes (#85005)
Brandona602cd215f48
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex bc57d57903fe..9693c060ea06 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -56,6 +56,18 @@ SANDBOX_LLM_GATEWAY_URL: str | None = get_from_env("SANDBOX_LLM_GATEWAY_URL", No# Both must be set; clearing either rolls back to the Python gateway.SANDBOX_AI_GATEWAY_URL: str | None = get_from_env("SANDBOX_AI_GATEWAY_URL", None, optional=True)SANDBOX_AI_GATEWAY_PRODUCTS: str | None = get_from_env("SANDBOX_AI_GATEWAY_PRODUCTS", None, optional=True)+# Gateway credential (phs_) the worker uses to mint per-run phe_ scoped tokens for+# gateway-routed sandbox runs. Unset: runs get no token and the agent server keeps them+# on the Python gateway, so the routing allowlist above is inert without it.+SANDBOX_AI_GATEWAY_MINT_KEY: str | None = get_from_env("SANDBOX_AI_GATEWAY_MINT_KEY", None, optional=True)+# Per-run spend cap and token lifetime for minted scoped tokens. The cap bounds one+# runaway run; the daily bound per team is cap x the scheduler's runs-per-day limit.+# TTL 0 (the default) derives TASKS_MAX_RUN_DURATION_SECONDS + 1h so a capped run+# never outlives its token; a positive value overrides.+SANDBOX_AI_GATEWAY_TOKEN_CAP_USD: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD", "5")+# Per-team per-run cap overrides as a JSON object of team id to dollars, e.g. {"2": "10"}.+SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES: str = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES", "")+SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS: int = get_from_env("SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS", 0, type_cast=int)SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=True)# OTLP destinations for agent-server run telemetry (PostHog Logs/APM).diff --git a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.tsindex 7327c0b92a52..d03b7021ead3 100644--- a/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.configure-environment.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { GatewayEnv } from "../adapters/claude/session/options";import type { Task } from "../types";-import { AgentServer } from "./agent-server";+import { AgentServer, codexAuthFromGatewayEnv } from "./agent-server";interface TestableServer {configureEnvironment(args?: {@@ -387,8 +387,10 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {"POSTHOG_PROJECT_ID","AI_GATEWAY_URL","AI_GATEWAY_PRODUCTS",+ "AI_GATEWAY_TOKEN",];const GO_GATEWAY = "https://ai-gateway.us.posthog.com";+ const SCOPED_TOKEN = "phe_test_scoped_token";beforeEach(() => {for (const key of ENV_KEYS) {@@ -403,6 +405,7 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {"signals_repo_selection","background_agents",].join(",");+ process.env.AI_GATEWAY_TOKEN = SCOPED_TOKEN;});afterEach(() => {@@ -531,4 +534,52 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {"background_agents",);});++ it("authenticates with the scoped token on the Go path", () => {+ const env = buildServer().configureEnvironment({+ originProduct: "signals_scout",+ aiStage: "scout:web-analytics",+ });++ expect(env.anthropicBaseUrl).toBe(GO_GATEWAY);+ expect(env.anthropicAuthToken).toBe(SCOPED_TOKEN);+ expect(env.openaiApiKey).toBe(SCOPED_TOKEN);+ });++ it("falls back to the Python gateway when no scoped token is present", () => {+ delete process.env.AI_GATEWAY_TOKEN;+ const env = buildServer().configureEnvironment({+ originProduct: "signals_scout",+ aiStage: "scout",+ });++ expect(env.anthropicBaseUrl).toBe("https://gateway.us.posthog.com/signals");+ expect(env.anthropicAuthToken).toBe("test-api-key");+ expect(env.openaiApiKey).toBe("test-api-key");+ });++ it("feeds the codex session the gateway bearer, not the raw run credential", () => {+ const routed = buildServer().configureEnvironment({+ originProduct: "signals_scout",+ aiStage: "scout:web-analytics",+ });+ expect(codexAuthFromGatewayEnv(routed)).toEqual({+ apiBaseUrl: `${GO_GATEWAY}/v1`,+ apiKey: SCOPED_TOKEN,+ });++ delete process.env.AI_GATEWAY_TOKEN;+ const unrouted = buildServer().configureEnvironment({ isInternal: false });+ expect(codexAuthFromGatewayEnv(unrouted).apiKey).toBe("test-api-key");+ });++ it("keeps the OAuth token as bearer for unrouted products", () => {+ const env = buildServer().configureEnvironment({ isInternal: false });++ expect(env.anthropicBaseUrl).toBe(+ "https://gateway.us.posthog.com/posthog_code",+ );+ expect(env.anthropicAuthToken).toBe("test-api-key");+ expect(env.openaiApiKey).toBe("test-api-key");+ });});diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex babfb0004155..57705bd0ad02 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -417,6 +417,18 @@ function buildMissingAttachmentNotice(count: number): string {);}+/**+ * 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-run+ * scoped token (see configureEnvironment).+ */+export function codexAuthFromGatewayEnv(env: GatewayEnv): {+ apiBaseUrl: string;+ apiKey: string;+} {+ return { apiBaseUrl: env.openaiBaseUrl, apiKey: env.openaiApiKey };+}+export class AgentServer {private config: AgentServerConfig;private sessionReadyBootMs?: number;@@ -1745,8 +1757,7 @@ export class AgentServer {runtimeAdapter === "codex"? {cwd: this.config.repositoryPath ?? "/tmp/workspace",- apiBaseUrl: gatewayEnv.openaiBaseUrl,- apiKey: this.config.apiKey,+ ...codexAuthFromGatewayEnv(gatewayEnv),// Bundled-binary hint for the native codex CLI: the codex// binary itself, or any file in its directory. Set in the// sandbox image (POSTHOG_CODEX_BINARY_PATH); when unset the@@ -4222,11 +4233,29 @@ ${commonInstructions}} = {}): GatewayEnv {const { apiKey, apiUrl, projectId } = this.config;const product = resolveGatewayProduct({ isInternal, originProduct });- const {- baseUrl: gatewayUrl,- isAiGateway,- aiProduct,- } = resolveGatewayTarget({ product, aiStage, posthogHost: apiUrl });+ // Go-gateway runs authenticate with the per-run scoped token minted by the+ // worker (pinned product + on-behalf-of team, per-run spend cap), not the+ // run's per-team OAuth token, whose team has no gateway wallet. A routed+ // product with no token therefore stays on the Python gateway.+ const gatewayToken = process.env.AI_GATEWAY_TOKEN?.trim() || undefined;+ let target = resolveGatewayTarget({+ product,+ aiStage,+ posthogHost: apiUrl,+ });+ if (target.isAiGateway && !gatewayToken) {+ this.logger.warn(+ `AI_GATEWAY_TOKEN missing for routed product ${target.aiProduct}; falling back to the Python gateway`,+ );+ target = resolveGatewayTarget({+ product,+ aiStage,+ posthogHost: apiUrl,+ env: { ...process.env, AI_GATEWAY_URL: undefined },+ });+ }+ const { baseUrl: gatewayUrl, isAiGateway, aiProduct } = target;+ const llmBearer = isAiGateway && gatewayToken ? gatewayToken : apiKey;const openaiBaseUrl = gatewayUrl.endsWith("/v1")? gatewayUrl: `${gatewayUrl}/v1`;@@ -4296,9 +4325,9 @@ ${commonInstructions}// gateway URL, auth token, or custom headers.return {anthropicBaseUrl: gatewayUrl,- anthropicAuthToken: apiKey,+ anthropicAuthToken: llmBearer,openaiBaseUrl,- openaiApiKey: apiKey,+ openaiApiKey: llmBearer,anthropicCustomHeaders: customHeaders,openaiCustomHeaders,posthogProjectId: String(projectId),diff --git a/products/desktop/packages/agent/src/utils/gateway-routing-cases.json b/products/desktop/packages/agent/src/utils/gateway-routing-cases.jsonnew file mode 100644index 000000000000..dca5519cc097--- /dev/null+++ b/products/desktop/packages/agent/src/utils/gateway-routing-cases.json@@ -0,0 +1,159 @@+{+ "comment": "Shared routing contract for the sandbox gateway matchers. Consumed by BOTH products/desktop/packages/agent/src/utils/gateway.test.ts and products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py, so the TypeScript resolver and its Python mirror cannot drift while both suites stay green. A drift means routed runs silently stop minting (or mint unused tokens).",+ "resolve_ai_product": [+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout",+ "internal": false,+ "expected": "signals_scout"+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout:web-analytics",+ "internal": false,+ "expected": "signals_scout"+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout:customer-analytics-billing-and-usage",+ "internal": false,+ "expected": "signals_scout"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "research",+ "internal": true,+ "expected": "signals_research"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "implementation",+ "internal": true,+ "expected": "signals_implementation"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "repo_selection",+ "internal": true,+ "expected": "signals_repo_selection"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "custom_agent",+ "internal": true,+ "expected": "signals_custom_agent"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": null,+ "internal": true,+ "expected": "signals"+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "match",+ "internal": false,+ "expected": "signals"+ },+ {+ "origin_product": "loop",+ "ai_stage": "implementation",+ "internal": false,+ "expected": "posthog_code"+ },+ {+ "origin_product": "slack",+ "ai_stage": null,+ "internal": false,+ "expected": "slack_app"+ },+ {+ "origin_product": "support_reply",+ "ai_stage": null,+ "internal": true,+ "expected": "conversations"+ },+ {+ "origin_product": "onboarding",+ "ai_stage": null,+ "internal": false,+ "expected": "onboarding"+ },+ {+ "origin_product": "posthog_ai",+ "ai_stage": null,+ "internal": true,+ "expected": "posthog_ai"+ },+ {+ "origin_product": "image_builder",+ "ai_stage": null,+ "internal": true,+ "expected": "background_agents"+ },+ {+ "origin_product": "user_created",+ "ai_stage": null,+ "internal": false,+ "expected": "posthog_code"+ }+ ],+ "routed": [+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout",+ "internal": false,+ "allowlist": "signals_scout,signals_research",+ "expected": true+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout:logs",+ "internal": false,+ "allowlist": "signals_scout",+ "expected": true+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout:web-analytics",+ "internal": false,+ "allowlist": "signals_scout:web-analytics",+ "expected": true+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout:logs",+ "internal": false,+ "allowlist": "signals_scout:web-analytics",+ "expected": false+ },+ {+ "origin_product": "signals_scout",+ "ai_stage": "scout",+ "internal": false,+ "allowlist": "signals_scout:web-analytics",+ "expected": false+ },+ {+ "origin_product": "signal_report",+ "ai_stage": "custom_agent",+ "internal": true,+ "allowlist": " , signals_custom_agent , ",+ "expected": true+ },+ {+ "origin_product": "loop",+ "ai_stage": null,+ "internal": false,+ "allowlist": "signals_scout",+ "expected": false+ },+ {+ "origin_product": "signal_report",+ "ai_stage": null,+ "internal": true,+ "allowlist": "signals",+ "expected": true+ }+ ]+}diff --git a/products/desktop/packages/agent/src/utils/gateway.test.ts b/products/desktop/packages/agent/src/utils/gateway.test.tsindex 35ddf8544035..334204e0e8cc 100644--- a/products/desktop/packages/agent/src/utils/gateway.test.ts+++ b/products/desktop/packages/agent/src/utils/gateway.test.ts@@ -6,6 +6,7 @@ import {resolveGatewayTarget,resolveLlmGatewayUrl,} from "./gateway";+import routingCases from "./gateway-routing-cases.json";describe("resolveGatewayProduct", () => {it.each([@@ -421,3 +422,37 @@ describe("resolveAiProduct", () => {expect(resolveAiProduct({ product })).toBe(product);});});++// Shared contract with the Python mirror (test_ai_gateway_token.py) — both suites+// consume gateway-routing-cases.json so the resolvers cannot drift independently.+describe("shared routing contract", () => {+ it.each(routingCases.resolve_ai_product)(+ "resolves $origin_product/$ai_stage -> $expected",+ ({ origin_product, ai_stage, internal, expected }) => {+ const product = resolveGatewayProduct({+ isInternal: internal,+ originProduct: origin_product,+ });+ expect(resolveAiProduct({ product, aiStage: ai_stage })).toBe(expected);+ },+ );++ it.each(routingCases.routed)(+ "routes $origin_product/$ai_stage under [$allowlist] -> $expected",+ ({ origin_product, ai_stage, internal, allowlist, expected }) => {+ const target = resolveGatewayTarget({+ product: resolveGatewayProduct({+ isInternal: internal,+ originProduct: origin_product,+ }),+ aiStage: ai_stage,+ posthogHost: "https://us.posthog.com",+ env: {+ AI_GATEWAY_URL: "https://ai-gateway.us.posthog.com",+ AI_GATEWAY_PRODUCTS: allowlist,+ },+ });+ expect(target.isAiGateway).toBe(expected);+ },+ );+});diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex ddf7b561132e..6d7f6e00df08 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -471,6 +471,7 @@ RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset("LLM_GATEWAY_URL","AI_GATEWAY_URL","AI_GATEWAY_PRODUCTS",+ "AI_GATEWAY_TOKEN","POSTHOG_RESUME_RUN_ID","POSTHOG_AGENT_OTEL_LOGS_URL","POSTHOG_AGENT_OTEL_LOGS_TOKEN",diff --git a/products/tasks/backend/logic/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.pyindex 069d1ce7d4d0..5072b13b0c9c 100644--- a/products/tasks/backend/logic/services/agentsh.py+++ b/products/tasks/backend/logic/services/agentsh.py@@ -529,6 +529,7 @@ def generate_policy_yaml(allowed_domains: list[str] | None = None) -> str:"LLM_GATEWAY_URL","AI_GATEWAY_URL","AI_GATEWAY_PRODUCTS",+ "AI_GATEWAY_TOKEN","IS_SANDBOX","PYTHONPATH",],diff --git a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.pyindex 44027a62be32..a4dea49642d6 100644--- a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py@@ -129,7 +129,8 @@ def create_sandbox_from_snapshot(input: CreateSandboxFromSnapshotInput) -> Createnvironment_variables = build_sandbox_environment_variables(github_token=github_token,access_token=access_token,- team_id=ctx.team_id,+ ctx=ctx,+ task=task,sandbox_environment=sandbox_env,otel_telemetry_enabled=ctx.agent_otel_telemetry_enabled,)diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex f0af96c9776e..e34abc9c51c5 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -45,7 +45,6 @@ from products.tasks.backend.temporal.metrics import (from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_runfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (- ai_gateway_env_vars,get_git_identity_env_vars,get_sandbox_api_url,get_sandbox_github_token,@@ -53,6 +52,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_snapshot_metadata,get_task_run_credential_user,parse_run_state,+ run_gateway_env_vars,)from .get_task_processing_context import TaskProcessingContext@@ -108,6 +108,45 @@ def _emit_provisioning_diagnostics(ctx: TaskProcessingContext, sandbox: object)emit_agent_log(ctx.run_id, "debug", f"Sandbox image build logs:\n{raw_excerpt}")+def _build_environment_variables(+ ctx: TaskProcessingContext, task: Task, github_token: str, access_token: str+) -> dict[str, str]:+ environment_variables = {+ "POSTHOG_PERSONAL_API_KEY": access_token,+ "POSTHOG_API_URL": get_sandbox_api_url(),+ "POSTHOG_PROJECT_ID": str(ctx.team_id),+ "JWT_PUBLIC_KEY": get_sandbox_jwt_public_key(),+ }++ if ctx.sandbox_environment_id:+ sandbox_environment = ctx.get_sandbox_environment()+ if sandbox_environment and sandbox_environment.environment_variables:+ safe_vars, skipped_keys = filter_user_sandbox_env_vars(sandbox_environment.environment_variables)+ environment_variables.update(safe_vars)++ emit_agent_log(+ ctx.run_id,+ "debug",+ f"Applied {len(safe_vars)} sandbox environment variable(s) from '{sandbox_environment.name}'",+ )+ if skipped_keys:+ emit_agent_log(+ ctx.run_id,+ "debug",+ f"Skipped reserved/blocked sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",+ )++ if github_token:+ environment_variables["GITHUB_TOKEN"] = github_token+ environment_variables["GH_TOKEN"] = github_token++ if settings.SANDBOX_LLM_GATEWAY_URL:+ environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL++ environment_variables.update(run_gateway_env_vars(ctx, task))+ return environment_variables++@dataclassclass GetSandboxForRepositoryInput:context: TaskProcessingContext@@ -223,40 +262,7 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbocause=e,)- environment_variables = {- "POSTHOG_PERSONAL_API_KEY": access_token,- "POSTHOG_API_URL": get_sandbox_api_url(),- "POSTHOG_PROJECT_ID": str(ctx.team_id),- "JWT_PUBLIC_KEY": get_sandbox_jwt_public_key(),- }-- sandbox_environment = None- if ctx.sandbox_environment_id:- sandbox_environment = ctx.get_sandbox_environment()- if sandbox_environment and sandbox_environment.environment_variables:- safe_vars, skipped_keys = filter_user_sandbox_env_vars(sandbox_environment.environment_variables)- environment_variables.update(safe_vars)-- emit_agent_log(- ctx.run_id,- "debug",- f"Applied {len(safe_vars)} sandbox environment variable(s) from '{sandbox_environment.name}'",- )- if skipped_keys:- emit_agent_log(- ctx.run_id,- "debug",- f"Skipped reserved/blocked sandbox environment variable keys from '{sandbox_environment.name}': {', '.join(sorted(skipped_keys))}",- )-- if github_token:- environment_variables["GITHUB_TOKEN"] = github_token- environment_variables["GH_TOKEN"] = github_token-- if settings.SANDBOX_LLM_GATEWAY_URL:- environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL-- environment_variables.update(ai_gateway_env_vars())+ environment_variables = _build_environment_variables(ctx, task, github_token, access_token)environment_variables.update(get_git_identity_env_vars(task, ctx.state))diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex a8017e922253..8234691f864b 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -82,7 +82,6 @@ from products.tasks.backend.temporal.process_task.sandbox_credentials import (set_git_remote_token,)from products.tasks.backend.temporal.process_task.utils import (- ai_gateway_env_vars,get_git_identity_env_vars,get_readonly_github_token,get_sandbox_api_url,@@ -92,6 +91,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_snapshot_metadata,get_task_run_credential_user,parse_run_state,+ run_gateway_env_vars,)from .get_task_processing_context import TaskProcessingContext@@ -465,7 +465,7 @@ def _build_environment_variables(if settings.SANDBOX_LLM_GATEWAY_URL:environment_variables["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL- environment_variables.update(ai_gateway_env_vars())+ environment_variables.update(run_gateway_env_vars(ctx, task))if settings.DEBUG:# Local eval runs pin models per unit; the agent's overload rescue would silently switch adiff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pynew file mode 100644index 000000000000..756cfc4d1229--- /dev/null+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -0,0 +1,182 @@+"""Per-run scoped-token minting for sandboxes routed to the Go ai-gateway.++Routed runs authenticate with a short-lived `phe_` token minted here from the worker's+gateway credential: pinned product and on-behalf-of team, per-run spend cap, one internal+wallet. Minting is best-effort and the matching must agree with `resolveGatewayTarget` in+products/desktop/packages/agent/src/utils/gateway.ts; the agent routes to the Go gateway+only when the product is allowlisted AND a token is present, so a mint failure or matcher+disagreement degrades the run to the Python gateway rather than failing it.+"""++import json+import time+import random+import logging+from typing import Any++from django.conf import settings++import requests+from prometheus_client import Counter++logger = logging.getLogger(__name__)++AI_GATEWAY_TOKEN_MINTS = Counter(+ "tasks_ai_gateway_token_mints_total",+ "Scoped-token mint attempts for gateway-routed sandbox runs",+ labelnames=["result"],+)++# Mirrors resolveGatewayProduct in products/desktop/packages/agent/src/utils/gateway.ts.+_ORIGIN_TO_GATEWAY_PRODUCT: dict[str, str] = {+ "loop": "posthog_code",+ "onboarding": "onboarding",+ "posthog_ai": "posthog_ai",+ "signal_report": "signals",+ "signals_scout": "signals",+ "slack": "slack_app",+ "support_reply": "conversations",+}++# Mirrors SIGNALS_STAGE_PRODUCTS + SCOUT_STAGE_PREFIX in gateway.ts.+_SIGNALS_STAGE_PRODUCTS = frozenset({"scout", "research", "implementation", "repo_selection", "custom_agent"})+_SCOUT_STAGE_PREFIX = "scout:"++# Products whose runs may mint an internally funded token. Mint scope needs+# server-side provenance: `internal` and some origin_product values are+# API-settable, so an unmapped origin marked internal resolves to+# background_agents and must never mint. Signals products qualify because their+# stages are set only by server flows and the signals_scout origin is reserved.+MINTABLE_PRODUCTS = frozenset(+ {+ "signals_scout",+ "signals_research",+ "signals_implementation",+ "signals_repo_selection",+ "signals_custom_agent",+ }+)++# Minting is optional (no token = Python-gateway fallback), so the total budget+# stays a few seconds: 2 attempts x 3s + one short backoff, not a 30s provisioning stall.+_MINT_ATTEMPTS = 2+_MINT_TIMEOUT_SECONDS = 3+++def resolve_sandbox_ai_product(origin_product: str | None, ai_stage: str | None, *, internal: bool = False) -> str:+ """The `ai_product` the agent server will resolve for this run."""+ gateway_product = _ORIGIN_TO_GATEWAY_PRODUCT.get(origin_product or "")+ if gateway_product is None:+ gateway_product = "background_agents" if internal else "posthog_code"+ if gateway_product == "signals" and ai_stage:+ stage = "scout" if ai_stage.startswith(_SCOUT_STAGE_PREFIX) else ai_stage+ if stage in _SIGNALS_STAGE_PRODUCTS:+ return f"signals_{stage}"+ return gateway_product+++def sandbox_product_routed(ai_product: str, ai_stage: str | None, products_csv: str) -> bool:+ """Whether the allowlist routes this run to the Go gateway.++ Entries may qualify scouts by skill (`signals_scout:web-analytics`); a plain product+ entry matches every run of that product.+ """+ entries = {entry.strip() for entry in products_csv.split(",") if entry.strip()}+ if ai_product in entries:+ return True+ if ai_stage and ai_stage.startswith(_SCOUT_STAGE_PREFIX):+ skill = ai_stage[len(_SCOUT_STAGE_PREFIX) :]+ return f"{ai_product}:{skill}" in entries+ return False+++def _token_ttl_seconds() -> int:+ """Token lifetime: the explicit setting, else the run-duration cap plus a settle+ buffer, so a capped run cannot outlive its token (expiry under a live run fails+ every remaining LLM call with no fallback). A disabled run cap derives the 24h+ mint maximum; interactive sessions are cap-exempt and could still outlive it,+ but only capped background products are routed. Clamped to mint bounds (60s..24h).+ """+ configured = int(settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS or 0)+ if configured <= 0:+ run_cap = int(getattr(settings, "TASKS_MAX_RUN_DURATION_SECONDS", 0) or 0)+ configured = run_cap + 3600 if run_cap > 0 else 86400+ return max(60, min(configured, 86400))+++def _token_cap_usd(team_id: int) -> str:+ """Per-run cap, with per-team overrides (JSON map of team id to dollars).++ Team 2's custom scouts run hotter than the external fleet, so it carries a+ higher cap than the default without raising everyone's ceiling.+ """+ raw = settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES+ if raw:+ try:+ override = json.loads(raw).get(str(team_id))+ except (ValueError, AttributeError):+ override = None+ logger.warning("ai_gateway_token: cap overrides setting is not a JSON object; using the default cap")+ if override is not None:+ return str(override)+ return str(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD)+++def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None) -> str | None:+ """Mint a `phe_` scoped token pinned to (ai_product, obo=team_id), or None on failure.++ `user` pins the acting identity (the run's distinct id) so routed runs keep+ per-user ledger and budget attribution instead of pooling under the team.+ Retries mint rate limits (429) and transient upstream errors with jittered+ backoff. Callers treat None as "route this run to the Python gateway".+ """+ base_url = (settings.SANDBOX_AI_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")+ mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY+ if not base_url or not mint_key:+ return None++ body: dict[str, Any] = {+ "cap_usd": _token_cap_usd(team_id),+ "ttl_seconds": _token_ttl_seconds(),+ "product": ai_product,+ "obo": str(team_id),+ }+ if user:+ body["user"] = user+ last_error: str = ""+ for attempt in range(_MINT_ATTEMPTS):+ try:+ response = requests.post(+ f"{base_url}/v1/tokens",+ json=body,+ headers={"Authorization": f"Bearer {mint_key}"},+ timeout=_MINT_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ last_error = str(e)+ else:+ if 200 <= response.status_code < 300:+ try:+ token = response.json().get("token")+ last_error = "mint response had no token"+ except (ValueError, AttributeError):+ token = None+ last_error = "mint response was not a JSON object"+ if token:+ AI_GATEWAY_TOKEN_MINTS.labels(result="ok").inc()+ return token+ elif response.status_code in (429,) or response.status_code >= 500:+ last_error = f"HTTP {response.status_code}"+ else:+ # 4xx other than 429 will not improve on retry (bad credential, bad body).+ last_error = f"HTTP {response.status_code}: {response.text[:200]}"+ break+ if attempt < _MINT_ATTEMPTS - 1:+ time.sleep((0.5 * 2**attempt) + random.uniform(0, 0.25))++ AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()+ logger.warning(+ "ai_gateway_token: mint failed, run falls back to the Python gateway",+ extra={"ai_product": ai_product, "team_id": team_id, "error": last_error},+ )+ return Nonediff --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.pynew file mode 100644index 000000000000..7bdc612244eb--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py@@ -0,0 +1,373 @@+import json+from pathlib import Path++import pytest+from unittest.mock import MagicMock, patch++from products.tasks.backend.temporal.process_task.ai_gateway_token import (+ mint_scoped_token,+ resolve_sandbox_ai_product,+ sandbox_product_routed,+)+from products.tasks.backend.temporal.process_task.utils import ai_gateway_env_vars+++class TestResolveSandboxAiProduct:+ """Must agree with resolveAiProduct/resolveGatewayProduct in+ products/desktop/packages/agent/src/utils/gateway.ts — a disagreement makes a+ routed run mint no token (degrades to Python) or mint an unused token."""++ @pytest.mark.parametrize(+ "origin_product,ai_stage,expected",+ [+ ("signals_scout", "scout", "signals_scout"),+ ("signals_scout", "scout:web-analytics", "signals_scout"),+ ("signal_report", "research", "signals_research"),+ ("signal_report", "implementation", "signals_implementation"),+ ("signal_report", "repo_selection", "signals_repo_selection"),+ ("signal_report", "custom_agent", "signals_custom_agent"),+ ("signal_report", None, "signals"),+ ("signal_report", "match", "signals"),+ ("loop", None, "posthog_code"),+ ("slack", None, "slack_app"),+ ("support_reply", None, "conversations"),+ ("onboarding", None, "onboarding"),+ ("posthog_ai", None, "posthog_ai"),+ ],+ )+ def test_mapping(self, origin_product, ai_stage, expected):+ assert resolve_sandbox_ai_product(origin_product, ai_stage) == expected++ def test_unmapped_internal_is_background_agents(self):+ assert resolve_sandbox_ai_product("image_builder", None, internal=True) == "background_agents"++ def test_unmapped_external_is_posthog_code(self):+ assert resolve_sandbox_ai_product("user_created", None) == "posthog_code"++ def test_stage_does_not_split_non_signals_products(self):+ assert resolve_sandbox_ai_product("loop", "implementation") == "posthog_code"+++class TestSharedRoutingContract:+ """Both matchers consume gateway-routing-cases.json (see the TS suite), so the+ TypeScript resolver and this Python mirror cannot drift while staying green."""++ _CASES = json.loads(+ (Path(__file__).parents[6] / "products/desktop/packages/agent/src/utils/gateway-routing-cases.json").read_text()+ )++ @pytest.mark.parametrize(+ "case", _CASES["resolve_ai_product"], ids=lambda c: f"{c['origin_product']}/{c['ai_stage']}"+ )+ def test_resolve_matches_contract(self, case):+ assert (+ resolve_sandbox_ai_product(case["origin_product"], case["ai_stage"], internal=case["internal"])+ == case["expected"]+ )++ @pytest.mark.parametrize("case", _CASES["routed"], ids=lambda c: f"{c['origin_product']}/{c['ai_stage']}")+ def test_routed_matches_contract(self, case):+ ai_product = resolve_sandbox_ai_product(case["origin_product"], case["ai_stage"], internal=case["internal"])+ assert sandbox_product_routed(ai_product, case["ai_stage"], case["allowlist"]) == case["expected"]+++class TestSandboxProductRouted:+ def test_plain_entry_matches_product(self):+ assert sandbox_product_routed("signals_research", "research", "signals_research,signals_scout")++ def test_plain_entry_matches_every_scout_skill(self):+ assert sandbox_product_routed("signals_scout", "scout:logs", "signals_scout")++ def test_skill_qualified_entry_matches_only_its_skill(self):+ entries = "signals_scout:web-analytics"+ assert sandbox_product_routed("signals_scout", "scout:web-analytics", entries)+ assert not sandbox_product_routed("signals_scout", "scout:logs", entries)+ assert not sandbox_product_routed("signals_scout", "scout", entries)++ def test_unlisted_product_is_not_routed(self):+ assert not sandbox_product_routed("posthog_code", None, "signals_scout")++ def test_whitespace_and_blank_entries_tolerated(self):+ assert sandbox_product_routed("signals_custom_agent", "custom_agent", " , signals_custom_agent , ")+++def mint_settings(settings):+ settings.SANDBOX_AI_GATEWAY_URL = "https://ai-gateway.dev.posthog.dev"+ settings.SANDBOX_AI_GATEWAY_PRODUCTS = "signals_scout,signals_research"+ settings.SANDBOX_AI_GATEWAY_MINT_KEY = "phs_test_mint"+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD = "3"+ settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 14400+ settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = ""+ return settings+++class TestMintScopedToken:+ def _response(self, status_code=201, body=None):+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = body or {}+ response.text = ""+ return response++ def test_mints_pinned_token(self, mint_settings):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"+ _, kwargs = post.call_args+ assert post.call_args[0][0] == "https://ai-gateway.dev.posthog.dev/v1/tokens"+ assert kwargs["json"] == {+ "cap_usd": "3",+ "ttl_seconds": 14400,+ "product": "signals_scout",+ "obo": "123",+ }+ assert kwargs["headers"] == {"Authorization": "Bearer phs_test_mint"}+ assert kwargs["timeout"] == 3++ def test_retries_mint_rate_limit_then_succeeds(self, mint_settings):+ with (+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post,+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.time.sleep") as sleep,+ ):+ post.side_effect = [self._response(429), self._response(201, {"token": "phe_abc"})]+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"+ assert sleep.called++ def test_accepts_200_and_201(self, mint_settings):+ """The gateway mints with 201 Created; accepting only 200 turned every+ successful mint into a silent Python-gateway fallback."""+ for code in (200, 201):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(code, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"++ def test_gives_up_after_retries(self, mint_settings):+ with (+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post,+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.time.sleep"),+ ):+ post.return_value = self._response(503)+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) is None+ assert post.call_count == 2++ def test_does_not_retry_a_credential_rejection(self, mint_settings):+ with (+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post,+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.time.sleep"),+ ):+ post.return_value = self._response(401)+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) is None+ assert post.call_count == 1++ def test_no_mint_key_mints_nothing(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_MINT_KEY = None+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) is None+ post.assert_not_called()++ def test_non_json_200_degrades_instead_of_raising(self, mint_settings):+ response = MagicMock()+ response.status_code = 200+ response.json.side_effect = ValueError("not json")+ response.text = "<html>proxy error</html>"+ with (+ patch(+ "products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post",+ return_value=response,+ ),+ patch("products.tasks.backend.temporal.process_task.ai_gateway_token.time.sleep"),+ ):+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) is None++ def test_ttl_derives_from_run_cap_when_unset(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 3 * 60 * 60+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 3 * 60 * 60 + 3600++ def test_ttl_clamps_to_gateway_max_when_run_cap_disabled(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_TTL_SECONDS = 0+ mint_settings.TASKS_MAX_RUN_DURATION_SECONDS = 0+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response(201, {"token": "phe_abc"})+ assert mint_scoped_token(ai_product="signals_scout", team_id=123) == "phe_abc"+ assert post.call_args.kwargs["json"]["ttl_seconds"] == 86400+++class TestAiGatewayEnvVars:+ def test_routed_run_gets_url_products_and_token(self, mint_settings):+ with patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token",+ return_value="phe_abc",+ ) as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout:logs")+ assert env == {+ "AI_GATEWAY_URL": "https://ai-gateway.dev.posthog.dev",+ "AI_GATEWAY_PRODUCTS": "signals_scout,signals_research",+ "AI_GATEWAY_TOKEN": "phe_abc",+ }+ mint.assert_called_once_with(ai_product="signals_scout", team_id=123, user=None)++ def test_unrouted_run_gets_no_token(self, mint_settings):+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="loop")+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_skill_qualified_allowlist_still_mints(self, mint_settings):+ """The D4-D6 batched scout flips route by skill-qualified entries alone; a mint+ gate that only honors plain product entries would silently no-op every batch."""+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "signals_scout:web-analytics"+ with patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token",+ return_value="phe_abc",+ ) as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout:web-analytics")+ assert env["AI_GATEWAY_TOKEN"] == "phe_abc"+ mint.assert_called_once_with(ai_product="signals_scout", team_id=123, user=None)++ def test_mint_failure_omits_token(self, mint_settings):+ with patch(+ "products.tasks.backend.temporal.process_task.utils.mint_scoped_token",+ return_value=None,+ ):+ env = ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout")+ assert "AI_GATEWAY_TOKEN" not in env+ assert env["AI_GATEWAY_URL"] == "https://ai-gateway.dev.posthog.dev"++ def test_no_run_context_still_sets_routing_pair(self, mint_settings):+ env = ai_gateway_env_vars()+ assert env == {+ "AI_GATEWAY_URL": "https://ai-gateway.dev.posthog.dev",+ "AI_GATEWAY_PRODUCTS": "signals_scout,signals_research",+ }++ def test_both_or_nothing_guard_unchanged(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_URL = None+ assert ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout") == {}+++class TestMintableGate:+ """Mint scope needs server-side provenance: `internal` and some origin_product+ values are API-settable, so a routed-but-unmintable product must never mint."""++ def test_caller_internal_flag_cannot_mint_for_background_agents(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "background_agents"+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="image_builder", internal=True)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_stageless_signal_report_cannot_mint_for_bare_signals(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "signals"+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint:+ env = ai_gateway_env_vars(team_id=123, origin_product="signal_report", ai_stage=None)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()+++class TestProvisioningBoundaries:+ """Every provisioning path derives its gateway env through run_gateway_env_vars,+ so no path can drop the team, origin, stage, internal, or acting-identity context+ minting depends on. These pin the one derivation and each path's use of it."""++ def _ctx(self):+ ctx = MagicMock()+ ctx.team_id = 7+ ctx.origin_product = "signals_scout"+ ctx.state = {"ai_stage": "scout:logs"}+ ctx.distinct_id = "user-1"+ ctx.sandbox_environment_id = None+ return ctx++ def _task(self):+ task = MagicMock()+ task.internal = True+ return task++ def test_run_gateway_env_vars_maps_the_full_context(self, mint_settings):+ from products.tasks.backend.temporal.process_task import utils++ with patch.object(utils, "ai_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"}) as env:+ out = utils.run_gateway_env_vars(self._ctx(), self._task())+ assert out == {"AI_GATEWAY_TOKEN": "phe"}+ env.assert_called_once_with(+ team_id=7,+ origin_product="signals_scout",+ ai_stage="scout:logs",+ internal=True,+ distinct_id="user-1",+ )++ def test_snapshot_builder_uses_the_shared_derivation(self, mint_settings):+ from products.tasks.backend.temporal.process_task import utils++ ctx, task = self._ctx(), self._task()+ with (+ patch.object(utils, "run_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"}) as env,+ patch(+ "products.tasks.backend.logic.services.connection_token.get_sandbox_jwt_public_key",+ return_value="jwt",+ ),+ patch.object(utils, "get_sandbox_api_url", return_value="url"),+ ):+ out = utils.build_sandbox_environment_variables(github_token="", access_token="tok", ctx=ctx, task=task)+ env.assert_called_once_with(ctx, task)+ assert out["AI_GATEWAY_TOKEN"] == "phe"++ def test_repository_builder_uses_the_shared_derivation(self, mint_settings):+ import importlib++ mod = importlib.import_module(+ "products.tasks.backend.temporal.process_task.activities.get_sandbox_for_repository"+ )++ ctx, task = self._ctx(), self._task()+ with (+ patch.object(mod, "run_gateway_env_vars", return_value={"AI_GATEWAY_TOKEN": "phe"}) as env,+ patch.object(mod, "get_sandbox_jwt_public_key", return_value="jwt"),+ patch.object(mod, "get_sandbox_api_url", return_value="url"),+ ):+ out = mod._build_environment_variables(ctx, task, "", "tok")+ env.assert_called_once_with(ctx, task)+ assert out["AI_GATEWAY_TOKEN"] == "phe"+++class TestUserPinAndCapOverride:+ def _response(self, body):+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = body+ response.text = ""+ return response++ def test_mint_pins_the_acting_user(self, mint_settings):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_scout", team_id=123, user="user-distinct-1")+ assert post.call_args.kwargs["json"]["user"] == "user-distinct-1"++ def test_mint_omits_user_when_unknown(self, mint_settings):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_scout", team_id=123)+ assert "user" not in post.call_args.kwargs["json"]++ def test_cap_override_applies_per_team(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = '{"2": "10"}'+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_scout", team_id=2)+ mint_scoped_token(ai_product="signals_scout", team_id=123)+ assert post.call_args_list[0].kwargs["json"]["cap_usd"] == "10"+ assert post.call_args_list[1].kwargs["json"]["cap_usd"] == "3"++ def test_malformed_overrides_fall_back_to_default(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD_OVERRIDES = "not json"+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = self._response({"token": "phe_abc"})+ mint_scoped_token(ai_product="signals_scout", team_id=2)+ assert post.call_args.kwargs["json"]["cap_usd"] == "3"diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.pyindex e39ecc6b798b..40e55dea0323 100644--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py@@ -429,3 +429,19 @@ def test_build_environment_variables_omits_otel_env_when_flag_disabled(_api, _jwenv = _build_environment_variables(ctx, MagicMock(), "", "access-token")assert not any(key.startswith("POSTHOG_AGENT_OTEL_") for key in env)+++def test_build_environment_variables_forwards_run_context_to_token_minting():+ """The fresh-provisioning path must forward team, origin, stage, and internal+ into token minting; a dropped kwarg silently degrades every fresh run to the+ Python gateway."""+ ctx = _context(origin_product="signals_scout", state={"ai_stage": "scout:logs"})+ task = MagicMock()+ task.internal = True+ with patch(+ "products.tasks.backend.temporal.process_task.activities.provision_sandbox.run_gateway_env_vars",+ return_value={"AI_GATEWAY_TOKEN": "phe"},+ ) as env:+ out = _build_environment_variables(ctx, task, "", "access-token")+ env.assert_called_once_with(ctx, task)+ assert out["AI_GATEWAY_TOKEN"] == "phe"diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex fe060e7a7bda..9cd55dc4cb25 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -1153,6 +1153,22 @@ class TestGetRelayedMcpServerNames(TestCase):assert get_relayed_mcp_server_names(task_run, {"grafana"}) == ["Playwright", "internal-cli"]+def _gateway_ctx_task() -> tuple[MagicMock, MagicMock]:+ """Duck ctx/task for build_sandbox_environment_variables' run-context shape."""+ ctx = MagicMock()+ ctx.team_id = 1+ ctx.origin_product = "signals_scout"+ ctx.state = {}+ ctx.distinct_id = "distinct-1"+ ctx.sandbox_environment_id = None+ task = MagicMock()+ task.internal = False+ return ctx, task+++_CTX, _TASK = _gateway_ctx_task()++@patch("products.tasks.backend.logic.services.connection_token.get_sandbox_jwt_public_key",return_value="test-jwt-key",@@ -1163,7 +1179,8 @@ class TestGetRelayedMcpServerNames(TestCase):)class TestBuildSandboxEnvironmentVariablesGateway(TestCase):def _build(self):- return build_sandbox_environment_variables(github_token=None, access_token="tok", team_id=1)+ ctx, task = _gateway_ctx_task()+ return build_sandbox_environment_variables(github_token=None, access_token="tok", ctx=ctx, task=task)@override_settings(SANDBOX_AI_GATEWAY_URL="https://ai-gateway.us.posthog.com",@@ -1204,7 +1221,7 @@ class TestBuildSandboxEnvironmentVariables(SimpleTestCase):SANDBOX_AGENT_OTEL_LOGS_TOKEN="phc_telemetry",SANDBOX_AGENT_OTEL_TRACES_URL="https://us.i.posthog.com/i/v1/traces",):- env = build_sandbox_environment_variables(None, "access-token", 1, otel_telemetry_enabled=True)+ env = build_sandbox_environment_variables(None, "access-token", _CTX, _TASK, otel_telemetry_enabled=True)assert env["POSTHOG_AGENT_OTEL_LOGS_URL"] == "https://us.i.posthog.com/i/v1/logs"assert env["POSTHOG_AGENT_OTEL_LOGS_TOKEN"] == "phc_telemetry"@@ -1224,7 +1241,7 @@ class TestBuildSandboxEnvironmentVariables(SimpleTestCase):SANDBOX_AGENT_OTEL_LOGS_TOKEN=None,SANDBOX_AGENT_OTEL_TRACES_URL="https://us.i.posthog.com/i/v1/traces",):- env = build_sandbox_environment_variables(None, "access-token", 1, otel_telemetry_enabled=True)+ env = build_sandbox_environment_variables(None, "access-token", _CTX, _TASK, otel_telemetry_enabled=True)assert not any(key.startswith("POSTHOG_AGENT_OTEL_") for key in env)@@ -1242,7 +1259,7 @@ class TestBuildSandboxEnvironmentVariables(SimpleTestCase):SANDBOX_AGENT_OTEL_LOGS_TOKEN="phc_telemetry",SANDBOX_AGENT_OTEL_TRACES_URL="https://us.i.posthog.com/i/v1/traces",):- env = build_sandbox_environment_variables(None, "access-token", 1)+ env = build_sandbox_environment_variables(None, "access-token", _CTX, _TASK)assert not any(key.startswith("POSTHOG_AGENT_OTEL_") for key in env)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 76b690b80e6c..f98ff9492e32 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -40,6 +40,12 @@ from products.tasks.backend.logic.services.run_actor import (loop_owner_eligible_for_credentials,)from products.tasks.backend.redis import get_tasks_cache+from products.tasks.backend.temporal.process_task.ai_gateway_token import (+ MINTABLE_PRODUCTS,+ mint_scoped_token,+ resolve_sandbox_ai_product,+ sandbox_product_routed,+)if TYPE_CHECKING:from posthog.models.user import User@@ -1226,12 +1232,16 @@ def get_sandbox_name_for_task(task_id: str) -> str:def build_sandbox_environment_variables(github_token: str | None,access_token: str,- team_id: int,+ ctx,+ task,sandbox_environment: Optional[Any] = None,otel_telemetry_enabled: bool = False,) -> dict[str, str]:"""Build the environment variables dict for a sandbox, merging user env vars from SandboxEnvironment.+ Takes the run's ctx/task wholesale so the gateway routing/mint env is derived by+ ``run_gateway_env_vars`` and no caller can drop part of the context.+User-provided env vars are applied first so system vars always take precedence,preventing a malicious SandboxEnvironment from overriding security-critical values."""@@ -1251,7 +1261,7 @@ def build_sandbox_environment_variables({"POSTHOG_PERSONAL_API_KEY": access_token,"POSTHOG_API_URL": get_sandbox_api_url(),- "POSTHOG_PROJECT_ID": str(team_id),+ "POSTHOG_PROJECT_ID": str(ctx.team_id),"JWT_PUBLIC_KEY": get_sandbox_jwt_public_key(),})@@ -1259,7 +1269,7 @@ def build_sandbox_environment_variables(if settings.SANDBOX_LLM_GATEWAY_URL:env_vars["LLM_GATEWAY_URL"] = settings.SANDBOX_LLM_GATEWAY_URL- env_vars.update(ai_gateway_env_vars())+ env_vars.update(run_gateway_env_vars(ctx, task))if otel_telemetry_enabled:env_vars.update(get_sandbox_otel_env_vars())@@ -1285,18 +1295,57 @@ def get_sandbox_otel_env_vars() -> dict[str, str]:return env_vars-def ai_gateway_env_vars() -> dict[str, str]:+def run_gateway_env_vars(ctx, task) -> dict[str, str]:+ """The gateway routing/mint env for one run, derived from its server-side context.++ Every sandbox provisioning path calls this rather than spelling out the kwargs, so+ no path can silently drop the team, origin, stage, internal, or acting-identity+ context that scoped-token minting depends on. `ctx` is the run's+ TaskProcessingContext (duck-typed to avoid an import cycle); `task` the Task row.+ """+ return ai_gateway_env_vars(+ team_id=ctx.team_id,+ origin_product=ctx.origin_product,+ ai_stage=(ctx.state or {}).get("ai_stage"),+ internal=task.internal,+ distinct_id=ctx.distinct_id,+ )+++def ai_gateway_env_vars(+ *,+ team_id: int | None = None,+ origin_product: str | None = None,+ ai_stage: str | None = None,+ internal: bool = False,+ distinct_id: str | None = None,+) -> dict[str, str]:"""Env vars routing listed products to the Go ai-gateway, shared by everyinjection site so the both-or-nothing guard cannot drift per site. Bothsettings or nothing: a URL with no product allowlist would route everysandbox caller, and a product list with no URL has nowhere to go.++ When the run's product is on the allowlist and a mint credential is+ configured, a per-run `phe_` scoped token is minted and injected as+ ``AI_GATEWAY_TOKEN``; the agent server routes to the Go gateway only when+ the token is present, so a missing token (mint failure, or a caller that+ cannot supply run context) degrades the run to the Python gateway."""- if settings.SANDBOX_AI_GATEWAY_URL and settings.SANDBOX_AI_GATEWAY_PRODUCTS:- return {- "AI_GATEWAY_URL": settings.SANDBOX_AI_GATEWAY_URL,- "AI_GATEWAY_PRODUCTS": settings.SANDBOX_AI_GATEWAY_PRODUCTS,- }- return {}+ if not (settings.SANDBOX_AI_GATEWAY_URL and settings.SANDBOX_AI_GATEWAY_PRODUCTS):+ return {}+ env_vars = {+ "AI_GATEWAY_URL": settings.SANDBOX_AI_GATEWAY_URL,+ "AI_GATEWAY_PRODUCTS": settings.SANDBOX_AI_GATEWAY_PRODUCTS,+ }+ if team_id is not None:+ ai_product = resolve_sandbox_ai_product(origin_product, ai_stage, internal=internal)+ if ai_product in MINTABLE_PRODUCTS and sandbox_product_routed(+ ai_product, ai_stage, settings.SANDBOX_AI_GATEWAY_PRODUCTS+ ):+ token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id)+ if token:+ env_vars["AI_GATEWAY_TOKEN"] = token+ return env_varsdef get_pr_authorship_mode(task: Task, state: dict[str, Any] | None = None) -> PrAuthorshipMode: