Skip to content

: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.

feat(tasks): route sandbox runs on the worker's pinned gateway product (#93879)

Brandonc27df4801206
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index b547977ebbe9..fd2d2275cdc9 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -175,6 +175,18 @@ over the default cap. Set the product override to `{}` to disable the built-in
implementation override. An empty environment value is treated as unset and
restores the built-in map.
+### Which gateway a sandbox run uses
+
+A run reaches the Go gateway only when its `ai_product` is listed in
+`SANDBOX_AI_GATEWAY_PRODUCTS` and the worker minted a scoped token for it. When the
+worker mints, it also injects `AI_GATEWAY_PRODUCT` and `AI_GATEWAY_AI_STAGE`, naming
+the product the token is pinned to, and the agent routes on those in preference to
+what it derives itself. Both are reserved keys: a sandbox environment cannot set them.
+
+When a run lands on the Python gateway unexpectedly, check those two variables first.
+Their absence means no token was minted, so the agent falls back to deriving the
+product from the task run it fetches at boot, which is the path that fails quietly.
+
### Agent run telemetry (optional)
To ship agent-server run metadata to PostHog Logs, set both of the first two; the third additionally produces one APM trace per run (root `task_run` span, a `turn` span per prompt, a `tool_call:<kind>` span per tool call) with trace/span ids stamped on the log records:
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.ts
index 26925583f3bf..6118f91839d7 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
@@ -424,6 +424,8 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
];
const GO_GATEWAY = "https://ai-gateway.us.posthog.com";
const SCOPED_TOKEN = "phe_test_scoped_token";
@@ -571,6 +573,36 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
);
});
+ // A failed boot fetch leaves aiStage null; without the env values the minted token goes unused.
+ it("routes on the worker's product and stage when the run fetch yielded no stage", () => {
+ process.env.AI_GATEWAY_PRODUCT = "signals_scout";
+ process.env.AI_GATEWAY_AI_STAGE = "scout:web-analytics";
+ const env = buildServer().configureEnvironment({
+ originProduct: "signals_scout",
+ aiStage: null,
+ taskId: "task-1",
+ taskRunId: "run-1",
+ });
+
+ expect(env.anthropicBaseUrl).toBe(GO_GATEWAY);
+ expect(env.anthropicAuthToken).toBe(SCOPED_TOKEN);
+ expect(parseBlob(env.anthropicCustomHeaders ?? "")).toMatchObject({
+ ai_product: "signals_scout",
+ ai_stage: "scout:web-analytics",
+ task_run_id: "run-1",
+ });
+ });
+
+ it("derives product and stage itself when the worker passes none", () => {
+ const env = buildServer().configureEnvironment({
+ originProduct: "signals_scout",
+ aiStage: null,
+ });
+
+ expect(env.anthropicBaseUrl).toBe("https://gateway.us.posthog.com/signals");
+ expect(env.anthropicAuthToken).toBe("test-api-key");
+ });
+
it("authenticates with the scoped token on the Go path", () => {
const env = buildServer().configureEnvironment({
originProduct: "signals_scout",
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index bb85df9c72f9..ef11ae282d57 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -1830,14 +1830,12 @@ export class AgentServer {
this.posthogAPI
.getTaskRun(payload.task_id, payload.run_id)
.catch((err) => {
- this.logger.debug(
- "Failed to fetch task run for session context",
- {
- taskId: payload.task_id,
- runId: payload.run_id,
- error: err,
- },
- );
+ // Without the run the stage is unknown, so routing falls back to the env product.
+ this.logger.warn("Failed to fetch task run for session context", {
+ taskId: payload.task_id,
+ runId: payload.run_id,
+ error: err,
+ });
return null;
}),
this.fetchTaskForSessionContext(payload.task_id),
@@ -4706,7 +4704,8 @@ ${commonInstructions}
// 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.
+ // product with no token therefore stays on the Python gateway. The worker's env values
+ // win, because the token is pinned to the product they name.
const gatewayToken = process.env.AI_GATEWAY_TOKEN?.trim() || undefined;
let target = resolveGatewayTarget({
product,
@@ -4724,7 +4723,12 @@ ${commonInstructions}
env: { ...process.env, AI_GATEWAY_URL: undefined },
});
}
- const { baseUrl: gatewayUrl, isAiGateway, aiProduct } = target;
+ const {
+ baseUrl: gatewayUrl,
+ isAiGateway,
+ aiProduct,
+ aiStage: resolvedStage,
+ } = target;
const llmBearer = isAiGateway && gatewayToken ? gatewayToken : apiKey;
const openaiBaseUrl = gatewayUrl.endsWith("/v1")
? gatewayUrl
@@ -4738,7 +4742,7 @@ ${commonInstructions}
task_origin_product: originProduct,
task_internal: isInternal,
signal_report_id: signalReportId,
- ai_stage: aiStage,
+ ai_stage: resolvedStage,
task_id: taskId,
task_run_id: taskRunId,
task_user_id: taskUserId,
diff --git a/products/desktop/packages/agent/src/utils/gateway.test.ts b/products/desktop/packages/agent/src/utils/gateway.test.ts
index 6172b2df0794..6ea109886802 100644
--- a/products/desktop/packages/agent/src/utils/gateway.test.ts
+++ b/products/desktop/packages/agent/src/utils/gateway.test.ts
@@ -233,7 +233,12 @@ describe("resolveGatewayTarget", () => {
posthogHost: PY_HOST,
env: SIGNALS_ENV,
}),
- ).toEqual({ baseUrl: GO, isAiGateway: true, aiProduct: "signals_scout" });
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout",
+ });
});
it("leaves an unlisted signals stage on the Python gateway", () => {
@@ -248,6 +253,7 @@ describe("resolveGatewayTarget", () => {
baseUrl: "https://gateway.us.posthog.com/signals",
isAiGateway: false,
aiProduct: "signals_implementation",
+ aiStage: "implementation",
});
});
@@ -305,7 +311,12 @@ describe("resolveGatewayTarget", () => {
posthogHost: PY_HOST,
env: SIGNALS_ENV,
}),
- ).toEqual({ baseUrl: GO, isAiGateway: true, aiProduct: "signals_scout" });
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout:web-analytics",
+ });
});
it("routes only the listed skill via a skill-qualified entry", () => {
@@ -320,7 +331,12 @@ describe("resolveGatewayTarget", () => {
posthogHost: PY_HOST,
env,
}),
- ).toEqual({ baseUrl: GO, isAiGateway: true, aiProduct: "signals_scout" });
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout:web-analytics",
+ });
expect(
resolveGatewayTarget({
product: "signals",
@@ -332,6 +348,7 @@ describe("resolveGatewayTarget", () => {
baseUrl: "https://gateway.us.posthog.com/signals",
isAiGateway: false,
aiProduct: "signals_scout",
+ aiStage: "scout:logs",
});
});
@@ -364,6 +381,112 @@ describe("resolveGatewayTarget", () => {
baseUrl: GO,
isAiGateway: true,
aiProduct: "signals_custom_agent",
+ aiStage: "custom_agent",
+ });
+ });
+
+ it("prefers the worker's product and stage over the local derivation", () => {
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: null,
+ posthogHost: PY_HOST,
+ env: {
+ ...SIGNALS_ENV,
+ AI_GATEWAY_PRODUCT: "signals_scout",
+ AI_GATEWAY_AI_STAGE: "scout:web-analytics",
+ },
+ }),
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout:web-analytics",
+ });
+ });
+
+ // Without a disagreeing case the preference can be deleted with the suite green.
+ it("uses the worker's product when the local derivation would pick another", () => {
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: "scout",
+ posthogHost: PY_HOST,
+ env: { ...SIGNALS_ENV, AI_GATEWAY_PRODUCT: "signals_research" },
+ }).aiProduct,
+ ).toBe("signals_research");
+ });
+
+ it("uses the worker's stage when the caller fetched a different one", () => {
+ // The stage decides the skill-qualified allowlist key and the blob's stage.
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: "scout:logs",
+ posthogHost: PY_HOST,
+ env: {
+ AI_GATEWAY_URL: GO,
+ AI_GATEWAY_PRODUCTS: "signals_scout:web-analytics",
+ AI_GATEWAY_AI_STAGE: "scout:web-analytics",
+ },
+ }),
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout:web-analytics",
+ });
+ });
+
+ it("matches a skill-qualified allowlist entry via the worker's stage", () => {
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: null,
+ posthogHost: PY_HOST,
+ env: {
+ AI_GATEWAY_URL: GO,
+ AI_GATEWAY_PRODUCTS: "signals_scout:web-analytics",
+ AI_GATEWAY_PRODUCT: "signals_scout",
+ AI_GATEWAY_AI_STAGE: "scout:web-analytics",
+ },
+ }).isAiGateway,
+ ).toBe(true);
+ });
+
+ it("keeps the allowlist gate for a worker-provided product", () => {
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: "summarization",
+ posthogHost: PY_HOST,
+ env: { ...SIGNALS_ENV, AI_GATEWAY_PRODUCT: "signals_emission" },
+ }),
+ ).toEqual({
+ baseUrl: "https://gateway.us.posthog.com/signals",
+ isAiGateway: false,
+ aiProduct: "signals_emission",
+ aiStage: "summarization",
+ });
+ });
+
+ it("ignores blank worker product and stage values", () => {
+ expect(
+ resolveGatewayTarget({
+ product: "signals",
+ aiStage: "scout",
+ posthogHost: PY_HOST,
+ env: {
+ ...SIGNALS_ENV,
+ AI_GATEWAY_PRODUCT: " ",
+ AI_GATEWAY_AI_STAGE: "",
+ },
+ }),
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: "signals_scout",
+ aiStage: "scout",
});
});
diff --git a/products/desktop/packages/agent/src/utils/gateway.ts b/products/desktop/packages/agent/src/utils/gateway.ts
index 16db9d60e55f..3a50b2473b4a 100644
--- a/products/desktop/packages/agent/src/utils/gateway.ts
+++ b/products/desktop/packages/agent/src/utils/gateway.ts
@@ -152,6 +152,8 @@ export interface GatewayTarget {
isAiGateway: boolean;
/** Product tag; only the Go gateway needs it sent explicitly. */
aiProduct: string;
+ /** Stage the product was resolved from: the worker's, else the caller's, else none. */
+ aiStage: string | null;
}
/**
@@ -169,6 +171,9 @@ export interface GatewayTarget {
* Scout entries may qualify by skill (`signals_scout:web-analytics`), matching
* only runs of that skill, so the scout fleet can migrate in batches. A plain
* `signals_scout` entry matches every skill.
+ *
+ * `AI_GATEWAY_PRODUCT` and `AI_GATEWAY_AI_STAGE` name the product the worker pinned the token
+ * to. They win over the local derivation, whose task-run fetch can fail and leave no stage.
*/
export function resolveGatewayTarget({
product,
@@ -181,11 +186,15 @@ export function resolveGatewayTarget({
posthogHost: string;
env?: Record<string, string | undefined>;
}): GatewayTarget {
- const aiProduct = resolveAiProduct({ product, aiStage });
+ const workerStage = (env.AI_GATEWAY_AI_STAGE ?? "").trim() || null;
+ const workerProduct = (env.AI_GATEWAY_PRODUCT ?? "").trim() || null;
+ const effectiveStage = workerStage ?? aiStage ?? null;
+ const aiProduct =
+ workerProduct ?? resolveAiProduct({ product, aiStage: effectiveStage });
const aiGatewayUrl = (env.AI_GATEWAY_URL ?? "").trim();
const routedProducts = parseAiGatewayProducts(env.AI_GATEWAY_PRODUCTS);
- const skillQualified = aiStage?.startsWith(SCOUT_STAGE_PREFIX)
- ? `${aiProduct}:${aiStage.slice(SCOUT_STAGE_PREFIX.length)}`
+ const skillQualified = effectiveStage?.startsWith(SCOUT_STAGE_PREFIX)
+ ? `${aiProduct}:${effectiveStage.slice(SCOUT_STAGE_PREFIX.length)}`
: null;
const routed =
aiGatewayUrl !== "" &&
@@ -199,11 +208,13 @@ export function resolveGatewayTarget({
}),
isAiGateway: true,
aiProduct,
+ aiStage: effectiveStage,
};
}
return {
baseUrl: resolveLlmGatewayUrl(env.LLM_GATEWAY_URL, posthogHost, product),
isAiGateway: false,
aiProduct,
+ aiStage: effectiveStage,
};
}
diff --git a/products/desktop/packages/core/src/settings/environmentSetup.ts b/products/desktop/packages/core/src/settings/environmentSetup.ts
index baa4e4a1aa3b..8084fd7016ab 100644
--- a/products/desktop/packages/core/src/settings/environmentSetup.ts
+++ b/products/desktop/packages/core/src/settings/environmentSetup.ts
@@ -330,6 +330,8 @@ const RESERVED_ENV_VAR_KEYS: ReadonlySet<string> = new Set([
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
"POSTHOG_RESUME_RUN_ID",
"POSTHOG_AGENT_OTEL_LOGS_URL",
"POSTHOG_AGENT_OTEL_LOGS_TOKEN",
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 5e0d3c5f0f5c..529a146c91f0 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -526,6 +526,8 @@ RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset(
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
"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.py
index 5072b13b0c9c..c3742cc32cfc 100644
--- a/products/tasks/backend/logic/services/agentsh.py
+++ b/products/tasks/backend/logic/services/agentsh.py
@@ -530,6 +530,8 @@ def generate_policy_yaml(allowed_domains: list[str] | None = None) -> str:
"AI_GATEWAY_URL",
"AI_GATEWAY_PRODUCTS",
"AI_GATEWAY_TOKEN",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
"IS_SANDBOX",
"PYTHONPATH",
],
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.py
index a66234e501be..854347be7cd2 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
@@ -4,6 +4,7 @@ from pathlib import Path
import pytest
from unittest.mock import MagicMock, patch
+from products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
from products.tasks.backend.temporal.process_task.ai_gateway_token import (
mint_scoped_token,
resolve_sandbox_ai_product,
@@ -210,6 +211,8 @@ class TestAiGatewayEnvVars:
"AI_GATEWAY_URL": "https://ai-gateway.dev.posthog.dev",
"AI_GATEWAY_PRODUCTS": "signals_scout,signals_research",
"AI_GATEWAY_TOKEN": "phe_abc",
+ "AI_GATEWAY_PRODUCT": "signals_scout",
+ "AI_GATEWAY_AI_STAGE": "scout:logs",
}
mint.assert_called_once_with(ai_product="signals_scout", team_id=123, user=None)
@@ -217,8 +220,15 @@ class TestAiGatewayEnvVars:
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
+ assert "AI_GATEWAY_PRODUCT" not in env
+ assert "AI_GATEWAY_AI_STAGE" not in env
mint.assert_not_called()
+ # The agent trusts these as the worker's word, so the API must refuse a run-supplied value.
+ def test_reserved_keys_cover_the_pinned_product_env(self):
+ assert "AI_GATEWAY_PRODUCT" in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
+ assert "AI_GATEWAY_AI_STAGE" in RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
+
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."""
@@ -238,6 +248,8 @@ class TestAiGatewayEnvVars:
):
env = ai_gateway_env_vars(team_id=123, origin_product="signals_scout", ai_stage="scout")
assert "AI_GATEWAY_TOKEN" not in env
+ # No token, no pinned product: the agent must not route on a product it cannot authenticate.
+ assert "AI_GATEWAY_PRODUCT" 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):
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 108d11d13261..403d0dd1f868 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1427,9 +1427,12 @@ def ai_gateway_env_vars(
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.
+ ``AI_GATEWAY_TOKEN``, with the product it is pinned to and the run's stage as
+ ``AI_GATEWAY_PRODUCT`` / ``AI_GATEWAY_AI_STAGE``; the agent routes on those and
+ treats its own task-run fetch as the fallback. 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 not (settings.SANDBOX_AI_GATEWAY_URL and settings.SANDBOX_AI_GATEWAY_PRODUCTS):
return {}
@@ -1445,6 +1448,9 @@ def ai_gateway_env_vars(
token = mint_scoped_token(ai_product=ai_product, team_id=team_id, user=distinct_id)
if token:
env_vars["AI_GATEWAY_TOKEN"] = token
+ env_vars["AI_GATEWAY_PRODUCT"] = ai_product
+ if ai_stage:
+ env_vars["AI_GATEWAY_AI_STAGE"] = ai_stage
return env_vars
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index eb682d7f55f1..2a8ce28534d7 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -145,7 +145,13 @@ class TestGeneratePolicyYaml(TestCase):
# the firewall strips either, the sandbox silently stays on the Python
# gateway, so a migrated product keeps billing under its old tag.
policy = yaml.safe_load(generate_policy_yaml([]))
- for key in ("LLM_GATEWAY_URL", "AI_GATEWAY_URL", "AI_GATEWAY_PRODUCTS"):
+ for key in (
+ "LLM_GATEWAY_URL",
+ "AI_GATEWAY_URL",
+ "AI_GATEWAY_PRODUCTS",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
+ ):
self.assertIn(key, policy["env_policy"]["allow"])
def test_go_gateway_hosts_reachable(self):