: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): session files and codex thread limit for custom prompts (#115212)
Julian Bez9b0b515e9cf5
diff --git a/packages/agent/packages/agent-contracts/src/domain-types.ts b/packages/agent/packages/agent-contracts/src/domain-types.tsindex 761678cd8476..19871379eeb2 100644--- a/packages/agent/packages/agent-contracts/src/domain-types.ts+++ b/packages/agent/packages/agent-contracts/src/domain-types.ts@@ -362,6 +362,7 @@ const taskRunStateFields = {ai_stage: optionalField(z.string()),auto_publish: optionalField(z.boolean()),benjamin_version: optionalField(z.string()),+ codex_max_subagents: optionalField(z.number().int().positive()),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.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex 43ae2700d5b6..5b0a56120796 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -2354,6 +2354,14 @@ export class AgentServer {? this.config.reasoningEffort: undefined,serviceTier: this.config.serviceTier,+ // Codex runs at most 3 sub-agents per session at once by default; the main agent does+ // not count. A run that starts more sub-agents at once sets its own limit.+ ...(runState?.codex_max_subagents && {+ configOverrides: {+ "agents.max_concurrent_threads_per_session":+ runState.codex_max_subagents,+ },+ }),developerInstructions: codexInstructions,httpHeaders: codexSubscriptionTokens? undefineddiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex c769d7fab979..7115f69782c5 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -514,6 +514,7 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset("benjamin_enabled","claude_model_access","claude_subscription_user_id",+ "codex_max_subagents","codex_model_access","codex_subscription_user_id","context_window",diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 620d65f10a16..11f88f0bfa60 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -65,6 +65,18 @@ class AgentTaskRunDTO:workflow_id: str+@dataclass(frozen=True, kw_only=True)+class SessionFile:+ """A text file a custom-prompt session puts in the sandbox before its first turn.++ The agent server writes it under the run's attachments directory and lists its path in the+ first prompt, so the agent and any sub-agent it starts can read it from disk.+ """++ name: str+ content: str++@dataclass(frozen=True)class StreamNotificationDelivery:"""Where a server-originated stream notification landed.diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex a9407966b648..4d69e54c473d 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -4,10 +4,10 @@ import reimport jsonimport asyncioimport logging-from collections.abc import Callable, Collection+from collections.abc import Callable, Collection, Sequencefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any-from uuid import UUID+from uuid import UUID, uuid4from django.conf import settingsfrom django.db import InterfaceError, OperationalError, close_old_connections@@ -21,8 +21,9 @@ from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import PosthogMcpScopes-from products.tasks.backend.facade.contracts import AgentTaskRunDTO-from products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRun+from products.tasks.backend.facade.api import upload_task_run_artifacts+from products.tasks.backend.facade.contracts import AgentTaskRunDTO, SessionFile+from products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRun, stamp_pending_user_message_idif TYPE_CHECKING:from temporalio.client import WorkflowHandle@@ -130,6 +131,9 @@ class CustomPromptSandboxContext:Codex-only: the claude adapter ignores it. ``None`` keeps the provider default. ``"flex"`` buysa cheaper, slower queue, but codex omits any tier its model catalogue does not advertise, so atier the pinned model doesn't list is a no-op (codex logs it and sends the request untiered)."""+ 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."""initial_permission_mode: str | None = None"""Agent approval mode. ``None`` lets ``_build_task`` pick the default (``"auto"`` for Codex). Aheadless run that calls MCP tools must set ``"full-access"`` (Codex) / ``"bypassPermissions"``@@ -258,6 +262,46 @@ class AgentTurnFailed(RuntimeError):return self.category in UPSTREAM_RETRYABLE_ERROR_CATEGORIES+SESSION_FILE_ARTIFACT_TYPE = "context"+++def _with_session_files(+ files: Sequence[SessionFile],+ description: str,+ team_id: int,+ before_task_dispatch: Callable[[UUID], dict[str, JsonValue] | None] | None,+) -> Callable[[UUID], dict[str, JsonValue] | None]:+ """Wrap `before_task_dispatch` so the run has its files before the workflow starts."""++ def attach(run_id: UUID) -> dict[str, JsonValue] | None:+ state = before_task_dispatch(run_id) if before_task_dispatch is not None else None+ task_id = TaskRun.objects.filter(id=run_id, team_id=team_id).values_list("task_id", flat=True).get()+ artifact_ids: list[JsonValue] = [uuid4().hex for _ in files]+ artifacts = [+ {+ "id": artifact_id,+ "name": file.name,+ "type": SESSION_FILE_ARTIFACT_TYPE,+ "content_bytes": file.content.encode("utf-8"),+ "content_type": "text/plain; charset=utf-8",+ }+ for artifact_id, file in zip(artifact_ids, files, strict=True)+ ]+ if upload_task_run_artifacts(run_id, task_id, team_id, artifacts=artifacts) is None:+ raise RuntimeError(f"Could not attach session files to run {run_id}")+ # The prompt goes as the pending message, because only that path sends the files with it.+ pending: dict[str, JsonValue] = {+ **(state or {}),+ "pending_user_message": description,+ "pending_user_artifact_ids": artifact_ids,+ }+ # Startup and the pending-message forwarder both deliver this prompt and dedupe on the id.+ stamp_pending_user_message_id(pending)+ return pending++ return attach++async def _create_task_and_trigger(description: str,context: CustomPromptSandboxContext,@@ -276,6 +320,7 @@ async def _create_task_and_trigger(before_task_dispatch: Callable[[UUID], dict[str, JsonValue] | None] | None = None,output_schema: dict[str, Any] | None = None,analytics_query_context: list[dict[str, object]] | None = None,+ files: Sequence[SessionFile] = (),) -> tuple[Task, TaskRun]:title = f"[sandbox_prompt:{step_name}] {description[:80]}" if step_name else description[:100]team = await sync_to_async(Team.objects.get)(id=context.team_id)@@ -289,10 +334,14 @@ async def _create_task_and_trigger(extra_run_state["mcp_exclude_tools"] = list(context.mcp_exclude_tools)if output_schema:extra_run_state["caller_ends_run"] = True+ if context.codex_max_subagents is not None:+ extra_run_state["codex_max_subagents"] = context.codex_max_subagentsif analytics_query_context is not None:queries = [query for query in analytics_query_context if query is not None]if queries:extra_run_state["analytics_query_context"] = queries+ if files:+ before_task_dispatch = _with_session_files(files, description, context.team_id, before_task_dispatch)task = await sync_to_async(Task.create_and_run)(team=team,title=title,diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.pyindex 649a03af2a68..954e25d853a0 100644--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport timeimport asyncioimport logging-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Sequencefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, TypeVarfrom uuid import UUID@@ -11,6 +11,7 @@ from uuid import UUIDfrom pydantic import BaseModel, JsonValue, ValidationErrorfrom products.tasks.backend.facade.api import record_run_failure_cause+from products.tasks.backend.facade.contracts import SessionFilefrom products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRunif TYPE_CHECKING:@@ -103,6 +104,7 @@ class MultiTurnSession:mcp_gateway_server_ids: list[str] | None = None,output_schema: dict[str, Any] | None = None,analytics_query_context: list[dict[str, object]] | None = None,+ files: Sequence[SessionFile] = (),) -> tuple[MultiTurnSession, _ModelT]:"""Start a multi-turn sandbox session and wait for the first structured response.@@ -147,6 +149,7 @@ class MultiTurnSession:mcp_gateway_server_ids=mcp_gateway_server_ids,output_schema=output_schema,analytics_query_context=analytics_query_context,+ files=files,)# A retry turn that fails to run is not a parse failure, so it must never reach the salvage path.salvageable = True@@ -226,6 +229,7 @@ class MultiTurnSession:mcp_gateway_server_ids: list[str] | None = None,output_schema: dict[str, Any] | None = None,analytics_query_context: list[dict[str, object]] | None = None,+ files: Sequence[SessionFile] = (),) -> tuple[MultiTurnSession, str]:"""Start a multi-turn sandbox session and return the first raw agent response.@@ -241,6 +245,10 @@ class MultiTurnSession:`mcp_gateway_server_ids` narrows the run's mounts to the listed gateway serversregardless of grant scope (a scout's per-scout selection). None leaves themunfiltered; an empty list mounts nothing.++ `files` go into the sandbox before the first turn, and the first prompt lists+ their paths. Use them for text too long for the agent to pass on itself, such as+ the task of a sub-agent."""task, task_run = await create_task_and_trigger(prompt,@@ -260,6 +268,7 @@ class MultiTurnSession:origin_key=origin_key,output_schema=output_schema,analytics_query_context=analytics_query_context,+ files=files,)logger.info("multi_turn: started task=%s run=%s step=%s", task.id, task_run.id, step_name or "unknown")# Get session's parent workflow to send heartbeats to keep the agent alive while waiting for turns.diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex dce3f3f40aee..3e9a0f5ad1d8 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -17,6 +17,8 @@ from posthog.models.user import Userfrom posthog.storage.object_storage import ObjectStorageErrorfrom products.tasks.backend.facade import agents as agents_facade+from products.tasks.backend.facade.api import _public_task_run_state+from products.tasks.backend.facade.contracts import SessionFilefrom products.tasks.backend.logic.services.custom_prompt_internals import (AgentError,AgentTurnFailed,@@ -1644,6 +1646,45 @@ class TestCreateTaskAndTriggerForwardsContext:else:assert dispatched_states[0]["private_ready"] is True+ @pytest.mark.asyncio+ async def test_session_files_reach_the_run_as_attachments_of_the_first_prompt(self) -> None:+ team, user = await sync_to_async(self._setup_team_and_user)()+ context = CustomPromptSandboxContext(team_id=team.id, user_id=user.id)+ files = [SessionFile(name="main.prompt.md", content="Review the PR."), SessionFile(name="perf.md", content="Ü")]++ with (+ patch("posthog.storage.object_storage.write") as write,+ patch("posthog.storage.object_storage.tag"),+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"),+ ):+ _, run = await _create_task_and_trigger(+ "prompt", context, files=files, before_task_dispatch=lambda run_id: {"private_ready": True}+ )++ persisted = await sync_to_async(TaskRun.objects.get)(id=run.id)+ manifest = {entry["id"]: entry for entry in persisted.artifacts}+ assert persisted.state["private_ready"] is True+ assert persisted.state["pending_user_message"] == "prompt"+ assert persisted.state["pending_user_message_id"]+ assert [manifest[artifact_id]["name"] for artifact_id in persisted.state["pending_user_artifact_ids"]] == [+ "main.prompt.md",+ "perf.md",+ ]+ written = {call.args[0]: call.args[1] for call in write.call_args_list}+ 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.+ 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)++ 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+@pytest.mark.asyncio@pytest.mark.parametrize(("output_schema", "expected_flag"), [({"type": "object"}, True), (None, None)])async def test_marks_a_schema_run_as_ended_by_the_caller(self, output_schema, expected_flag):