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(signals): add codex runtime support to the pipeline (#68750)

Joshua Snyder0a2b9453d06a
diff --git a/products/signals/backend/agent_runtime.py b/products/signals/backend/agent_runtime.py
new file mode 100644
index 000000000000..c2d2eb6d4a86
--- /dev/null
+++ b/products/signals/backend/agent_runtime.py
@@ -0,0 +1,162 @@
+"""Per-team, per-step agent runtime/model overrides for the signals agentic steps, resolved from
+the `signals-pipeline-models` flag payload.
+
+Each agentic step (report research, repo selection, scout, custom-agent loops) can be pinned to a
+different runtime/model/effort per team, with no deploy — e.g. trial Codex + gpt-5.5 on `research`
+for one team while everyone else stays on the default Claude runtime. Mirrors the `signals-scout`
+payload pattern in `scout_harness/team_limits.py`: one 100%-on payload flag, read for a synthetic
+discovery distinct_id, parsed defensively so a malformed payload falls back to the agent-server
+default rather than breaking a run.
+
+Payload shape (`team_configs` maps team id — or the `*` wildcard — to per-step overrides):
+
+ {
+ "team_configs": {
+ "2": {
+ "steps": {
+ "research": {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "xhigh"},
+ "repo_selection": {"runtime_adapter": "codex", "model": "gpt-5.5"},
+ "*": {"model": "claude-sonnet-4-6"}
+ }
+ },
+ "*": {"steps": {"research": {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "xhigh"}}}
+ }
+ }
+
+Resolution for `(team_id, step)` is most-specific-first, first match wins (atomic — a step block's
+fields are taken as a set so a Codex runtime never pairs with a Claude model):
+
+ team_configs[team_id].steps[step]
+ → team_configs[team_id].steps["*"]
+ → team_configs["*"].steps[step]
+ → team_configs["*"].steps["*"]
+ → default (agent-server Claude runtime)
+
+A resolved override threads through `CustomPromptSandboxContext`
+(runtime_adapter/model/reasoning_effort) → `Task.create_and_run` → the run state → the agent server
+(see `products/tasks` RuntimeAdapter). A step config may set only `model` (swap the model within the
+default Claude runtime) or `runtime_adapter` + `model` together (switch the whole harness, e.g.
+Codex). Missing fields stay `None` (agent-server default).
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+
+# Must stay 100%-on so the payload is served for the synthetic discovery distinct_id.
+SIGNALS_PIPELINE_MODELS_FLAG = "signals-pipeline-models"
+
+# Config is team-keyed in the payload, not per-user, so the read uses a fixed distinct_id.
+PIPELINE_MODELS_DISCOVERY_DISTINCT_ID = "internal_signals_pipeline_models_discovery"
+
+WILDCARD = "*"
+
+# Step names match the `ai_stage` tags on $ai_generation so payload authors target the
+# vocabulary they see in LLM analytics.
+STEP_SCOUT = "scout"
+STEP_RESEARCH = "research"
+STEP_REPO_SELECTION = "repo_selection"
+STEP_CUSTOM_AGENT = "custom_agent"
+
+
+@dataclass(frozen=True)
+class AgentRuntime:
+ """The runtime/model/effort override for one signals agentic sandbox run.
+
+ All-`None` keeps the agent server's built-in default (the Claude runtime). The three move as a
+ set — a Codex runtime with a Claude model id would mis-route — so a payload step block resolves
+ them together, atomically.
+ """
+
+ runtime_adapter: str | None = None
+ model: str | None = None
+ reasoning_effort: str | None = None
+
+
+DEFAULT_RUNTIME = AgentRuntime()
+
+# The Codex trial config (used by the local `analyze_report --codex` override).
+CODEX_RUNTIME = AgentRuntime(runtime_adapter="codex", model="gpt-5.5", reasoning_effort="xhigh")
+
+
+def _read_flag_payload() -> dict | None:
+ """Read + parse the `signals-pipeline-models` flag payload once.
+
+ The flag must stay 100%-on so the payload is served for the synthetic discovery distinct_id;
+ `match_value=True` forces the true-variant payload under local evaluation. Returns the parsed
+ dict, or `None` when the payload is absent / not an object / unreadable — a read error never
+ breaks a run, callers fall back to the default. Mirrors `scout_harness/team_limits._read_flag_payload`.
+ """
+ try:
+ payload = posthoganalytics.get_feature_flag_payload(
+ SIGNALS_PIPELINE_MODELS_FLAG, PIPELINE_MODELS_DISCOVERY_DISTINCT_ID, match_value=True
+ )
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ return payload if isinstance(payload, dict) else None
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
+def _parse_runtime(step_block: object) -> AgentRuntime:
+ """Parse one step's config blob into an `AgentRuntime`; anything malformed → default.
+
+ Fields are optional and independently typed-checked: a non-string (or empty) value for a field
+ is dropped to `None` rather than failing the whole block, so a typo in `reasoning_effort` can't
+ silently un-set the `model`. A non-dict block (or empty) yields the default — the "fail to
+ parse → fall back to defaults" contract."""
+ if not isinstance(step_block, dict):
+ return DEFAULT_RUNTIME
+
+ def _str_or_none(key: str) -> str | None:
+ value = step_block.get(key)
+ return value if isinstance(value, str) and value else None
+
+ return AgentRuntime(
+ runtime_adapter=_str_or_none("runtime_adapter"),
+ model=_str_or_none("model"),
+ reasoning_effort=_str_or_none("reasoning_effort"),
+ )
+
+
+def _resolve_from_payload(payload: dict | None, team_id: int, step: str) -> AgentRuntime:
+ """Resolve `(team_id, step)` against an already-read payload, most-specific-first.
+
+ Walks team layers (`team_id` then `*`) and, within each, step layers (`step` then `*`); the
+ first present step block wins and is parsed atomically. A present-but-malformed block parses to
+ the default (and stops the walk) — a deliberate config of that exact slot. Absent everywhere →
+ default."""
+ if not isinstance(payload, dict):
+ return DEFAULT_RUNTIME
+ team_configs = payload.get("team_configs")
+ if not isinstance(team_configs, dict):
+ return DEFAULT_RUNTIME
+
+ for team_key in (str(team_id), WILDCARD):
+ team_block = team_configs.get(team_key)
+ if not isinstance(team_block, dict):
+ continue
+ steps = team_block.get("steps")
+ if not isinstance(steps, dict):
+ continue
+ for step_key in (step, WILDCARD):
+ step_block = steps.get(step_key)
+ if step_block is not None:
+ return _parse_runtime(step_block)
+ return DEFAULT_RUNTIME
+
+
+def resolve_agent_runtime(team_id: int, step: str) -> AgentRuntime:
+ """The runtime/model/effort override for `(team_id, step)`, or the default when unconfigured.
+
+ Reads the `signals-pipeline-models` payload once and resolves most-specific-first (see
+ `_resolve_from_payload`). Any failure — unreadable/malformed payload — falls back to the
+ default; gating the runtime must never be able to fail an agentic run. Blocking network I/O
+ (the payload read), so async callers wrap this in `database_sync_to_async`."""
+ return _resolve_from_payload(_read_flag_payload(), team_id, step)
diff --git a/products/signals/backend/custom_agent/base.py b/products/signals/backend/custom_agent/base.py
index baf33c799fe9..a29dfb3e0ba3 100644
--- a/products/signals/backend/custom_agent/base.py
+++ b/products/signals/backend/custom_agent/base.py
@@ -10,6 +10,7 @@ from pydantic import BaseModel, Field, ValidationError
from posthog.models import Team
from posthog.sync import database_sync_to_async
+from products.signals.backend.agent_runtime import STEP_CUSTOM_AGENT, resolve_agent_runtime
from products.signals.backend.artefact_schemas import ArtefactContent, artefact_type_for
from products.signals.backend.auto_start import maybe_autostart_from_report_artefacts
from products.signals.backend.custom_agent.persistence import (
@@ -602,13 +603,18 @@ Return only a JSON object matching this schema. Do not include markdown fences o
SIGNALS_REPORT_RESEARCH_ENV_NAME,
tasks_facade.SandboxNetworkAccessLevel.TRUSTED,
)
+ agent_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(
+ self.team_id, STEP_CUSTOM_AGENT
+ )
context = CustomPromptSandboxContext(
team_id=self.team_id,
user_id=self.user_id,
repository=self.repository,
sandbox_environment_id=sandbox_environment_id,
posthog_mcp_scopes="read_only",
- model=self.model,
+ model=agent_runtime.model or self.model,
+ runtime_adapter=agent_runtime.runtime_adapter,
+ reasoning_effort=agent_runtime.reasoning_effort,
)
session, raw_text = await MultiTurnSession.start_raw(
prompt=prompt,
diff --git a/products/signals/backend/management/commands/analyze_report.py b/products/signals/backend/management/commands/analyze_report.py
index c6c17a524761..534c0d47e7ec 100644
--- a/products/signals/backend/management/commands/analyze_report.py
+++ b/products/signals/backend/management/commands/analyze_report.py
@@ -8,12 +8,14 @@ the multi-turn research path while the eval infrastructure is built.
import json
import asyncio
import logging
+from dataclasses import replace
from datetime import UTC, datetime
from pathlib import Path
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
+from products.signals.backend.agent_runtime import CODEX_RUNTIME
from products.signals.backend.report_generation.research import ReportResearchOutput, run_multi_turn_research
from products.signals.backend.temporal.types import SignalData
from products.tasks.backend.facade.agents import resolve_sandbox_context_for_local_dev
@@ -182,6 +184,12 @@ class Command(BaseCommand):
action="store_true",
help="Stream full raw S3 log lines instead of only agent messages",
)
+ parser.add_argument(
+ "--codex",
+ action="store_true",
+ help="Run the research agent on the Codex runtime + gpt-5.5 (local trial of the "
+ "`signals-pipeline-models` payload's effect on the `research` step)",
+ )
def handle(self, *args, **options):
if not settings.DEBUG:
@@ -213,6 +221,15 @@ class Command(BaseCommand):
self.stdout.write(self.style.ERROR(str(e)))
return
+ if options["codex"]:
+ context = replace(
+ context,
+ runtime_adapter=CODEX_RUNTIME.runtime_adapter,
+ model=CODEX_RUNTIME.model,
+ reasoning_effort=CODEX_RUNTIME.reasoning_effort,
+ )
+ self.stdout.write(f"Runtime override: {CODEX_RUNTIME.runtime_adapter} / {CODEX_RUNTIME.model}")
+
self.stdout.write(f"Mode: {mode}")
self.stdout.write(f"Signals: {len(signals)}")
self.stdout.write("")
diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.py
index fa94a8a50142..ed9b1f5f3931 100644
--- a/products/signals/backend/report_generation/select_repo.py
+++ b/products/signals/backend/report_generation/select_repo.py
@@ -14,6 +14,9 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING
+from posthog.sync import database_sync_to_async
+
+from products.signals.backend.agent_runtime import STEP_REPO_SELECTION, resolve_agent_runtime
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.repo_selection import (
REPO_SELECTION_DUMMY_REPOSITORY,
@@ -62,6 +65,11 @@ async def select_repository_for_team(
— Signals/custom agents have no picker fallback, so callers treat ``repository=None`` as
"no match / requires human input".
"""
+ # Resolved at the single repo-selection chokepoint so both callers (custom agent +
+ # report flow) pick it up.
+ agent_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(
+ team_id, STEP_REPO_SELECTION
+ )
try:
return await select_repository(
team_id=team_id,
@@ -73,6 +81,9 @@ async def select_repository_for_team(
sandbox_environment_id=sandbox_environment_id,
verbose=verbose,
output_fn=output_fn,
+ model=agent_runtime.model,
+ runtime_adapter=agent_runtime.runtime_adapter,
+ reasoning_effort=agent_runtime.reasoning_effort,
)
except RepoSelectionRejectedError as exc:
# Preserve legacy behavior: surface validation reject as null with reason so callers'
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 5f0840eb90c1..5ed9e732c599 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -16,6 +16,7 @@ from posthog.models.team.team import Team
from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
+from products.signals.backend.agent_runtime import STEP_SCOUT, resolve_agent_runtime
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S, STALE_RUN_CUTOFF_S
@@ -222,6 +223,20 @@ async def arun_signals_scout(
scout_model = await database_sync_to_async(resolve_scout_model, thread_sensitive=False)(
team, skill.name, str(run_id)
)
+
+ # A runtime pin takes precedence over the scout-model gate and replaces it wholesale —
+ # runtime/model/effort move as a set so a Codex runtime never pairs with a glm model.
+ # Model-only payload entries are deliberately ignored for scout: the gate supplies
+ # model+runtime as a pair, and overriding one without the other would mis-route.
+ agent_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(team_id, STEP_SCOUT)
+ if agent_runtime.runtime_adapter:
+ runtime_adapter: str | None = agent_runtime.runtime_adapter
+ model = agent_runtime.model
+ reasoning_effort: str | None = agent_runtime.reasoning_effort
+ else:
+ runtime_adapter = scout_model.runtime_adapter
+ model = scout_model.model
+ reasoning_effort = None
try:
last_message, task_run_id = await _spawn_and_run(
team=team,
@@ -232,8 +247,9 @@ async def arun_signals_scout(
repository=repository,
verbose=verbose,
user_id=user_id,
- model=scout_model.model,
- runtime_adapter=scout_model.runtime_adapter,
+ model=model,
+ runtime_adapter=runtime_adapter,
+ reasoning_effort=reasoning_effort,
)
runtime_s = time.monotonic() - started
emitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(
@@ -353,14 +369,15 @@ async def _spawn_and_run(
verbose: bool,
user_id: int,
model: str | None,
- runtime_adapter: str | None,
+ runtime_adapter: str | None = None,
+ reasoning_effort: str | None = None,
) -> tuple[str, str]:
"""Spawn the sandbox, create the bridge row before the first turn, run the agent.
- `user_id` is the acting user resolved (and validated non-None) by the caller. `model` is the
- agent-model override (`None` keeps the agent-server default), and `runtime_adapter` is the runtime
- that serves it (paired with `model` — the agent server derives the provider from it). Returns
- `(last_message, task_run_id)`.
+ `user_id` is the acting user resolved (and validated non-None) by the caller. `model`,
+ `runtime_adapter`, and `reasoning_effort` are the agent runtime overrides (`model` paired with the
+ `runtime_adapter` that serves it — the agent server derives the provider from it; all `None` keeps
+ the agent-server default Claude runtime). Returns `(last_message, task_run_id)`.
"""
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
team.id,
@@ -397,10 +414,9 @@ async def _spawn_and_run(
# (the `scouts-model-selection` gate routes it here). The model the gateway actually serves
# is tagged on each $ai_generation, so per-run model is queryable in LLM analytics.
model=model,
- # The runtime that serves `model`. Paired with it because the agent server derives the LLM
- # provider from the runtime — a model with no runtime can't be routed and falls back to the
- # server default. `None` alongside a `None` model keeps the agent-server defaults for both.
+ # Paired with `model`: the agent server derives the LLM provider from the runtime.
runtime_adapter=runtime_adapter,
+ reasoning_effort=reasoning_effort,
)
prompt = build_run_prompt(skill, run_id=str(run_id), team_id=team.id, started_at=started_at)
logger.info(
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 7107c6bbe633..5bf2cf190086 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -15,6 +15,7 @@ from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
from products.business_knowledge.backend.logic import is_available_for_team
+from products.signals.backend.agent_runtime import STEP_RESEARCH, resolve_agent_runtime
from products.signals.backend.artefact_schemas import ArtefactContent, SuggestedReviewers
from products.signals.backend.auto_start import ReviewerContent, maybe_autostart_implementation_task
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
@@ -331,6 +332,9 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
input.team_id, SIGNALS_REPORT_RESEARCH_ENV_NAME, tasks_facade.SandboxNetworkAccessLevel.TRUSTED
)
+ agent_runtime = await database_sync_to_async(resolve_agent_runtime, thread_sensitive=False)(
+ input.team_id, STEP_RESEARCH
+ )
context = CustomPromptSandboxContext(
team_id=input.team_id,
user_id=user_id,
@@ -340,6 +344,9 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
# artefacts, but never writes artefacts itself — the pipeline persists its
# structured outputs after the session.
posthog_mcp_scopes="read_only",
+ model=agent_runtime.model,
+ runtime_adapter=agent_runtime.runtime_adapter,
+ reasoning_effort=agent_runtime.reasoning_effort,
)
has_bk = await database_sync_to_async(_team_has_business_knowledge, thread_sensitive=False)(input.team_id)
# 2. Load previous research if this is a re-promoted report
diff --git a/products/signals/backend/test/test_agent_runtime.py b/products/signals/backend/test/test_agent_runtime.py
new file mode 100644
index 000000000000..054df2fce82f
--- /dev/null
+++ b/products/signals/backend/test/test_agent_runtime.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import json
+
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.signals.backend.agent_runtime import DEFAULT_RUNTIME, AgentRuntime, resolve_agent_runtime
+
+_READ_PATH = "products.signals.backend.agent_runtime._read_flag_payload"
+_PAYLOAD_FN_PATH = "products.signals.backend.agent_runtime.posthoganalytics.get_feature_flag_payload"
+
+# Team 2: research → full Codex swap; every other step → model-only (sonnet, still Claude runtime).
+# Wildcard team: only `scout` is overridden (no step wildcard).
+_PAYLOAD = {
+ "team_configs": {
+ "2": {
+ "steps": {
+ "research": {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "xhigh"},
+ "*": {"model": "claude-sonnet-4-6"},
+ }
+ },
+ "*": {"steps": {"scout": {"runtime_adapter": "codex", "model": "gpt-5.5"}}},
+ }
+}
+
+_CODEX = AgentRuntime(runtime_adapter="codex", model="gpt-5.5", reasoning_effort="xhigh")
+_SONNET_MODEL_ONLY = AgentRuntime(runtime_adapter=None, model="claude-sonnet-4-6", reasoning_effort=None)
+_CODEX_NO_EFFORT = AgentRuntime(runtime_adapter="codex", model="gpt-5.5", reasoning_effort=None)
+
+
+class TestResolveAgentRuntime:
+ @parameterized.expand(
+ [
+ # team-specific + step-specific wins
+ ("team_step_exact", 2, "research", _CODEX),
+ # team-specific step-wildcard beats the wildcard team's specific step
+ ("team_step_wildcard_over_wildcard_team", 2, "scout", _SONNET_MODEL_ONLY),
+ ("team_step_wildcard_for_unlisted_step", 2, "repo_selection", _SONNET_MODEL_ONLY),
+ # wildcard team applies when the team isn't listed
+ ("wildcard_team_step_exact", 999, "scout", _CODEX_NO_EFFORT),
+ # unlisted step under wildcard team with no step-wildcard → default
+ ("wildcard_team_step_missing", 999, "research", DEFAULT_RUNTIME),
+ ]
+ )
+ def test_resolution_precedence(self, _name: str, team_id: int, step: str, expected: AgentRuntime) -> None:
+ with patch(_READ_PATH, return_value=_PAYLOAD):
+ assert resolve_agent_runtime(team_id, step) == expected
+
+ @parameterized.expand(
+ [
+ ("payload_none", None),
+ ("payload_not_dict", ["nope"]),
+ ("missing_team_configs", {"other": {}}),
+ ("team_configs_not_dict", {"team_configs": ["nope"]}),
+ ("step_block_not_dict", {"team_configs": {"2": {"steps": {"research": "codex"}}}}),
+ ]
+ )
+ def test_malformed_payload_falls_back_to_default(self, _name: str, payload: object) -> None:
+ with patch(_READ_PATH, return_value=payload):
+ assert resolve_agent_runtime(2, "research") == DEFAULT_RUNTIME
+
+ def test_non_string_field_is_dropped_not_fatal(self) -> None:
+ # A bad reasoning_effort must not un-set the otherwise-valid model/runtime.
+ payload = {
+ "team_configs": {
+ "2": {"steps": {"research": {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": 5}}}
+ }
+ }
+ with patch(_READ_PATH, return_value=payload):
+ assert resolve_agent_runtime(2, "research") == _CODEX_NO_EFFORT
+
+ def test_payload_served_as_json_string_is_parsed(self) -> None:
+ with patch(_PAYLOAD_FN_PATH, return_value=json.dumps(_PAYLOAD)):
+ assert resolve_agent_runtime(2, "research") == _CODEX
+
+ def test_flag_read_failure_falls_back_to_default(self) -> None:
+ with patch(_PAYLOAD_FN_PATH, side_effect=RuntimeError("flag service down")):
+ assert resolve_agent_runtime(2, "research") == DEFAULT_RUNTIME
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index e692c07bca80..7332297813b6 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -21,6 +21,7 @@ from posthog.models import Organization, Team
from posthog.models.scoping import team_scope
from posthog.sync import database_sync_to_async
+from products.signals.backend.agent_runtime import AgentRuntime
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S
@@ -508,6 +509,11 @@ async def test_run_pins_sandbox_to_resolved_scout_model(
"products.signals.backend.scout_harness.runner.resolve_scout_model",
return_value=resolved,
),
+ # No `signals-pipeline-models` runtime pin: the scouts-glm model gate drives the run.
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_agent_runtime",
+ return_value=AgentRuntime(),
+ ),
patch(
"products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",
return_value="env-id",
@@ -523,6 +529,46 @@ async def test_run_pins_sandbox_to_resolved_scout_model(
assert captured["context"].runtime_adapter == expected_runtime_adapter
+async def test_codex_runtime_pin_overrides_scout_model(ateam, aerrors_skill):
+ # A runtime pin replaces the scouts-glm gated model wholesale (runtime/model move as a set).
+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
+ captured: dict = {}
+
+ async def _capture_start(*args, on_task_run_created=None, **kwargs):
+ captured.update(kwargs)
+ if on_task_run_created is not None:
+ await on_task_run_created(session.task_run)
+ return session, result
+
+ with (
+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_scout_model",
+ return_value="@cf/zai-org/glm-5.2",
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_agent_runtime",
+ return_value=AgentRuntime(runtime_adapter="codex", model="gpt-5.5", reasoning_effort="high"),
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",
+ return_value="env-id",
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",
+ return_value=42,
+ ),
+ ):
+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ ctx = captured["context"]
+ assert ctx.runtime_adapter == "codex"
+ assert ctx.model == "gpt-5.5"
+ assert ctx.reasoning_effort == "high"
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam, aerrors_skill):
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index c0f4bc2da0cf..44aee2cdc8b7 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -349,6 +349,9 @@ async def select_repository(
verbose: bool = False,
output_fn: OutputFn = None,
on_research_session: Callable[[str, str], None] | None = None,
+ model: str | None = None,
+ runtime_adapter: str | None = None,
+ reasoning_effort: str | None = None,
) -> RepoSelectionResult:
"""Select the most relevant repository for a free-form request context.
@@ -413,6 +416,11 @@ async def select_repository(
# Read-only PostHog scopes so the agent can call `execute-sql` against `system.integration_repository_cache`.
posthog_mcp_scopes="read_only",
sandbox_resources=SandboxResources(cpu_cores=2, memory_gb=8),
+ # Optional agent runtime/model override (e.g. the Codex runtime + gpt-5.5). All-None keeps
+ # the agent-server default; threaded through from the caller's per-step resolution.
+ model=model,
+ runtime_adapter=runtime_adapter,
+ reasoning_effort=reasoning_effort,
)
session, result = await MultiTurnSession.start(
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index a92f97986771..65f5912af926 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -96,10 +96,10 @@ class CustomPromptSandboxContext:
agent server's default when ``None``. Used by evals to pin a specific
model so cross-run comparisons are stable."""
runtime_adapter: str | None = None
- """The agent runtime that serves ``model`` (``"claude"`` → Anthropic, ``"codex"`` → OpenAI).
- Set it alongside a non-default ``model``: the agent server derives the provider from the runtime,
- so a model handed over with no runtime can't be routed and falls back to the server default.
- ``None`` keeps the agent server's default runtime (only valid when ``model`` is also ``None``)."""
+ """The harness serving ``model`` (``"claude"`` | ``"codex"``); the agent server derives the
+ provider from it, so a pinned model must ship with its matching runtime. ``None`` = default."""
+ reasoning_effort: str | None = None
+ """Agent reasoning effort (``"low"``…``"max"``); valid values depend on runtime+model."""
sandbox_resources: SandboxResources | None = None
"""Override the sandbox's compute (CPU / memory). Unset fields keep the
SandboxConfig defaults (4 cores / 16 GB)."""
@@ -149,6 +149,7 @@ async def create_task_and_trigger(
sandbox_environment_id=context.sandbox_environment_id,
model=context.model,
runtime_adapter=context.runtime_adapter,
+ reasoning_effort=context.reasoning_effort,
internal=internal,
sandbox_resources=context.sandbox_resources,
sandbox_timeout_seconds=context.sandbox_timeout_seconds,
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 8397f2050262..e0fe18dc9f9b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -514,11 +514,9 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
if model:
extra_state["model"] = model
- # The model's runtime adapter and the provider derived from it. The agent server can't route
- # a model without its runtime (it resolves the provider from the runtime), so callers that pin
- # a non-default model must pass the matching runtime — mirrors the warm path in `facade/api`.
- # Codex runs need permission mode `auto` (same default the warm path applies) so a headless
- # run doesn't stall waiting on a prompt; an explicit `initial_permission_mode` still wins.
+ # `runtime_adapter` selects the harness (claude | codex) and the agent server derives
+ # the provider from it, so a pinned model must ship with its matching runtime. Codex runs
+ # default permission mode to `auto` so a headless run doesn't stall on a prompt.
if runtime_adapter:
extra_state["runtime_adapter"] = runtime_adapter
provider = get_provider_for_runtime_adapter(runtime_adapter)
@@ -526,7 +524,6 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
extra_state["provider"] = provider.value
if initial_permission_mode is None and runtime_adapter == RuntimeAdapter.CODEX.value:
initial_permission_mode = "auto"
-
if reasoning_effort:
extra_state["reasoning_effort"] = reasoning_effort