: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): move the model catalogue into tasks and expose it over HTTP (#78312)
Vojta Bartoš5267964f5650
diff --git a/products/slack_app/backend/services/llm_models.py b/products/slack_app/backend/services/llm_models.pydeleted file mode 100644index 7e2a78ff0113..000000000000--- a/products/slack_app/backend/services/llm_models.py+++ /dev/null@@ -1,62 +0,0 @@-"""Slack-app view of the models the LLM gateway exposes for `slack_app`.--The gateway is the source of truth — hardcoding the list here would mean a-Slack-side PR every time it changes. Cached via Django's shared cache so the-Home tab publish never blocks on a gateway round-trip; the fetch timeout is-capped at 3s because it sits on the Slack interactivity hot path (trigger_id-expires after ~3s), and failures are negatively cached for 30s so a broken-gateway can't make every interaction wait the full timeout.-"""--from __future__ import annotations--from dataclasses import dataclass--from django.core.cache import cache--import structlog--from posthog.llm.gateway_client import get_llm_client--logger = structlog.get_logger(__name__)--_CACHE_KEY = "slack_app:llm_gateway_models"-_CACHE_TTL_SECONDS = 30 * 60-_NEGATIVE_CACHE_TTL_SECONDS = 30-_FETCH_TIMEOUT_SECONDS = 3.0---@dataclass(frozen=True)-class GatewayModel:- id: str- owned_by: str- context_window: int---def list_slack_app_models() -> tuple[GatewayModel, ...]:- """Return the model list the `slack_app` gateway product exposes.-- Returns an empty tuple on any error. The empty result is briefly cached- so subsequent interactions during an outage fail fast.- """- cached = cache.get(_CACHE_KEY)- if cached is not None:- return cached-- try:- page = get_llm_client(product="slack_app").with_options(timeout=_FETCH_TIMEOUT_SECONDS).models.list()- except Exception:- logger.exception("slack_app_llm_gateway_models_fetch_failed")- cache.set(_CACHE_KEY, (), timeout=_NEGATIVE_CACHE_TTL_SECONDS)- return ()-- models = tuple(- GatewayModel(- id=m.id,- owned_by=getattr(m, "owned_by", ""),- context_window=getattr(m, "context_window", 0),- )- for m in page.data- )- cache.set(_CACHE_KEY, models, timeout=_CACHE_TTL_SECONDS)- return modelsdiff --git a/products/slack_app/backend/services/model_catalogue.py b/products/slack_app/backend/services/model_catalogue.pyindex 3d2688eabfd7..35f9b6002578 100644--- a/products/slack_app/backend/services/model_catalogue.py+++ b/products/slack_app/backend/services/model_catalogue.py@@ -1,200 +1,49 @@"""Which models a Slack-triggered run may use, and how to name them.-The catalogue is the live LLM-gateway model list for the `slack_app` product-(`llm_models`) intersected with the runtime adapters the tasks product knows how to-drive. Anything the gateway serves under a provider we can't route — bedrock, vertex —-is dropped rather than offered.+The catalogue itself lives in the tasks product — one definition every surface derives+from, so the App Home picker, the web composer, and `model_override` can never disagree+about what exists. This module binds it to the `slack_app` gateway product and adds the+one piece of presentation Slack owns: mrkdwn phrasing.-This is the single source for both consumers: the App Home picker renders it as a+This is the single source for both Slack consumers: the App Home picker renders it as aBlock Kit dropdown tree, and `model_override` matches a model named in a Slack mention-against it. Neither may hardcode a model list, and neither owns the display labels.+against it. Neither may hardcode a model list."""from __future__ import annotations-import re-from dataclasses import dataclass+from typing import TYPE_CHECKING+if TYPE_CHECKING:+ # Importing this at runtime would execute `gateway_client`, pulling the Anthropic and OpenAI+ # SDKs onto slack_app's import path. It is only ever used as an annotation.+ from posthog.llm.gateway_client import Product-def _runtime_adapter_by_provider() -> dict[str, str]:- """Gateway `owned_by` → tasks runtime adapter.- Inverted from the tasks product's own adapter → provider mapping rather than- written out here, so the two can never disagree about which runtime serves a- provider. Providers with no adapter (bedrock, vertex) are simply absent, which is- what drops their models from the catalogue.- """- # Deferred because `facade.run_config` re-exports from a module that imports the- # tasks ORM, mcp_store, and sandbox config at import time; keeping that off the- # slack_app import path is the reason, and the App Home tests' `sys.modules` swap- # depends on it staying that way.- from products.tasks.backend.facade.run_config import ( # noqa: PLC0415- RuntimeAdapter,- get_provider_for_runtime_adapter,- )-- by_provider = {}- for adapter in RuntimeAdapter:- provider = get_provider_for_runtime_adapter(adapter)- if provider is not None:- by_provider[provider.value] = adapter.value- return by_provider---# Runtime + effort labels are UI strings with no tasks-product equivalent. Model-# display labels are computed from the model id on the fly via `format_model_id` so we-# never have to hand-maintain a model→label map.-RUNTIME_ADAPTER_DISPLAY_NAMES: dict[str, str] = {- "claude": "Claude (Anthropic)",- "codex": "Codex (OpenAI)",-}--# Vendor initialisms that must not be title-cased into "Gpt".-_MODEL_ACRONYMS: dict[str, str] = {"gpt": "GPT", "glm": "GLM"}--REASONING_EFFORT_DISPLAY_NAMES: dict[str, str] = {- "low": "Low",- "medium": "Medium",- "high": "High",- "xhigh": "Extra high",- "max": "Max",- "ultracode": "Ultracode",-}---@dataclass(frozen=True)-class ModelChoice:- """One model a Slack run may use, with the efforts that model supports."""-- runtime_adapter: str- model: str- label: str- supported_efforts: tuple[str, ...]+from products.tasks.backend.facade.model_catalogue import (+ REASONING_EFFORT_DISPLAY_NAMES,+ RUNTIME_ADAPTER_DISPLAY_NAMES,+ ModelChoice,+ RuntimeGroup,+ available_model_choices as _available_model_choices,+ filter_unsupported_effort,+ format_model_id,+ group_by_runtime,+ label_for,+ runtime_adapter_for,+)--@dataclass(frozen=True)-class RuntimeGroup:- """The models one runtime drives, under the name that runtime goes by."""-- runtime_adapter: str- label: str- choices: tuple[ModelChoice, ...]---def group_by_runtime(choices: tuple[ModelChoice, ...]) -> tuple[RuntimeGroup, ...]:- """The catalogue as a runtime → models tree, in the order the catalogue gave.-- Both consumers present the catalogue this way and neither should decide for itself- what a runtime is called: the App Home modal renders the tree as linked dropdowns,- and the model-override classifier renders it as the list of ids it may pick from.- The classifier needs the grouping to be visible rather than implied — people qualify- a model with the runtime it belongs to ("codex sol"), and a flat list gives that word- nothing to attach to, most sharply where a runtime name is also part of a model id- (`gpt-5.3-codex`). A runtime with no models simply doesn't appear.- """- by_adapter: dict[str, list[ModelChoice]] = {}- for choice in choices:- by_adapter.setdefault(choice.runtime_adapter, []).append(choice)- return tuple(- RuntimeGroup(- runtime_adapter=adapter,- label=label_for(adapter, RUNTIME_ADAPTER_DISPLAY_NAMES),- choices=tuple(grouped),- )- for adapter, grouped in by_adapter.items()- )+SLACK_APP_GATEWAY_PRODUCT: Product = "slack_app"def available_model_choices() -> tuple[ModelChoice, ...]:"""Every model a Slack-triggered run may use.Empty when the gateway is unreachable — callers must treat that as "no choice to- offer" rather than falling back to a hardcoded list, so a gateway outage can't- route a run to a model the gateway would reject anyway.+ offer" rather than falling back to a hardcoded list, so a gateway outage can't route+ a run to a model the gateway would reject anyway."""- from products.slack_app.backend.services.llm_models import list_slack_app_models # noqa: PLC0415- from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts # noqa: PLC0415-- by_provider = _runtime_adapter_by_provider()- choices = []- for model in list_slack_app_models():- runtime_adapter = by_provider.get(model.owned_by)- if runtime_adapter is None:- continue- choices.append(- ModelChoice(- runtime_adapter=runtime_adapter,- model=model.id,- label=format_model_id(model.id),- supported_efforts=tuple(e.value for e in get_supported_reasoning_efforts(runtime_adapter, model.id)),- )- )- return tuple(choices)---def runtime_adapter_for(model: str | None) -> str | None:- """Which runtime drives this model, per the tasks catalogue.-- The adapter is a property of the model rather than an independent choice, so- deriving it is what keeps a `(runtime_adapter, model)` pair from ever disagreeing.- `None` for a model the tasks product has no runtime for.- """- from products.tasks.backend.facade.run_config import get_runtime_adapter_for_model # noqa: PLC0415-- adapter = get_runtime_adapter_for_model(model)- return adapter.value if adapter else None---def filter_unsupported_effort(runtime_adapter: str | None, model: str | None, effort: str | None) -> str | None:- """Drop an effort the given model doesn't support (e.g. a user saved `high` on a- thinking model and then picked a non-thinking one).-- The single answer to "is this effort legal for this pair" — the stored-row resolver- in `slack_settings` and the run resolver in `run_preferences` both route through it.- """- from products.tasks.backend.facade.run_config import get_supported_reasoning_efforts # noqa: PLC0415-- if not effort:- return None- return effort if effort in {e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)} else None---def format_model_id(model_id: str) -> str:- """Turn a gateway model id into a display name: `Claude Opus 4.8`, `GPT-5.6 Sol`.-- Every family goes through the same rules — strip the provider prefix, glue a- version onto a leading acronym, title-case the rest — so a new model is named- without anyone touching a lookup table.- """- clean = model_id- for provider in _runtime_adapter_by_provider():- if clean.startswith(f"{provider}/"):- clean = clean[len(provider) + 1 :]- break-- # Collapse `4-8` into `4.8` so version components survive the dash split.- words = re.split(r"[-_]", re.sub(r"(\d)-(\d)", r"\1.\2", clean))- acronym = _MODEL_ACRONYMS.get(words[0].lower())- if acronym is None:- return " ".join(_titled(word) for word in words)- # `gpt` + `5.6` reads as `GPT-5.6`, the way the vendor writes it, with any- # remaining qualifier ("sol", "codex", "mini") as its own word.- head = f"{acronym}-{words[1]}" if len(words) > 1 else acronym- return " ".join([head, *(_titled(word) for word in words[2:])])---def _titled(word: str) -> str:- """Capitalise a name part, leaving bare version numbers alone."""- if re.fullmatch(r"[0-9.]+", word):- return word- return word[:1].upper() + word[1:].lower()---def label_for(value: str | None, mapping: dict[str, str]) -> str:- """Display name for a stored value, falling back to the value itself."""- if not value:- return "—"- return mapping.get(value, value)+ return _available_model_choices(SLACK_APP_GATEWAY_PRODUCT)def describe_run_model(model: str | None, reasoning_effort: str | None) -> str:diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.pyindex aa559d62a1b7..991cc25f83b7 100644--- a/products/slack_app/backend/tests/services/test_run_preferences.py+++ b/products/slack_app/backend/tests/services/test_run_preferences.py@@ -133,14 +133,14 @@ class TestAvailableModelChoices:def test_drops_providers_we_cannot_route(self):"""The gateway serves models under providers the tasks product has no runtimefor; offering one would produce a run the gateway rejects."""- from products.slack_app.backend.services.llm_models import GatewayModel+ from products.tasks.backend.facade.model_catalogue import GatewayModelgateway = (GatewayModel(id="claude-fable-5", owned_by="anthropic", context_window=200000),GatewayModel(id="titan-express", owned_by="bedrock", context_window=8000),)with patch(- "products.slack_app.backend.services.llm_models.list_slack_app_models",+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",return_value=gateway,):assert [c.model for c in available_model_choices()] == ["claude-fable-5"]diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex a0ce57e47dcd..272833a54c8c 100644--- a/products/slack_app/backend/tests/services/test_slack_app_home.py+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py@@ -116,12 +116,12 @@ def admin_user():@pytest.fixture(autouse=True)def _stub_picker_facade():- """Stub `tasks.facade.run_config` and the LLM-gateway model fetch.+ """Stub the tasks run-config facade and the LLM-gateway model fetch.- The tasks facade pulls in `tasks.temporal` on import, which the test env- can't satisfy. The gateway fetch would hit a real network. Both get- replaced with deterministic in-memory fakes covering every model the- renderer and handler tests reference.+ The facade pulls in `tasks.temporal` on import, which the test env can't+ satisfy. The gateway fetch would hit a real network. Both are replaced with+ deterministic in-memory fakes covering every model the renderer and handler+ tests reference."""class _Effort:@@ -217,26 +217,31 @@ def _stub_picker_facade():_GatewayModel(id="gpt-5", owned_by="openai"),_GatewayModel(id="gpt-5.5", owned_by="openai"),)- llm_models_name = "products.slack_app.backend.services.llm_models"- fake_llm_models: Any = ModuleType(llm_models_name)- fake_llm_models.list_slack_app_models = lambda: gateway_models- fake_llm_models.GatewayModel = _GatewayModel+ # The catalogue reads the run-config internals directly rather than through the facade,+ # so those lookups are replaced one at a time. Standing the facade stub in for the whole+ # module would blank every other name on it — the GitHub helpers `facade.api` defers to+ # among them.+ utils_name = "products.tasks.backend.temporal.process_task.utils"+ model_catalogue = importlib.import_module("products.tasks.backend.logic.services.model_catalogue")saved_facade = sys.modules.get(facade_name)- saved_llm = sys.modules.get(llm_models_name)sys.modules[facade_name] = fake- sys.modules[llm_models_name] = fake_llm_models+ # The provider → adapter map is cached for the process, so the fake only governs once+ # the cache is dropped on the way in and back out.+ model_catalogue._runtime_adapter_by_provider.cache_clear()try:- yield+ with (+ patch(f"{utils_name}.get_supported_reasoning_efforts", fake_get_supported),+ patch(f"{utils_name}.get_provider_for_runtime_adapter", fake_get_provider),+ patch.object(model_catalogue, "list_gateway_models", return_value=gateway_models),+ ):+ yieldfinally:+ model_catalogue._runtime_adapter_by_provider.cache_clear()if saved_facade is None:sys.modules.pop(facade_name, None)else:sys.modules[facade_name] = saved_facade- if saved_llm is None:- sys.modules.pop(llm_models_name, None)- else:- sys.modules[llm_models_name] = saved_llm# ---------------------------------------------------------------------------diff --git a/products/tasks/backend/facade/model_catalogue.py b/products/tasks/backend/facade/model_catalogue.pynew file mode 100644index 000000000000..2a6b1ce1a05c--- /dev/null+++ b/products/tasks/backend/facade/model_catalogue.py@@ -0,0 +1,38 @@+"""Facade re-exports for the live model catalogue a run picker offers.++Kept separate from `facade/run_config.py` because that one is deliberately+framework-free — pure enums and parse helpers — while this reaches the LLM gateway over+the network and caches through Django. Cross-product callers (the Slack app's App Home+picker and model-override classifier) import from here rather than reaching into+`logic/services/`.+"""++from products.tasks.backend.logic.services.model_catalogue import (+ REASONING_EFFORT_DISPLAY_NAMES,+ RUNTIME_ADAPTER_DISPLAY_NAMES,+ TASK_RUN_GATEWAY_PRODUCT,+ GatewayModel,+ ModelChoice,+ RuntimeGroup,+ available_model_choices,+ filter_unsupported_effort,+ format_model_id,+ group_by_runtime,+ label_for,+ runtime_adapter_for,+)++__all__ = [+ "REASONING_EFFORT_DISPLAY_NAMES",+ "RUNTIME_ADAPTER_DISPLAY_NAMES",+ "TASK_RUN_GATEWAY_PRODUCT",+ "GatewayModel",+ "ModelChoice",+ "RuntimeGroup",+ "available_model_choices",+ "filter_unsupported_effort",+ "format_model_id",+ "group_by_runtime",+ "label_for",+ "runtime_adapter_for",+]diff --git a/products/tasks/backend/logic/services/model_catalogue.py b/products/tasks/backend/logic/services/model_catalogue.pynew file mode 100644index 000000000000..5c98ac488d38--- /dev/null+++ b/products/tasks/backend/logic/services/model_catalogue.py@@ -0,0 +1,301 @@+"""Which models a task run may use, and how to name them.++The catalogue is the live LLM-gateway model list for a gateway product, intersected+with the runtime adapters this product knows how to drive. Anything the gateway serves+under a provider we can't route — bedrock, vertex — is dropped rather than offered.++Every surface that offers a model picker derives from here: the task composer in the+web app (`posthog_code`), the Slack App Home picker and the model-override classifier+(`slack_app`). None of them may hardcode a model list, and none of them owns the+display labels — a new model ships by appearing on the gateway, not by a PR per+surface.++The gateway is fetched through Django's shared cache so a picker render never blocks on+a round-trip; the timeout is capped at 3s because Slack's interactivity path expires+`trigger_id` after ~3s, and failures are negatively cached for 30s so a broken gateway+can't make every interaction wait the full timeout.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from functools import lru_cache+from typing import TYPE_CHECKING++from django.core.cache import cache++import structlog++if TYPE_CHECKING:+ from posthog.llm.gateway_client import Product++logger = structlog.get_logger(__name__)++# The gateway product a user-initiated task run authenticates as — the same one the+# sandbox agent uses, so the picker can only ever offer models the run itself may call.+TASK_RUN_GATEWAY_PRODUCT: Product = "posthog_code"++_CACHE_KEY_PREFIX = "tasks:llm_gateway_models"+_CACHE_TTL_SECONDS = 30 * 60+_NEGATIVE_CACHE_TTL_SECONDS = 30+_FETCH_TIMEOUT_SECONDS = 3.0++# Runtime + effort labels are UI strings with no run-config equivalent. Model display+# labels are computed from the model id on the fly via `format_model_id` so we never+# have to hand-maintain a model→label map.+RUNTIME_ADAPTER_DISPLAY_NAMES: dict[str, str] = {+ "claude": "Claude (Anthropic)",+ "codex": "Codex (OpenAI)",+}++REASONING_EFFORT_DISPLAY_NAMES: dict[str, str] = {+ "low": "Low",+ "medium": "Medium",+ "high": "High",+ "xhigh": "Extra high",+ "max": "Max",+ "ultracode": "Ultracode",+}++# Vendor initialisms that must not be title-cased into "Gpt".+_MODEL_ACRONYMS: dict[str, str] = {"gpt": "GPT", "glm": "GLM"}+++@dataclass(frozen=True)+class GatewayModel:+ id: str+ owned_by: str+ context_window: int+++@dataclass(frozen=True)+class ModelChoice:+ """One model a run may use, with the efforts that model supports.++ `supported_efforts` is empty for a model with no effort control — that is a real+ answer, not missing metadata, so a picker should render the model with no effort+ dropdown rather than hiding it.+ """++ runtime_adapter: str+ model: str+ label: str+ supported_efforts: tuple[str, ...]+++@dataclass(frozen=True)+class RuntimeGroup:+ """The models one runtime drives, under the name that runtime goes by."""++ runtime_adapter: str+ label: str+ choices: tuple[ModelChoice, ...]+++def group_by_runtime(choices: tuple[ModelChoice, ...]) -> tuple[RuntimeGroup, ...]:+ """The catalogue as a runtime → models tree, in the order the catalogue gave.++ Consumers present the catalogue this way and none should decide for itself what a+ runtime is called: the App Home modal renders the tree as linked dropdowns, and the+ model-override classifier renders it as the list of ids it may pick from. The+ classifier needs the grouping to be visible rather than implied — people qualify a+ model with the runtime it belongs to ("codex sol"), and a flat list gives that word+ nothing to attach to, most sharply where a runtime name is also part of a model id+ (`gpt-5.3-codex`). A runtime with no models simply doesn't appear.+ """+ by_adapter: dict[str, list[ModelChoice]] = {}+ for choice in choices:+ by_adapter.setdefault(choice.runtime_adapter, []).append(choice)+ return tuple(+ RuntimeGroup(+ runtime_adapter=adapter,+ label=label_for(adapter, RUNTIME_ADAPTER_DISPLAY_NAMES),+ choices=tuple(grouped),+ )+ for adapter, grouped in by_adapter.items()+ )+++def _cache_quietly(key: str, value: tuple[GatewayModel, ...], timeout: int) -> None:+ """Caching is an optimization — an unreachable cache must not fail the caller."""+ try:+ cache.set(key, value, timeout=timeout)+ except Exception:+ logger.exception("tasks_llm_gateway_models_cache_write_failed", cache_key=key)+++def list_gateway_models(product: Product) -> tuple[GatewayModel, ...]:+ """Return the model list the given gateway product exposes.++ Returns an empty tuple on any error, the cache included — a picker with no models is a+ worse day than a 500 for every caller. The empty result is briefly cached so subsequent+ calls during a gateway outage fail fast.+ """+ cache_key = f"{_CACHE_KEY_PREFIX}:{product}"++ # Deferred: `gateway_client` pulls the Anthropic and OpenAI SDKs, and this module is reachable from+ # the tasks API's import path — every other caller in the repo defers it for the same reason.+ from posthog.llm.gateway_client import get_llm_client # noqa: PLC0415 — keeps the LLM SDKs off startup paths++ try:+ cached = cache.get(cache_key)+ if cached is not None:+ return cached++ page = get_llm_client(product=product).with_options(timeout=_FETCH_TIMEOUT_SECONDS).models.list()+ except Exception:+ logger.exception("tasks_llm_gateway_models_fetch_failed", gateway_product=product)+ _cache_quietly(cache_key, (), _NEGATIVE_CACHE_TTL_SECONDS)+ return ()++ models = tuple(+ GatewayModel(+ id=m.id,+ owned_by=getattr(m, "owned_by", ""),+ context_window=getattr(m, "context_window", 0),+ )+ for m in page.data+ )+ _cache_quietly(cache_key, models, _CACHE_TTL_SECONDS)+ return models+++def available_model_choices(product: Product) -> tuple[ModelChoice, ...]:+ """Every model a run on the given gateway product may use.++ Empty when the gateway is unreachable — callers must treat that as "no choice to+ offer" rather than falling back to a hardcoded list, so a gateway outage can't route+ a run to a model the gateway would reject anyway.+ """+ # Deferred because `temporal.process_task.utils` pulls the tasks ORM, mcp_store, and+ # sandbox config at import time; keeping that off the import path of every catalogue+ # consumer is the reason, and the App Home tests' `sys.modules` swap depends on it+ # staying that way.+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — see above+ get_supported_reasoning_efforts,+ )++ by_provider = _runtime_adapter_by_provider()+ choices = []+ for model in list_gateway_models(product):+ runtime_adapter = by_provider.get(model.owned_by)+ if runtime_adapter is None:+ continue+ choices.append(+ ModelChoice(+ runtime_adapter=runtime_adapter,+ model=model.id,+ label=format_model_id(model.id),+ supported_efforts=tuple(e.value for e in get_supported_reasoning_efforts(runtime_adapter, model.id)),+ )+ )+ return tuple(choices)+++def runtime_adapter_for(model: str | None) -> str | None:+ """Which runtime drives this model, per the static run-config map.++ The adapter is a property of the model rather than an independent choice, so+ deriving it is what keeps a `(runtime_adapter, model)` pair from ever disagreeing.+ `None` for a model this product has no runtime for.+ """+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — see `available_model_choices`+ get_runtime_adapter_for_model,+ )++ adapter = get_runtime_adapter_for_model(model)+ return adapter.value if adapter else None+++def filter_unsupported_effort(runtime_adapter: str | None, model: str | None, effort: str | None) -> str | None:+ """Drop an effort the given model doesn't support (e.g. a user saved `high` on a+ thinking model and then picked a non-thinking one).++ The single answer to "is this effort legal for this pair" — every stored-preference+ resolver routes through it.+ """+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — see `available_model_choices`+ get_supported_reasoning_efforts,+ )++ if not effort:+ return None+ return effort if effort in {e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)} else None+++@lru_cache(maxsize=1)+def _runtime_adapter_by_provider() -> dict[str, str]:+ """Gateway `owned_by` → runtime adapter.++ Inverted from the adapter → provider mapping rather than written out here, so the+ two can never disagree about which runtime serves a provider. Providers with no+ adapter (bedrock, vertex) are simply absent, which is what drops their models from+ the catalogue.+ """+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — see `available_model_choices`+ RuntimeAdapter,+ get_provider_for_runtime_adapter,+ )++ by_provider = {}+ for adapter in RuntimeAdapter:+ provider = get_provider_for_runtime_adapter(adapter)+ if provider is not None:+ by_provider[provider.value] = adapter.value+ return by_provider+++def format_model_id(model_id: str) -> str:+ """Turn a gateway model id into a display name: `Claude Opus 4.8`, `GPT-5.6 Sol`.++ Every family goes through the same rules — strip the provider prefix, glue a version+ onto a leading acronym, title-case the rest — so a new model is named without anyone+ touching a lookup table.+ """+ clean = model_id+ for provider in _runtime_adapter_by_provider():+ if clean.startswith(f"{provider}/"):+ clean = clean[len(provider) + 1 :]+ break++ # Collapse `4-8` into `4.8` so version components survive the dash split.+ words = re.split(r"[-_]", re.sub(r"(\d)-(\d)", r"\1.\2", clean))+ acronym = _MODEL_ACRONYMS.get(words[0].lower())+ if acronym is None:+ return " ".join(_titled(word) for word in words)+ # `gpt` + `5.6` reads as `GPT-5.6`, the way the vendor writes it, with any remaining+ # qualifier ("sol", "codex", "mini") as its own word.+ head = f"{acronym}-{words[1]}" if len(words) > 1 else acronym+ return " ".join([head, *(_titled(word) for word in words[2:])])+++def _titled(word: str) -> str:+ """Capitalise a name part, leaving bare version numbers alone."""+ if re.fullmatch(r"[0-9.]+", word):+ return word+ return word[:1].upper() + word[1:].lower()+++def label_for(value: str | None, mapping: dict[str, str]) -> str:+ """Display name for a stored value, falling back to the value itself."""+ if not value:+ return "—"+ return mapping.get(value, value)+++__all__ = [+ "REASONING_EFFORT_DISPLAY_NAMES",+ "RUNTIME_ADAPTER_DISPLAY_NAMES",+ "TASK_RUN_GATEWAY_PRODUCT",+ "GatewayModel",+ "ModelChoice",+ "RuntimeGroup",+ "available_model_choices",+ "filter_unsupported_effort",+ "format_model_id",+ "group_by_runtime",+ "label_for",+ "list_gateway_models",+ "runtime_adapter_for",+]diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 2c32e3a12c5e..32ad560deb4f 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -42,6 +42,7 @@ from products.tasks.backend.facade.contracts import (TaskUserBasicInfo,WizardCloudRunDTO,)+from products.tasks.backend.facade.model_catalogue import ModelChoicefrom products.tasks.backend.facade.run_config import (ALL_INITIAL_PERMISSION_MODE_CHOICES,CODEX_INITIAL_PERMISSION_MODE_CHOICES,@@ -416,9 +417,12 @@ class TaskSerializer(DataclassSerializer):latest_run = TaskRunDetailSerializer(allow_null=True, required=False, help_text="Latest run details for this task")created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)slack_thread_references = SlackThreadReferenceSerializer(many=True, read_only=True)+ # Not `read_only`, even though this is a response-only serializer: `@validated_request` re-reads+ # its own output through `to_internal_value`, which drops read-only fields, and `runtime` is+ # required on `TaskDetailDTO` — so a read-only declaration makes that round-trip raise. Writes+ # never reach here; they go through `TaskCreateSerializer` / `TaskWriteSerializer`.runtime = serializers.ChoiceField(choices=tasks_facade.TaskRuntime.choices,- read_only=True,help_text="Agent protocol and harness used for this task's runs.",)@@ -2061,6 +2065,37 @@ class TaskPinResponseSerializer(serializers.Serializer):pinned = serializers.BooleanField(help_text="Current pin state for the requester.")+class ModelChoiceSerializer(DataclassSerializer):+ """One model a run may use. Reads a `ModelChoice` straight off the catalogue facade.++ Both enums are declared with the same choices the run-detail response uses, so clients get the+ generated adapter/effort types here rather than bare strings.+ """++ runtime_adapter = serializers.ChoiceField(+ choices=[adapter.value for adapter in RuntimeAdapter],+ help_text="Runtime that drives this model, such as 'claude' or 'codex'.",+ )+ display_name = serializers.CharField(+ source="label", help_text="Display name for the model, such as 'Claude Opus 4.8'."+ )+ supported_efforts = serializers.ListField(+ child=serializers.ChoiceField(choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS]),+ help_text="Reasoning efforts this model accepts, in ascending order. Empty for a model with no effort control.",+ )++ class Meta:+ dataclass = ModelChoice+ fields = ["runtime_adapter", "model", "display_name", "supported_efforts"]+++class ModelCatalogueResponseSerializer(serializers.Serializer):+ models = ModelChoiceSerializer(+ many=True,+ help_text="Every model a run may use, newest catalogue from the LLM gateway. Empty when the gateway is unreachable.",+ )++class RepositoryReadinessQuerySerializer(serializers.Serializer):repository = serializers.CharField(required=True, help_text="Repository in org/repo format")window_days = serializers.IntegerField(required=False, default=7, min_value=1, max_value=30)diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex d64974fc0db9..3f66521bab40 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -68,6 +68,7 @@ from products.tasks.backend.facade.metrics import (observe_stream_length_on_connect,observe_stream_resume_gap,)+from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choicesfrom products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactTypefrom products.tasks.backend.facade.streams import (TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,@@ -82,6 +83,7 @@ from products.tasks.backend.facade.streams import (from products.tasks.backend.presentation.serializers import (CodeInviteRedeemRequestSerializer,ConnectionTokenResponseSerializer,+ ModelCatalogueResponseSerializer,PinnedTaskIdsResponseSerializer,RepositoryReadinessQuerySerializer,RepositoryReadinessResponseSerializer,@@ -562,6 +564,21 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()return Response({"task_ids": tasks_facade.list_pinned_task_ids(self.team_id, user_id)})+ @extend_schema(+ responses={200: ModelCatalogueResponseSerializer},+ summary="List available models",+ description=(+ "Return the models a task run may use, with the reasoning efforts each one supports. "+ "Derived from the live LLM gateway catalogue, so a newly released model appears without a client change. "+ "An empty list means the gateway is unreachable — clients should fall back to their own default rather "+ "than treating it as 'no models exist'."+ ),+ )+ @action(detail=False, methods=["get"], url_path="models", required_scopes=["task:read"])+ def models(self, request, **kwargs):+ choices = available_model_choices(TASK_RUN_GATEWAY_PRODUCT)+ return Response(ModelCatalogueResponseSerializer({"models": choices}).data)+@extend_schema(request=TaskPinRequestSerializer, responses={200: TaskPinResponseSerializer})@action(detail=True, methods=["post"], url_path="pin", required_scopes=["task:write"])@validated_request(request_serializer=TaskPinRequestSerializer)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex e020cb772d40..2d1c239acf4b 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -49,6 +49,7 @@ from products.tasks.backend.logic.services.connection_token import (get_sandbox_jwt_public_key,reset_sandbox_jwt_key_cache,)+from products.tasks.backend.logic.services.model_catalogue import GatewayModelfrom products.tasks.backend.logic.services.staged_artifacts import (RUN_ARTIFACT_TTL_DAYS,build_task_artifact_entry,@@ -79,6 +80,7 @@ from products.tasks.backend.presentation.serializers import (TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES,TaskRunLivingArtifactChartRequestSerializer,+ TaskSerializer,)from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token@@ -11862,3 +11864,72 @@ class TestTaskRunSlackTaskApiAccess(BaseTaskAPITest):response = self.client.get(url)self.assertEqual(response.status_code, expected_status)+++class TestModelCatalogueAPI(BaseTaskAPITest):+ GATEWAY_MODELS = (+ GatewayModel(id="claude-opus-4-8", owned_by="anthropic", context_window=200_000),+ GatewayModel(id="gpt-5.5", owned_by="openai", context_window=400_000),+ GatewayModel(id="titan-express", owned_by="bedrock", context_window=8_000),+ )++ def test_returns_routable_gateway_models_with_their_efforts(self):+ with patch(+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",+ return_value=self.GATEWAY_MODELS,+ ):+ response = self.client.get("/api/projects/@current/tasks/models/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ models = response.json()["models"]+ # Bedrock has no runtime adapter, so `titan-express` can't be offered.+ self.assertEqual([m["model"] for m in models], ["claude-opus-4-8", "gpt-5.5"])+ self.assertEqual(models[0]["runtime_adapter"], "claude")+ self.assertEqual(models[0]["display_name"], "Claude Opus 4.8")+ self.assertIn("max", models[0]["supported_efforts"])++ def test_unreachable_cache_yields_an_empty_catalogue_rather_than_an_error(self):+ # The cache is an optimization in front of the gateway; if Redis is down the endpoint still has to+ # answer with the documented empty catalogue rather than 500 every caller.+ with patch(+ "products.tasks.backend.logic.services.model_catalogue.cache.get",+ side_effect=RuntimeError("redis down"),+ ):+ response = self.client.get("/api/projects/@current/tasks/models/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"models": []})++ def test_unreachable_gateway_yields_an_empty_catalogue_rather_than_an_error(self):+ # `list_gateway_models` swallows gateway failures into an empty tuple; the endpoint must pass+ # that through so a client falls back to its own default instead of showing an error state.+ with patch(+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",+ return_value=(),+ ):+ response = self.client.get("/api/projects/@current/tasks/models/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"models": []})+++class TestTaskSerializerResponseRoundTrip(BaseTaskAPITest):+ def test_task_response_can_be_read_back(self):+ # `@validated_request` re-reads its own response through `to_internal_value` whenever DEBUG is+ # on (posthog/api/mixins.py). That read drops read-only fields, so declaring one that+ # `TaskDetailDTO` requires makes the dataclass constructor raise pydantic's ValidationError —+ # which `is_valid(raise_exception=False)` doesn't catch, 500ing the endpoint in local dev.+ # CI runs with DEBUG off, so this round trip is the only thing guarding the response shape.+ #+ # The creator needs a surname: `created_by.last_name` rejects a blank string, and that+ # field-level error short-circuits DRF before it builds the dataclass, masking the bug.+ self.user.last_name = "Tester"+ self.user.save()+ task = self.create_task()++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ reread = TaskSerializer(data=response.json())+ self.assertTrue(reread.is_valid(), reread.errors)+ self.assertEqual(reread.validated_data.runtime, task.runtime)diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 9d201d25ba1f..1b1145532852 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1590,7 +1590,7 @@ export interface TaskDetailDTOApi {** * `acp` - ACP* * `pi` - Pi */- readonly runtime: RuntimeEnumApi+ runtime: RuntimeEnumApi/** @nullable */repository: string | nullrepositories: string[]@@ -3698,6 +3698,30 @@ export interface WizardCloudRunDTOApi {started_at?: string | null}+/**+ * One model a run may use. Reads a `ModelChoice` straight off the catalogue facade.+ *+ * Both enums are declared with the same choices the run-detail response uses, so clients get the+ * generated adapter/effort types here rather than bare strings.+ */+export interface ModelChoiceApi {+ /** Runtime that drives this model, such as 'claude' or 'codex'.+ *+ * * `claude` - claude+ * * `codex` - codex */+ runtime_adapter: RuntimeAdapterEnumApi+ model: string+ /** Display name for the model, such as 'Claude Opus 4.8'. */+ display_name: string+ /** Reasoning efforts this model accepts, in ascending order. Empty for a model with no effort control. */+ supported_efforts: ReasoningEffortEnumApi[]+}++export interface ModelCatalogueResponseApi {+ /** Every model a run may use, newest catalogue from the LLM gateway. Empty when the gateway is unreachable. */+ models: ModelChoiceApi[]+}+export interface PinnedTaskIdsResponseApi {/** Visible task IDs pinned by the requester, newest pin first. */task_ids: string[]diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex d27694487b49..5c0683664c84 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -31,6 +31,7 @@ import type {LoopsTriggerCreateBodyOne,LoopsTriggerCreateBodyThree,LoopsTriggerCreateBodyTwo,+ ModelCatalogueResponseApi,PaginatedChannelDTOListApi,PaginatedChannelFeedMessageDTOListApi,PaginatedChannelInstructionsDTOListApi,@@ -2403,6 +2404,24 @@ export const tasksActiveWizardRunRetrieve = async (})}+export const getTasksModelsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tasks/models/`+}++/**+ * Return the models a task run may use, with the reasoning efforts each one supports. Derived from the live LLM gateway catalogue, so a newly released model appears without a client change. An empty list means the gateway is unreachable — clients should fall back to their own default rather than treating it as 'no models exist'.+ * @summary List available models+ */+export const tasksModelsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<ModelCatalogueResponseApi> => {+ return apiMutator<ModelCatalogueResponseApi>(getTasksModelsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getTasksPinnedRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/tasks/pinned/`}diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 358403727950..2bbe5cd04192 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -418,6 +418,9 @@ tools:- internal- created_at- updated_at+ tasks-models-retrieve:+ operation: tasks_models_retrieve+ enabled: falsetasks-partial-update:operation: tasks_partial_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4b84af3a4e56..2e9813fc63c1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45466,6 +45466,30 @@ export namespace Schemas {readonly last_seen_at: string | null;}+ /**+ * One model a run may use. Reads a `ModelChoice` straight off the catalogue facade.+ *+ * Both enums are declared with the same choices the run-detail response uses, so clients get the+ * generated adapter/effort types here rather than bare strings.+ */+ export interface ModelChoice {+ /** Runtime that drives this model, such as 'claude' or 'codex'.+ *+ * * `claude` - claude+ * * `codex` - codex */+ runtime_adapter: RuntimeAdapterEnum;+ model: string;+ /** Display name for the model, such as 'Claude Opus 4.8'. */+ display_name: string;+ /** Reasoning efforts this model accepts, in ascending order. Empty for a model with no effort control. */+ supported_efforts: ReasoningEffortEnum[];+ }++ export interface ModelCatalogueResponse {+ /** Every model a run may use, newest catalogue from the LLM gateway. Empty when the gateway is unreachable. */+ models: ModelChoice[];+ }+/*** * `FeatureFlag` - feature flag*/@@ -51587,7 +51611,7 @@ export namespace Schemas {** * `acp` - ACP* * `pi` - Pi */- readonly runtime: RuntimeEnum;+ runtime: RuntimeEnum;/** @nullable */repository: string | null;repositories: string[];