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): let codex runs share the prompt cache across sessions (#116776)

Julian Bez96a916bb5c3f
diff --git a/packages/agent/packages/agent-contracts/src/domain-types.ts b/packages/agent/packages/agent-contracts/src/domain-types.ts
index 5d5f68e105b2..b461ac514fe3 100644
--- a/packages/agent/packages/agent-contracts/src/domain-types.ts
+++ b/packages/agent/packages/agent-contracts/src/domain-types.ts
@@ -369,6 +369,7 @@ const taskRunStateFields = {
auto_publish: optionalField(z.boolean()),
benjamin_version: optionalField(z.string()),
codex_max_subagents: optionalField(z.number().int().positive()),
+ codex_shared_prompt_cache: optionalField(z.boolean()),
initial_permission_mode: optionalField(executionModeSchema),
initial_prompt_override: optionalField(z.string()),
pending_followup_messages: optionalField(
diff --git a/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts b/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts
index 207a77f7d975..1edfb4992847 100644
--- a/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.configure-environment.test.ts
@@ -24,6 +24,7 @@ interface TestableServer {
snapshotKind?: string | null;
prewarmed?: boolean | null;
executionEnvironment?: "local" | "cloud";
+ sharedPromptCache?: boolean;
}): GatewayEnv;
}
@@ -684,6 +685,31 @@ describe("AgentServer.configureEnvironment on the Go ai-gateway", () => {
expect(claude.openaiCustomHeaders?.["X-PostHog-Trace-Id"]).toBeUndefined();
});
+ // Codex sub-agents reach the gateway with the process headers only, so the
+ // shared cache scope has to ride the OpenAI record, and only when the run asks.
+ it("sends the shared prompt cache scope only when the run asks for it", () => {
+ const run = {
+ originProduct: "signal_report",
+ aiStage: "scout",
+ runtimeAdapter: "codex",
+ };
+ const shared = buildServer().configureEnvironment({
+ ...run,
+ sharedPromptCache: true,
+ });
+ const keyed = buildServer().configureEnvironment(run);
+
+ expect(shared.openaiCustomHeaders?.["X-PostHog-Prompt-Cache-Scope"]).toBe(
+ "shared",
+ );
+ expect(shared.anthropicCustomHeaders).not.toContain(
+ "X-PostHog-Prompt-Cache-Scope",
+ );
+ expect(
+ keyed.openaiCustomHeaders?.["X-PostHog-Prompt-Cache-Scope"],
+ ).toBeUndefined();
+ });
+
it("keeps non-signals products on their existing ai_product name", () => {
const env = buildServer().configureEnvironment({ isInternal: true });
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 1c08c351b116..5b63a332b01b 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -2161,6 +2161,7 @@ export class AgentServer {
: null,
prewarmed: preTaskRun ? this.prewarmedRun : null,
executionEnvironment: "cloud",
+ sharedPromptCache: preTaskRun?.state.codex_shared_prompt_cache === true,
});
// Only that stamped header makes the run id a trace the generations land
diff --git a/packages/agent/packages/agent/src/server/gateway-env.ts b/packages/agent/packages/agent/src/server/gateway-env.ts
index 5ecc9aa43b6f..1393c11e9434 100644
--- a/packages/agent/packages/agent/src/server/gateway-env.ts
+++ b/packages/agent/packages/agent/src/server/gateway-env.ts
@@ -31,6 +31,7 @@ export interface GatewayEnvInput {
snapshotKind?: string | null;
prewarmed?: boolean | null;
executionEnvironment?: "local" | "cloud";
+ sharedPromptCache?: boolean;
}
export function buildGatewayEnv(
@@ -56,6 +57,7 @@ export function buildGatewayEnv(
snapshotKind,
prewarmed,
executionEnvironment,
+ sharedPromptCache,
}: GatewayEnvInput = {},
logger: Logger,
): GatewayEnv {
@@ -158,6 +160,11 @@ export function buildGatewayEnv(
openaiCustomHeaders["X-PostHog-Flex-Fallback"] = "standard";
}
}
+ // The Go gateway then drops Codex's per-session prompt_cache_key on every
+ // request of the process, sub-agents included, so runs share one cache.
+ if (sharedPromptCache) {
+ openaiCustomHeaders["X-PostHog-Prompt-Cache-Scope"] = "shared";
+ }
// Codex sends no trace header, so the gateway stamps a fresh id per
// request and a run's generations each land in a trace of one. Codex-only:
// this header outranks `traceparent`, so setting it for Claude would
diff --git a/products/review_hog/backend/reviewer/sandbox/executor.py b/products/review_hog/backend/reviewer/sandbox/executor.py
index d337b631ab18..0fa23dcb05a9 100644
--- a/products/review_hog/backend/reviewer/sandbox/executor.py
+++ b/products/review_hog/backend/reviewer/sandbox/executor.py
@@ -112,6 +112,8 @@ async def run_sandbox_review(
runtime_adapter=runtime_adapter,
reasoning_effort=reasoning_effort,
codex_max_subagents=codex_max_subagents,
+ # Coordinator sub-agents carry no prompt cache marker, so only the run-wide scope shares their prefix.
+ codex_shared_prompt_cache=True,
initial_permission_mode=initial_permission_mode,
# Unset means "full" — never hand that to a session fed untrusted PR-comment text.
posthog_mcp_scopes=REVIEW_MCP_SCOPES,
@@ -161,6 +163,7 @@ async def start_sandbox_session(
model=model,
runtime_adapter=runtime_adapter,
reasoning_effort=reasoning_effort,
+ codex_shared_prompt_cache=True,
initial_permission_mode=initial_permission_mode,
# Unset means "full" — never hand that to a session fed untrusted PR-comment text.
posthog_mcp_scopes=REVIEW_MCP_SCOPES,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 30724d6accc0..cd574ccc6b2a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -517,6 +517,7 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset(
"claude_subscription_user_id",
"codex_max_subagents",
"codex_model_access",
+ "codex_shared_prompt_cache",
"codex_subscription_user_id",
"context_window",
"custom_image_id",
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index 4d69e54c473d..d20b8783f04f 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -134,6 +134,10 @@ class CustomPromptSandboxContext:
codex_max_subagents: int | None = None
"""Codex sub-agents one session may run at once, not counting the main agent. Codex-only.
``None`` keeps the Codex default of 3."""
+ codex_shared_prompt_cache: bool = False
+ """Let runs that start from the same prompt prefix read each other's prompt cache. Codex-only. The
+ agent server asks the AI gateway to drop Codex's per-session cache key on every request of the run,
+ sub-agents included."""
initial_permission_mode: str | None = None
"""Agent approval mode. ``None`` lets ``_build_task`` pick the default (``"auto"`` for Codex). A
headless run that calls MCP tools must set ``"full-access"`` (Codex) / ``"bypassPermissions"``
@@ -336,6 +340,8 @@ async def _create_task_and_trigger(
extra_run_state["caller_ends_run"] = True
if context.codex_max_subagents is not None:
extra_run_state["codex_max_subagents"] = context.codex_max_subagents
+ if context.codex_shared_prompt_cache:
+ extra_run_state["codex_shared_prompt_cache"] = True
if analytics_query_context is not None:
queries = [query for query in analytics_query_context if query is not None]
if queries:
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 3e9a0f5ad1d8..a6bf02b99f9b 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -1674,16 +1674,20 @@ class TestCreateTaskAndTriggerForwardsContext:
assert [written[entry["storage_path"]] for entry in manifest.values()] == [b"Review the PR.", "Ü".encode()]
@pytest.mark.asyncio
- async def test_codex_thread_limit_reaches_the_state_the_agent_server_reads(self) -> None:
- # The agent server sees only allowlisted state keys, so a dropped key silently keeps the default limit.
+ async def test_codex_options_reach_the_state_the_agent_server_reads(self) -> None:
+ # The agent server sees only allowlisted state keys, so a dropped key silently keeps the Codex default.
team, user = await sync_to_async(self._setup_team_and_user)()
- context = CustomPromptSandboxContext(team_id=team.id, user_id=user.id, codex_max_subagents=9)
+ context = CustomPromptSandboxContext(
+ team_id=team.id, user_id=user.id, codex_max_subagents=9, codex_shared_prompt_cache=True
+ )
with patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"):
task_run = await agents_facade.create_task_and_trigger("prompt", context)
persisted = await sync_to_async(TaskRun.objects.get)(id=task_run.run_id)
- assert _public_task_run_state(persisted.state)["codex_max_subagents"] == 9
+ public_state = _public_task_run_state(persisted.state)
+ assert public_state["codex_max_subagents"] == 9
+ assert public_state["codex_shared_prompt_cache"] is True
@pytest.mark.asyncio
@pytest.mark.parametrize(("output_schema", "expected_flag"), [({"type": "object"}, True), (None, None)])