: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(agent-platform): model selection via spec.models (auto/manual) + runtime fallback (#64825)
Ben White23a96b82aa51
diff --git a/products/agent_platform/backend/logic/janitor_client.py b/products/agent_platform/backend/logic/janitor_client.pyindex 56323e6062d5..0a6e6ba0afff 100644--- a/products/agent_platform/backend/logic/janitor_client.py+++ b/products/agent_platform/backend/logic/janitor_client.py@@ -203,6 +203,11 @@ class JanitorClient:# Roll-up endpoints powering the fleet overview tiles. The# janitor side owns the JSONB read so Django doesn't reach across DBs.+ def get_models(self) -> dict:+ """The served-model catalog + curated auto-level map. Project-agnostic+ (the gateway catalog is global), so no params."""+ return self._call("GET", "/models")+def aggregate_for_application(self, application_id: str, *, since: str | None = None) -> dict:params: dict[str, Any] = {"application_id": application_id}if since:diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.pyindex 62ab00fe1c1e..00720cdc3a2f 100644--- a/products/agent_platform/backend/logic/spec_schema.py+++ b/products/agent_platform/backend/logic/spec_schema.py@@ -131,14 +131,106 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {"$schema": "https://json-schema.org/draft/2020-12/schema","type": "object","properties": {- "model": {- "type": "string",- "minLength": 1,- # Mirror of `ModelIdSchema` in agent-shared/src/spec/spec.ts. Runtime- # `resolveModel` demands `<provider>/<model-id>`; rejecting bare ids- # at authoring time keeps the node side from failing every session- # against a freshly-promoted revision.- "pattern": r"^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$",+ # Model selection (mirrors `AgentSpecSchema.models`, default+ # auto/medium). auto: platform resolves `level` to a cross-provider list+ # at runtime. manual: author's explicit priority list.+ "models": {+ "description": (+ "How this agent selects its model. `auto`: pick a quality/cost `level` and the platform "+ "resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: "+ "give an explicit priority-ordered `models` list (primary first). `optimize_for` governs "+ "how the chosen model is treated across the session's turns."+ ),+ "default": {"mode": "auto", "level": "medium", "optimize_for": "cost"},+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "mode": {"type": "string", "const": "auto"},+ "level": {+ "description": (+ "Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning "+ "jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded "+ "work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a "+ "priority-ordered cross-provider list at session start."+ ),+ "default": "medium",+ "type": "string",+ "enum": ["low", "medium", "high"],+ },+ "reasoning": {+ "description": (+ "Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … "+ "xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/"+ "spec default."+ ),+ "type": "string",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ },+ "optimize_for": {+ "description": (+ "Session model stability vs. resilience. `cost` (default): the first turn picks a "+ "working model and PINS it for the whole session — keeps the provider's prompt cache "+ "warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if "+ "the pinned model is down the turn fails rather than re-reading the whole context cold "+ "on another provider. `availability`: fail over to the next model when the session's "+ "model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` "+ "for long/expensive sessions, `availability` where uptime matters more than spend."+ ),+ "default": "cost",+ "type": "string",+ "enum": ["cost", "availability"],+ },+ },+ "required": ["mode"],+ "additionalProperties": False,+ },+ {+ "type": "object",+ "properties": {+ "mode": {"type": "string", "const": "manual"},+ "models": {+ "description": "Explicit priority-ordered fallback list — the runner tries entries in order (primary first).",+ "minItems": 1,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "model": {+ "description": "Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).",+ "type": "string",+ "minLength": 1,+ # Mirror of `ModelIdSchema` in agent-shared/src/spec/spec.ts.+ # `<provider>/<model-id>` — bare ids freeze fine but the+ # gateway 400s on first session; reject at authoring time.+ "pattern": r"^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$",+ },+ "reasoning": {+ "description": "Per-model reasoning effort override (else the spec default).",+ "type": "string",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ },+ },+ "required": ["model"],+ "additionalProperties": False,+ },+ },+ "optimize_for": {+ "description": (+ "Session model stability vs. resilience. `cost` (default): pin the first working model "+ "for the whole session (warm prompt cache, no mid-session failover). `availability`: "+ "fail over down this list when the session's model fails (survives outages, re-reads "+ "context cold)."+ ),+ "default": "cost",+ "type": "string",+ "enum": ["cost", "availability"],+ },+ },+ "required": ["mode", "models"],+ "additionalProperties": False,+ },+ ],},"triggers": {"default": [],@@ -546,7 +638,6 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {"required": ["max_turns", "max_tool_calls", "max_wall_seconds", "max_memory_mb", "max_cpu_cores"],"additionalProperties": False,},- "entrypoint": {"default": "agent.md", "type": "string"},"reasoning": {"type": "string", "enum": ["minimal", "low", "medium", "high", "xhigh"]},"framework_prompt": {"type": "object",@@ -585,15 +676,21 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {"additionalProperties": False,},},+ # Structural required list (the RAW schema). Every entry here has a+ # `default`, so `_relax_required_for_defaults` drops all of them from+ # `AGENT_SPEC_JSON_SCHEMA_FOR_WRITE` — the schema authoring/validation+ # actually runs against (serializers.validate_spec). So a spec may omit+ # any of these, incl. `models`: the runner falls back to auto/medium.+ # The old top-level `model` field is gone entirely; `models` replaces it.+ # Mirror `AgentSpecSchema` in services/agent-shared/src/spec/spec.ts."required": [- "model",+ "models","triggers","tools","mcps","skills","secrets","limits",- "entrypoint",],"additionalProperties": False,}diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex 319a6a12c925..00ae3165a5d8 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -161,19 +161,31 @@ class JanitorUpstreamError(APIException):# still see the upstream payload.if isinstance(e.body, dict):msg = e.body.get("error") or e.body.get("detail") or e.body.get("message")- # Append structured upstream errors (custom-tool compile failures carry- # errors=[{kind, message, line}]) so the caller + concierge model see the- # concrete reason, not just the opaque `tool_compile_failed` code.+ # Append structured upstream errors so the caller + concierge model+ # see the concrete reason, not just the opaque code. Two shapes:+ # custom-tool compile -> top-level errors=[{kind, message, line}];+ # freeze/validate -> report.errors=[{code, message, pointer}] (e.g.+ # invalid_model from the models gate).sub_errors = e.body.get("errors")+ if not sub_errors:+ report = e.body.get("report")+ sub_errors = report.get("errors") if isinstance(report, dict) else Noneif isinstance(sub_errors, list) and sub_errors:parts: list[str] = []for er in sub_errors:if not isinstance(er, dict) or not isinstance(er.get("message"), str):continue- kind = er.get("kind")+ kind = er.get("kind") or er.get("code")line = er.get("line")+ pointer = er.get("pointer")prefix = f"{kind}: " if isinstance(kind, str) else ""- suffix = f" (line {line})" if isinstance(line, int) else ""+ suffix = (+ f" (line {line})"+ if isinstance(line, int)+ else f" [{pointer}]"+ if isinstance(pointer, str)+ else ""+ )parts.append(f"{prefix}{er['message']}{suffix}")if parts:joined = "; ".join(parts)@@ -577,6 +589,7 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object_read_actions = ["list","retrieve",+ "models","sessions_list","sessions_retrieve","session_logs",@@ -960,6 +973,25 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):raise JanitorUpstreamError(e) from ereturn Response(payload)+ @extend_schema(+ operation_id="agent_applications_models",+ description=(+ "Served-model catalog — each model's id, provider, context window, and "+ "USD-per-million-token pricing — plus the curated auto-level → model map. "+ "Project-agnostic; sourced from the AI gateway catalog. Powers the config "+ "UI model browser and the agent builder's model-choosing skill."+ ),+ )+ @action(detail=False, methods=["get"], url_path="models")+ def models(self, request: Request, **kwargs) -> Response:+ """The model catalog. Proxies the janitor, which owns the gateway-catalog+ client and the level map (single source for runtime + UI + agents)."""+ try:+ payload = _janitor().get_models()+ except JanitorClientError as e:+ raise JanitorUpstreamError(e) from e+ return Response(payload)+@extend_schema(operation_id="agent_applications_sessions_list",parameters=[@@ -2144,7 +2176,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(detail=True, methods=["post"], url_path="validate")def validate(self, request: Request, **kwargs) -> Response:- """Pre-flight checks before freeze + promote: entrypoint file exists,+ """Pre-flight checks before freeze + promote: agent.md exists,every native tool id is registered, every custom tool has itscompiled.js + schema.json, every skill path exists, every declaredsecret has a value set in this revision's env block. Returns@@ -2266,7 +2298,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"Fully-assembled system prompt the runner would pass ""to pi-ai for a session against this revision. ""Concatenates the platform framework preamble, the "- "bundle's `agent.md` (or `spec.entrypoint`), and the "+ "bundle's `agent.md`, and the ""skills index. Inspect before promotion to confirm ""the model will see what you expect."),diff --git a/products/agent_platform/backend/tests/test_freeze_skill_refs.py b/products/agent_platform/backend/tests/test_freeze_skill_refs.pyindex daa4f3f206cf..05e18112df18 100644--- a/products/agent_platform/backend/tests/test_freeze_skill_refs.py+++ b/products/agent_platform/backend/tests/test_freeze_skill_refs.py@@ -189,7 +189,7 @@ class TestFreezeResolvesSkillRefs(APIBaseTest):self._detail_url,{"spec": {- "model": "faux/new",+ "models": {"mode": "manual", "models": [{"model": "faux/new"}]},"triggers": [],# Author attempt to inject/spoof a skill — must be ignored."skills": [{"id": "evil", "path": "skills/evil/SKILL.md", "source_version_id": "019e-fake"}],@@ -199,7 +199,7 @@ class TestFreezeResolvesSkillRefs(APIBaseTest):)self.assertEqual(res.status_code, 200, res.content)self.revision.refresh_from_db()- self.assertEqual(self.revision.spec["model"], "faux/new")+ self.assertEqual(self.revision.spec["models"]["models"][0]["model"], "faux/new")# skills[] is the preserved server value, not the author's spoof.self.assertEqual([s["id"] for s in self.revision.spec["skills"]], ["triage"])self.assertEqual(self.revision.spec["skills"][0]["source_version_id"], "019e-real")diff --git a/products/agent_platform/backend/tests/test_models_catalog.py b/products/agent_platform/backend/tests/test_models_catalog.pynew file mode 100644index 000000000000..43388833f998--- /dev/null+++ b/products/agent_platform/backend/tests/test_models_catalog.py@@ -0,0 +1,63 @@+"""+The model-catalog endpoint (`agent_applications/models/`) — a project-agnostic+read that proxies the janitor's `/models` (which owns the gateway-catalog client+and the level map). These guards make sure Django forwards correctly, surfaces+the payload intact, and keeps the action in the read-scope map so personal API+keys can read it.+"""++from __future__ import annotations++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from ..presentation.views import AgentApplicationViewSet+++class TestAgentApplicationModels(APIBaseTest):+ databases = {+ "default",+ "persons_db_writer",+ "persons_db_reader",+ "agent_platform_db_writer",+ "agent_platform_db_reader",+ }++ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/agent_applications/models/"++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_models_proxies_janitor(self, mock_janitor) -> None:+ payload = {+ "models": [+ {+ "model": "anthropic/claude-haiku-4.5",+ "provider": "anthropic",+ "context_window": 200000,+ "input": 1,+ "output": 5,+ }+ ],+ "levels": {+ "low": ["anthropic/claude-haiku-4.5", "openai/gpt-5-mini"],+ "medium": ["anthropic/claude-sonnet-4.6", "openai/gpt-5"],+ "high": ["anthropic/claude-opus-4.7", "openai/gpt-5-pro"],+ },+ }+ mock_janitor.return_value.get_models.return_value = payload++ resp = self.client.get(self.url)++ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ self.assertEqual(resp.json(), payload)+ # No params — the catalog is project-agnostic.+ mock_janitor.return_value.get_models.assert_called_once_with()++ def test_models_is_a_declared_read_action(self) -> None:+ # If `models` slips out of `scope_object_read_actions`, the scope check+ # denies personal-API-key reads — which is exactly what the config UI+ # and the agent builder rely on. Guard against drift.+ self.assertIn("models", AgentApplicationViewSet.scope_object_read_actions)diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.pyindex e39aa950d79c..0760e0d9b3bd 100644--- a/products/agent_platform/backend/tests/test_preview_proxy.py+++ b/products/agent_platform/backend/tests/test_preview_proxy.py@@ -42,7 +42,6 @@ def _base_spec() -> dict[str, Any]:"integrations": [],"secrets": [],"limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},- "entrypoint": "agent.md",}diff --git a/products/agent_platform/backend/tests/test_preview_token.py b/products/agent_platform/backend/tests/test_preview_token.pyindex 4eff5e93d733..3eefe41f156e 100644--- a/products/agent_platform/backend/tests/test_preview_token.py+++ b/products/agent_platform/backend/tests/test_preview_token.py@@ -53,7 +53,6 @@ def _base_spec(triggers: list[dict[str, Any]] | None = None, modes: list[str] |"integrations": [],"secrets": [],"limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},- "entrypoint": "agent.md",}diff --git a/products/agent_platform/backend/tests/test_revision_create.py b/products/agent_platform/backend/tests/test_revision_create.pyindex c1413e77d6ab..65c142db8148 100644--- a/products/agent_platform/backend/tests/test_revision_create.py+++ b/products/agent_platform/backend/tests/test_revision_create.py@@ -16,7 +16,7 @@ from rest_framework import statusfrom ..models import AgentApplication-_SPEC = {"model": "anthropic/claude-haiku-4-5"}+_SPEC = {"models": {"mode": "manual", "models": [{"model": "anthropic/claude-haiku-4-5"}]}}class TestRevisionCreateBundleUri(APIBaseTest):diff --git a/products/agent_platform/backend/tests/test_spec_schema.py b/products/agent_platform/backend/tests/test_spec_schema.pyindex bbd7624ea1a2..aea30c07663a 100644--- a/products/agent_platform/backend/tests/test_spec_schema.py+++ b/products/agent_platform/backend/tests/test_spec_schema.py@@ -52,25 +52,42 @@ def _with_auth(spec: dict) -> dict:@pytest.mark.parametrize(("name", "spec"),[- ("minimal", {"model": "anthropic/claude-haiku-4-5"}),+ ("minimal", {}),+ # `model` is optional — auto/medium is the runner's default, so a spec+ # may omit it entirely.+ ("no_model", {}),+ # models auto: level + default; `model` can be dropped.+ ("models_auto", {"models": {"mode": "auto", "level": "high"}}),+ # auto omitting level (defaulted to medium) + per-policy reasoning.+ ("models_auto_defaults", {"models": {"mode": "auto", "reasoning": "high"}}),+ # models manual: provider-diverse priority list, per-entry reasoning.+ (+ "models_manual",+ {+ "models": {+ "mode": "manual",+ "models": [+ {"model": "anthropic/claude-sonnet-4-6", "reasoning": "high"},+ {"model": "openai/gpt-5"},+ ],+ }+ },+ ),("with_chat_trigger",{- "model": "test/x","triggers": [{"type": "chat", "config": {}}],},),("kitchen_sink",{- "model": "test/x","triggers": [{"type": "chat", "config": {}},{"type": "webhook", "config": {"path": "/hook"}},],"tools": [{"kind": "native", "id": "@posthog/query"}],"skills": [{"id": "research", "path": "skills/research.md"}],- "entrypoint": "agent.md",},),# Nested defaults must mirror zod: omitting fields with defaults at@@ -80,14 +97,12 @@ def _with_auth(spec: dict) -> dict:("slack_omits_mention_only",{- "model": "test/x","triggers": [{"type": "slack", "config": {"trusted_workspaces": "*"}}],},),("cron_omits_timezone",{- "model": "test/x","triggers": [{"type": "cron", "config": {"name": "hourly", "schedule": "0 * * * *", "prompt": "run it"}}],@@ -96,7 +111,6 @@ def _with_auth(spec: dict) -> dict:("mcp_omits_config",{- "model": "test/x","triggers": [{"type": "mcp", "config": {}}],},),@@ -105,7 +119,6 @@ def _with_auth(spec: dict) -> dict:("external_mcp_unique_tools",{- "model": "test/x","mcps": [{"id": "linear",@@ -121,7 +134,6 @@ def _with_auth(spec: dict) -> dict:("external_mcp_byo_headers_with_secret",{- "model": "test/x","secrets": ["GITHUB_TOKEN"],"mcps": [{@@ -143,7 +155,6 @@ def _with_auth(spec: dict) -> dict:("skill_from_template",{- "model": "test/x","skills": [{"id": "research",@@ -158,7 +169,6 @@ def _with_auth(spec: dict) -> dict:("custom_template_tool",{- "model": "test/x","tools": [{"kind": "custom_template",@@ -172,25 +182,24 @@ def _with_auth(spec: dict) -> dict:# max_output_tokens is optional; runner picks a reasoning-aware default.("limits_max_output_tokens",- {"model": "test/x", "limits": {"max_output_tokens": 16384}},+ {"limits": {"max_output_tokens": 16384}},),# Bare-string secrets keep parsing (back-compat path); the runtime# http-request refuses to substitute them, but the spec itself is# still valid.("secrets_bare_string",- {"model": "test/x", "secrets": ["GITHUB_TOKEN"]},+ {"secrets": ["GITHUB_TOKEN"]},),# Object-form secret with allowed_hosts — the egress-binding shape.("secrets_with_allowed_hosts",- {"model": "test/x", "secrets": [{"name": "GH_PAT", "allowed_hosts": ["api.github.com"]}]},+ {"secrets": [{"name": "GH_PAT", "allowed_hosts": ["api.github.com"]}]},),# Mixed bare + object forms in the same spec — common during migration.("secrets_mixed_forms",{- "model": "test/x","secrets": ["LEGACY", {"name": "GH_PAT", "allowed_hosts": ["api.github.com", "*.github.com"]}],},),@@ -199,7 +208,10 @@ def _with_auth(spec: dict) -> dict:# promote, so authors may omit it.("identity_provider_principal_binding",- {"model": "test/x", "identity_providers": [{"kind": "posthog", "binding": "principal"}]},+ {+ "models": {"mode": "auto", "level": "low"},+ "identity_providers": [{"kind": "posthog", "binding": "principal"}],+ },),],)@@ -210,42 +222,60 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:@pytest.mark.parametrize(("name", "spec", "expected_substring"),[- # The exact case we hit today: a spec that looks like an application- # row (name/description) instead of a runtime config (model).- ("missing_model", {"name": "Hedgebox Helper"}, "model"),- # `model` must be a non-empty string. zod uses min(1); JSON Schema- # mirrors that via minLength.- ("empty_model", {"model": ""}, "model"),- # `model` must match `<provider>/<model-id>`; the runtime resolver- # demands the prefix and would otherwise crash sessions at first- # turn against any spec that slipped through with a bare id.- ("bare_model_id", {"model": "claude-haiku-4-5"}, "model"),- ("uppercase_provider", {"model": "Anthropic/claude-haiku-4-5"}, "model"),- ("missing_model_id", {"model": "anthropic/"}, "model"),+ # A spec that looks like an application row (name/description) instead+ # of a runtime config. `model` is optional now, so the rejection is on+ # the stray top-level `name` key (additionalProperties: false), not a+ # missing model.+ ("app_row_shaped", {"name": "Hedgebox Helper"}, "name"),+ # `model` is optional, but when present must be a non-empty string. zod+ # uses min(1); JSON Schema mirrors that via minLength.+ # models is a discriminated union on `mode`; an unknown mode+ # matches neither auto nor manual arm.+ ("models_bad_mode", {"models": {"mode": "cheapest"}}, "models"),+ # manual mode requires a non-empty `models` list.+ ("models_manual_empty", {"models": {"mode": "manual", "models": []}}, "models"),+ # Manual model ids MUST be `<provider>/<model-id>` — bare ids freeze+ # fine but the gateway 400s on first session. Pattern enforced here so+ # the author gets the error at authoring time.+ (+ "models_manual_bare_id",+ {"models": {"mode": "manual", "models": [{"model": "claude-haiku-4-5"}]}},+ "models",+ ),+ (+ "models_manual_uppercase_provider",+ {"models": {"mode": "manual", "models": [{"model": "Anthropic/claude-haiku-4-5"}]}},+ "models",+ ),+ (+ "models_manual_missing_model_id",+ {"models": {"mode": "manual", "models": [{"model": "anthropic/"}]}},+ "models",+ ),# `triggers` must be an array if present, not a string.- ("triggers_wrong_type", {"model": "test/x", "triggers": "all"}, "triggers"),+ ("triggers_wrong_type", {"triggers": "all"}, "triggers"),# Discriminated union: an unknown trigger type doesn't match any of# the chat/slack/webhook/cron/mcp variants.("unknown_trigger_type",- {"model": "test/x", "triggers": [{"type": "carrier_pigeon", "config": {}}]},+ {"triggers": [{"type": "carrier_pigeon", "config": {}}]},"triggers",),# Top-level `additionalProperties: false` should reject extra keys —# exactly the `name` / `description` case I tripped earlier.- ("extra_top_level_key", {"model": "test/x", "description": "agent"}, "description"),+ ("extra_top_level_key", {"description": "agent"}, "description"),# Non-defaulted nested fields must still be rejected when missing —# the relaxation only removes required-with-defaults, not all required.# jsonschema's `oneOf` error doesn't surface which arm failed for what# reason; we just assert the trigger element itself is flagged.("slack_missing_trusted_workspaces",- {"model": "test/x", "triggers": [{"type": "slack", "config": {"mention_only": False}}]},+ {"triggers": [{"type": "slack", "config": {"mention_only": False}}]},"triggers.0",),("cron_missing_schedule",- {"model": "test/x", "triggers": [{"type": "cron", "config": {"timezone": "UTC"}}]},+ {"triggers": [{"type": "cron", "config": {"timezone": "UTC"}}]},"triggers.0",),# Duplicate tool names in `mcps[].external.tools[]` — JSON Schema can't@@ -254,7 +284,6 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:("external_mcp_duplicate_tool_strings",{- "model": "test/x","mcps": [{"id": "linear",@@ -270,7 +299,6 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:("external_mcp_duplicate_tool_string_and_object",{- "model": "test/x","mcps": [{"id": "linear",@@ -287,12 +315,12 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:# spec never reaches the DB in the first place.("cron_missing_prompt",- {"model": "test/x", "triggers": [{"type": "cron", "config": {"name": "sweep", "schedule": "0 9 * * *"}}]},+ {"triggers": [{"type": "cron", "config": {"name": "sweep", "schedule": "0 9 * * *"}}]},"triggers.0",),("cron_missing_name",- {"model": "test/x", "triggers": [{"type": "cron", "config": {"schedule": "0 9 * * *", "prompt": "go"}}]},+ {"triggers": [{"type": "cron", "config": {"schedule": "0 9 * * *", "prompt": "go"}}]},"triggers.0",),# spec.secrets[] object form must declare allowed_hosts. An object@@ -301,7 +329,7 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:# explicit way to say that.("secrets_object_missing_allowed_hosts",- {"model": "test/x", "secrets": [{"name": "GH_PAT"}]},+ {"secrets": [{"name": "GH_PAT"}]},"secrets",),# An empty allowed_hosts means "bound to nothing" — not what an@@ -309,7 +337,7 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:# bare-string form.("secrets_empty_allowed_hosts",- {"model": "test/x", "secrets": [{"name": "GH_PAT", "allowed_hosts": []}]},+ {"secrets": [{"name": "GH_PAT", "allowed_hosts": []}]},"secrets",),# identity_providers: the `agent` binding (one app-scoped credential@@ -317,7 +345,10 @@ def test_validate_spec_accepts_valid_payloads(name: str, spec: dict) -> None:# rejects it until it lands — kept in lockstep with the zod enum.("identity_provider_agent_binding_rejected",- {"model": "test/x", "identity_providers": [{"kind": "posthog", "binding": "agent"}]},+ {+ "models": {"mode": "auto", "level": "low"},+ "identity_providers": [{"kind": "posthog", "binding": "agent"}],+ },"identity_providers",),],@@ -329,7 +360,6 @@ def test_validate_spec_rejects_invalid_payloads(name: str, spec: dict, expected__SLACK_SPEC = {- "model": "test/x","triggers": [{"type": "slack", "config": {"trusted_workspaces": "*"}}],}@@ -357,7 +387,7 @@ def test_missing_required_secrets_for_slack_trigger(name: str, env: dict, expectdef test_missing_required_secrets_skips_triggers_without_requirements() -> None:- spec = {"model": "test/x", "triggers": [{"type": "chat", "config": {}}]}+ spec = {"triggers": [{"type": "chat", "config": {}}]}assert missing_required_secrets(spec, {}) == []diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.tsindex d8a20650ce44..612eabd1563c 100644--- a/products/agent_platform/frontend/generated/api.schemas.ts+++ b/products/agent_platform/frontend/generated/api.schemas.ts@@ -244,6 +244,39 @@ export interface SkillRefApi {version?: number}+/**+ * How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns.+ */+export type AgentRevisionApiSpecModels =+ | {+ mode: 'auto'+ /** Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start. */+ level?: 'low' | 'medium' | 'high'+ /** Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default. */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'+ /** Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend. */+ optimize_for?: 'cost' | 'availability'+ }+ | {+ mode: 'manual'+ /**+ * Explicit priority-ordered fallback list — the runner tries entries in order (primary first).+ * @minItems 1+ */+ models: {+ /**+ * Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).+ * @minLength 1+ * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$+ */+ model: string+ /** Per-model reasoning effort override (else the spec default). */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'+ }[]+ /** Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold). */+ optimize_for?: 'cost' | 'availability'+ }+export type AgentRevisionApiSpecTriggersItem =| {type: 'slack'@@ -567,11 +600,8 @@ export type AgentRevisionApiSpecResume = {}export type AgentRevisionApiSpec = {- /**- * @minLength 1- * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$- */- model: string+ /** How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns. */+ models: AgentRevisionApiSpecModelstriggers: AgentRevisionApiSpecTriggersItem[]tools: AgentRevisionApiSpecToolsItem[]mcps: AgentRevisionApiSpecMcpsItem[]@@ -579,7 +609,6 @@ export type AgentRevisionApiSpec = {identity_providers?: AgentRevisionApiSpecIdentityProvidersItem[]secrets: AgentRevisionApiSpecSecretsItem[]limits: AgentRevisionApiSpecLimits- entrypoint: stringreasoning?: AgentRevisionApiSpecReasoningframework_prompt?: AgentRevisionApiSpecFrameworkPromptresume?: AgentRevisionApiSpecResume@@ -628,6 +657,39 @@ export interface PaginatedAgentRevisionListApi {results: AgentRevisionApi[]}+/**+ * How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns.+ */+export type PatchedAgentRevisionApiSpecModels =+ | {+ mode: 'auto'+ /** Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start. */+ level?: 'low' | 'medium' | 'high'+ /** Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default. */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'+ /** Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend. */+ optimize_for?: 'cost' | 'availability'+ }+ | {+ mode: 'manual'+ /**+ * Explicit priority-ordered fallback list — the runner tries entries in order (primary first).+ * @minItems 1+ */+ models: {+ /**+ * Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).+ * @minLength 1+ * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$+ */+ model: string+ /** Per-model reasoning effort override (else the spec default). */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'+ }[]+ /** Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold). */+ optimize_for?: 'cost' | 'availability'+ }+export type PatchedAgentRevisionApiSpecTriggersItem =| {type: 'slack'@@ -973,11 +1035,8 @@ export type PatchedAgentRevisionApiSpecResume = {}export type PatchedAgentRevisionApiSpec = {- /**- * @minLength 1- * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$- */- model: string+ /** How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns. */+ models: PatchedAgentRevisionApiSpecModelstriggers: PatchedAgentRevisionApiSpecTriggersItem[]tools: PatchedAgentRevisionApiSpecToolsItem[]mcps: PatchedAgentRevisionApiSpecMcpsItem[]@@ -985,7 +1044,6 @@ export type PatchedAgentRevisionApiSpec = {identity_providers?: PatchedAgentRevisionApiSpecIdentityProvidersItem[]secrets: PatchedAgentRevisionApiSpecSecretsItem[]limits: PatchedAgentRevisionApiSpecLimits- entrypoint: stringreasoning?: PatchedAgentRevisionApiSpecReasoningframework_prompt?: PatchedAgentRevisionApiSpecFrameworkPromptresume?: PatchedAgentRevisionApiSpecResume@@ -1161,7 +1219,7 @@ export interface AgentRevisionSystemPromptResponseApi {revision_id: string/** Active framework preamble version. Bumps when the platform's `# Platform guidance` content changes meaningfully (decision rules, sections renamed, behavioural defaults flipped). Authors can pin to a specific version via `spec.framework_prompt.version_pin`. */framework_prompt_version: number- /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md` (or `spec.entrypoint`), and the skills index. Inspect before promotion to confirm the model will see what you expect. */+ /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md`, and the skills index. Inspect before promotion to confirm the model will see what you expect. */system_prompt: string}diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.tsindex cb29f5e7a99e..56458afcc9d5 100644--- a/products/agent_platform/frontend/generated/api.ts+++ b/products/agent_platform/frontend/generated/api.ts@@ -1325,7 +1325,7 @@ export const getAgentApplicationsRevisionsValidateCreateUrl = (}/**- * Pre-flight checks before freeze + promote: entrypoint file exists,+ * Pre-flight checks before freeze + promote: agent.md exists,* every native tool id is registered, every custom tool has its* compiled.js + schema.json, every skill path exists, every declared* secret has a value set in this revision's env block. Returns@@ -1968,6 +1968,23 @@ export const agentApplicationsUsersConnectionDelete = async (})}+export const getAgentApplicationsModelsUrl = (projectId: string) => {+ return `/api/projects/${projectId}/agent_applications/models/`+}++/**+ * Served-model catalog — each model's id, provider, context window, and USD-per-million-token pricing — plus the curated auto-level → model map. Project-agnostic; sourced from the AI gateway catalog. Powers the config UI model browser and the agent builder's model-choosing skill.+ */+export const agentApplicationsModels = async (+ projectId: string,+ options?: RequestInit+): Promise<AgentApplicationApi> => {+ return apiMutator<AgentApplicationApi>(getAgentApplicationsModelsUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getAgentFleetApprovalsListUrl = (projectId: string, params?: AgentFleetApprovalsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.tsindex 3c5479a302a2..d7b09ec7375a 100644--- a/products/agent_platform/frontend/generated/api.zod.ts+++ b/products/agent_platform/frontend/generated/api.zod.ts@@ -105,8 +105,19 @@ export const AgentMemoryUpdateFileBody = /* @__PURE__ */ zod* PUT .../revisions/<id>/bundle/ bulk push (replace|merge)*/export const agentApplicationsRevisionsCreateBodyBundleUriDefault = ``+export const agentApplicationsRevisionsCreateBodySpecModelsOneLevelDefault = `medium`+export const agentApplicationsRevisionsCreateBodySpecModelsOneOptimizeForDefault = `cost`-export const agentApplicationsRevisionsCreateBodySpecModelRegExp = new RegExp('^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$')+export const agentApplicationsRevisionsCreateBodySpecModelsTwoModelsItemModelRegExp = new RegExp(+ '^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$'+)++export const agentApplicationsRevisionsCreateBodySpecModelsTwoOptimizeForDefault = `cost`+export const agentApplicationsRevisionsCreateBodySpecModelsDefault = {+ mode: 'auto' as const,+ level: 'medium' as const,+ optimize_for: 'cost' as const,+}export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault = falseexport const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = falseexport const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false@@ -203,7 +214,6 @@ export const agentApplicationsRevisionsCreateBodySpecLimitsDefault = {max_memory_mb: 512,max_cpu_cores: 0.25,}-export const agentApplicationsRevisionsCreateBodySpecEntrypointDefault = `agent.md`export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptOmitDefault = []export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptVersionPinExclusiveMin = 0export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptVersionPinMax = 2147483647@@ -223,7 +233,63 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({),spec: zod.object({- model: zod.string().min(1).regex(agentApplicationsRevisionsCreateBodySpecModelRegExp),+ models: zod+ .union([+ zod.object({+ mode: zod.literal('auto'),+ level: zod+ .enum(['low', 'medium', 'high'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsOneLevelDefault)+ .describe(+ 'Quality\/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe(+ 'Reasoning\/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider\/spec default.'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsOneOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long\/expensive sessions, `availability` where uptime matters more than spend."+ ),+ }),+ zod.object({+ mode: zod.literal('manual'),+ models: zod+ .array(+ zod.object({+ model: zod+ .string()+ .min(1)+ .regex(agentApplicationsRevisionsCreateBodySpecModelsTwoModelsItemModelRegExp)+ .describe(+ 'Canonical model id, e.g. `anthropic\/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe('Per-model reasoning effort override (else the spec default).'),+ })+ )+ .min(1)+ .describe(+ 'Explicit priority-ordered fallback list — the runner tries entries in order (primary first).'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsTwoOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold)."+ ),+ }),+ ])+ .default(agentApplicationsRevisionsCreateBodySpecModelsDefault)+ .describe(+ "How this agent selects its model. `auto`: pick a quality\/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."+ ),triggers: zod.array(zod.union([@@ -673,7 +739,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({.default(agentApplicationsRevisionsCreateBodySpecLimitsMaxCpuCoresDefault),}).default(agentApplicationsRevisionsCreateBodySpecLimitsDefault),- entrypoint: zod.string().default(agentApplicationsRevisionsCreateBodySpecEntrypointDefault),reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),framework_prompt: zod.object({@@ -714,8 +779,19 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({* ready/live the spec is frozen — change requires a new revision.*/export const agentApplicationsRevisionsUpdateBodyBundleUriDefault = ``+export const agentApplicationsRevisionsUpdateBodySpecModelsOneLevelDefault = `medium`+export const agentApplicationsRevisionsUpdateBodySpecModelsOneOptimizeForDefault = `cost`++export const agentApplicationsRevisionsUpdateBodySpecModelsTwoModelsItemModelRegExp = new RegExp(+ '^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$'+)-export const agentApplicationsRevisionsUpdateBodySpecModelRegExp = new RegExp('^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$')+export const agentApplicationsRevisionsUpdateBodySpecModelsTwoOptimizeForDefault = `cost`+export const agentApplicationsRevisionsUpdateBodySpecModelsDefault = {+ mode: 'auto' as const,+ level: 'medium' as const,+ optimize_for: 'cost' as const,+}export const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = falseexport const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = falseexport const agentApplicationsRevisionsUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false@@ -812,7 +888,6 @@ export const agentApplicationsRevisionsUpdateBodySpecLimitsDefault = {max_memory_mb: 512,max_cpu_cores: 0.25,}-export const agentApplicationsRevisionsUpdateBodySpecEntrypointDefault = `agent.md`export const agentApplicationsRevisionsUpdateBodySpecFrameworkPromptOmitDefault = []export const agentApplicationsRevisionsUpdateBodySpecFrameworkPromptVersionPinExclusiveMin = 0export const agentApplicationsRevisionsUpdateBodySpecFrameworkPromptVersionPinMax = 2147483647@@ -832,7 +907,63 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({),spec: zod.object({- model: zod.string().min(1).regex(agentApplicationsRevisionsUpdateBodySpecModelRegExp),+ models: zod+ .union([+ zod.object({+ mode: zod.literal('auto'),+ level: zod+ .enum(['low', 'medium', 'high'])+ .default(agentApplicationsRevisionsUpdateBodySpecModelsOneLevelDefault)+ .describe(+ 'Quality\/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe(+ 'Reasoning\/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider\/spec default.'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsUpdateBodySpecModelsOneOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long\/expensive sessions, `availability` where uptime matters more than spend."+ ),+ }),+ zod.object({+ mode: zod.literal('manual'),+ models: zod+ .array(+ zod.object({+ model: zod+ .string()+ .min(1)+ .regex(agentApplicationsRevisionsUpdateBodySpecModelsTwoModelsItemModelRegExp)+ .describe(+ 'Canonical model id, e.g. `anthropic\/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe('Per-model reasoning effort override (else the spec default).'),+ })+ )+ .min(1)+ .describe(+ 'Explicit priority-ordered fallback list — the runner tries entries in order (primary first).'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsUpdateBodySpecModelsTwoOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold)."+ ),+ }),+ ])+ .default(agentApplicationsRevisionsUpdateBodySpecModelsDefault)+ .describe(+ "How this agent selects its model. `auto`: pick a quality\/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."+ ),triggers: zod.array(zod.union([@@ -1282,7 +1413,6 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({.default(agentApplicationsRevisionsUpdateBodySpecLimitsMaxCpuCoresDefault),}).default(agentApplicationsRevisionsUpdateBodySpecLimitsDefault),- entrypoint: zod.string().default(agentApplicationsRevisionsUpdateBodySpecEntrypointDefault),reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),framework_prompt: zod.object({@@ -1346,8 +1476,19 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({* PUT .../revisions/<id>/bundle/ bulk push (replace|merge)*/export const agentApplicationsRevisionsPartialUpdateBodyBundleUriDefault = ``+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsOneLevelDefault = `medium`+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsOneOptimizeForDefault = `cost`++export const agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoModelsItemModelRegExp = new RegExp(+ '^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$'+)-export const agentApplicationsRevisionsPartialUpdateBodySpecModelRegExp = new RegExp('^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$')+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoOptimizeForDefault = `cost`+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsDefault = {+ mode: 'auto' as const,+ level: 'medium' as const,+ optimize_for: 'cost' as const,+}export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false@@ -1444,7 +1585,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault = {max_memory_mb: 512,max_cpu_cores: 0.25,}-export const agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault = `agent.md`export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptOmitDefault = []export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptVersionPinExclusiveMin = 0export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptVersionPinMax = 2147483647@@ -1464,7 +1604,65 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o),spec: zod.object({- model: zod.string().min(1).regex(agentApplicationsRevisionsPartialUpdateBodySpecModelRegExp),+ models: zod+ .union([+ zod.object({+ mode: zod.literal('auto'),+ level: zod+ .enum(['low', 'medium', 'high'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsOneLevelDefault)+ .describe(+ 'Quality\/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe(+ 'Reasoning\/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider\/spec default.'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsOneOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long\/expensive sessions, `availability` where uptime matters more than spend."+ ),+ }),+ zod.object({+ mode: zod.literal('manual'),+ models: zod+ .array(+ zod.object({+ model: zod+ .string()+ .min(1)+ .regex(+ agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoModelsItemModelRegExp+ )+ .describe(+ 'Canonical model id, e.g. `anthropic\/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe('Per-model reasoning effort override (else the spec default).'),+ })+ )+ .min(1)+ .describe(+ 'Explicit priority-ordered fallback list — the runner tries entries in order (primary first).'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold)."+ ),+ }),+ ])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsDefault)+ .describe(+ "How this agent selects its model. `auto`: pick a quality\/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."+ ),triggers: zod.array(zod.union([@@ -1936,7 +2134,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o.default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxCpuCoresDefault),}).default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault),- entrypoint: zod.string().default(agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault),reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),framework_prompt: zod.object({diff --git a/products/agent_platform/services/agent-janitor/src/config.ts b/products/agent_platform/services/agent-janitor/src/config.tsindex a8bfd9ffcc5e..6c15ca01d121 100644--- a/products/agent_platform/services/agent-janitor/src/config.ts+++ b/products/agent_platform/services/agent-janitor/src/config.ts@@ -149,6 +149,17 @@ export const AgentJanitorConfigSchema = PlatformConfigSchema.extend({.describe('forcePathStyle for the S3 client. Default true (SeaweedFS + MinIO both need it; real S3 accepts it).'),+ aiGatewayUrl: z+ .string()+ .url()+ .default(() => (isDev() ? 'http://localhost:8080/v1' : 'http://ai-gateway/v1'))+ .describe(+ 'AI gateway base URL (incl. /v1) — the SAME gateway the runner dispatches against. The model-catalog read for models validation hits {url}/models.'+ ),+ posthogAiGatewayKey: z+ .string()+ .optional()+ .describe('Optional phs_ bearer for the model-catalog read; /models is otherwise unauthenticated.'),})export type AgentJanitorConfig = z.infer<typeof AgentJanitorConfigSchema>@@ -177,6 +188,8 @@ const ENV_KEY_MAP = extendEnvKeyMap<AgentJanitorConfig>(PLATFORM_ENV_KEY_MAP, {AGENT_BUNDLE_S3_ACCESS_KEY_ID: 'bundleS3AccessKeyId',AGENT_BUNDLE_S3_SECRET_ACCESS_KEY: 'bundleS3SecretAccessKey',AGENT_BUNDLE_S3_FORCE_PATH_STYLE: 'bundleS3ForcePathStyle',+ POSTHOG_AI_GATEWAY_URL: 'aiGatewayUrl',+ POSTHOG_AI_GATEWAY_KEY: 'posthogAiGatewayKey',})export function loadAgentJanitorConfig(env: NodeJS.ProcessEnv = process.env): AgentJanitorConfig {diff --git a/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts b/products/agent_platform/services/agent-janitor/src/cron-tick.test.tsindex 47b14e1eb9c2..ea634c735772 100644--- a/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts+++ b/products/agent_platform/services/agent-janitor/src/cron-tick.test.ts@@ -68,7 +68,7 @@ async function deploy(created_by_id: null,bundle_uri: 's3://x/',spec: AgentSpecSchema.parse({- model: 'anthropic/claude-haiku-4-5',+ models: { mode: 'manual', models: [{ model: 'anthropic/claude-haiku-4-5' }] },triggers: opts.triggers,}),})diff --git a/products/agent_platform/services/agent-janitor/src/index.ts b/products/agent_platform/services/agent-janitor/src/index.tsindex 85e28c0eb321..d1c881c69145 100644--- a/products/agent_platform/services/agent-janitor/src/index.ts+++ b/products/agent_platform/services/agent-janitor/src/index.ts@@ -23,6 +23,8 @@ import {createLogger,createMetricsServer,createModalSandboxTerminator,+ DirectHttpClient,+ HttpGatewayCatalog,initMetrics,installProcessHandlers,isDev,@@ -154,6 +156,15 @@ async function main(): Promise<void> {'memory.s3.enabled')+ // Served-model catalog off the same gateway the runner uses — validate ++ // freeze reject a models the gateway can't serve. DirectHttpClient:+ // cluster-internal, smokescreen would deny it.+ const gatewayCatalog = new HttpGatewayCatalog({+ baseUrl: config.aiGatewayUrl,+ bearer: config.posthogAiGatewayKey,+ http: new DirectHttpClient(),+ })+const app = buildJanitorApp({queue,sweep,@@ -163,6 +174,7 @@ async function main(): Promise<void> {memoryStore,tabularStore,identityAdmin,+ gatewayCatalog,internalSigningKey: config.internalSigningKey,})app.listen(config.port, () => {diff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.tsindex 198a528bedda..32d327969c4f 100644--- a/products/agent_platform/services/agent-janitor/src/server.test.ts+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts@@ -18,6 +18,7 @@ import {AgentSession,AgentSpecSchema,buildTestBundleStore,+ type CatalogModel,EMPTY_USAGE_TOTAL,INTERNAL_JWT_AUDIENCE,mintInternalJwt,@@ -100,6 +101,77 @@ describe('janitor HTTP', () => {expect(res.status).toBe(200)})+ it('GET /models returns per-Mtok pricing + levels resolved to canonical ids', async () => {+ // haiku is dated-only with a dashed undated alias — the form the level+ // list uses; resolution must map it to the catalog canonical.+ const catalog: CatalogModel[] = [+ {+ canonical: 'anthropic/claude-haiku-4.5',+ id: 'claude-haiku-4-5-20251001',+ owned_by: 'anthropic',+ context_window: 200_000,+ aliases: ['claude-haiku-4-5'],+ pricing: { prompt: 0.000001, completion: 0.000005, cache_read: 0.0000001 },+ },+ {+ canonical: 'openai/gpt-5-mini',+ id: 'gpt-5-mini',+ owned_by: 'openai',+ context_window: 400_000,+ aliases: [],+ pricing: { prompt: 0.00000025, completion: 0.000002 },+ },+ {+ canonical: 'anthropic/claude-opus-4.7',+ id: 'claude-opus-4-7',+ owned_by: 'anthropic',+ context_window: 1_000_000,+ aliases: [],+ pricing: { prompt: 0.000005, completion: 0.000025 },+ },+ {+ canonical: 'openai/gpt-5-pro',+ id: 'gpt-5-pro',+ owned_by: 'openai',+ context_window: 400_000,+ aliases: [],+ pricing: { prompt: 0.000015, completion: 0.00012 },+ },+ ]+ const queue = new PgSessionQueue(pool)+ const app = buildJanitorApp({+ queue,+ sweep: { queue, stuckRunningThresholdMs: 60_000 },+ gatewayCatalog: { list: async () => catalog },+ })++ const res = await request(app).get('/models')+ expect(res.status).toBe(200)+ const haiku = (res.body.models as Array<Record<string, unknown>>).find(+ (m) => m.model === 'anthropic/claude-haiku-4.5'+ )+ // Per-token USD → per-Mtok; cache omitted when the model has none.+ expect(haiku).toMatchObject({+ provider: 'anthropic',+ context_window: 200_000,+ input: 1,+ output: 5,+ cache_read: 0.1,+ })+ expect(haiku).not.toHaveProperty('cache_write')+ // Levels resolve the dashed-alias level entries to catalog canonicals.+ expect(res.body.levels.low).toEqual(['anthropic/claude-haiku-4.5', 'openai/gpt-5-mini'])+ expect(res.body.levels.high).toEqual(['anthropic/claude-opus-4.7', 'openai/gpt-5-pro'])+ })++ it('GET /models fails open with an empty catalog when no gateway is wired', async () => {+ const { app } = mk()+ const res = await request(app).get('/models')+ expect(res.status).toBe(200)+ expect(res.body.models).toEqual([])+ expect(Object.keys(res.body.levels)).toEqual(['low', 'medium', 'high'])+ })+it('GET /sessions?application_id= returns summaries, newest first', async () => {const { queue, app } = mk()const a = { ...session('s-a'), application_id: uuidFor('app-1'), created_at: '2026-05-01T00:00:00Z' }@@ -639,7 +711,7 @@ describe('janitor HTTP', () => {created_by_id: null,bundle_uri: 'mem://b',spec: AgentSpecSchema.parse({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{type: 'chat',@@ -691,7 +763,7 @@ describe('janitor HTTP', () => {created_by_id: null,bundle_uri: 'mem://b',spec: AgentSpecSchema.parse({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{type: 'cron',@@ -728,7 +800,7 @@ describe('janitor HTTP', () => {created_by_id: null,bundle_uri: 'mem://b',spec: AgentSpecSchema.parse({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{type: 'cron',@@ -892,7 +964,7 @@ describe('janitor HTTP', () => {apps[0].id,revisionId,JSON.stringify({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{ type: 'chat', config: {} }], // missing `auth`}),]@@ -921,7 +993,7 @@ describe('janitor HTTP', () => {apps[0].id,revisionId,JSON.stringify({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{ type: 'chat', config: {} }], // missing `auth`}),]@@ -933,7 +1005,7 @@ describe('janitor HTTP', () => {skills: [],tools: [],spec: {- model: 'test/y',+ models: { mode: 'manual', models: [{ model: 'test/y' }] },triggers: [{type: 'chat',@@ -948,7 +1020,7 @@ describe('janitor HTTP', () => {// parse it strictly, so a successful read proves the merge wrote a// valid spec.const after = await revisions.getRevision(draftId)- expect(after?.spec.model).toBe('test/y')+ expect(after?.spec.models).toEqual({ mode: 'manual', models: [{ model: 'test/y' }], optimize_for: 'cost' })})it('returns 503 when the revision/bundle stores are not configured', async () => {@@ -1033,7 +1105,7 @@ describe('janitor HTTP', () => {created_by_id: null,bundle_uri: 'mem://b',spec: AgentSpecSchema.parse({- model: 'test/x',+ models: { mode: 'manual', models: [{ model: 'test/x' }] },triggers: [{type: 'chat',diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.tsindex e18311ebbf80..592552739497 100644--- a/products/agent_platform/services/agent-janitor/src/server.ts+++ b/products/agent_platform/services/agent-janitor/src/server.ts@@ -45,6 +45,7 @@ import { randomUUID } from 'node:crypto'import { z } from 'zod'import {+ acceptedModelIds,accumulateUsage,AgentRevision,AgentRevisionRaw,@@ -52,6 +53,8 @@ import {AgentSpec,AgentSpecSchema,ApprovalRequest,+ CatalogModel,+ GatewayCatalog,ApprovalStore,applyApprovalDecision,BundleEntry,@@ -68,6 +71,7 @@ import {isDev,lastAssistantTextPreview,MemoryStore,+ MODEL_POLICY_LEVELS,PgIdentityAdminStore,readTypedBundle,RevisionStore,@@ -125,6 +129,9 @@ export interface JanitorServerOpts {* non-`/healthz` request. Unset → middleware is skipped (dev / harness).*/internalSigningKey?: string+ /** Served-model catalog. When set, `validate` + freeze reject a models+ * the gateway doesn't serve; omitted → the model check is skipped. */+ gatewayCatalog?: GatewayCatalog}const SessionStateSchema = z.enum(['queued', 'running', 'completed', 'closed', 'failed'])@@ -342,6 +349,52 @@ const DecideApprovalBodySchema = z.object({reason: z.string().optional(),})+interface CatalogModelRow {+ model: string+ provider: string+ context_window: number+ input: number+ output: number+ cache_read?: number+ cache_write?: number+}++/** Per-token USD → per-Mtok, rounded so the UI sees `3` not `0.0000030004`. */+function perMtok(perToken: number | undefined): number | undefined {+ return perToken === undefined ? undefined : Math.round(perToken * 1e6 * 1000) / 1000+}++function catalogToModels(catalog: CatalogModel[]): CatalogModelRow[] {+ return catalog+ .map((m) => {+ const row: CatalogModelRow = {+ model: m.canonical,+ provider: m.owned_by,+ context_window: m.context_window,+ input: perMtok(m.pricing.prompt) ?? 0,+ output: perMtok(m.pricing.completion) ?? 0,+ }+ const cacheRead = perMtok(m.pricing.cache_read)+ const cacheWrite = perMtok(m.pricing.cache_write)+ if (cacheRead !== undefined) {+ row.cache_read = cacheRead+ }+ if (cacheWrite !== undefined) {+ row.cache_write = cacheWrite+ }+ return row+ })+ .sort((a, b) => a.model.localeCompare(b.model))+}++/** Resolve each curated level's members to their catalog canonical id (the+ * level list uses alias forms); fall back to the raw id when the catalog is+ * empty or the model isn't served. */+function resolveLevels(catalog: CatalogModel[]): Record<string, string[]> {+ const canonicalFor = (id: string): string => catalog.find((m) => acceptedModelIds([m]).has(id))?.canonical ?? id+ return Object.fromEntries(Object.entries(MODEL_POLICY_LEVELS).map(([level, ids]) => [level, ids.map(canonicalFor)]))+}+export function buildJanitorApp(opts: JanitorServerOpts): Express {const app = express()// Dev only: serve /metrics on the request port (no dedicated scrape server —@@ -390,6 +443,20 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {res.json({ ok: true })})+ /* ───────────────────────────── models ─────────────────────────────── */+ // The served-model catalog (id, provider, context, pricing per Mtok) plus+ // the curated auto-level → model map, both from the single source the+ // runner/validation already use. Powers the config-UI model browser (via+ // Django REST) and, through the PostHog MCP, the agent builder's+ // model-choosing skill. Pricing-free on an unreachable gateway (empty list).+ app.get(+ '/models',+ asyncHandler(async (_req, res) => {+ const catalog = opts.gatewayCatalog ? await opts.gatewayCatalog.list() : []+ res.json({ models: catalogToModels(catalog), levels: resolveLevels(catalog) })+ })+ )+/* ───────────────────────────── sessions ───────────────────────────── */app.get(@@ -882,8 +949,9 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {}))const validateInput: AgentRevision = { ...ok.rev!, spec: derivedSpec }+ const freezeCatalog = opts.gatewayCatalog ? await opts.gatewayCatalog.list() : []const report = await instrument({ key: 'freeze.validate', log, context: ctx }, () =>- validateRevisionBundle(validateInput, opts.bundles!)+ validateRevisionBundle(validateInput, opts.bundles!, freezeCatalog))if (!report.ok) {res.status(422).json({ error: 'validation_failed', report })@@ -917,7 +985,8 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {res.status(404).json({ error: 'revision_not_found' })return}- const report = await validateRevisionBundle(rev, opts.bundles!)+ const validateCatalog = opts.gatewayCatalog ? await opts.gatewayCatalog.list() : []+ const report = await validateRevisionBundle(rev, opts.bundles!, validateCatalog)res.json(report)}))diff --git a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts b/products/agent_platform/services/agent-janitor/src/validate-spec.test.tsindex 736a395a29a6..4ac7d2714849 100644--- a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts+++ b/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts@@ -5,6 +5,7 @@ import {AgentRevision,AgentSpecSchema,buildTestBundleStore,+ type CatalogModel,newTestPrefix,S3BundleStore,wipeTestPrefix,@@ -46,7 +47,7 @@ function mkRev(spec: Partial<z.input<typeof AgentSpecSchema>> = {}): AgentRevisibundle_uri: 'mem://',bundle_sha256: null,spec: AgentSpecSchema.parse({- model: 'anthropic/claude-haiku-4-5',+ models: { mode: 'manual', models: [{ model: 'anthropic/claude-haiku-4-5' }] },triggers: [{ type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },],@@ -66,24 +67,47 @@ describe('validateRevisionBundle', () => {expect(report.resolved_natives).toEqual([])})+ it('flags a manual model the gateway does not serve; passes one it does', async () => {+ const bundles = makeBundles()+ await bundles.write('rev1', 'agent.md', 'hi')+ const catalog: CatalogModel[] = [+ {+ canonical: 'anthropic/claude-haiku-4.5',+ id: 'claude-haiku-4-5-20251001',+ aliases: ['claude-haiku-4-5'],+ owned_by: 'anthropic',+ context_window: 200_000,+ pricing: { prompt: 0.000001, completion: 0.000005 },+ },+ ]+ const bad = mkRev({ models: { mode: 'manual', models: [{ model: 'openai/gpt-nope' }] } })+ const badReport = await validateRevisionBundle(bad, bundles, catalog)+ expect(badReport.ok).toBe(false)+ expect(badReport.errors).toContainEqual(+ expect.objectContaining({ code: 'invalid_model', pointer: 'spec.models.models[0].model' })+ )+ // the default rev's haiku model resolves against this catalog+ const good = await validateRevisionBundle(mkRev(), bundles, catalog)+ expect(good.errors.filter((e) => e.code === 'invalid_model')).toEqual([])+ })++ it('fails open on the model check when no catalog is supplied', async () => {+ const bundles = makeBundles()+ await bundles.write('rev1', 'agent.md', 'hi')+ const rev = mkRev({ models: { mode: 'manual', models: [{ model: 'made/up' }] } })+ const report = await validateRevisionBundle(rev, bundles)+ expect(report.errors.filter((e) => e.code === 'invalid_model')).toEqual([])+ })+it('reports missing_entrypoint when agent.md is absent', async () => {const bundles = makeBundles()const report = await validateRevisionBundle(mkRev(), bundles)expect(report.ok).toBe(false)expect(report.errors).toEqual([- { code: 'missing_entrypoint', message: expect.stringContaining('agent.md'), pointer: 'spec.entrypoint' },+ { code: 'missing_entrypoint', message: expect.stringContaining('agent.md'), pointer: 'agent.md' },])})- it('honors a custom spec.entrypoint', async () => {- const bundles = makeBundles()- await bundles.write('rev1', 'prompts/main.md', 'hi')- const ok = await validateRevisionBundle(mkRev({ entrypoint: 'prompts/main.md' }), bundles)- expect(ok.ok).toBe(true)- const miss = await validateRevisionBundle(mkRev({ entrypoint: 'prompts/other.md' }), bundles)- expect(miss.errors[0].code).toBe('missing_entrypoint')- })-it('catches unknown native tool ids and resolves valid ones', async () => {const bundles = makeBundles()await bundles.write('rev1', 'agent.md', 'hi')@@ -240,7 +264,7 @@ describe('validateRevisionBundle', () => {expect(report.errors).toEqual([{code: 'secret_no_host_binding',- pointer: 'spec.entrypoint',+ pointer: 'agent.md',message: expect.stringContaining('SLACK_BOT_TOKEN'),},])diff --git a/products/agent_platform/services/agent-janitor/src/validate-spec.ts b/products/agent_platform/services/agent-janitor/src/validate-spec.tsindex e66438858032..69edbb818d26 100644--- a/products/agent_platform/services/agent-janitor/src/validate-spec.ts+++ b/products/agent_platform/services/agent-janitor/src/validate-spec.ts@@ -16,7 +16,14 @@import cronParser from 'cron-parser'-import { AgentRevision, AgentSpec, BundleStore, getSecretAllowedHosts } from '@posthog/agent-shared'+import {+ AgentRevision,+ AgentSpec,+ BundleStore,+ type CatalogModel,+ getSecretAllowedHosts,+ validateModelPolicy,+} from '@posthog/agent-shared'import { hasNativeTool } from '@posthog/agent-tools'export type ValidationCode =@@ -29,6 +36,7 @@ export type ValidationCode =| 'duplicate_cron_name'| 'unknown_cron_placeholder'| 'secret_no_host_binding'+ | 'invalid_model'| 'required_client_tool_with_non_chat_trigger'/**@@ -98,7 +106,11 @@ export interface ValidationReport {resolved_natives: string[]}-export async function validateRevisionBundle(rev: AgentRevision, bundle: BundleStore): Promise<ValidationReport> {+export async function validateRevisionBundle(+ rev: AgentRevision,+ bundle: BundleStore,+ catalogModels: CatalogModel[] = []+): Promise<ValidationReport> {const errors: ValidationError[] = []const warnings: ValidationWarning[] = []const resolvedNatives: string[] = []@@ -114,12 +126,22 @@ export async function validateRevisionBundle(rev: AgentRevision, bundle: BundleS})}- const entrypoint = rev.spec.entrypoint || 'agent.md'- if (!(await bundle.exists(rev.id, entrypoint))) {+ if (!(await bundle.exists(rev.id, 'agent.md'))) {errors.push({code: 'missing_entrypoint',- message: `entrypoint "${entrypoint}" is not present in the bundle`,- pointer: 'spec.entrypoint',+ message: 'agent.md is not present in the bundle',+ pointer: 'agent.md',+ })+ }++ // models must reference models the gateway serves — catch it at freeze,+ // not as a runtime 400 in a user's session. Fails open on an empty+ // (unreachable) catalog; see gateway-catalog.ts.+ for (const issue of validateModelPolicy(rev.spec.models, catalogModels)) {+ errors.push({+ code: 'invalid_model',+ message: `models: "${issue.model}" ${issue.reason}`,+ pointer: issue.pointer,})}@@ -263,13 +285,13 @@ const SECRET_REF = /\$\{([A-Z][A-Z0-9_]*)\}/ginterface ScanTarget {path: string- /** Where the error attaches — `spec.entrypoint` or `spec.skills[i].path`. */+ /** Where the error attaches — `agent.md` or `spec.skills[i].path`. */pointer: string}/**- * Cross-check spec.secrets[] against `${NAME}` references in the agent.md- * entrypoint and each declared skill body. A reference to a bare-string+ * Cross-check spec.secrets[] against `${NAME}` references in agent.md+ * and each declared skill body. A reference to a bare-string* `spec.secrets[]` entry is `secret_no_host_binding` at session start (the* runtime refuses substitution into model-controlled URL/headers/body), so* catch it here instead of letting it surface as a tool error on first call.@@ -283,7 +305,7 @@ async function checkSecretHostBindings(bundle: BundleStore,errors: ValidationError[]): Promise<void> {- const targets: ScanTarget[] = [{ path: rev.spec.entrypoint || 'agent.md', pointer: 'spec.entrypoint' }]+ const targets: ScanTarget[] = [{ path: 'agent.md', pointer: 'agent.md' }]for (const [i, skill] of rev.spec.skills.entries()) {targets.push({ path: skill.path, pointer: `spec.skills[${i}].path` })}diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.tsindex 2adfe1e4ca15..6d34c7aadfb3 100644--- a/products/agent_platform/services/agent-runner/src/index.ts+++ b/products/agent_platform/services/agent-runner/src/index.ts@@ -32,6 +32,7 @@ import {createMetricsServer,handleMetricsRequest,HttpClient,+ HttpGatewayCatalog,HttpGatewayClient,initMetrics,installProcessHandlers,@@ -217,6 +218,17 @@ async function main(): Promise<void> {? new HttpGatewayClient({ baseUrl: config.aiGatewayUrl, http: new DirectHttpClient() }): null+ // Served-model catalog off the same gateway the data plane uses — source of+ // truth for models resolution + the models tool. DirectHttpClient:+ // cluster-internal, smokescreen would deny it.+ const gatewayCatalog = config.useAiGateway+ ? new HttpGatewayCatalog({+ baseUrl: config.aiGatewayUrl,+ bearer: config.posthogAiGatewayKey,+ http: new DirectHttpClient(),+ })+ : undefined+// Agent memory: S3-backed file store. Required everywhere — the runner// refuses to boot without it so the `@posthog/memory-*` + `@posthog/table-*`// tools always work the same way in dev as in prod. Bucket + endpoint are@@ -323,6 +335,7 @@ async function main(): Promise<void> {apiKey: config.posthogAiGatewayKey!,}): undefined,+ gatewayCatalog,// Per-session bearer for pi-ai's `streamSimple` (no client-level default).// Gateway path → the static phs_ (cost bills to the team that owns it);// direct path → boot-time provider key (ANTHROPIC_API_KEY / OPENAI / etc).diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.tsindex d5fe10df55d3..3b09bd0bc8c0 100644--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts@@ -34,6 +34,7 @@ import {type ApprovalType,BundleStore,CredentialBroker,+ GatewayCatalog,getSecretAllowedHosts,HttpFetcher,IdentityAuthRequiredError,@@ -175,6 +176,10 @@ export interface AgentToolDeps {* against. Forwarded straight onto `ToolContext.posthogApiBaseUrl`.*/posthogApiBaseUrl: string+ /** Gateway model catalog, forwarded onto `ToolContext.gatewayCatalog` for+ * the `@posthog/agent-applications-models` tool. Absent when the gateway+ * is disabled. */+ gatewayCatalog?: GatewayCatalog}export interface BuiltAgentTools {@@ -572,6 +577,7 @@ function buildToolContext(deps: AgentToolDeps, resolvedIdentities?: ToolContext[resolvedIdentities,http: deps.http,posthogApiBaseUrl: deps.posthogApiBaseUrl,+ gatewayCatalog: deps.gatewayCatalog,}}diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.tsindex 90f54cdf815f..36e2c2439180 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts@@ -1,6 +1,8 @@import type { S3Client } from '@aws-sdk/client-s3'import {type AssistantMessage,+ type AssistantMessageEvent,+ createAssistantMessageEventStream,fauxAssistantMessage,fauxToolCall,type Model,@@ -168,7 +170,7 @@ async function run(await seedSessionRow(session)}return runSession(rev, session, {- model: fauxModel((over.script as AssistantMessage[]) ?? [stop('ok')]),+ models: [{ model: fauxModel((over.script as AssistantMessage[]) ?? [stop('ok')]) }],bundle,sandbox: null,secrets: {},@@ -788,6 +790,162 @@ describe('driver runSession', () => {})})+ /**+ * Multi-model fallback. The driver wraps the base streamFn with+ * `fallbackStreamFn` whenever `models.length > 1`. A pre-commit transient+ * failure on the primary falls over to the next model; a single-model spec+ * skips the wrapper entirely (legacy behaviour).+ */+ describe('multi-model fallback', () => {+ // A streamFn that fails model `a` once (pre-commit 429) then answers on+ // model `b`. Mirrors the faux provider's `start`→`error` shape so the+ // commit guard treats it as a pre-commit failure.+ const fallbackStreamFn = (): Parameters<typeof runSession>[2]['streamFn'] => {+ return (model) => {+ const stream = createAssistantMessageEventStream()+ queueMicrotask(() => {+ if (model.id === 'a') {+ const errored = fauxAssistantMessage('', {+ stopReason: 'error',+ errorMessage: '429 rate limit',+ })+ const evs: AssistantMessageEvent[] = [+ { type: 'start', partial: fauxAssistantMessage('') },+ { type: 'error', reason: 'error', error: errored },+ ]+ for (const e of evs) {+ stream.push(e)+ }+ stream.end(errored)+ return+ }+ const done = fauxAssistantMessage('recovered', { stopReason: 'stop' })+ const partial = { ...done }+ const evs: AssistantMessageEvent[] = [+ { type: 'start', partial: fauxAssistantMessage('') },+ { type: 'text_delta', contentIndex: 0, delta: 'recovered', partial },+ { type: 'done', reason: 'stop', message: done },+ ]+ for (const e of evs) {+ stream.push(e)+ }+ stream.end(done)+ })+ return stream+ }+ }++ it('falls over to the second model on a transient primary failure', async () => {+ const session = makeSession()+ const out = await run(makeRev(), session, {+ models: [{ model: fauxModel([stop('x')]) }, { model: fauxModel([stop('y')]) }].map((m, i) => ({+ // Distinct ids so the streamFn can route per attempt.+ model: { ...m.model, id: i === 0 ? 'a' : 'b' },+ })),+ streamFn: fallbackStreamFn(),+ })+ // The session completed on the fallback model's answer.+ expect(out.state).toBe('completed')+ const last = session.conversation.at(-1) as { role: string; content: unknown }+ expect(last.role).toBe('assistant')+ })++ it('tags the direct-path $ai_generation with the fallback attempt + fallback_from', async () => {+ // The observability contract for the feature: after a fallover the+ // emitted generation must carry which attempt answered (>0) and the+ // primary it fell back from, so AI observability can answer "did it+ // fall back, and off which model".+ const events: AnalyticsEvent[] = []+ const out = await run(makeRev(), makeSession(), {+ models: [{ model: fauxModel([stop('x')]) }, { model: fauxModel([stop('y')]) }].map((m, i) => ({+ model: { ...m.model, id: i === 0 ? 'a' : 'b' },+ })),+ streamFn: fallbackStreamFn(),+ analytics: { write: async (batch: AnalyticsEvent[]) => void events.push(...batch) },+ })+ expect(out.state).toBe('completed')+ const gens = events.filter((e): e is AnalyticsGenerationEvent => e.kind === 'generation')+ expect(gens).toHaveLength(1)+ expect(gens[0].model_attempt).toBe(1)+ expect(gens[0].fallback_from).toBe('a')+ })++ it('cost mode pins to the conversation last-served model on resume (no primary probe)', async () => {+ // A resumed session whose last assistant turn ran on `b`. With the+ // default `optimize_for: cost`, the next turn must dispatch ONLY `b`+ // — not probe the priority primary `a` — so the cache stays warm.+ const dispatched: string[] = []+ const recordFn: Parameters<typeof runSession>[2]['streamFn'] = (model) => {+ dispatched.push(model.id)+ const stream = createAssistantMessageEventStream()+ queueMicrotask(() => {+ const done = fauxAssistantMessage('ok', { stopReason: 'stop' })+ stream.push({ type: 'start', partial: fauxAssistantMessage('') })+ stream.push({ type: 'done', reason: 'stop', message: done })+ stream.end(done)+ })+ return stream+ }+ const session = makeSession({+ conversation: [+ { role: 'user', content: 'hi', timestamp: Date.now() },+ { role: 'assistant', content: [], model: 'b', timestamp: Date.now() } as never,+ ],+ })+ const out = await run(makeRev(), session, {+ models: [{ model: fauxModel([stop('x')]) }, { model: fauxModel([stop('y')]) }].map((m, i) => ({+ model: { ...m.model, id: i === 0 ? 'a' : 'b' },+ })),+ streamFn: recordFn,+ })+ expect(out.state).toBe('completed')+ expect(dispatched).toEqual(['b'])+ })++ // Regression: a real provider echoes the PROVIDER-SAFE tool name+ // (`posthog_meta-end-turn`), not the `@posthog/...` original. The+ // sanitizing wrapper must translate it back, and on the multi-model path+ // it must run OUTSIDE the fallback wrapper — the fallback re-emits the+ // `done` event (safe name) into a fresh stream, so an inner sanitizing+ // result() never reaches the loop. The faux provider can't exercise this+ // (it echoes the original verbatim), so we emit the safe name by hand.+ it('translates a provider-safe tool name echoed through the fallback wrapper', async () => {+ let calls = 0+ const safeEndTurn = (): Parameters<typeof runSession>[2]['streamFn'] => {+ return () => {+ calls+++ const stream = createAssistantMessageEventStream()+ queueMicrotask(() => {+ // First turn: end_turn under its provider-safe name. If the+ // map misses, the loop returns "tool not found" and keeps+ // going — a second call. With the fix it's intercepted and+ // the turn terminates after one call.+ const done =+ calls === 1+ ? fauxAssistantMessage([fauxToolCall('posthog_meta-end-turn', {})], {+ stopReason: 'toolUse',+ })+ : fauxAssistantMessage('fallthrough', { stopReason: 'stop' })+ stream.push({ type: 'start', partial: fauxAssistantMessage('') })+ stream.push({ type: 'done', reason: calls === 1 ? 'toolUse' : 'stop', message: done })+ stream.end(done)+ })+ return stream+ }+ }+ const out = await run(makeRev(), makeSession(), {+ models: [{ model: fauxModel([stop('x')]) }, { model: fauxModel([stop('y')]) }].map((m, i) => ({+ model: { ...m.model, id: i === 0 ? 'a' : 'b' },+ })),+ streamFn: safeEndTurn(),+ })+ expect(out.state).toBe('completed')+ // The safe name resolved to @posthog/meta-end-turn and terminated the+ // turn on the first model call — no "not found" + retry.+ expect(calls).toBe(1)+ })+ })+/*** Generation-event emission splits by path: on the gateway path the gateway* emits the cost-bearing `$ai_generation`, so the runner must NOT emit itsdiff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex 0a1ac6557548..57b20df20372 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -35,7 +35,7 @@import type { AgentContext, AgentEvent, AgentEventSink, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core'import { runAgentLoop } from '@earendil-works/pi-agent-core'-import type { AssistantMessage, Message, Model } from '@earendil-works/pi-ai'+import type { AssistantMessage, Message } from '@earendil-works/pi-ai'import { streamSimple } from '@earendil-works/pi-ai'import { randomUUID } from 'node:crypto'@@ -54,6 +54,7 @@ import {CredentialBroker,createLogger,FRAMEWORK_PROMPT_VERSION,+ GatewayCatalog,GatewayClient,generationSpanId,HttpFetcher,@@ -85,14 +86,32 @@ import {import { approvalMarkerRequestId, ApprovalPolicy, dispatchApprovedResult, queueApprovalResult } from './approval'import { AgentToolDeps, buildAgentTools, MetaControl, RealToolExecute, ToolResultDetails } from './build-agent-tools'+import { fallbackStreamFn, ResolvedModel } from './fallback-stream'import { resolveMaxOutputTokens } from './max-output-tokens'import type { McpOpenFailure, OpenedMcp } from './mcp-clients'import { lookupMcpToolApproval } from './mcp-tool-lookup'import { providerSafeName } from './provider-safe-names'+/** The model id that served the most recent assistant turn, if any. Seeds the+ * fallback wrapper's sticky lead / cost-mode pin so it survives suspend→resume,+ * not just consecutive in-process turns. */+function lastServedModelId(conversation: ConversationMessage[]): string | undefined {+ for (let i = conversation.length - 1; i >= 0; i--) {+ const message = conversation[i]+ if (message.role === 'assistant' && message.model) {+ return message.model+ }+ }+ return undefined+}+export interface RunSessionDeps {- /** The pi-ai Model to invoke for this session (resolved from rev.spec.model). */- model: Model<string>+ /**+ * Priority-ordered models the loop tries (primary first, fallbacks after).+ * Resolved once per session from `modelPolicyToList(rev.spec)`. On a+ * fallback-eligible provider failure the wrapper retries the next entry.+ */+ models: ResolvedModel[]/** Per-call API key (provider-specific). */apiKey?: string/**@@ -218,6 +237,8 @@ export interface RunSessionDeps {http: HttpFetcher/** Base URL for the PostHog API. Forwarded into `ToolContext.posthogApiBaseUrl`. */posthogApiBaseUrl: string+ /** Gateway model catalog; forwarded into `ToolContext.gatewayCatalog`. */+ gatewayCatalog?: GatewayCatalog/** Operator override (AGENT_MAX_OUTPUT_TOKENS); clamps below model.maxTokens. */maxOutputTokensOverride?: number/**@@ -247,6 +268,12 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsif (!deps.approvals) {throw new Error('RunSessionDeps.approvals is required — refusing to run with approval gating disabled.')}+ if (deps.models.length === 0) {+ throw new Error('RunSessionDeps.models is required — resolve via modelPolicyToList(rev.spec).')+ }+ // Primary (highest-priority) model — identity for max-tokens, error context,+ // and the analytics fallback tag. Fallbacks (if any) live after it.+ const primaryModel = deps.models[0].model// Slack-triggered sessions: the runner relays each finalized assistant// message into the thread (see the turn_end handler). The model is told as// much so it replies in natural language instead of forcing everything@@ -453,6 +480,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsmcpClients: deps.mcpClients,http: deps.http,posthogApiBaseUrl: deps.posthogApiBaseUrl,+ gatewayCatalog: deps.gatewayCatalog,}const { tools, nameToId } = await buildAgentTools(rev, toolDeps)@@ -589,6 +617,10 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsturn++controlThisTurn = undefinedpartialAssistantText = ''+ // Reset fallback tracking; the wrapper's hooks repopulate it+ // for this turn's outbound call(s).+ modelAttempt = 0+ fellBackFrom = undefinedawait emit('turn_started', { turn })// Show "working on it" in the thread while this turn runs.await slackStatus?.start(':hourglass_flowing_sand: _Working on it…_')@@ -809,8 +841,15 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsturn,span_id: genSpan,distinct_id: distinctId,- model: msg.model ?? deps.model.id,- provider: msg.provider ?? deps.model.provider,+ // The model that ACTUALLY answered: pi-ai stamps the+ // answering model on `msg`, so a fallback turn tags the+ // fallback model. Falls back to the resolved primary id.+ model: msg.model ?? deps.models[modelAttempt]?.model.id ?? primaryModel.id,+ provider:+ msg.provider ?? deps.models[modelAttempt]?.model.provider ?? primaryModel.provider,+ // Marker when this turn fell over to a non-primary model.+ model_attempt: modelAttempt > 0 ? modelAttempt : undefined,+ fallback_from: fellBackFrom,input: inputSnapshot,output: msg.content,input_tokens: msg.usage?.input ?? 0,@@ -856,8 +895,8 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depssession.conversation.push({role: 'assistant',content: [{ type: 'text', text: partialAssistantText }],- model: deps.model.id,- provider: deps.model.provider,+ model: primaryModel.id,+ provider: primaryModel.provider,stopReason: 'aborted',timestamp: Date.now(),} satisfies AssistantMessageRecord)@@ -896,25 +935,56 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsreturn { state: 'completed', turns: turn }}- // Tools are registered under their original ids so the loop matches calls- // by name. Sanitize names on the wire (strict providers reject `@`/`/`) and- // translate provider-echoed names back to the original before the loop sees- // the assistant message. The faux provider echoes the script's (original)- // name verbatim — the reverse map misses and leaves it unchanged.+ // Tools register under their original ids; the loop matches calls by name.+ // Sanitize names on the wire (strict providers reject `@`/`/`) and translate+ // provider-echoed names back before the loop sees the assistant message.//- // Two wrappers compose: the gateway-metadata wrapper (when active) stamps- // per-call request ids + headers; the sanitizing wrapper rewrites tool- // names. Order doesn't change behaviour — both touch separate fields —- // but gateway is outer so the request id is generated at the top of the- // chain, before name sanitization mutates the context payload pi-ai sees.- let baseStreamFn: StreamFn = deps.streamFn ?? streamSimple+ // Compose inner→outer: gateway-metadata (per-call request id + headers),+ // multi-model fallback (walks the priority list), sanitizing. Sanitizing+ // MUST be outermost: the fallback wrapper re-emits the winning attempt into+ // a fresh stream whose result() resolves from the forwarded `done` event,+ // which still carries provider-safe names — only the outer sanitizing+ // result() runs last and maps them back to `@posthog/...`. Fallback inside+ // sanitizing → every multi-model tool call dispatches as "tool not found".+ let coreStreamFn: StreamFn = deps.streamFn ?? streamSimpleif (deps.gatewayHeaders || deps.gatewayUsage) {- baseStreamFn = gatewayMetadataStreamFn(baseStreamFn, session.id, deps.gatewayHeaders, turnRequestIds)+ coreStreamFn = gatewayMetadataStreamFn(coreStreamFn, session.id, deps.gatewayHeaders, turnRequestIds)+ }++ // Which model answered this turn, for the `$ai_generation` tag. Reset per+ // `turn_start`; the fallback hooks repopulate it. Single-model sessions+ // skip the wrapper → identical to today.+ let modelAttempt = 0+ let fellBackFrom: string | undefined+ if (deps.models.length > 1) {+ // Session-sticky model selection (see `spec.models.optimize_for`):+ // - `cost` (default): pin to the model that served the first turn so+ // its prompt cache stays warm; no cross-model failover after.+ // - `availability`: lead with the last-served model but fail over.+ // Seed from the conversation's last assistant turn so the pin / sticky+ // lead survives a suspend→resume, not just consecutive in-process turns.+ coreStreamFn = fallbackStreamFn(+ coreStreamFn,+ deps.models,+ {+ onAttempt: (index) => {+ modelAttempt = index+ },+ onFallback: (fromIndex, fromModel, reason) => {+ fellBackFrom = fromModel.id+ runLog.warn({ from: fromModel.id, attempt: fromIndex, reason }, 'model.fallback')+ },+ },+ {+ optimizeFor: rev.spec.models.optimize_for,+ initialServedId: lastServedModelId(session.conversation),+ }+ )}- const streamFn = sanitizingStreamFn(baseStreamFn, nameToId)+ const streamFn = sanitizingStreamFn(coreStreamFn, nameToId)const resolvedMaxTokens = resolveMaxOutputTokens({- modelMaxTokens: deps.model.maxTokens,+ modelMaxTokens: primaryModel.maxTokens,configOverride: deps.maxOutputTokensOverride,specRequested: rev.spec.limits.max_output_tokens,reasoning: rev.spec.reasoning,@@ -925,7 +995,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsrequested: resolvedMaxTokens.clamped.requested,ceiling: resolvedMaxTokens.clamped.ceiling,source: resolvedMaxTokens.clamped.source,- model: deps.model.id,+ model: primaryModel.id,},'max_output_tokens.clamped')@@ -944,11 +1014,15 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps[],context,{- model: deps.model,+ // The fallback wrapper owns model selection across the list;+ // this is the loop's identity model (primary) for any model+ // metadata it reads outside the stream.+ model: primaryModel,apiKey: deps.apiKey,maxTokens: resolvedMaxTokens.value,- // pi-ai ignores `reasoning` for non-reasoning models, so forward unconditionally.- reasoning: rev.spec.reasoning,+ // Primary entry's reasoning (folds in spec default); the wrapper+ // overrides per-attempt. pi-ai ignores it for non-reasoning models.+ reasoning: deps.models[0].reasoning,convertToLlm: (messages) => messages as unknown as Message[],// The loop contract requires this hook to never throw. Drain// atomically from PG so a `/send` that lands during this turn@@ -1161,9 +1235,9 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsfunction errorContext(): Record<string, unknown> {return {source: deps.gatewayHeaders ? 'ai_gateway' : 'provider',- model: deps.model.id,- provider: deps.model.provider,- api: deps.model.api,+ model: primaryModel.id,+ provider: primaryModel.provider,+ api: primaryModel.api,}}diff --git a/products/agent_platform/services/agent-runner/src/loop/fallback-stream.test.ts b/products/agent_platform/services/agent-runner/src/loop/fallback-stream.test.tsnew file mode 100644index 000000000000..d84da60c5895--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/fallback-stream.test.ts@@ -0,0 +1,478 @@+import type { StreamFn } from '@earendil-works/pi-agent-core'+import {+ type AssistantMessage,+ type AssistantMessageEvent,+ createAssistantMessageEventStream,+ type Model,+} from '@earendil-works/pi-ai'+import { describe, expect, it, vi } from 'vitest'++import { fallbackStreamFn, isFallbackEligible, type ResolvedModel } from './fallback-stream'++function fakeModel(id: string): Model<string> {+ return {+ id,+ name: id,+ api: 'faux',+ provider: 'faux',+ baseUrl: 'http://localhost:0',+ reasoning: false,+ input: ['text'],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 1000,+ maxTokens: 1000,+ } as unknown as Model<string>+}++function msg(over: Partial<AssistantMessage> = {}): AssistantMessage {+ return {+ role: 'assistant',+ content: [],+ api: 'faux',+ provider: 'faux',+ model: 'm',+ usage: {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 0,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: 'stop',+ timestamp: 0,+ ...over,+ } as AssistantMessage+}++/** A base StreamFn that emits the given event sequence then ends with `result`. */+function scriptedBase(+ byModelId: Record<string, { events: AssistantMessageEvent[]; result: AssistantMessage }>+): StreamFn {+ return (model) => {+ const stream = createAssistantMessageEventStream()+ const script = byModelId[model.id]+ queueMicrotask(() => {+ for (const e of script.events) {+ stream.push(e)+ }+ stream.end(script.result)+ })+ return stream+ }+}++/** Drive a stream the way the loop does: collect events + the final result. */+async function drive(+ stream: ReturnType<StreamFn>+): Promise<{ events: AssistantMessageEvent[]; result: AssistantMessage }> {+ const s = await stream+ const events: AssistantMessageEvent[] = []+ for await (const e of s) {+ events.push(e)+ }+ return { events, result: await s.result() }+}++const success = (text: string): { events: AssistantMessageEvent[]; result: AssistantMessage } => {+ const partial = msg({ content: [{ type: 'text', text }] })+ return {+ events: [+ { type: 'start', partial: msg() },+ { type: 'text_start', contentIndex: 0, partial },+ { type: 'text_delta', contentIndex: 0, delta: text, partial },+ { type: 'done', reason: 'stop', message: partial },+ ],+ result: partial,+ }+}++/** Pre-commit error: `start` then `error` with empty content (faux-style). */+const preCommitError = (reason: string): { events: AssistantMessageEvent[]; result: AssistantMessage } => {+ const errored = msg({ stopReason: 'error', errorMessage: reason })+ return {+ events: [+ { type: 'start', partial: msg() },+ { type: 'error', reason: 'error', error: errored },+ ],+ result: errored,+ }+}++describe('isFallbackEligible', () => {+ it.each([+ ['429 Too Many Requests', true],+ ['rate limit exceeded', true],+ ['ECONNRESET', true],+ ['socket hang up', true],+ ['503 upstream', true],+ ['quota exceeded', true],+ ['400 bad request', false],+ ['401 unauthorized', false],+ ['403 forbidden', false],+ ['some random validation failure', false],+ [undefined, false],+ ])('%s -> %s', (reason, expected) => {+ expect(isFallbackEligible(reason as string | undefined)).toBe(expected)+ })+})++describe('fallbackStreamFn', () => {+ const models = (ids: string[]): ResolvedModel[] => ids.map((id) => ({ model: fakeModel(id) }))++ it('uses the primary model when it succeeds (no fallover)', async () => {+ const base = scriptedBase({ a: success('hi'), b: success('unused') })+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onFallback })+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('stop')+ expect(onFallback).not.toHaveBeenCalled()+ })++ it('falls over to the next model on a transient pre-commit failure', async () => {+ const base = scriptedBase({ a: preCommitError('429 rate limit'), b: success('recovered') })+ const onAttempt = vi.fn()+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onAttempt, onFallback })+ const { result, events } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('stop')+ expect(result.content).toEqual([{ type: 'text', text: 'recovered' }])+ // The first model's pre-commit `start`/`error` must NOT leak downstream.+ expect(events.some((e) => e.type === 'error')).toBe(false)+ expect(onFallback).toHaveBeenCalledTimes(1)+ expect(onFallback).toHaveBeenCalledWith(0, expect.objectContaining({ id: 'a' }), '429 rate limit')+ expect(onAttempt).toHaveBeenCalledWith(1, expect.objectContaining({ id: 'b' }))+ })++ it('does NOT fall over on a permanent client error — surfaces it from the primary', async () => {+ const base = scriptedBase({ a: preCommitError('400 bad request'), b: success('never') })+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onFallback })+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('400 bad request')+ expect(onFallback).not.toHaveBeenCalled()+ })++ it('surfaces the last error when every model fails transiently (attempt cap = list length)', async () => {+ const calls: string[] = []+ const base: StreamFn = (model) => {+ calls.push(model.id)+ return scriptedBase({+ a: preCommitError('429 a'),+ b: preCommitError('503 b'),+ })(model, { messages: [] } as never, undefined)+ }+ const fn = fallbackStreamFn(base, models(['a', 'b']))+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('503 b')+ // Exactly the list length — no extra attempts.+ expect(calls).toEqual(['a', 'b'])+ })++ it('cannot fall over once committed — a mid-stream error stays on the committed model', async () => {+ // Model `a` commits (emits content) then fails. We must NOT retry `b`.+ const partial = msg({ content: [{ type: 'text', text: 'partial' }] })+ const committedThenError: { events: AssistantMessageEvent[]; result: AssistantMessage } = {+ events: [+ { type: 'start', partial: msg() },+ { type: 'text_delta', contentIndex: 0, delta: 'partial', partial },+ { type: 'error', reason: 'error', error: msg({ stopReason: 'error', errorMessage: '503 mid' }) },+ ],+ result: msg({ stopReason: 'error', errorMessage: '503 mid' }),+ }+ const base = scriptedBase({ a: committedThenError, b: success('should not run') })+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onFallback })+ const { result, events } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('503 mid')+ // The committed content WAS forwarded downstream.+ expect(events.some((e) => e.type === 'text_delta')).toBe(true)+ expect(onFallback).not.toHaveBeenCalled()+ })++ it('applies each entry per-entry reasoning on its attempt', async () => {+ const seen: Array<string | undefined> = []+ const base: StreamFn = (model, _ctx, opts) => {+ seen.push(opts?.reasoning)+ return scriptedBase({ a: preCommitError('429'), b: success('ok') })(model, { messages: [] } as never, opts)+ }+ const list: ResolvedModel[] = [+ { model: fakeModel('a'), reasoning: 'low' },+ { model: fakeModel('b'), reasoning: 'high' },+ ]+ const fn = fallbackStreamFn(base, list)+ await drive(fn(fakeModel('a'), { messages: [] } as never, { reasoning: 'medium' } as never))+ expect(seen).toEqual(['low', 'high'])+ })++ // The contract says `base` shouldn't throw, but the wrapper defends against+ // it (a throw before commit is indistinguishable from a pre-commit failure).+ it('falls over when the base THROWS an eligible error before committing', async () => {+ const base: StreamFn = (model) => {+ if (model.id === 'a') {+ throw new Error('503 boom')+ }+ return scriptedBase({ b: success('recovered') })(model, { messages: [] } as never, undefined)+ }+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onFallback })+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('stop')+ expect(result.content).toEqual([{ type: 'text', text: 'recovered' }])+ expect(onFallback).toHaveBeenCalledWith(0, expect.objectContaining({ id: 'a' }), '503 boom')+ })++ it('synthesizes an error message when the base THROWS a non-eligible error (no fallover)', async () => {+ const calls: string[] = []+ const base: StreamFn = (model) => {+ calls.push(model.id)+ throw new Error('400 nope')+ }+ const onFallback = vi.fn()+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onFallback })+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('400 nope')+ // Permanent → surfaced from the primary, second model never tried.+ expect(calls).toEqual(['a'])+ expect(onFallback).not.toHaveBeenCalled()+ })++ describe('session stickiness (optimize_for)', () => {+ // A base that records which models were tried per turn and routes its+ // response per (turn, model id). `turn.n` is bumped between drives.+ function turnRoutedBase(+ tried: string[][],+ turn: { n: number },+ respond: (turn: number, id: string) => { events: AssistantMessageEvent[]; result: AssistantMessage }+ ): StreamFn {+ return (model) => {+ if (!tried[turn.n]) {+ tried[turn.n] = []+ }+ tried[turn.n].push(model.id)+ const script = respond(turn.n, model.id)+ const stream = createAssistantMessageEventStream()+ queueMicrotask(() => {+ for (const e of script.events) {+ stream.push(e)+ }+ stream.end(script.result)+ })+ return stream+ }+ }++ const drive2 = (fn: StreamFn): ReturnType<typeof drive> =>+ drive(fn(fakeModel('a'), { messages: [] } as never, undefined))++ it('cost (default): pins the first served model — later turns never try the others', async () => {+ const tried: string[][] = []+ const turn = { n: 0 }+ // turn 0: a fails transiently → b serves and becomes the pin.+ const base = turnRoutedBase(tried, turn, (t, id) =>+ t === 0 && id === 'a' ? preCommitError('429') : success(id)+ )+ const fn = fallbackStreamFn(base, models(['a', 'b'])) // optimize_for defaults to cost+ await drive2(fn)+ turn.n = 1+ await drive2(fn)+ turn.n = 2+ await drive2(fn)+ expect(tried[0]).toEqual(['a', 'b']) // turn 0 walked a → b+ expect(tried[1]).toEqual(['b']) // pinned to b — a is never tried again+ expect(tried[2]).toEqual(['b'])+ })++ it('cost: a pinned model failing does NOT fall over — it surfaces the error', async () => {+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (t, id) => {+ if (t === 0 && id === 'a') {+ return preCommitError('429') // establish pin = b+ }+ if (t === 1 && id === 'b') {+ return preCommitError('503') // pinned model now fails+ }+ return success(id)+ })+ const fn = fallbackStreamFn(base, models(['a', 'b']))+ await drive2(fn)+ turn.n = 1+ const { result } = await drive2(fn)+ // Cost mode is pinned to b: it must NOT fall back to the (healthy) a.+ expect(tried[1]).toEqual(['b'])+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('503')+ })++ it('availability: leads with the sticky model but falls over when it fails, then re-sticks', async () => {+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (t, id) => {+ if (t === 0 && id === 'a') {+ return preCommitError('429') // establish served = b+ }+ if (t === 1 && id === 'b') {+ return preCommitError('503') // sticky b fails → fall over to a+ }+ return success(id)+ })+ const fn = fallbackStreamFn(base, models(['a', 'b']), undefined, { optimizeFor: 'availability' })+ await drive2(fn) // turn 0: a → b+ turn.n = 1+ const turn1 = await drive2(fn) // turn 1: lead b, b fails, fall over to a+ expect(tried[1]).toEqual(['b', 'a'])+ expect(turn1.result.content).toEqual([{ type: 'text', text: 'a' }])+ turn.n = 2+ await drive2(fn) // turn 2: re-stuck to the survivor a+ expect(tried[2]).toEqual(['a'])+ })++ it('seeds the pin from initialServedId so it survives a resume (cost)', async () => {+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (_t, id) => success(id))+ const fn = fallbackStreamFn(base, models(['a', 'b']), undefined, { initialServedId: 'b' })+ await drive2(fn)+ // First turn after resume is already pinned to the resumed model.+ expect(tried[0]).toEqual(['b'])+ })++ it('reports the ORIGINAL policy index for a sticky non-primary lead', async () => {+ const onAttempt = vi.fn()+ const base = scriptedBase({ a: success('a'), b: success('b') })+ const fn = fallbackStreamFn(+ base,+ models(['a', 'b']),+ { onAttempt },+ {+ optimizeFor: 'availability',+ initialServedId: 'b',+ }+ )+ await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ // b leads, but its policy index (1) is what analytics records.+ expect(onAttempt).toHaveBeenCalledWith(1, expect.objectContaining({ id: 'b' }))+ })++ it('cost: pins the PRIMARY when it serves first, and still will not fall over if it later fails', async () => {+ // The common case: the primary is healthy on turn 0, so cost pins it+ // and never even considers the fallback — including on a later failure.+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (t, id) =>+ t === 1 && id === 'a' ? preCommitError('503') : success(id)+ )+ const fn = fallbackStreamFn(base, models(['a', 'b'])) // cost default+ await drive2(fn) // turn 0: primary a serves → pin = a (b never tried)+ turn.n = 1+ const { result } = await drive2(fn) // turn 1: a fails; cost must NOT try b+ expect(tried[0]).toEqual(['a'])+ expect(tried[1]).toEqual(['a'])+ expect(result.stopReason).toBe('error')+ })++ it('availability: a stuck MIDDLE model leads, then the rest follow in ORIGINAL priority order', async () => {+ // 3 models a,b,c with served=b. Order must be [b, a, c]: sticky lead+ // first, then the remaining models in priority order (a before c) —+ // exercises the reorder beyond the trivial 2-model case. b and a fail+ // so the whole fall-through order is observable.+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (_t, id) => (id === 'c' ? success(id) : preCommitError('503')))+ const fn = fallbackStreamFn(base, models(['a', 'b', 'c']), undefined, {+ optimizeFor: 'availability',+ initialServedId: 'b',+ })+ const { result } = await drive2(fn)+ expect(tried[0]).toEqual(['b', 'a', 'c'])+ expect(result.content).toEqual([{ type: 'text', text: 'c' }])+ })++ it('ignores a stale initialServedId no longer in the list and walks from the primary', async () => {+ // e.g. the pinned model was dropped from the policy between runs.+ const tried: string[][] = []+ const turn = { n: 0 }+ const base = turnRoutedBase(tried, turn, (_t, id) => success(id))+ const fn = fallbackStreamFn(base, models(['a', 'b']), undefined, { initialServedId: 'ghost' })+ await drive2(fn)+ expect(tried[0]).toEqual(['a'])+ })++ it('fires onPinLost when the seeded sticky model is no longer in the list', async () => {+ // The pin loss must surface — otherwise a delisted model silently+ // costs the session its prompt-cache warmth, only visible+ // indirectly as a lower hit-rate downstream.+ const onPinLost = vi.fn()+ const base = scriptedBase({ a: success('a'), b: success('b') })+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onPinLost }, { initialServedId: 'ghost' })+ await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(onPinLost).toHaveBeenCalledWith('ghost')+ })++ it('does not fire onPinLost when the seeded sticky model is still in the list', async () => {+ const onPinLost = vi.fn()+ const base = scriptedBase({ a: success('a'), b: success('b') })+ const fn = fallbackStreamFn(base, models(['a', 'b']), { onPinLost }, { initialServedId: 'b' })+ await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(onPinLost).not.toHaveBeenCalled()+ })+ })++ describe('IIFE error guard', () => {+ // The wrapper runs its dispatch loop in a detached async IIFE so the+ // returned stream is available synchronously. Any path that lets that+ // promise reject without ending the stream would hang callers awaiting+ // `.result()`. These tests pin the guarantee.++ it('ends the stream when `stream.result()` rejects AFTER the first content event (post-commit)', async () => {+ // Once we've forwarded an event downstream, we can't fall over —+ // but we also can't let the rejection float. The guard must surface+ // the failure as a stop=error result rather than leaving `.result()`+ // pending forever (which is what the pre-fix `void (async ...)`+ // would have done).+ const base: StreamFn = () => {+ // A hand-rolled stream whose iterator yields one content event+ // then ends, but whose `result()` rejects — exercises the+ // `if (committed) throw err` re-raise path. Built by hand+ // (not via createAssistantMessageEventStream) so we have full+ // control over the rejection without depending on its API.+ async function* iter(): AsyncGenerator<AssistantMessageEvent> {+ yield {+ type: 'text_delta',+ contentIndex: 0,+ delta: 'hello',+ partial: msg({ content: [{ type: 'text', text: 'hello' }] }),+ } as AssistantMessageEvent+ }+ const gen = iter()+ return {+ [Symbol.asyncIterator]: () => gen,+ result: () => Promise.reject(new Error('mid-stream provider crash')),+ } as unknown as ReturnType<StreamFn>+ }+ const fn = fallbackStreamFn(base, models(['a']))+ // Must resolve, not hang. If the guard regresses, this test+ // times out under vitest's default test timeout.+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toMatch(/mid-stream/)+ })++ it('ends the stream when `base` throws synchronously on the FIRST attempt with no fallback eligible', async () => {+ // Defensive guard for the no-throw contract being violated by a bug+ // (not a network error). Must surface as an error result with no fallover.+ const base: StreamFn = () => {+ throw new Error('exploded')+ }+ const fn = fallbackStreamFn(base, models(['a']))+ const { result } = await drive(fn(fakeModel('a'), { messages: [] } as never, undefined))+ expect(result.stopReason).toBe('error')+ expect(result.errorMessage).toBe('exploded')+ })+ })+})diff --git a/products/agent_platform/services/agent-runner/src/loop/fallback-stream.ts b/products/agent_platform/services/agent-runner/src/loop/fallback-stream.tsnew file mode 100644index 000000000000..93dc0f1cafc9--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/fallback-stream.ts@@ -0,0 +1,288 @@+/**+ * Multi-model fallback wrapper around a base `StreamFn`. Tries a priority list+ * (primary first) in order; retries the next model on a fallback-eligible+ * failure, else stops. Eligible = transient/provider-side (5xx/conn/timeout/429+ * via `isFallbackEligible`); NOT permanent 4xx or aborts. Commit guard: once a+ * content-bearing event is forwarded the turn is committed and we can't fall+ * over (a bare `start` doesn't count). Capped at the list length.+ */++import type { StreamFn } from '@earendil-works/pi-agent-core'+import type { AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Model } from '@earendil-works/pi-ai'+import { createAssistantMessageEventStream } from '@earendil-works/pi-ai'++import { categorize, ReasoningEffort } from '@posthog/agent-shared'++import { classifyGatewayError } from './gateway-error'++/** A model from the policy list, resolved to a concrete pi-ai Model + its reasoning knob. */+export interface ResolvedModel {+ model: Model<string>+ reasoning?: ReasoningEffort+}++/** Content-bearing event types — forwarding any of these commits the turn downstream. */+function isContentEvent(e: AssistantMessageEvent): boolean {+ return e.type !== 'start' && e.type !== 'error'+}++/**+ * A pre-commit failure is fallback-eligible only when transient/provider-side:+ * 5xx / conn / timeout / 429. Permanent client errors (bad_request / non-429+ * 4xx) and aborts are NOT eligible.+ *+ * `categorize()` covers conn/timeout (`transient_infra`) and 429/quota+ * (`quota_exhausted`); `classifyGatewayError` adds the HTTP-status signal so a+ * bare `5xx` (which categorize doesn't pattern-match) is eligible and a non-429+ * 4xx is hard-excluded even if a substring would otherwise match.+ */+export function isFallbackEligible(errorMessage: string | undefined): boolean {+ const reason = errorMessage ?? ''+ const g = classifyGatewayError(reason)+ // Permanent client status (any non-429 4xx) → never eligible.+ if (g && g.status >= 400 && g.status < 500 && g.status !== 429) {+ return false+ }+ // 5xx upstream / 429 throttle off the status prefix → eligible.+ if (g && (g.status >= 500 || g.status === 429)) {+ return true+ }+ const cat = categorize(reason)+ return cat === 'transient_infra' || cat === 'quota_exhausted'+}++/** Notified on each fall-over so the caller can mark analytics. */+export interface FallbackHooks {+ /** The model that just answered, with its ORIGINAL policy index (0-based).+ * >0 means a non-primary model served (a fallover this turn, or a sticky+ * lead carried over from a prior turn). */+ onAttempt?: (index: number, model: Model<string>) => void+ /** A model was skipped after a fallback-eligible failure (original index). */+ onFallback?: (fromIndex: number, fromModel: Model<string>, reason: string | undefined) => void+ /** The session's sticky model is no longer in the `models` list (delisted+ * from the gateway or removed from the spec), so the pin is broken and+ * attempt order falls back to the policy primary. Surfaced so the caller+ * can record the cache-warmth regression — otherwise it shows up only+ * indirectly as a lower prompt-cache hit rate. */+ onPinLost?: (servedId: string) => void+}++/** Session-stability knobs. See `ModelOptimizeForSchema` in agent-shared. */+export interface FallbackStickiness {+ /**+ * `cost` (default): once a model has served a turn, pin to it — every later+ * turn uses ONLY that model, no cross-model failover (keeps the provider's+ * prompt cache warm). `availability`: lead with the sticky model but still+ * fail over to the rest of the list on failure.+ */+ optimizeFor?: 'cost' | 'availability'+ /**+ * The model that served the previous turn (e.g. read off a resumed+ * conversation's last assistant message). Seeds the sticky lead / the pin so+ * stickiness survives suspend→resume, not just consecutive in-process turns.+ */+ initialServedId?: string+}++/** Original-policy-indexed view of a model, so hooks report the policy position+ * regardless of the per-turn attempt order. */+interface IndexedModel {+ entry: ResolvedModel+ index: number+}++/**+ * The attempt order for one turn:+ * - no model served yet → full list in priority order (walk to find one).+ * - `cost` + a served model → just that model (no failover).+ * - `availability` + a served model → that model first, then the rest in+ * priority order (sticky lead + failover).+ */+function attemptOrder(models: ResolvedModel[], servedId: string | undefined, optimizeFor: string): IndexedModel[] {+ const indexed: IndexedModel[] = models.map((entry, index) => ({ entry, index }))+ if (!servedId) {+ return indexed+ }+ const pos = indexed.findIndex((x) => x.entry.model.id === servedId)+ if (pos < 0) {+ return indexed+ }+ if (optimizeFor === 'cost') {+ return [indexed[pos]]+ }+ const [lead] = indexed.splice(pos, 1)+ return [lead, ...indexed]+}++/**+ * Build a `StreamFn` that walks `models` in priority order. The `model` arg the+ * loop passes is ignored — this owns model selection — but each attempt honours+ * the caller's `options` (apiKey, headers, signal) with the entry's `reasoning`+ * applied on top.+ *+ * Session-sticky: across turns the wrapper remembers the model that last served+ * and prefers it, so the provider's prompt cache stays warm rather than+ * thrashing. `stickiness.optimizeFor` decides what happens on a later failure —+ * `cost` pins (no failover), `availability` falls over. See `attemptOrder`.+ */+export function fallbackStreamFn(+ base: StreamFn,+ models: ResolvedModel[],+ hooks?: FallbackHooks,+ stickiness?: FallbackStickiness+): StreamFn {+ if (models.length === 0) {+ throw new Error('fallbackStreamFn requires at least one model')+ }+ const optimizeFor = stickiness?.optimizeFor ?? 'cost'+ // The model that served the most recent successful turn; persists across+ // turns within this wrapped fn. Seeded from a resumed conversation.+ let servedId = stickiness?.initialServedId+ return (_model, context, options) => {+ // `servedId` is set but no longer in the models list — the pin has+ // been broken (the model was delisted, or `models` was edited).+ // Surface it via `onPinLost` so the caller can log / mark analytics;+ // `attemptOrder` will return the full list and we'll repick from+ // primary. Done here (not inside the IIFE) so a missing hook+ // doesn't depend on whether `attemptOrder` is reached.+ if (servedId && !models.some((m) => m.model.id === servedId)) {+ hooks?.onPinLost?.(servedId)+ servedId = undefined+ }+ const order = attemptOrder(models, servedId, optimizeFor)+ const out = createAssistantMessageEventStream()+ // Track current attempt so the outer guard knows whether we've+ // committed when something unexpected throws inside the IIFE.+ let lastEntry: ResolvedModel = order[0].entry+ let lastCommitted = false+ const run = async (): Promise<void> => {+ for (let pos = 0; pos < order.length; pos++) {+ const { entry, index } = order[pos]+ lastEntry = entry+ const last = pos === order.length - 1+ const opts = { ...options, reasoning: entry.reasoning ?? options?.reasoning }+ let committed = false+ try {+ const stream = await base(entry.model, context, opts)+ const buffered: AssistantMessageEvent[] = []+ for await (const event of stream) {+ if (committed) {+ out.push(event)+ continue+ }+ if (isContentEvent(event)) {+ // First real progress — commit: flush buffered envelope + this event.+ committed = true+ lastCommitted = true+ servedId = entry.model.id+ hooks?.onAttempt?.(index, entry.model)+ for (const b of buffered) {+ out.push(b)+ }+ buffered.length = 0+ out.push(event)+ continue+ }+ // Bare `start` / pre-commit `error`: hold until we know the outcome.+ buffered.push(event)+ }+ const result = await stream.result()+ if (committed) {+ out.end(result)+ return+ }+ // Stream ended before any content: a pure success (rare) or a+ // pre-commit failure. Success → forward + done. Failure →+ // fall over when eligible and attempts remain.+ const failed = result.stopReason === 'error' || result.stopReason === 'aborted'+ if (!failed) {+ servedId = entry.model.id+ hooks?.onAttempt?.(index, entry.model)+ for (const b of buffered) {+ out.push(b)+ }+ out.end(result)+ return+ }+ if (!last && result.stopReason === 'error' && isFallbackEligible(result.errorMessage)) {+ hooks?.onFallback?.(index, entry.model, result.errorMessage)+ continue+ }+ // Permanent / abort / exhausted / cost-pinned: surface this failure downstream.+ hooks?.onAttempt?.(index, entry.model)+ for (const b of buffered) {+ out.push(b)+ }+ out.end(result)+ return+ } catch (err) {+ // The contract says base must not throw; defensively treat a+ // throw as a pre-commit failure (we never forwarded anything,+ // so we can still fall over). Once committed, re-raise to the+ // outer guard, which surfaces it on the stream — never let the+ // promise float (would leave callers awaiting `.result()` hung).+ if (committed) {+ throw err+ }+ const reason = err instanceof Error ? err.message : String(err)+ if (!last && isFallbackEligible(reason)) {+ hooks?.onFallback?.(index, entry.model, reason)+ continue+ }+ const message: AssistantMessage = {+ role: 'assistant',+ content: [],+ api: entry.model.api,+ provider: entry.model.provider,+ model: entry.model.id,+ usage: {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 0,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: 'error',+ errorMessage: reason,+ timestamp: Date.now(),+ }+ hooks?.onAttempt?.(index, entry.model)+ out.push({ type: 'error', reason: 'error', error: message })+ out.end(message)+ return+ }+ }+ }+ // No matter how `run` exits — normal completion, post-commit re-throw,+ // or an unexpected throw from `out.push` / destructuring / `base()` not+ // matching the no-throw contract — we MUST end the stream so callers+ // awaiting `.result()` don't hang.+ run().catch((err) => {+ const reason = err instanceof Error ? err.message : String(err)+ const message: AssistantMessage = {+ role: 'assistant',+ content: [],+ api: lastEntry.model.api,+ provider: lastEntry.model.provider,+ model: lastEntry.model.id,+ usage: {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 0,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: 'error',+ errorMessage: reason,+ timestamp: Date.now(),+ }+ if (!lastCommitted) {+ out.push({ type: 'error', reason: 'error', error: message })+ }+ out.end(message)+ })+ return out as AssistantMessageEventStream+ }+}diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex e8d28d2c7a02..d4777a3cf528 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -35,11 +35,14 @@ import {IdentityLinkStateStore,IdentityStore,FailureNotifier,+ filterServableEntries,+ GatewayCatalog,GatewayClient,getSecretAllowedHosts,HttpFetcher,LogSink,MemoryStore,+ modelPolicyToList,TabularStore,WebSearchProvider,RevisionStore,@@ -67,11 +70,15 @@ export interface WorkerDeps {/** Resolved per-application secrets — wire from the team's encrypted env. */resolveSecrets: (session: AgentSession) => Promise<Record<string, string>>/**- * Resolve a session's spec.model string to a concrete pi-ai Model. Defaults- * to `resolveModelCached(spec.model)` which works for built-in providers.- * Override for custom-endpoint models (ai-gateway) or test faux models.+ * Resolve a single model-id string (one entry of the resolved policy list)+ * to a concrete pi-ai Model. Defaults to `resolveModelCached` which works+ * for built-in providers. Override for custom-endpoint models (ai-gateway)+ * or test faux models. Applied per-entry across `modelPolicyToList(spec)`.*/resolveModel?: (specModel: string) => Model<string>+ /** Served-model catalog. Filters the resolved model list to servable models+ * before dispatch and feeds `ToolContext` for the models tool. */+ gatewayCatalog?: GatewayCatalog/*** Per-session API key resolver. The resolved key is passed to the driver's* loop config; defaults to no key. On the ai-gateway path this returns@@ -527,8 +534,32 @@ export class Worker {)}}+ // Expand the policy to a priority list, then drop entries the gateway+ // no longer serves (no-op without a catalog; never empties a non-empty+ // list — see `filterServableEntries`).const resolveModel = this.deps.resolveModel ?? resolveModelCached- const model = resolveModel(rev.spec.model)+ const catalogModels = this.deps.gatewayCatalog ? await this.deps.gatewayCatalog.list() : []+ const policyList = modelPolicyToList(rev.spec)+ if (this.deps.gatewayCatalog && catalogModels.length === 0) {+ // Fail-open: with no catalog we can't filter, so the policy list+ // ships as-authored. An empty catalog behind a *configured*+ // gateway is either a fetch that failed with no cached fallback+ // or a gateway serving nothing — both can dispatch a delisted+ // model that 400s on the first call. Surface it loudly so it's+ // not indistinguishable from a healthy run. Cleanly refusing to+ // start on a genuinely-empty (vs transiently-unreachable) catalog+ // needs a freshness signal on the catalog read — tracked as a+ // follow-up (see PR review).+ sLog.warn(+ { policy_entries: policyList.length },+ 'model.catalog_empty_fail_open — dispatching unfiltered model policy'+ )+ }+ const policyEntries = filterServableEntries(policyList, catalogModels)+ const models = policyEntries.map((entry) => ({+ model: resolveModel(entry.model),+ reasoning: entry.reasoning,+ }))const apiKey = await this.deps.resolveApiKey?.(session)const gatewayHeaders = this.deps.resolveGatewayHeaders?.(session)const gatewayUsage = await this.deps.resolveGatewayUsage?.(session)@@ -537,7 +568,7 @@ export class Worker {// to address the agent's ingress directly.const buildApprovalUrl = this.deps.buildApprovalUrlconst outcome = await runSession(rev, session, {- model,+ models,apiKey,bundle: this.deps.bundle,sandbox,@@ -568,6 +599,7 @@ export class Worker {mcpFailures,http: this.deps.http,posthogApiBaseUrl: this.deps.posthogApiBaseUrl,+ gatewayCatalog: this.deps.gatewayCatalog,maxOutputTokensOverride: this.deps.maxOutputTokens,inputs: this.deps.queue,onTurnPersist: async (s) => {diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.tsindex 3e3ef531bdc0..a511fd20df89 100644--- a/products/agent_platform/services/agent-shared/src/index.ts+++ b/products/agent_platform/services/agent-shared/src/index.ts@@ -62,6 +62,7 @@ export * from './runtime/metrics'export * from './runtime/process-handlers'export * from './runtime/encryption'export * from './runtime/team-api-key-resolver'+export * from './runtime/gateway-catalog'export * from './runtime/gateway-client'export * from './runtime/failure-notifier'export * from './runtime/http-client'diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.tsindex d4aea44ca68a..aaf96b52ff1b 100644--- a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts@@ -70,10 +70,16 @@ maybeDescribe('Postgres impls (real PG)', () => {})expect(rev.state).toBe('draft')- const newSpec = AgentSpecSchema.parse({ model: 'test/mock-static:hello' })+ const newSpec = AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'mock-static/hello' }] },+ })await store.updateSpec(rev.id, newSpec)const after = await store.getRevision(rev.id)- expect(after!.spec.model).toBe('test/mock-static:hello')+ expect(after!.spec.models).toEqual({+ mode: 'manual',+ models: [{ model: 'mock-static/hello' }],+ optimize_for: 'cost',+ })await store.setRevisionState(rev.id, 'live')await store.setLiveRevision(app.id, rev.id)diff --git a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.tsindex 91fe1ddf3007..a6119cf51187 100644--- a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts@@ -87,6 +87,10 @@ export interface AnalyticsGenerationEvent extends AnalyticsEventBase {cost_usd?: number/** pi-ai stopReason — `stop`, `length`, `toolUse`, `error`, `aborted`. */stop_reason?: string+ /** 0-based index of the model in the policy list that answered. >0 means a fallback. */+ model_attempt?: number+ /** Model id we fell back FROM (the primary that failed), when a fallback happened. */+ fallback_from?: string}export interface AnalyticsSpanEvent extends AnalyticsEventBase {@@ -213,6 +217,12 @@ export function buildAnalyticsProperties(event: AnalyticsEvent): Record<string,if (event.stop_reason) {base.$ai_stop_reason = event.stop_reason}+ if (event.model_attempt !== undefined) {+ base.$agent_model_attempt = event.model_attempt+ }+ if (event.fallback_from) {+ base.$ai_fallback_from = event.fallback_from+ }} else if (event.kind === 'span') {base.$ai_span_name = event.tool_namebase.$ai_tool_call_id = event.tool_call_iddiff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.test.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.test.tsnew file mode 100644index 000000000000..301f84bc5dab--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.test.ts@@ -0,0 +1,242 @@+import { describe, expect, it, vi } from 'vitest'++import { MODEL_POLICY_LEVELS, type ModelPolicy } from '../spec/spec'+import {+ acceptedModelIds,+ type CatalogModel,+ filterServableEntries,+ HttpGatewayCatalog,+ isModelServable,+ validateModelLevels,+ validateModelPolicy,+} from './gateway-catalog'++function model(over: Partial<CatalogModel> & Pick<CatalogModel, 'canonical' | 'id' | 'owned_by'>): CatalogModel {+ return {+ aliases: [],+ context_window: 200_000,+ pricing: { prompt: 0.000001, completion: 0.000005 },+ ...over,+ }+}++// Mirrors the live gateway: haiku is dated-only with an undated alias; sonnet+// 4.6 / opus 4.7 advertise undated ids; gpt-5 family is plain canonicals.+const CATALOG: CatalogModel[] = [+ model({+ canonical: 'anthropic/claude-haiku-4.5',+ id: 'claude-haiku-4-5-20251001',+ owned_by: 'anthropic',+ aliases: ['claude-haiku-4-5'],+ }),+ model({ canonical: 'anthropic/claude-sonnet-4.6', id: 'claude-sonnet-4-6', owned_by: 'anthropic' }),+ model({ canonical: 'anthropic/claude-opus-4.7', id: 'claude-opus-4-7', owned_by: 'anthropic' }),+ model({ canonical: 'openai/gpt-5', id: 'gpt-5', owned_by: 'openai' }),+ model({ canonical: 'openai/gpt-5-mini', id: 'gpt-5-mini', owned_by: 'openai' }),+ model({ canonical: 'openai/gpt-5-pro', id: 'gpt-5-pro', owned_by: 'openai' }),+]++describe('acceptedModelIds', () => {+ it('indexes canonical, bare suffix, id, alias, and provider-prefixed forms', () => {+ const ids = acceptedModelIds([CATALOG[0]])+ for (const form of [+ 'anthropic/claude-haiku-4.5', // canonical+ 'claude-haiku-4.5', // bare suffix+ 'claude-haiku-4-5-20251001', // id+ 'anthropic/claude-haiku-4-5-20251001', // provider + id+ 'claude-haiku-4-5', // alias+ 'anthropic/claude-haiku-4-5', // provider + alias (the MODEL_POLICY_LEVELS form)+ ]) {+ expect(ids.has(form)).toBe(true)+ }+ expect(ids.has('anthropic/claude-haiku-9')).toBe(false)+ })+})++describe('isModelServable', () => {+ it.each([+ ['anthropic/claude-haiku-4-5', true], // dashed undated, provider-prefixed (alias form)+ ['anthropic/claude-haiku-4.5', true], // canonical+ ['openai/gpt-5-pro', true],+ ['openai/gpt-5-thinking', false], // the drift that broke the old high tier+ ['anthropic/claude-opus-9', false],+ ])('%s -> %s', (id, expected) => {+ expect(isModelServable(CATALOG, id as string)).toBe(expected)+ })+})++describe('validateModelPolicy', () => {+ it('flags each unservable model in a manual policy with a pointer', () => {+ const policy: ModelPolicy = {+ mode: 'manual',+ models: [{ model: 'anthropic/claude-haiku-4-5' }, { model: 'openai/gpt-foo' }, { model: 'openai/gpt-5' }],+ optimize_for: 'cost',+ }+ const issues = validateModelPolicy(policy, CATALOG)+ expect(issues).toHaveLength(1)+ expect(issues[0]).toMatchObject({ model: 'openai/gpt-foo', pointer: 'spec.models.models[1].model' })+ })++ it('accepts an auto policy whose level has at least one servable member', () => {+ expect(validateModelPolicy({ mode: 'auto', level: 'high', optimize_for: 'cost' }, CATALOG)).toEqual([])+ })++ it('flags an auto policy only when the whole level is unservable', () => {+ const issues = validateModelPolicy({ mode: 'auto', level: 'high', optimize_for: 'cost' }, [CATALOG[3]]) // only openai/gpt-5+ // high = [opus-4-7, gpt-5-pro, sonnet-4-6]; none is openai/gpt-5 → whole level dead+ expect(issues).toHaveLength(1)+ expect(issues[0].pointer).toBe('spec.models.level')+ })++ it('fails open on servability when the catalog is empty (unreachable gateway)', () => {+ // `made/up` is well-formatted; absent the catalog we can't say if it's served,+ // so we let it through rather than blocking authoring.+ expect(+ validateModelPolicy({ mode: 'manual', models: [{ model: 'made/up' }], optimize_for: 'cost' }, [])+ ).toEqual([])+ })++ it('still flags a malformed manual model id even when the catalog is empty', () => {+ // Format check runs unconditionally — a bare id like `haiku-4-5` will 400 at+ // the gateway regardless of catalog state, so catching it at freeze is+ // strictly more useful than waiting for the first session to fail.+ const issues = validateModelPolicy(+ { mode: 'manual', models: [{ model: 'haiku-4-5' }], optimize_for: 'cost' },+ []+ )+ expect(issues).toHaveLength(1)+ expect(issues[0]).toMatchObject({+ model: 'haiku-4-5',+ pointer: 'spec.models.models[0].model',+ reason: expect.stringContaining('provider'),+ })+ })++ it('reports only the format error (not also "not served") when a model id is malformed', () => {+ // Otherwise the author sees two errors for the same entry and the+ // servability one is misleading (gateway will reject the format first).+ const issues = validateModelPolicy(+ { mode: 'manual', models: [{ model: 'haiku-4-5' }], optimize_for: 'cost' },+ CATALOG+ )+ expect(issues).toHaveLength(1)+ expect(issues[0].reason).toMatch(/provider/)+ })+})++describe('validateModelLevels', () => {+ it('passes when every curated tier member is served (guards MODEL_POLICY_LEVELS drift)', () => {+ const full = [+ ...CATALOG,+ // include the remaining tier members so all of low/medium/high resolve+ ]+ const issues = validateModelLevels(full)+ // CATALOG already covers haiku-4-5, gpt-5-mini, sonnet-4-6, gpt-5, opus-4-7, gpt-5-pro+ // which is exactly every member of MODEL_POLICY_LEVELS.+ expect(issues).toEqual([])+ })++ it('reports the dead tier member when a tier drifts off the catalog', () => {+ const withoutGpt5Pro = CATALOG.filter((m) => m.canonical !== 'openai/gpt-5-pro')+ const issues = validateModelLevels(withoutGpt5Pro)+ expect(issues).toEqual([+ {+ model: 'openai/gpt-5-pro',+ pointer: 'MODEL_POLICY_LEVELS.high',+ reason: 'tier member not served by the gateway',+ },+ ])+ })++ it('the committed MODEL_POLICY_LEVELS only references models present in this fixture', () => {+ // Belt-and-suspenders: the curated constant must be a subset of what we+ // model as served, so adding a new tier member without a catalog entry+ // fails here. (A live-catalog version of this runs in agent-tests e2e.)+ const accepted = acceptedModelIds(CATALOG)+ const all = Object.values(MODEL_POLICY_LEVELS).flat()+ expect(all.filter((m) => !accepted.has(m))).toEqual([])+ })+})++describe('filterServableEntries', () => {+ it('drops unservable entries', () => {+ const kept = filterServableEntries([{ model: 'openai/gpt-5' }, { model: 'openai/gpt-gone' }], CATALOG)+ expect(kept).toEqual([{ model: 'openai/gpt-5' }])+ })++ it('returns the original list when filtering would empty it (never strand a session)', () => {+ const entries = [{ model: 'openai/gpt-gone' }]+ expect(filterServableEntries(entries, CATALOG)).toBe(entries)+ })++ it('returns the original list when the catalog is empty', () => {+ const entries = [{ model: 'anything' }]+ expect(filterServableEntries(entries, [])).toBe(entries)+ })+})++describe('HttpGatewayCatalog', () => {+ const wire = {+ data: [+ {+ id: 'claude-haiku-4-5-20251001',+ canonical: 'anthropic/claude-haiku-4.5',+ owned_by: 'anthropic',+ context_window: 200000,+ aliases: ['claude-haiku-4-5'],+ pricing: {+ prompt: '0.000001',+ completion: '0.000005',+ cache_read: '0.0000001',+ cache_write: '0.00000125',+ },+ },+ // a malformed row (no pricing) is dropped, not fatal+ { id: 'broken', canonical: 'x/broken', owned_by: 'x' },+ ],+ }+ const okResponse = (): Response => ({ ok: true, status: 200, json: async () => wire }) as unknown as Response++ it('parses /models, drops malformed rows, and converts decimal-string pricing to numbers', async () => {+ const fetch = vi.fn().mockResolvedValue(okResponse())+ const cat = new HttpGatewayCatalog({ baseUrl: 'http://gw/v1', bearer: 'phs_x', http: { fetch } })+ const models = await cat.list()+ expect(models).toHaveLength(1)+ expect(models[0]).toMatchObject({ canonical: 'anthropic/claude-haiku-4.5', context_window: 200000 })+ expect(models[0].pricing).toEqual({+ prompt: 0.000001,+ completion: 0.000005,+ cache_read: 0.0000001,+ cache_write: 0.00000125,+ })+ // hit /v1/models with the bearer+ expect(fetch).toHaveBeenCalledWith('http://gw/v1/models', expect.objectContaining({ method: 'GET' }))+ expect(fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer phs_x')+ })++ it('caches within the TTL (one fetch for two calls)', async () => {+ const fetch = vi.fn().mockResolvedValue(okResponse())+ const cat = new HttpGatewayCatalog({ baseUrl: 'http://gw/v1', http: { fetch }, ttlMs: 10_000 })+ await cat.list()+ await cat.list()+ expect(fetch).toHaveBeenCalledTimes(1)+ })++ it('fails open: serves [] on the first failed fetch rather than throwing', async () => {+ const fetch = vi.fn().mockResolvedValue({ ok: false, status: 503 } as unknown as Response)+ const cat = new HttpGatewayCatalog({ baseUrl: 'http://gw/v1', http: { fetch } })+ await expect(cat.list()).resolves.toEqual([])+ })++ it('serves last-good through a transient failure after a successful fetch', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(okResponse())+ .mockResolvedValueOnce({ ok: false, status: 503 } as unknown as Response)+ const cat = new HttpGatewayCatalog({ baseUrl: 'http://gw/v1', http: { fetch }, ttlMs: 0 })+ const first = await cat.list()+ const second = await cat.list() // TTL 0 forces a refetch which fails+ expect(second).toEqual(first)+ expect(second).toHaveLength(1)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.ts b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.tsnew file mode 100644index 000000000000..811699a12454--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/gateway-catalog.ts@@ -0,0 +1,326 @@+/**+ * Gateway model catalog — the agent platform's source of truth for which+ * models are runnable, their pricing, and their context window.+ *+ * Reads the SAME gateway the runner dispatches against (`GET {baseUrl}/models`),+ * so author-time validation and runtime resolution agree with what will+ * actually run. The curated tier groupings (`MODEL_POLICY_LEVELS` in spec.ts)+ * are reconciled against this: the catalog says what's *possible*, the groups+ * say what's *meaningful*. A model string is only real if it appears here.+ */++import { MODEL_POLICY_LEVELS, type ModelEntry, type ModelPolicy, type ModelLevel } from '../spec/spec'+import type { HttpFetcher } from './http-client'+import { createLogger } from './logger'++/** Per-token USD costs. `cache_*` are per-model-optional (OpenAI has no+ * cache_write; bare models have neither). */+export interface CatalogModelPricing {+ prompt: number+ completion: number+ cache_read?: number+ cache_write?: number+}++/** One served model, normalized from the gateway's `/v1/models` row. */+export interface CatalogModel {+ /** Stable provider-prefixed id, e.g. `anthropic/claude-haiku-4.5`. Prefer this everywhere. */+ canonical: string+ /** Advertised provider SKU, e.g. `claude-haiku-4-5-20251001`. */+ id: string+ /** Other accepted spellings (e.g. the undated `claude-haiku-4-5`). */+ aliases: string[]+ /** Primary provider, e.g. `anthropic`. */+ owned_by: string+ /** Max context window in tokens (0 when the gateway didn't report it). */+ context_window: number+ pricing: CatalogModelPricing+}++/** Async accessor over the cached catalog. */+export interface GatewayCatalog {+ /** All served models. Cached; refreshes past the TTL; serves last-good+ * through a transient gateway failure (empty only if never fetched). */+ list(): Promise<CatalogModel[]>+}++// ── Wire shape (GET /v1/models) ──────────────────────────────────────────+// Pricing values arrive as decimal strings to preserve precision; parse at+// the boundary.+interface WirePricing {+ prompt?: string+ completion?: string+ cache_read?: string+ cache_write?: string+}+interface WireModel {+ id?: string+ canonical?: string+ owned_by?: string+ context_window?: number+ aliases?: string[] | null+ pricing?: WirePricing+}+interface WireResponse {+ data?: WireModel[]+}++function parseDecimal(s: string | undefined): number | undefined {+ if (s === undefined) {+ return undefined+ }+ const n = Number(s)+ return Number.isFinite(n) ? n : undefined+}++function parseModel(w: WireModel): CatalogModel | null {+ // A row without an id, canonical, or usable input/output price isn't+ // routable+billable, so it isn't part of the vocabulary.+ if (!w.id || !w.canonical || !w.pricing) {+ return null+ }+ const prompt = parseDecimal(w.pricing.prompt)+ const completion = parseDecimal(w.pricing.completion)+ if (prompt === undefined || completion === undefined) {+ return null+ }+ return {+ canonical: w.canonical,+ id: w.id,+ aliases: (w.aliases ?? []).filter((a): a is string => typeof a === 'string'),+ owned_by: w.owned_by ?? w.canonical.split('/')[0] ?? '',+ context_window: typeof w.context_window === 'number' ? w.context_window : 0,+ pricing: {+ prompt,+ completion,+ cache_read: parseDecimal(w.pricing.cache_read),+ cache_write: parseDecimal(w.pricing.cache_write),+ },+ }+}++// ── Pure reconciliation helpers (catalog snapshot in, decision out) ───────+// Kept pure so they're testable without a live gateway and reusable from the+// runner (runtime resolution) and janitor (author-time validation).++/** Every string the gateway would accept for a model: canonical, its bare+ * suffix, the SKU id, each alias, and the provider-prefixed id/aliases. This+ * mirrors the gateway resolver's acceptance set so client-side checks match+ * what dispatch will accept. */+export function acceptedModelIds(models: CatalogModel[]): Set<string> {+ const out = new Set<string>()+ for (const m of models) {+ out.add(m.canonical)+ const slash = m.canonical.indexOf('/')+ if (slash > 0) {+ out.add(m.canonical.slice(slash + 1))+ }+ out.add(m.id)+ if (m.owned_by) {+ out.add(`${m.owned_by}/${m.id}`)+ }+ for (const alias of m.aliases) {+ out.add(alias)+ if (m.owned_by) {+ out.add(`${m.owned_by}/${alias}`)+ }+ }+ }+ return out+}++/** True if the gateway serves `modelId` in any accepted form. */+export function isModelServable(models: CatalogModel[], modelId: string): boolean {+ return acceptedModelIds(models).has(modelId)+}++export interface ModelPolicyIssue {+ model: string+ pointer: string+ reason: string+}++/**+ * Author-time validation of a `models` against the catalog. `manual`:+ * each listed model must be servable (author's to fix). `auto`: only flagged+ * when the level resolves to nothing servable — a single dead tier member is+ * platform drift, caught by `validateModelLevels` in CI, not the author's+ * problem.+ *+ * Catalog availability gates the SERVABILITY check (empty → fail-open, see+ * HttpGatewayCatalog) but NOT the FORMAT check: a bare model id like+ * `haiku-4-5` will 400 at the gateway regardless of catalog state, and we'd+ * rather catch it at freeze than ship a session that fails on the first call.+ */+// Mirror of `ModelIdSchema` in agent-shared/src/spec/spec.ts and+// `_AGENT_SPEC_JSON_SCHEMA_RAW.models.manual.models[].model.pattern` in+// backend/logic/spec_schema.py — keep all three in sync.+const MODEL_ID_PATTERN = /^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$/++export function validateModelPolicy(policy: ModelPolicy, models: CatalogModel[]): ModelPolicyIssue[] {+ const issues: ModelPolicyIssue[] = []+ if (policy.mode === 'manual') {+ // Format check runs unconditionally — see the function docstring.+ policy.models.forEach((entry, i) => {+ if (!MODEL_ID_PATTERN.test(entry.model)) {+ issues.push({+ model: entry.model,+ pointer: `spec.models.models[${i}].model`,+ reason: 'must be "<provider>/<model-id>"',+ })+ }+ })+ if (models.length === 0) {+ return issues+ }+ const accepted = acceptedModelIds(models)+ policy.models.forEach((entry, i) => {+ // Skip the servability check if the id is already malformed —+ // the format error above is the more actionable signal.+ if (MODEL_ID_PATTERN.test(entry.model) && !accepted.has(entry.model)) {+ issues.push({+ model: entry.model,+ pointer: `spec.models.models[${i}].model`,+ reason: 'not served by the gateway',+ })+ }+ })+ return issues+ }+ if (models.length === 0) {+ return issues+ }+ const accepted = acceptedModelIds(models)+ const members = MODEL_POLICY_LEVELS[policy.level] ?? []+ if (members.some((m) => accepted.has(m))) {+ return issues+ }+ issues.push({+ model: members.join(', ') || policy.level,+ pointer: 'spec.models.level',+ reason: `level "${policy.level}" resolves to no model the gateway currently serves`,+ })+ return issues+}++/**+ * CI/test guard: every model in the curated `MODEL_POLICY_LEVELS` must be+ * servable. Catches drift between the hand-maintained tiers and the live+ * catalog (e.g. a tier pointing at a delisted SKU) before it reaches an+ * `auto` agent at runtime. Returns one issue per dead tier member.+ */+export function validateModelLevels(models: CatalogModel[]): ModelPolicyIssue[] {+ const accepted = acceptedModelIds(models)+ const issues: ModelPolicyIssue[] = []+ for (const level of Object.keys(MODEL_POLICY_LEVELS) as ModelLevel[]) {+ for (const model of MODEL_POLICY_LEVELS[level]) {+ if (!accepted.has(model)) {+ issues.push({+ model,+ pointer: `MODEL_POLICY_LEVELS.${level}`,+ reason: 'tier member not served by the gateway',+ })+ }+ }+ }+ return issues+}++/**+ * Runtime servability filter: keep only entries the catalog serves. If that+ * would drop everything (stale/empty catalog, or a manual list the catalog+ * doesn't know yet), return the original list unchanged — never strand a live+ * session on a catalog hiccup. The author-time gate is where bad models get+ * rejected; this is belt-and-suspenders.+ */+export function filterServableEntries(entries: ModelEntry[], models: CatalogModel[]): ModelEntry[] {+ if (models.length === 0) {+ return entries+ }+ const accepted = acceptedModelIds(models)+ const kept = entries.filter((e) => accepted.has(e.model))+ return kept.length > 0 ? kept : entries+}++// ── HTTP catalog client ──────────────────────────────────────────────────++export interface HttpGatewayCatalogOpts {+ /** Gateway base URL incl. version, e.g. `http://localhost:8080/v1`. */+ baseUrl: string+ /** `phs_` bearer with `llm_gateway:read`. Sent when set; the /models+ * read is otherwise unauthenticated. */+ bearer?: string+ /**+ * Outbound HTTP. Wire a `DirectHttpClient` — the gateway is+ * cluster-internal and smokescreen would deny it as RFC1918. Never pass+ * the proxy-bound `HttpClient`.+ */+ http: HttpFetcher+ /** Cache TTL in ms. Default 60_000. */+ ttlMs?: number+ /** Per-fetch timeout in ms. Default 5_000. */+ timeoutMs?: number+}++export class HttpGatewayCatalog implements GatewayCatalog {+ private readonly log = createLogger('gateway-catalog')+ private readonly baseUrl: string+ private readonly bearer: string | undefined+ private readonly http: HttpFetcher+ private readonly ttlMs: number+ private readonly timeoutMs: number+ private cache: { at: number; models: CatalogModel[] } | null = null+ private inflight: Promise<CatalogModel[]> | null = null++ constructor(opts: HttpGatewayCatalogOpts) {+ this.baseUrl = opts.baseUrl.replace(/\/$/, '')+ this.bearer = opts.bearer+ this.http = opts.http+ this.ttlMs = opts.ttlMs ?? 60_000+ this.timeoutMs = opts.timeoutMs ?? 5_000+ }++ async list(): Promise<CatalogModel[]> {+ if (this.cache && Date.now() - this.cache.at < this.ttlMs) {+ return this.cache.models+ }+ if (this.inflight) {+ return this.inflight+ }+ this.inflight = this.fetchModels()+ .then((models) => {+ this.cache = { at: Date.now(), models }+ return models+ })+ .catch((err) => {+ // Serve last-good through a transient gateway blip; never throw+ // — a catalog read must not be able to fail a promote or a+ // session. Empty only when we've never had a good fetch.+ this.log.warn({ err: err instanceof Error ? err.message : String(err) }, 'gateway_catalog_fetch_failed')+ return this.cache?.models ?? []+ })+ .finally(() => {+ this.inflight = null+ })+ return this.inflight+ }++ private async fetchModels(): Promise<CatalogModel[]> {+ const headers: Record<string, string> = { Accept: 'application/json' }+ if (this.bearer) {+ headers.Authorization = `Bearer ${this.bearer}`+ }+ const res = await this.http.fetch(`${this.baseUrl}/models`, {+ method: 'GET',+ headers,+ signal: AbortSignal.timeout(this.timeoutMs),+ })+ if (!res.ok) {+ throw new Error(`gateway /models HTTP ${res.status}`)+ }+ const body = (await res.json()) as WireResponse+ const models = (body.data ?? []).map(parseModel).filter((m): m is CatalogModel => m !== null)+ this.log.debug({ count: models.length }, 'gateway_catalog_loaded')+ return models+ }+}diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec.test.tsindex 99cbd55b92a8..c88acc01cf57 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts@@ -3,45 +3,24 @@ import {AgentSpecSchema,AuthConfigSchema,getSecretAllowedHosts,- ModelIdSchema,+ MODEL_POLICY_LEVELS,+ modelPolicyToList,principalsMatch,secretHostMatches,} from './spec'-describe('ModelIdSchema', () => {- // Runtime (`resolveModel` in agent-runner/src/models/pi-client.ts) demands- // `<provider>/<model-id>`; if authoring lets a bare id through, the runner- // crashes the session at first turn. Keep the contract enforced here.- it.each([- ['anthropic/claude-haiku-4-5', true],- ['anthropic/claude-opus-4-7', true],- ['openai/gpt-4o-mini', true],- ['ai-gateway/claude-haiku-4-5', true],- ['openai/o1-preview', true],- ['claude-haiku-4-5', false], // bare id — the runtime explosion this guards against- ['', false],- ['anthropic/', false],- ['/claude-haiku-4-5', false],- ['Anthropic/Claude', false], // provider must be lowercase- ['anthropic/claude haiku', false], // no spaces- ])('%s → %s', (input, valid) => {- expect(ModelIdSchema.safeParse(input).success).toBe(valid)- })-})-describe('AgentSpecSchema', () => {it('parses a minimal spec with defaults', () => {- const parsed = AgentSpecSchema.parse({ model: 'anthropic/claude-opus-4-7' })- expect(parsed.model).toBe('anthropic/claude-opus-4-7')+ const parsed = AgentSpecSchema.parse({})+ expect(parsed.models).toEqual({ mode: 'auto', level: 'medium', optimize_for: 'cost' })expect(parsed.triggers).toEqual([])expect(parsed.tools).toEqual([])- expect(parsed.entrypoint).toBe('agent.md')expect(parsed.limits.max_turns).toBe(50)})it('parses a fully-populated spec', () => {const spec: AgentSpec = AgentSpecSchema.parse({- model: 'anthropic/claude-opus-4-7',+ models: { mode: 'auto', level: 'high' },triggers: [{ type: 'slack', config: { channel_id: 'C01', mention_only: true, trusted_workspaces: '*' } },{ type: 'webhook', config: { path: '/hook' }, auth: { modes: [{ type: 'posthog_internal' }] } },@@ -54,7 +33,6 @@ describe('AgentSpecSchema', () => {skills: [{ id: 'deep-research', path: 'skills/deep-research/SKILL.md' }],secrets: ['ACME_KEY'],limits: { max_turns: 10, max_tool_calls: 50, max_wall_seconds: 300 },- entrypoint: 'agent.md',})expect(spec.triggers).toHaveLength(2)expect(spec.tools).toHaveLength(2)@@ -63,33 +41,72 @@ describe('AgentSpecSchema', () => {describe('limits.max_output_tokens', () => {it('defaults to undefined (runner picks a reasoning-aware default)', () => {- const parsed = AgentSpecSchema.parse({ model: 'test/x' })+ const parsed = AgentSpecSchema.parse({})expect(parsed.limits.max_output_tokens).toBeUndefined()})it('accepts an integer value', () => {- const parsed = AgentSpecSchema.parse({ model: 'test/x', limits: { max_output_tokens: 16_384 } })+ const parsed = AgentSpecSchema.parse({ model: 'x', limits: { max_output_tokens: 16_384 } })expect(parsed.limits.max_output_tokens).toBe(16_384)})it('rejects zero and negative values', () => {- expect(() => AgentSpecSchema.parse({ model: 'test/x', limits: { max_output_tokens: 0 } })).toThrow()- expect(() => AgentSpecSchema.parse({ model: 'test/x', limits: { max_output_tokens: -1 } })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', limits: { max_output_tokens: 0 } })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', limits: { max_output_tokens: -1 } })).toThrow()})it('rejects values above the typo-guard upper bound', () => {- expect(() => AgentSpecSchema.parse({ model: 'test/x', limits: { max_output_tokens: 200_001 } })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', limits: { max_output_tokens: 200_001 } })).toThrow()})})it('rejects unknown trigger type', () => {expect(() =>- AgentSpecSchema.parse({ model: 'test/x', triggers: [{ type: 'carrier-pigeon', config: {} }] })+ AgentSpecSchema.parse({ model: 'x', triggers: [{ type: 'carrier-pigeon', config: {} }] })).toThrow()})it('rejects unknown tool kind', () => {- expect(() => AgentSpecSchema.parse({ model: 'test/x', tools: [{ kind: 'rogue', id: 'x' }] })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', tools: [{ kind: 'rogue', id: 'x' }] })).toThrow()+ })++ describe('models.manual model id format', () => {+ // ModelIdSchema enforces `<provider>/<model-id>` so a bare id doesn't+ // freeze fine and then 400 on the very first session. Mirrored by+ // the Python schema in backend/logic/spec_schema.py.+ it('rejects a bare model id (no provider prefix)', () => {+ expect(() =>+ AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'claude-haiku-4-5' }] },+ })+ ).toThrow(/provider/)+ })++ it('rejects an uppercase provider', () => {+ expect(() =>+ AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'Anthropic/claude-haiku-4-5' }] },+ })+ ).toThrow(/provider/)+ })++ it('rejects a missing model id (trailing slash)', () => {+ expect(() =>+ AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'anthropic/' }] },+ })+ ).toThrow(/provider/)+ })++ it('accepts a canonical `<provider>/<model-id>`', () => {+ const parsed = AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'anthropic/claude-haiku-4-5' }] },+ })+ expect(parsed.models).toMatchObject({+ mode: 'manual',+ models: [{ model: 'anthropic/claude-haiku-4-5' }],+ })+ })})describe('cron trigger config', () => {@@ -101,7 +118,7 @@ describe('AgentSpecSchema', () => {it('parses a minimal cron trigger with all defaults', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: minimal }],})const t = spec.triggers[0]@@ -117,7 +134,7 @@ describe('AgentSpecSchema', () => {it('parses a fully-populated cron trigger', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{type: 'cron',@@ -144,7 +161,7 @@ describe('AgentSpecSchema', () => {it('rejects a name with disallowed characters', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, name: 'Weekly_Digest' } }],})).toThrow()@@ -153,7 +170,7 @@ describe('AgentSpecSchema', () => {it('rejects a name with a leading hyphen', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, name: '-digest' } }],})).toThrow()@@ -162,7 +179,7 @@ describe('AgentSpecSchema', () => {it('rejects an empty schedule', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, schedule: '' } }],})).toThrow()@@ -171,7 +188,7 @@ describe('AgentSpecSchema', () => {it('rejects an empty prompt', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, prompt: '' } }],})).toThrow()@@ -180,7 +197,7 @@ describe('AgentSpecSchema', () => {it('rejects a prompt longer than 4096 chars', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, prompt: 'x'.repeat(4097) } }],})).toThrow()@@ -189,7 +206,7 @@ describe('AgentSpecSchema', () => {it('rejects an unknown catch_up mode', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, catch_up: 'fire-twice' } }],})).toThrow()@@ -198,7 +215,7 @@ describe('AgentSpecSchema', () => {it('rejects max_catch_up_age_seconds above the 7-day cap', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, max_catch_up_age_seconds: 7 * 86400 + 1 } }],})).toThrow()@@ -207,7 +224,7 @@ describe('AgentSpecSchema', () => {it('rejects max_catch_up_age_seconds below 1', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'cron', config: { ...minimal, max_catch_up_age_seconds: 0 } }],})).toThrow()@@ -216,18 +233,18 @@ describe('AgentSpecSchema', () => {describe('framework_prompt config', () => {it('defaults to undefined when not present', () => {- const spec = AgentSpecSchema.parse({ model: 'test/x' })+ const spec = AgentSpecSchema.parse({ model: 'x' })expect(spec.framework_prompt).toBeUndefined()})it('parses an empty config with default omit list', () => {- const spec = AgentSpecSchema.parse({ model: 'test/x', framework_prompt: {} })+ const spec = AgentSpecSchema.parse({ model: 'x', framework_prompt: {} })expect(spec.framework_prompt?.omit).toEqual([])})it('parses a populated omit list', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',framework_prompt: { omit: ['meta_tool_guidance', 'reasoning_hint'] },})expect(spec.framework_prompt?.omit).toEqual(['meta_tool_guidance', 'reasoning_hint'])@@ -236,7 +253,7 @@ describe('AgentSpecSchema', () => {it('rejects unknown omit values', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',framework_prompt: { omit: ['unknown_section'] },})).toThrow()@@ -244,7 +261,7 @@ describe('AgentSpecSchema', () => {it('parses a version_pin', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',framework_prompt: { version_pin: 1 },})expect(spec.framework_prompt?.version_pin).toBe(1)@@ -253,7 +270,7 @@ describe('AgentSpecSchema', () => {it('rejects negative version_pin', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',framework_prompt: { version_pin: 0 },})).toThrow()@@ -263,7 +280,7 @@ describe('AgentSpecSchema', () => {describe('approval-gated tools', () => {it('defaults tools to requires_approval: false with admin-only policy', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{ kind: 'native', id: '@posthog/query' }],})const t = spec.tools[0]@@ -280,7 +297,7 @@ describe('AgentSpecSchema', () => {it('parses requires_approval: true with overridden policy fields', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -304,7 +321,7 @@ describe('AgentSpecSchema', () => {it('rejects ttl_ms below 1 minute', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -320,7 +337,7 @@ describe('AgentSpecSchema', () => {it('rejects ttl_ms above 7 days', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -337,7 +354,7 @@ describe('AgentSpecSchema', () => {// An empty (or unrecognised) legacy `approvers` derives no `type`, so// it lands on the `principal` default rather than throwing.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -356,7 +373,7 @@ describe('AgentSpecSchema', () => {it('parses an explicit agent type', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -381,7 +398,7 @@ describe('AgentSpecSchema', () => {// (+ `allow_agent_approver`); the preprocess derives `type` and drops// the legacy keys so old revisions keep validating.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -405,7 +422,7 @@ describe('AgentSpecSchema', () => {it('rejects an invalid approval type', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',tools: [{kind: 'native',@@ -424,7 +441,7 @@ describe('AgentSpecSchema', () => {// Bare strings in tools[] are the post-PR-7 equivalent of the// old allowlist[]: gates inclusion, no approval policy.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{id: 'linear',@@ -443,7 +460,7 @@ describe('AgentSpecSchema', () => {it('parses object-form tools[] entries with approval gating', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{id: 'posthog',@@ -480,7 +497,7 @@ describe('AgentSpecSchema', () => {// author wants the object slot reserved for a future config knob// (e.g. description override) without flipping the gate on.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{id: 'linear',@@ -499,7 +516,7 @@ describe('AgentSpecSchema', () => {it('defaults secrets to [] and tools to undefined when omitted on external', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{ id: 'linear', url: 'https://mcp.linear.app/sse' }],})const m = spec.mcps[0]@@ -514,7 +531,7 @@ describe('AgentSpecSchema', () => {// @posthog/http-request — the runner walks headers + substitutes// ${NAME} from `secrets[]` before opening the client.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{id: 'github',@@ -567,7 +584,7 @@ describe('AgentSpecSchema', () => {},},])('rejects an external entry with $label', ({ mcp }) => {- expect(() => AgentSpecSchema.parse({ model: 'test/x', mcps: [mcp] })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', mcps: [mcp] })).toThrow()})it('silently drops a legacy `allowlist[]` field (zod default + PR 7 hard-break)', () => {@@ -578,7 +595,7 @@ describe('AgentSpecSchema', () => {// their old narrowed set. This test pins the no-op so a future// `.strict()` add (which would reject) is a conscious choice.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',mcps: [{id: 'linear',@@ -595,19 +612,19 @@ describe('AgentSpecSchema', () => {describe('resume config (per-agent TTL on completed sessions)', () => {it('defaults to undefined when not present (preserves today behaviour)', () => {- const spec = AgentSpecSchema.parse({ model: 'test/x' })+ const spec = AgentSpecSchema.parse({ model: 'x' })expect(spec.resume).toBeUndefined()})it('applies sensible defaults when an empty resume section is present', () => {- const spec = AgentSpecSchema.parse({ model: 'test/x', resume: {} })+ const spec = AgentSpecSchema.parse({ model: 'x', resume: {} })expect(spec.resume?.enabled).toBe(false)expect(spec.resume?.max_completed_age_ms).toBe(7 * 24 * 60 * 60_000)})it('parses an opt-in week-long TTL config', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',resume: { enabled: true, max_completed_age_ms: 14 * 24 * 60 * 60_000 },})expect(spec.resume?.enabled).toBe(true)@@ -615,7 +632,7 @@ describe('AgentSpecSchema', () => {})it('rejects a non-positive max_completed_age_ms', () => {- expect(() => AgentSpecSchema.parse({ model: 'test/x', resume: { max_completed_age_ms: 0 } })).toThrow()+ expect(() => AgentSpecSchema.parse({ model: 'x', resume: { max_completed_age_ms: 0 } })).toThrow()})})@@ -627,13 +644,13 @@ describe('AgentSpecSchema', () => {it('declarative triggers require an auth block', () => {// webhook/chat/mcp must declare who can call them — no implicit default.expect(() =>- AgentSpecSchema.parse({ model: 'test/x', triggers: [{ type: 'webhook', config: { path: '/h' } }] })+ AgentSpecSchema.parse({ model: 'x', triggers: [{ type: 'webhook', config: { path: '/h' } }] })).toThrow()})it('per-trigger auth lands on the trigger', () => {const parsed = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',triggers: [{ type: 'chat', config: {}, auth: { modes: [{ type: 'posthog' }] } }],})const chat = parsed.triggers[0]@@ -675,13 +692,13 @@ describe('AgentSpecSchema', () => {describe('secrets[] — host-binding union', () => {it('accepts a bare-string entry (back-compat; resolvable but unbound)', () => {- const spec = AgentSpecSchema.parse({ model: 'test/x', secrets: ['ACME_KEY'] })+ const spec = AgentSpecSchema.parse({ model: 'x', secrets: ['ACME_KEY'] })expect(spec.secrets).toEqual(['ACME_KEY'])})it('accepts the object form with allowed_hosts', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',secrets: [{ name: 'SLACK_BOT_TOKEN', allowed_hosts: ['slack.com'] }],})expect(spec.secrets).toEqual([{ name: 'SLACK_BOT_TOKEN', allowed_hosts: ['slack.com'] }])@@ -693,7 +710,7 @@ describe('AgentSpecSchema', () => {// ship with host bindings. http-request only refuses egress on// the bare-string entries at substitution time.const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',secrets: ['LEGACY', { name: 'GH_PAT', allowed_hosts: ['api.github.com'] }],})expect(spec.secrets).toHaveLength(2)@@ -705,7 +722,7 @@ describe('AgentSpecSchema', () => {// declare "no binding."expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',secrets: [{ name: 'X', allowed_hosts: [] }],})).toThrow()@@ -714,7 +731,7 @@ describe('AgentSpecSchema', () => {it('rejects an object entry missing the name', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',secrets: [{ allowed_hosts: ['x.example'] }],})).toThrow()@@ -723,7 +740,7 @@ describe('AgentSpecSchema', () => {describe('getSecretAllowedHosts', () => {const spec: AgentSpec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',secrets: ['LEGACY', { name: 'GH_PAT', allowed_hosts: ['api.github.com', '*.github.com'] }],})@@ -780,7 +797,7 @@ describe('AgentSpecSchema', () => {describe('identity_providers[] binding', () => {it('accepts the per-asker `principal` binding (defaulting when omitted)', () => {const spec = AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',identity_providers: [{ kind: 'posthog' }],})expect(spec.identity_providers[0]?.binding).toBe('principal')@@ -789,10 +806,90 @@ describe('AgentSpecSchema', () => {it('rejects the unimplemented `agent` binding (the runtime seam exists, but a spec cannot select it)', () => {expect(() =>AgentSpecSchema.parse({- model: 'test/x',+ model: 'x',identity_providers: [{ kind: 'posthog', binding: 'agent' }],})).toThrow()})})})++describe('modelPolicyToList', () => {+ it('expands an auto level to its priority list, order preserved, no reasoning by default', () => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'auto', level: 'low' } })+ expect(modelPolicyToList(spec)).toEqual(+ MODEL_POLICY_LEVELS.low.map((model) => ({ model, reasoning: undefined }))+ )+ })++ it('defaults to the auto/medium list when models is omitted', () => {+ const spec = AgentSpecSchema.parse({})+ expect(modelPolicyToList(spec).map((e) => e.model)).toEqual([...MODEL_POLICY_LEVELS.medium])+ })++ it('auto: policy.reasoning applies to every resolved entry', () => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'auto', level: 'high', reasoning: 'high' } })+ expect(modelPolicyToList(spec).every((e) => e.reasoning === 'high')).toBe(true)+ })++ it('auto: falls back to spec.reasoning when the policy declares none', () => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'auto', level: 'medium' }, reasoning: 'low' })+ expect(modelPolicyToList(spec).every((e) => e.reasoning === 'low')).toBe(true)+ })++ it('auto: policy.reasoning wins over spec.reasoning', () => {+ const spec = AgentSpecSchema.parse({+ models: { mode: 'auto', level: 'medium', reasoning: 'xhigh' },+ reasoning: 'low',+ })+ expect(modelPolicyToList(spec).every((e) => e.reasoning === 'xhigh')).toBe(true)+ })++ it('manual: passes the explicit list through in order, per-entry reasoning preserved', () => {+ const spec = AgentSpecSchema.parse({+ models: {+ mode: 'manual',+ models: [{ model: 'anthropic/claude-opus-4-7', reasoning: 'high' }, { model: 'openai/gpt-5' }],+ },+ })+ expect(modelPolicyToList(spec)).toEqual([+ { model: 'anthropic/claude-opus-4-7', reasoning: 'high' },+ { model: 'openai/gpt-5', reasoning: undefined },+ ])+ })++ it('manual: an entry without its own reasoning inherits spec.reasoning', () => {+ const spec = AgentSpecSchema.parse({+ models: { mode: 'manual', models: [{ model: 'openai/gpt-5' }] },+ reasoning: 'medium',+ })+ expect(modelPolicyToList(spec)).toEqual([{ model: 'openai/gpt-5', reasoning: 'medium' }])+ })+})++describe('models.optimize_for', () => {+ it('defaults to cost on an auto policy', () => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'auto', level: 'medium' } })+ expect(spec.models.optimize_for).toBe('cost')+ })++ it('defaults to cost on a manual policy', () => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'manual', models: [{ model: 'openai/gpt-5' }] } })+ expect(spec.models.optimize_for).toBe('cost')+ })++ it('defaults to cost when models is omitted entirely', () => {+ expect(AgentSpecSchema.parse({}).models.optimize_for).toBe('cost')+ })++ it.each(['cost', 'availability'] as const)('accepts optimize_for: %s', (mode) => {+ const spec = AgentSpecSchema.parse({ models: { mode: 'auto', level: 'high', optimize_for: mode } })+ expect(spec.models.optimize_for).toBe(mode)+ })++ it('rejects an unknown optimize_for', () => {+ expect(() =>+ AgentSpecSchema.parse({ models: { mode: 'auto', level: 'high', optimize_for: 'latency' } })+ ).toThrow()+ })+})diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex 58a76652685c..98181be65765 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -9,10 +9,20 @@ import { z } from 'zod'import type { TriggerMetadata } from '../runtime/trigger-metadata'+/**+ * Canonical model id: `<provider>/<model-id>` (e.g. `anthropic/claude-haiku-4-5`).+ *+ * Reject bare ids at authoring time so we don't freeze a revision the gateway+ * can't serve. `resolveModel` / `acceptedModelIds` operate on the prefixed+ * form; a bare `haiku-4-5` would pass `.min(1)` here, freeze, then fail the+ * very first session with a 400 from the gateway. Mirror of+ * `_AGENT_SPEC_JSON_SCHEMA_RAW.models.manual.models[].model.pattern` in+ * `backend/logic/spec_schema.py` — keep the two in sync.+ */export const ModelIdSchema = z.string().min(1)- .regex(/^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$/, 'must be "<provider>/<model-id>", e.g. "anthropic/claude-haiku-4-5"')+ .regex(/^[a-z0-9_-]+\/[a-zA-Z0-9._:-]+$/, 'model id must be "<provider>/<model-id>"')/*** Auth modes. Auth is a property of the TRIGGER, not the spec — declarative@@ -677,6 +687,58 @@ export type AuthConfig = z.infer<typeof AuthConfigSchema>*/export const ReasoningEffortSchema = z.enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+/** One model in a manual priority list; per-entry `reasoning` overrides the spec default. */+export const ModelEntrySchema = z.object({+ model: ModelIdSchema,+ reasoning: ReasoningEffortSchema.optional(),+})++/** Quality/cost level for `auto` policy; mapped to a maintained model list (below). */+export const ModelLevelSchema = z.enum(['low', 'medium', 'high'])++/**+ * How the runner treats the priority list across a session's turns.+ *+ * - `cost` (default): the first turn walks the list until a model answers, then+ * pins that model for the rest of the session — every later turn uses ONLY it,+ * no cross-model failover. One provider per session keeps its prompt cache warm+ * (cache reads are ~0.1–0.5× of full input), which dominates multi-turn cost.+ * The trade: if the pinned model goes down mid-session the turn fails (after+ * pi-ai's same-provider retries) rather than switching — switching a large+ * cached session to a cold provider re-reads the whole context at full price.+ * - `availability`: the runner still leads with the last-served model (sticky, so+ * it doesn't thrash) but DOES fail over to the next model on failure, trading+ * that cold-cache re-read for keeping the session alive.+ */+export const ModelOptimizeForSchema = z.enum(['cost', 'availability'])++/** `auto`: platform resolves `level` to a priority-ordered list at runtime.+ * `manual`: author's explicit priority list.+ * `optimize_for` (both): session model stability vs. resilience — see above. */+export const ModelPolicySchema = z.discriminatedUnion('mode', [+ z.object({+ mode: z.literal('auto'),+ level: ModelLevelSchema.default('medium'),+ reasoning: ReasoningEffortSchema.optional(),+ optimize_for: ModelOptimizeForSchema.default('cost'),+ }),+ z.object({+ mode: z.literal('manual'),+ models: z.array(ModelEntrySchema).min(1),+ optimize_for: ModelOptimizeForSchema.default('cost'),+ }),+])++/** `auto` level → priority-ordered, cross-provider list (also the fallback chain).+ * The curated grouping layer over the gateway catalog: ids here MUST be+ * gateway-served. `validateModelLevels` (gateway-catalog.ts) guards that in+ * CI; the runner filters this against the live catalog at session start. */+export const MODEL_POLICY_LEVELS: Record<z.infer<typeof ModelLevelSchema>, readonly string[]> = {+ low: ['anthropic/claude-haiku-4-5', 'openai/gpt-5-mini'],+ medium: ['anthropic/claude-sonnet-4-6', 'openai/gpt-5'],+ high: ['anthropic/claude-opus-4-7', 'openai/gpt-5-pro'],+}+/*** Author-facing knobs for the framework-injected system-prompt preamble.*/@@ -780,7 +842,8 @@ export const IdentityProviderConfigSchema = z.discriminatedUnion('kind', [export type IdentityProviderConfig = z.infer<typeof IdentityProviderConfigSchema>export const AgentSpecSchema = z.object({- model: ModelIdSchema,+ /** Model selection: auto level (default) or manual priority list. Resolve via `modelPolicyToList`. */+ models: ModelPolicySchema.default({ mode: 'auto', level: 'medium', optimize_for: 'cost' }),triggers: z.array(TriggerSchema).default([]),tools: z.array(ToolRefSchema).default([]),mcps: z.array(McpRefSchema).default([]),@@ -795,13 +858,29 @@ export const AgentSpecSchema = z.object({max_memory_mb: 512,max_cpu_cores: 0.25,}),- entrypoint: z.string().default('agent.md'),reasoning: ReasoningEffortSchema.optional(),framework_prompt: FrameworkPromptConfigSchema.optional(),resume: ResumeConfigSchema.optional(),})export type AgentSpec = z.infer<typeof AgentSpecSchema>+export type ModelEntry = z.infer<typeof ModelEntrySchema>+export type ModelLevel = z.infer<typeof ModelLevelSchema>+export type ModelOptimizeFor = z.infer<typeof ModelOptimizeForSchema>+export type ModelPolicy = z.infer<typeof ModelPolicySchema>++/** Priority-ordered models the runner tries (primary first). Reasoning: per-entry → auto override → spec default. */+export function modelPolicyToList(spec: Pick<AgentSpec, 'models' | 'reasoning'>): ModelEntry[] {+ const policy = spec.models+ if (policy.mode === 'manual') {+ return policy.models.map((m) => ({ model: m.model, reasoning: m.reasoning ?? spec.reasoning }))+ }+ return MODEL_POLICY_LEVELS[policy.level].map((model) => ({+ model,+ reasoning: policy.reasoning ?? spec.reasoning,+ }))+}+export type Trigger = z.infer<typeof TriggerSchema>export type TriggerType = Trigger['type']diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.tsindex 933cff1ae4c2..1f0bb0e23b2b 100644--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts@@ -79,10 +79,10 @@ describe('buildSystemPrompt', () => {expect(prompt).not.toContain('Available skills')})- it('falls back when entrypoint missing', async () => {- const spec = AgentSpecSchema.parse({ model: 'test/x' })+ it('falls back when agent.md missing', async () => {+ const spec = AgentSpecSchema.parse({ model: 'x' })const prompt = await buildSystemPrompt(makeRev(spec), bundle)- expect(prompt).toMatch(/missing entrypoint/)+ expect(prompt).toMatch(/missing agent\.md/)})it('injects the framework preamble before agent.md', async () => {diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.tsindex 402073d52da7..cb87de603006 100644--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts@@ -4,7 +4,7 @@* 1. Framework preamble — platform-owned guidance about the state* machine, meta tools, and (slice 2+) tool failure / approval* handling / reasoning hints. See `framework-preamble.ts`.- * 2. agent.md (or spec.entrypoint) — author-owned instructions. Wins+ * 2. agent.md — author-owned instructions. Wins* over the preamble through normal natural-language precedence* (the model reads it after).* 3. Skills index — listed as one line per skill (`- <id>: <description>`).@@ -75,11 +75,10 @@ export async function buildSystemPrompt(// defaults via normal natural-language instructions.parts.push(renderFrameworkPreamble(rev))- const entry = rev.spec.entrypoint || 'agent.md'- if (await bundle.exists(rev.id, entry)) {- parts.push(await bundle.readText(rev.id, entry))+ if (await bundle.exists(rev.id, 'agent.md')) {+ parts.push(await bundle.readText(rev.id, 'agent.md'))} else {- parts.push('(missing entrypoint — please add agent.md)')+ parts.push('(missing agent.md — please add it)')}if (rev.spec.skills.length > 0) {diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.tsindex 2bad3092df47..4039eabe8d42 100644--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts@@ -20,6 +20,7 @@ import { Static, TSchema, Type } from 'typebox'import type { MemoryStore } from '../memory/store'import type { TabularStore } from '../memory/tabular-store'import type { Credential } from '../runtime/credential-broker'+import type { GatewayCatalog } from '../runtime/gateway-catalog'import type { HttpFetcher } from '../runtime/http-client'import type { WebSearchProvider } from '../runtime/web-search'@@ -147,6 +148,13 @@ export interface ToolContext {* reads inside tool code.*/posthogApiBaseUrl: string+ /**+ * Served-model catalog for the `@posthog/agent-applications-models` tool.+ * Read it here, not via `ctx.http` — the catalog routes through a+ * DirectHttpClient (the gateway is cluster-internal; smokescreen would deny+ * a proxy-bound call). Absent when the gateway is off.+ */+ gatewayCatalog?: GatewayCatalog/*** Ordered web-search provider chain for `@posthog/web-search` (primary* first, configured fallbacks next). Built from `AGENT_WEB_SEARCH_*`diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.tsindex b6a08fbe738f..68cdec92c7b6 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts@@ -106,14 +106,13 @@ export type TypedTool = z.infer<typeof TypedToolSchema>*/export const TypedSpecSchema = z.object({- model: z.string().min(1).optional(),+ models: z.unknown().optional(),triggers: z.array(z.unknown()).optional(),mcps: z.array(z.unknown()).optional(),identity_providers: z.array(z.unknown()).optional(),secrets: z.array(z.string()).optional(),limits: z.unknown().optional(),auth: z.unknown().optional(),- entrypoint: z.string().optional(),reasoning: z.string().optional(),framework_prompt: z.unknown().optional(),resume: z.unknown().optional(),diff --git a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.tsindex 4dcf3944892e..449fab45fb00 100644--- a/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/cron-trigger.test.ts@@ -44,7 +44,7 @@ describe('cron trigger: real e2e', () => {const { application, revision } = await c.deployAgent({slug: 'cron-digest',spec: {- model: 'faux/test',+ models: { mode: 'manual', models: [{ model: 'faux/test' }] },triggers: [{type: 'cron',@@ -114,7 +114,7 @@ describe('cron trigger: real e2e', () => {const { application, revision } = await c.deployAgent({slug: 'cron-manual',spec: {- model: 'faux/test',+ models: { mode: 'manual', models: [{ model: 'faux/test' }] },triggers: [{type: 'cron',@@ -155,7 +155,7 @@ describe('cron trigger: real e2e', () => {const { revision } = await c.deployAgent({slug: 'cron-dedupe',spec: {- model: 'faux/test',+ models: { mode: 'manual', models: [{ model: 'faux/test' }] },triggers: [{type: 'cron',diff --git a/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.tsindex 30e2bfd69850..dc89cf1a4c93 100644--- a/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/example-posthog-ai.test.ts@@ -69,6 +69,10 @@ describe('example: posthog-ai bundle', () => {it('runs on an OpenAI model the local gateway supports', async () => {const { spec } = await loadBundle()- expect(AgentSpecSchema.parse(spec).model).toBe('openai/gpt-5.5')+ expect(AgentSpecSchema.parse(spec).models).toEqual({+ mode: 'manual',+ models: [{ model: 'openai/gpt-5.5' }],+ optimize_for: 'cost',+ })})})diff --git a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.tsindex ea8294f29898..6551a5e28022 100644--- a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts@@ -1,6 +1,6 @@/**- * Per-agent spec.model: two agents in the same cluster declare different- * spec.model strings. The runner resolves each through `resolveModel`, and the+ * Per-agent models: two agents in the same cluster declare different+ * models strings. The runner resolves each through `resolveModel`, and the* resolved Model is what the driver streams with.** `resolveModel` is the routing seam (called once per session in the worker),@@ -54,7 +54,7 @@ function fauxModelFor(specModel: string): Model<string> {return { id: specModel, name: specModel, api: 'faux', provider: 'faux' } as unknown as Model<string>}-describe('per-agent spec.model resolution: real e2e', () => {+describe('per-agent models resolution: real e2e', () => {let pool: Poollet bundlePrefix: stringlet bundleTestStore: BundleTestStore@@ -89,7 +89,7 @@ describe('per-agent spec.model resolution: real e2e', () => {await pool.end()})- it('two agents with different spec.model values resolve distinct Models', async () => {+ it('two agents with different models values resolve distinct Models', async () => {const bundle = bundleTestStore.storeconst revisions = new PgRevisionStore(pool)const queue = new PgSessionQueue(pool)@@ -107,7 +107,7 @@ describe('per-agent spec.model resolution: real e2e', () => {approvals: new PgApprovalStore(pool),bus,resolveSecrets: async () => ({}),- // Per-agent model resolution — keys off spec.model verbatim. This is+ // Per-agent model resolution — keys off models verbatim. This is// the seam the driver streams with, so recording here proves routing.resolveModel: (specModel) => {modelsResolved.push(specModel)@@ -116,14 +116,14 @@ describe('per-agent spec.model resolution: real e2e', () => {maxConcurrency: 1,})- // Two agents with distinct spec.model strings.+ // Two agents with distinct models strings.for (const [slug, model] of [['agent-a', 'faux/model-A'],['agent-b', 'faux/model-B'],] as const) {const app = await revisions.createApplication({ team_id: 1, slug, name: slug, description: '' })const spec = AgentSpecSchema.parse({- model,+ models: { mode: 'manual', models: [{ model }] },triggers: [{type: 'chat',diff --git a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.tsindex 055c4870100c..ed43c17fb939 100644--- a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts@@ -39,7 +39,7 @@ export default {// (which auto-freezes); we use them directly to keep the revision draft.function defaultSpec(): Record<string, unknown> {return {- model: 'faux/faux',+ models: { mode: 'manual', models: [{ model: 'faux/faux' }] },triggers: [{ type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },],@@ -95,7 +95,11 @@ describe('typed bundle authoring API: real e2e', () => {// skills + tools start empty.expect(res.body.bundle.skills).toEqual([])expect(res.body.bundle.tools).toEqual([])- expect(res.body.bundle.spec).toEqual(expect.objectContaining({ model: 'faux/faux' }))+ expect(res.body.bundle.spec).toEqual(+ expect.objectContaining({+ models: { mode: 'manual', models: [{ model: 'faux/faux' }], optimize_for: 'cost' },+ })+ )expect(res.body.warnings).toEqual([])})})@@ -122,7 +126,7 @@ describe('typed bundle authoring API: real e2e', () => {},],spec: {- model: 'faux/faux',+ models: { mode: 'manual', models: [{ model: 'faux/faux' }] },triggers: [{type: 'chat',@@ -239,12 +243,16 @@ describe('typed bundle authoring API: real e2e', () => {})const newSpec = {...defaultSpec(),- model: 'faux/changed',+ models: { mode: 'manual', models: [{ model: 'faux/changed' }] },}const put = await request(c.janitor).put(`/revisions/${rid}/spec`).send({ spec: newSpec })expect(put.status).toBe(200)const get = await request(c.janitor).get(`/revisions/${rid}/bundle`)- expect(get.body.bundle.spec.model).toBe('faux/changed')+ expect(get.body.bundle.spec.models).toEqual({+ mode: 'manual',+ models: [{ model: 'faux/changed' }],+ optimize_for: 'cost',+ })expect(get.body.bundle.skills).toHaveLength(1)expect(get.body.bundle.tools).toHaveLength(1)})diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.jsonindex fd8aa0f06393..31069f951a9c 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-approval-demo/spec.json@@ -1,5 +1,5 @@{- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },"reasoning": "low","triggers": [{diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.mdindex 7c592e07830f..7bfc17543379 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/choosing-the-model/SKILL.md@@ -1,63 +1,113 @@# Skill — choosing the model-Load whenever you're about to set `spec.model` on a new or edited-agent, OR the user asks "which model should I use?" / "is this the-right model?" / "what's the cheapest model that'll work?".+Load whenever you're about to set `spec.models` on a new or+edited agent, OR the user asks "which model should I use?" / "is+this the right model?" / "what's the cheapest model that'll work?".-Your job: **recommend a model based on the agent's actual job,-explain the tradeoff clearly, and let the user decide.** Don't+Your job: **recommend a model policy based on the agent's actual+job, explain the tradeoff clearly, and let the user decide.** Don'tdefault to the most expensive model out of habit. Don't default to-the cheapest either. Match model to job.+the cheapest either. Match the policy to the job.++## auto is the default — start there++The model lives in `spec.models`, a discriminated union on+`mode`:++- **`auto`** (the default for almost every agent) — you pick a+ `level` (`low` / `medium` / `high`, default `medium`) and the+ platform resolves it to a maintained, priority-ordered,+ cross-provider model list at runtime. The list is kept current as+ models ship and prices move, so an `auto` agent rides upgrades+ without a spec edit and falls back across providers automatically.+- **`manual`** — an explicit, author-ordered priority list. Only+ reach for this when the agent genuinely needs a specific model+ (a fine-tune, a capability only one model has, a contractual /+ compliance pin). It opts you OUT of platform model upgrades.++```jsonc+// auto — the recommendation for most agents+{ "models": { "mode": "auto", "level": "medium" } }++// auto with reasoning, when the job benefits from deliberation+{ "models": { "mode": "auto", "level": "high", "reasoning": "high" } }++// manual — explicit, PROVIDER-DIVERSE priority list+{ "models": { "mode": "manual", "models": [+ { "model": "anthropic/claude-sonnet-4-6", "reasoning": "high" },+ { "model": "openai/gpt-5" }+] } }+```## The cost / quality axesThree independent dials in roughly increasing cost:-1. **Model family** — Haiku < Sonnet < Opus (Anthropic); GPT-5-mini- < GPT-5 < GPT-5-thinking (OpenAI); Gemini-flash < Gemini-pro.- Within a vendor each step up is ~3-8× the per-token cost.-2. **Reasoning level** (`spec.reasoning`) — `minimal` < `low` <- `medium` < `high` < `xhigh`. Adds deliberation tokens, multiplies- per-turn cost. Only meaningful for `high`+ on reasoning-heavy- tasks; for skim-and-respond agents it's pure waste.+1. **Level / model** — `auto` `low` < `medium` < `high`; or, in+ `manual`, the specific model you pin. Within a vendor each step up+ is ~3-8× the per-token cost.+2. **Reasoning** — `minimal` < `low` < `medium` < `high` < `xhigh`.+ Set it on the policy (`auto.reasoning`) or per-model+ (`models[].reasoning`, which overrides). Adds deliberation tokens,+ multiplies per-turn cost. Only meaningful for `high`+ on+ reasoning-heavy tasks; for skim-and-respond agents it's pure waste.3. **Context budget** (`spec.limits.max_output_tokens` + conversationlength over multi-turn) — longer conversations re-feed the wholehistory each turn, so multi-turn agents pay quadratically.-A small Haiku agent with `reasoning: minimal` on short-conversations runs ~$0.01/session. A Sonnet agent at `reasoning:-high` on 50-turn debugging sessions runs ~$3/session. Two orders of-magnitude, same platform.+A `low` agent with `reasoning: minimal` on short conversations runs+~$0.01/session. A `high` agent at `reasoning: high` on 50-turn+debugging sessions runs ~$3/session. Two orders of magnitude, same+platform.-## The decision flowchart+## Picking the levelWalk this with the user — out loud, not in your head. The skillthey're paying for is your reasoning, not your answer.```textWhat's the job?-├── Short, formulaic, no reasoning ........ Haiku, reasoning: minimal+├── Short, formulaic, no reasoning ........ auto/low, reasoning: minimal│ ("look up a thing and reply") (slack lookup bots, FAQ bots,│ webhook responders)-├── Multi-step but bounded ................ Sonnet, reasoning unset+├── Multi-step but bounded ................ auto/medium, reasoning unset│ ("query data, format an answer") (analytics summaries, status│ reports, structured drafts)-├── Open-ended reasoning, single hop ...... Sonnet, reasoning: medium+├── Open-ended reasoning, single hop ...... auto/medium, reasoning: medium│ ("triage this alert, suggest a fix") (oncall triage, code review,│ planning, light debugging)-├── Long, branching, with backtracking .... Sonnet, reasoning: high+├── Long, branching, with backtracking .... auto/high, reasoning: high│ ("debug this failing session, work (the Agent Builder itself, deep│ through hypotheses") investigations, multi-turn│ editing flows)-└── Cutting edge / research-grade ......... Opus / GPT-5-thinking, high+└── Cutting edge / research-grade ......... auto/high, reasoning: xhigh("solve this novel problem") (rare — flag the costexplicitly to the user)```-Default recommendation when uncertain: **`anthropic/claude-sonnet-4-6`-with `reasoning` unset.** It's the platform's stable workhorse —-good enough for almost anything, not embarrassingly expensive for-the simple cases.+Default recommendation when uncertain: **`{ mode: "auto", level:+"medium" }`, reasoning unset.** Good enough for almost anything, not+embarrassingly expensive for the simple cases — and it tracks model+upgrades for free.++## When manual is worth it — and how to order it++Reach for `manual` only when the job needs a specific model. When you+do, **order the list provider-diverse.** The list is a fallback chain:+the runner tries each in order until one answers. A fallback to the+same provider as the primary doesn't help when that provider is the+thing that's down — list a different vendor next so an outage degrades+instead of failing.++- Good: `[ anthropic/claude-sonnet-4-6, openai/gpt-5 ]` — Anthropic+ down → OpenAI catches it.+- Pointless: `[ anthropic/claude-sonnet-4-6,+anthropic/claude-haiku-4-5 ]` — one provider outage takes out both.++Set per-model `reasoning` when the fallback should think differently+from the primary (e.g. high on the primary, unset on a cheaper+backstop). If the whole policy wants the same reasoning, set it once+on the spec instead.## The conversation to have@@ -71,39 +121,43 @@ model, do this — IN ORDER, don't skip the asking:short-formulaic-no-reasoning job — one API call, one reply, nobranching."3. **Recommend with the cost tradeoff stated.** "I'd recommend- `anthropic/claude-haiku-4-5` at `reasoning: minimal`. Expected- cost: ~$0.005-$0.02 per @-mention. A Sonnet equivalent would be- ~$0.05-$0.20 per @-mention — 10× more for no quality difference- on this job."+ `{ mode: auto, level: low }` at `reasoning: minimal`. Expected+ cost: ~$0.005-$0.02 per @-mention. A `high`-level equivalent+ would be ~$0.05-$0.20 per @-mention — 10× more for no quality+ difference on this job."4. **Offer the user the upgrade explicitly.** "If you'd rather pay- more for slightly better natural-language framing of the reply,- I can use Sonnet. Or if you want the cheapest possible, we can- try `anthropic/claude-haiku-4-5` at `reasoning: minimal` and see- if the replies feel right. Which way do you want to go?"+ more for slightly better natural-language framing of the reply, I+ can move to `medium`. Or if this is a contractual must-use-vendor-X+ case, we can pin a manual list. Which way do you want to go?"5. **Wait for the user's pick.** Don't default. Don't assume. Don't- "just go with Sonnet to be safe."+ "just go with medium to be safe."For the open-ended reasoning cases the conversation flips: lead with-"this job benefits from deliberation; I'd recommend Sonnet with-`reasoning: medium`, ~$0.20-$0.50 per session. A Haiku version+"this job benefits from deliberation; I'd recommend `auto/medium`+with `reasoning: medium`, ~$0.20-$0.50 per session. A `low` versionmight cost $0.02/session but you'll see it miss things on harder-inputs. Want me to start with Sonnet and we can dial down if-sessions feel over-budget?"+inputs. Want me to start there and we can dial down if sessions feel+over-budget?"## When to push back on the user-The user might ask for the wrong model. Push back gently:--- **User picks Opus / GPT-5-thinking for a lookup bot.** "Opus on a- one-API-call agent is a ~50× cost markup for zero quality win on- this job. I'd recommend Haiku — happy to upgrade if you see- quality issues, but starting at Opus is paying for capability you- can't use here."-- **User picks Haiku for a debugging agent.** "Haiku tends to miss- the subtle hypotheses on multi-turn debugging — the kind of agent- that helps less than it costs to run. I'd recommend Sonnet- starting point. If cost matters, we can put a tight+The user might ask for the wrong policy. Push back gently:++- **User picks `auto/high` (or pins Opus) for a lookup bot.** "A+ top-tier model on a one-API-call agent is a ~50× cost markup for+ zero quality win on this job. I'd recommend `low` — happy to+ upgrade if you see quality issues, but starting at the top is+ paying for capability you can't use here."+- **User picks `auto/low` for a debugging agent.** "`low` tends to+ miss the subtle hypotheses on multi-turn debugging — the kind of+ agent that helps less than it costs to run. I'd recommend `medium`+ as the starting point. If cost matters, we can put a tight`max_wall_seconds` / `max_turns` to cap session cost."+- **User pins a single-provider manual list.** "A same-provider+ fallback doesn't survive that provider having an outage — if you+ want a fallback at all, let's make the second entry a different+ vendor. Otherwise `auto` already gives you cross-provider+ fallback for free."- **User picks `reasoning: xhigh` on anything that isn't research-grade.** "`xhigh` adds 5-10× the per-turn cost for diminishingreturns past `high`. Worth it for truly novel problems; for almost@@ -112,22 +166,17 @@ The user might ask for the wrong model. Push back gently:## Cost estimation when the user asks-For the rough back-of-envelope:--| Model | Input $/1M tok | Output $/1M tok | Notes |-| ----------------------------- | -------------- | --------------- | --------------------------------------- |-| `anthropic/claude-haiku-4-5` | ~$0.80 | ~$4 | Fast, cheap, good at structured work |-| `anthropic/claude-sonnet-4-6` | ~$3 | ~$15 | Platform default; balanced quality/cost |-| `anthropic/claude-opus-4-7` | ~$15 | ~$75 | High-end reasoning; rare to need |-| `openai/gpt-5-mini` | ~$0.25 | ~$2 | Cheapest competent option |-| `openai/gpt-5` | ~$2.50 | ~$10 | OpenAI workhorse |-| `openai/gpt-5-thinking` | ~$15 | ~$60 | Heavy reasoning, similar tier to Opus |+Don't ballpark from a hardcoded table — prices and the models behind+each `auto` level move. **Call `@posthog/agent-applications-models`**: it+returns every served model with its provider, context window, and+per-million-token pricing. Find the model(s) the policy resolves to and+quote from that. It's also the source of truth for which model ids are+valid in a `models` — promote rejects any that aren't served.-(These shift; ground-truth lives in-`@posthog/get-llm-total-costs-for-project` for actual billed rates.-Use this table for ballparking the conversation, not for invoices.)+For actual billed spend on an existing agent, use+`@posthog/get-llm-total-costs-for-project`.-Quick session-cost arithmetic, for the recommendation conversation:+Quick session-cost arithmetic, once you have live rates:```textsession cost ≈ (avg_input_tokens × input_rate)@@ -146,12 +195,14 @@ $1?" precision so they can make a real choice.A good model-pick conversation finishes with:-- The user said which model they want.+- The user said which policy they want.- The user understood why you suggested it.- The user understood roughly what it'll cost per session.-- The agent's `spec.model` is set.-- If reasoning matters, `spec.reasoning` is set explicitly (not- defaulted).+- The agent's `spec.models` is set (`auto` unless the job+ truly needs a `manual` pin).+- Any `manual` list is provider-diverse, ordered primary-first.+- If reasoning matters, it's set explicitly (on the policy or+ per-model), not defaulted.- If session cost matters, `spec.limits.max_turns` /`max_wall_seconds` reflect the cap the user chose.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.mdindex a1e4a41c898b..19095b11fc22 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/cost-and-quota-analysis/SKILL.md@@ -184,7 +184,7 @@ GROUP BY agentThen explain the delta in terms of the spec:-- Different model? Check `spec.model`.+- Different model? Check `spec.models`.- Different reasoning level? Check `spec.reasoning` — a higher level(`high` / `xhigh`) adds deliberation tokens on thinking-heavy turns.- More turns? Likely a prompt issue — `max($agent_turn)` per session,@@ -222,7 +222,7 @@ Useful to know when someone asks "how do I make it cheaper?":| Lever | Effect || ---------------------------------- | ------------------------------------------------------------------- |-| Model (`spec.model`) | Biggest factor — claude-haiku is ~1/5 sonnet, gpt-4-mini is similar |+| Model (`spec.models`) | Biggest factor — claude-haiku is ~1/5 sonnet, gpt-4-mini is similar || Reasoning level (`spec.reasoning`) | Higher levels (`high` / `xhigh`) add deliberation tokens || Skills layout | Many skills loaded per turn means a fatter system prompt every turn || Custom tool egress | Tools that fetch large pages inflate input tokens on the next turn |diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.mdindex e20a585c10c3..c2cd002d80e7 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md@@ -53,15 +53,15 @@ sees it.Choose the right verb:-| Verb | When | Reversibility |-| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |-| `posthog__agent-applications-revisions-partial-update` | Change `spec` fields (model, limits, triggers, tools[], identity_providers, mcps) — merges into the spec | Easy — the next update overwrites |-| `posthog__agent-applications-revisions-spec-update` | Replace the whole `spec` at once (a large rewrite) | Easy — overwrites the spec |-| `posthog__agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |-| `posthog__llm-skills-search` / `posthog__llm-skills-create` | Find or author a skill in the llma-skill store | Easy — the store keeps every version |-| `posthog__agent-applications-revisions-skill-refs-set` | Set which store skills the draft pins (`skill_refs`) | Easy — re-set the list; nothing is deleted |-| `posthog__agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |-| `posthog__agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |+| Verb | When | Reversibility |+| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `posthog__agent-applications-revisions-partial-update` | Change `spec` fields (models, limits, triggers, tools[], identity_providers, mcps) — merges into the spec | Easy — the next update overwrites |+| `posthog__agent-applications-revisions-spec-update` | Replace the whole `spec` at once (a large rewrite) | Easy — overwrites the spec |+| `posthog__agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |+| `posthog__llm-skills-search` / `posthog__llm-skills-create` | Find or author a skill in the llma-skill store | Easy — the store keeps every version |+| `posthog__agent-applications-revisions-skill-refs-set` | Set which store skills the draft pins (`skill_refs`) | Easy — re-set the list; nothing is deleted |+| `posthog__agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |+| `posthog__agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |These are all `posthog__*` MCP tools — there's no bulk bundle-replaceverb, which is deliberate: edit the one thing that changeddiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.mdindex dd1f4a4d1361..edc760a3ebfc 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/platform-mental-model/SKILL.md@@ -99,8 +99,8 @@ the team's slack integration.Read this whenever you find yourself reaching for "where does theagent's prompt live?" or "where do I edit the model?":-- The **model** is in `spec.model`. Edit via- `revisions-partial-update` on a draft.+- The **model** is in `spec.models` (auto level or manual+ list). Edit via `revisions-partial-update` on a draft.- The **system prompt** is `bundle/agent.md`. Edit via`revisions-agent-md-update`.- The **skills the model can load** are listed in `spec.skills[]`diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.jsonindex cf9c7c7492e8..470f0d3ed0bb 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json@@ -1,5 +1,5 @@{- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "auto", "level": "high" },"reasoning": "high","triggers": [{@@ -239,6 +239,7 @@"agent-applications-env-keys-get","agent-native-tools-list","agent-resolve-resource",+ "agent-applications-models","execute-sql","insight-query","get-llm-total-costs-for-project",diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/tests/01-inspect-agent-happy-path.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/tests/01-inspect-agent-happy-path.jsonindex 44757580d1cd..e5bb8b53f78a 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/tests/01-inspect-agent-happy-path.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/tests/01-inspect-agent-happy-path.json@@ -29,7 +29,7 @@"state": "live","bundle_sha256": "abc123","spec": {- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },"triggers": [{ "type": "cron", "config": { "schedule": "0 9 * * 1", "timezone": "UTC" } }],"tools": [{ "kind": "native", "id": "@posthog/query" },diff --git a/products/agent_platform/services/agent-tests/src/examples/kudos-bot/spec.json b/products/agent_platform/services/agent-tests/src/examples/kudos-bot/spec.jsonindex 84ebfc12387c..7b65de96b45f 100644--- a/products/agent_platform/services/agent-tests/src/examples/kudos-bot/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/kudos-bot/spec.json@@ -1,5 +1,5 @@{- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },"reasoning": "medium","triggers": [{diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.jsonindex e71570f52ba4..25fdcf9e4f74 100644--- a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json@@ -1,5 +1,5 @@{- "model": "openai/gpt-5.5",+ "models": { "mode": "manual", "models": [{ "model": "openai/gpt-5.5" }] },"triggers": [{"type": "slack",@@ -53,6 +53,5 @@"max_tool_calls": 100,"max_wall_seconds": 600},- "reasoning": "medium",- "entrypoint": "agent.md"+ "reasoning": "medium"}diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.jsonindex b2d6a7e9fffa..77d93960d680 100644--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json@@ -1,5 +1,5 @@{- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },"triggers": [{"auth": {@@ -184,6 +184,5 @@"max_wall_seconds": 600},"reasoning": "high",- "mcps": [],- "entrypoint": "agent.md"+ "mcps": []}diff --git a/products/agent_platform/services/agent-tests/src/examples/wake-me-up/spec.json b/products/agent_platform/services/agent-tests/src/examples/wake-me-up/spec.jsonindex ff72c6769ebf..fdba69209c60 100644--- a/products/agent_platform/services/agent-tests/src/examples/wake-me-up/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/wake-me-up/spec.json@@ -1,5 +1,5 @@{- "model": "anthropic/claude-sonnet-4-6",+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },"reasoning": "high","triggers": [{diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.tsindex 56ca8ab618fd..692112ffeef0 100644--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts@@ -541,8 +541,8 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Clusterdescription: input.description ?? '',})const rawSpec: Record<string, unknown> = {- // Default model is "faux/<name>"; tests can override via spec.model.- model: 'faux/faux',+ // Default model is "faux/<name>"; tests can override via spec.models.+ models: { mode: 'manual', models: [{ model: 'faux/faux' }] },triggers: [{ type: 'chat', config: {} },// Default to "*" for tests — individual cases overridediff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.tsindex bd35bb0b1c42..b491a3470a40 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts@@ -18,7 +18,7 @@ describe('@posthog/agent-applications-spec-schema', () => {expect(result.section).toBeNull()const schema = result.spec_json_schema as Record<string, unknown>expect(schema.type).toBe('object')- expect((schema.required as string[]) ?? []).toContain('model')+ expect((schema.required as string[]) ?? []).toContain('models')expect(schema.properties).toHaveProperty('triggers')expect(schema.properties).toHaveProperty('tools')expect(schema.properties).toHaveProperty('secrets')diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yamlindex c2fc5849e339..f03ae07cd7d2 100644--- a/services/mcp/definitions/agent_platform.yaml+++ b/services/mcp/definitions/agent_platform.yaml@@ -124,6 +124,22 @@ tools:List every agent application in the project. Returns id, slug, name, description, live_revision, archivedstate. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the`reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.+ agent-applications-models:+ operation: agent_applications_models+ enabled: true+ scopes:+ - agents:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List models + what each auto level resolves to+ description: >+ Read-only model catalog for `spec.models`. Returns every model the gateway serves (id, provider, display+ name, per-Mtok input/output cost) plus `levels` — the concrete, priority-ordered model list each `auto`+ level (`low` / `medium` / `high`) currently resolves to. Use this to answer "what will auto/medium actually+ run?" and to pick ids for a `manual` policy instead of guessing. The level membership is resolved live+ against the catalog, so it reflects what the runner picks today, not a hardcoded list.agent-applications-partial-update:operation: agent_applications_partial_updateenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 29c31fd6621a..046dfae82cda 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -336,6 +336,21 @@},"feature_flag": "agent-platform"},+ "agent-applications-models": {+ "description": "Read-only model catalog for `spec.models`. Returns every model the gateway serves (id, provider, display name, per-Mtok input/output cost) plus `levels` — the concrete, priority-ordered model list each `auto` level (`low` / `medium` / `high`) currently resolves to. Use this to answer \"what will auto/medium actually run?\" and to pick ids for a `manual` policy instead of guessing. The level membership is resolved live against the catalog, so it reflects what the runner picks today, not a hardcoded list.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "List models + what each auto level resolves to",+ "title": "List models + what each auto level resolves to",+ "required_scopes": ["agents:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "agent-platform"+ },"agent-applications-partial-update": {"description": "Edit `name` / `description`. The env block is managed separately (raw secret entry goes through the agent console's secret editor, not MCP), and `live_revision` is set by promoting a revision.","category": "Agent stack",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 96af6b10767a..2c876e2ff9c4 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -336,6 +336,21 @@},"feature_flag": "agent-platform"},+ "agent-applications-models": {+ "description": "Read-only model catalog for `spec.models`. Returns every model the gateway serves (id, provider, display name, per-Mtok input/output cost) plus `levels` — the concrete, priority-ordered model list each `auto` level (`low` / `medium` / `high`) currently resolves to. Use this to answer \"what will auto/medium actually run?\" and to pick ids for a `manual` policy instead of guessing. The level membership is resolved live against the catalog, so it reflects what the runner picks today, not a hardcoded list.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "List models + what each auto level resolves to",+ "title": "List models + what each auto level resolves to",+ "required_scopes": ["agents:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "agent-platform"+ },"agent-applications-partial-update": {"description": "Edit `name` / `description`. The env block is managed separately (raw secret entry goes through the agent console's secret editor, not MCP), and `live_revision` is set by promoting a revision.","category": "Agent stack",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ed57e2a4f4d5..d002d3af12f6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8198,6 +8198,37 @@ export namespace Schemas {tools: AgentNativeToolEntry[];}+ /**+ * How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns.+ */+ export type AgentRevisionSpecModels = {+ mode: 'auto';+ /** Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start. */+ level?: 'low' | 'medium' | 'high';+ /** Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default. */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';+ /** Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend. */+ optimize_for?: 'cost' | 'availability';+ } | {+ mode: 'manual';+ /**+ * Explicit priority-ordered fallback list — the runner tries entries in order (primary first).+ * @minItems 1+ */+ models: ({+ /**+ * Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).+ * @minLength 1+ * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$+ */+ model: string;+ /** Per-model reasoning effort override (else the spec default). */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';+ })[];+ /** Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold). */+ optimize_for?: 'cost' | 'availability';+ };+export type AgentRevisionSpecTriggersItem = {type: 'slack';config: {@@ -8510,11 +8541,8 @@ export namespace Schemas {};export type AgentRevisionSpec = {- /**- * @minLength 1- * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$- */- model: string;+ /** How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns. */+ models: AgentRevisionSpecModels;triggers: AgentRevisionSpecTriggersItem[];tools: AgentRevisionSpecToolsItem[];mcps: AgentRevisionSpecMcpsItem[];@@ -8522,7 +8550,6 @@ export namespace Schemas {identity_providers?: AgentRevisionSpecIdentityProvidersItem[];secrets: AgentRevisionSpecSecretsItem[];limits: AgentRevisionSpecLimits;- entrypoint: string;reasoning?: AgentRevisionSpecReasoning;framework_prompt?: AgentRevisionSpecFrameworkPrompt;resume?: AgentRevisionSpecResume;@@ -8657,7 +8684,7 @@ export namespace Schemas {revision_id: string;/** Active framework preamble version. Bumps when the platform's `# Platform guidance` content changes meaningfully (decision rules, sections renamed, behavioural defaults flipped). Authors can pin to a specific version via `spec.framework_prompt.version_pin`. */framework_prompt_version: number;- /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md` (or `spec.entrypoint`), and the skills index. Inspect before promotion to confirm the model will see what you expect. */+ /** Fully-assembled system prompt the runner would pass to pi-ai for a session against this revision. Concatenates the platform framework preamble, the bundle's `agent.md`, and the skills index. Inspect before promotion to confirm the model will see what you expect. */system_prompt: string;}@@ -34925,6 +34952,37 @@ export namespace Schemas {tags?: string[];}+ /**+ * How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns.+ */+ export type PatchedAgentRevisionSpecModels = {+ mode: 'auto';+ /** Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start. */+ level?: 'low' | 'medium' | 'high';+ /** Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default. */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';+ /** Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend. */+ optimize_for?: 'cost' | 'availability';+ } | {+ mode: 'manual';+ /**+ * Explicit priority-ordered fallback list — the runner tries entries in order (primary first).+ * @minItems 1+ */+ models: ({+ /**+ * Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).+ * @minLength 1+ * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$+ */+ model: string;+ /** Per-model reasoning effort override (else the spec default). */+ reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';+ })[];+ /** Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold). */+ optimize_for?: 'cost' | 'availability';+ };+export type PatchedAgentRevisionSpecTriggersItem = {type: 'slack';config: {@@ -35237,11 +35295,8 @@ export namespace Schemas {};export type PatchedAgentRevisionSpec = {- /**- * @minLength 1- * @pattern ^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$- */- model: string;+ /** How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns. */+ models: PatchedAgentRevisionSpecModels;triggers: PatchedAgentRevisionSpecTriggersItem[];tools: PatchedAgentRevisionSpecToolsItem[];mcps: PatchedAgentRevisionSpecMcpsItem[];@@ -35249,7 +35304,6 @@ export namespace Schemas {identity_providers?: PatchedAgentRevisionSpecIdentityProvidersItem[];secrets: PatchedAgentRevisionSpecSecretsItem[];limits: PatchedAgentRevisionSpecLimits;- entrypoint: string;reasoning?: PatchedAgentRevisionSpecReasoning;framework_prompt?: PatchedAgentRevisionSpecFrameworkPrompt;resume?: PatchedAgentRevisionSpecResume;diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.tsindex 663a81c63f0b..e0072cf00972 100644--- a/services/mcp/src/generated/agent_platform/api.ts+++ b/services/mcp/src/generated/agent_platform/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 34 enabled ops+ * PostHog API - MCP 35 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -157,8 +157,19 @@ export const AgentApplicationsRevisionsCreateParams = /* @__PURE__ */ zod.object})export const agentApplicationsRevisionsCreateBodyBundleUriDefault = ``+export const agentApplicationsRevisionsCreateBodySpecModelsOneLevelDefault = `medium`+export const agentApplicationsRevisionsCreateBodySpecModelsOneOptimizeForDefault = `cost`-export const agentApplicationsRevisionsCreateBodySpecModelRegExp = new RegExp('^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$')+export const agentApplicationsRevisionsCreateBodySpecModelsTwoModelsItemModelRegExp = new RegExp(+ '^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$'+)++export const agentApplicationsRevisionsCreateBodySpecModelsTwoOptimizeForDefault = `cost`+export const agentApplicationsRevisionsCreateBodySpecModelsDefault = {+ mode: 'auto' as const,+ level: 'medium' as const,+ optimize_for: 'cost' as const,+}export const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigMentionOnlyDefault = falseexport const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = falseexport const agentApplicationsRevisionsCreateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false@@ -255,7 +266,6 @@ export const agentApplicationsRevisionsCreateBodySpecLimitsDefault = {max_memory_mb: 512,max_cpu_cores: 0.25,}-export const agentApplicationsRevisionsCreateBodySpecEntrypointDefault = `agent.md`export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptOmitDefault = []export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptVersionPinExclusiveMin = 0export const agentApplicationsRevisionsCreateBodySpecFrameworkPromptVersionPinMax = 2147483647@@ -275,7 +285,63 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({),spec: zod.object({- model: zod.string().min(1).regex(agentApplicationsRevisionsCreateBodySpecModelRegExp),+ models: zod+ .union([+ zod.object({+ mode: zod.literal('auto'),+ level: zod+ .enum(['low', 'medium', 'high'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsOneLevelDefault)+ .describe(+ 'Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe(+ 'Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default.'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsOneOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend."+ ),+ }),+ zod.object({+ mode: zod.literal('manual'),+ models: zod+ .array(+ zod.object({+ model: zod+ .string()+ .min(1)+ .regex(agentApplicationsRevisionsCreateBodySpecModelsTwoModelsItemModelRegExp)+ .describe(+ 'Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe('Per-model reasoning effort override (else the spec default).'),+ })+ )+ .min(1)+ .describe(+ 'Explicit priority-ordered fallback list — the runner tries entries in order (primary first).'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsCreateBodySpecModelsTwoOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold)."+ ),+ }),+ ])+ .default(agentApplicationsRevisionsCreateBodySpecModelsDefault)+ .describe(+ "How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."+ ),triggers: zod.array(zod.union([@@ -725,7 +791,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({.default(agentApplicationsRevisionsCreateBodySpecLimitsMaxCpuCoresDefault),}).default(agentApplicationsRevisionsCreateBodySpecLimitsDefault),- entrypoint: zod.string().default(agentApplicationsRevisionsCreateBodySpecEntrypointDefault),reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),framework_prompt: zod.object({@@ -835,7 +900,19 @@ export const AgentApplicationsRevisionsPartialUpdateParams = /* @__PURE__ */ zod),})-export const agentApplicationsRevisionsPartialUpdateBodySpecModelRegExp = new RegExp('^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$')+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsOneLevelDefault = `medium`+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsOneOptimizeForDefault = `cost`++export const agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoModelsItemModelRegExp = new RegExp(+ '^[a-z0-9_-]+/[a-zA-Z0-9._:-]+$'+)++export const agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoOptimizeForDefault = `cost`+export const agentApplicationsRevisionsPartialUpdateBodySpecModelsDefault = {+ mode: 'auto' as const,+ level: 'medium' as const,+ optimize_for: 'cost' as const,+}export const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigMentionOnlyDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAutoResumeThreadsDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecTriggersItemOneConfigAllowWorkspaceParticipantsDefault = false@@ -932,7 +1009,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault = {max_memory_mb: 512,max_cpu_cores: 0.25,}-export const agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault = `agent.md`export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptOmitDefault = []export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptVersionPinExclusiveMin = 0export const agentApplicationsRevisionsPartialUpdateBodySpecFrameworkPromptVersionPinMax = 2147483647@@ -952,7 +1028,65 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o),spec: zod.object({- model: zod.string().min(1).regex(agentApplicationsRevisionsPartialUpdateBodySpecModelRegExp),+ models: zod+ .union([+ zod.object({+ mode: zod.literal('auto'),+ level: zod+ .enum(['low', 'medium', 'high'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsOneLevelDefault)+ .describe(+ 'Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe(+ 'Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default.'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsOneOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend."+ ),+ }),+ zod.object({+ mode: zod.literal('manual'),+ models: zod+ .array(+ zod.object({+ model: zod+ .string()+ .min(1)+ .regex(+ agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoModelsItemModelRegExp+ )+ .describe(+ 'Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).'+ ),+ reasoning: zod+ .enum(['minimal', 'low', 'medium', 'high', 'xhigh'])+ .optional()+ .describe('Per-model reasoning effort override (else the spec default).'),+ })+ )+ .min(1)+ .describe(+ 'Explicit priority-ordered fallback list — the runner tries entries in order (primary first).'+ ),+ optimize_for: zod+ .enum(['cost', 'availability'])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsTwoOptimizeForDefault)+ .describe(+ "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold)."+ ),+ }),+ ])+ .default(agentApplicationsRevisionsPartialUpdateBodySpecModelsDefault)+ .describe(+ "How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."+ ),triggers: zod.array(zod.union([@@ -1424,7 +1558,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o.default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsMaxCpuCoresDefault),}).default(agentApplicationsRevisionsPartialUpdateBodySpecLimitsDefault),- entrypoint: zod.string().default(agentApplicationsRevisionsPartialUpdateBodySpecEntrypointDefault),reasoning: zod.enum(['minimal', 'low', 'medium', 'high', 'xhigh']).optional(),framework_prompt: zod.object({@@ -1962,7 +2095,7 @@ export const AgentApplicationsRevisionsToolsDestroyParams = /* @__PURE__ */ zod.})/**- * Pre-flight checks before freeze + promote: entrypoint file exists,+ * Pre-flight checks before freeze + promote: agent.md exists,* every native tool id is registered, every custom tool has its* compiled.js + schema.json, every skill path exists, every declared* secret has a value set in this revision's env block. Returns@@ -2241,6 +2374,17 @@ export const AgentApplicationsSessionLogsQueryParams = /* @__PURE__ */ zod.objecsearch: zod.string().min(1).optional().describe('Case-insensitive substring search across log messages.'),})+/**+ * Served-model catalog — each model's id, provider, context window, and USD-per-million-token pricing — plus the curated auto-level → model map. Project-agnostic; sourced from the AI gateway catalog. Powers the config UI model browser and the agent builder's model-choosing skill.+ */+export const AgentApplicationsModelsParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})+/*** Read-only catalog of every @posthog/* native tool the runner knows.*/diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.tsindex 51859b24c2fd..0128f315a674 100644--- a/services/mcp/src/tools/generated/agent_platform.ts+++ b/services/mcp/src/tools/generated/agent_platform.ts@@ -173,6 +173,22 @@ const agentApplicationsList = (): ToolBase<},})+const AgentApplicationsModelsSchema = z.object({})++const agentApplicationsModels = (): ToolBase<typeof AgentApplicationsModelsSchema, Schemas.AgentApplication> => ({+ name: 'agent-applications-models',+ schema: AgentApplicationsModelsSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsModelsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.AgentApplication>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/models/`,+ })+ return result+ },+})+const AgentApplicationsPartialUpdateSchema = AgentApplicationsPartialUpdateParams.omit({ project_id: true }).extend(AgentApplicationsPartialUpdateBody.shape)@@ -857,6 +873,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'agent-applications-env-keys-get': agentApplicationsEnvKeysGet,'agent-applications-env-keys-list': agentApplicationsEnvKeysList,'agent-applications-list': agentApplicationsList,+ 'agent-applications-models': agentApplicationsModels,'agent-applications-partial-update': agentApplicationsPartialUpdate,'agent-applications-preview-proxy': agentApplicationsPreviewProxy,'agent-applications-retrieve': agentApplicationsRetrieve,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-models.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-models.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-models.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.jsonindex 2603091c61e7..5c62a58da63c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json@@ -23,10 +23,6 @@},"spec": {"properties": {- "entrypoint": {- "default": "agent.md",- "type": "string"- },"framework_prompt": {"properties": {"omit": {@@ -268,10 +264,80 @@},"type": "array"},- "model": {- "minLength": 1,- "pattern": "^[a-z0-9_-]+\\/[a-zA-Z0-9._:-]+$",- "type": "string"+ "models": {+ "anyOf": [+ {+ "properties": {+ "level": {+ "default": "medium",+ "description": "Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.",+ "enum": ["low", "medium", "high"],+ "type": "string"+ },+ "mode": {+ "const": "auto",+ "type": "string"+ },+ "optimize_for": {+ "default": "cost",+ "description": "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend.",+ "enum": ["cost", "availability"],+ "type": "string"+ },+ "reasoning": {+ "description": "Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default.",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ "type": "string"+ }+ },+ "required": ["mode"],+ "type": "object"+ },+ {+ "properties": {+ "mode": {+ "const": "manual",+ "type": "string"+ },+ "models": {+ "description": "Explicit priority-ordered fallback list — the runner tries entries in order (primary first).",+ "items": {+ "properties": {+ "model": {+ "description": "Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).",+ "minLength": 1,+ "pattern": "^[a-z0-9_-]+\\/[a-zA-Z0-9._:-]+$",+ "type": "string"+ },+ "reasoning": {+ "description": "Per-model reasoning effort override (else the spec default).",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ "type": "string"+ }+ },+ "required": ["model"],+ "type": "object"+ },+ "minItems": 1,+ "type": "array"+ },+ "optimize_for": {+ "default": "cost",+ "description": "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold).",+ "enum": ["cost", "availability"],+ "type": "string"+ }+ },+ "required": ["mode", "models"],+ "type": "object"+ }+ ],+ "default": {+ "level": "medium",+ "mode": "auto",+ "optimize_for": "cost"+ },+ "description": "How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."},"reasoning": {"enum": ["minimal", "low", "medium", "high", "xhigh"],@@ -939,7 +1005,6 @@"type": "array"}},- "required": ["model"],"type": "object"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.jsonindex 70ce76ef3428..95d3c6f5df30 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json@@ -26,10 +26,6 @@},"spec": {"properties": {- "entrypoint": {- "default": "agent.md",- "type": "string"- },"framework_prompt": {"properties": {"omit": {@@ -271,10 +267,80 @@},"type": "array"},- "model": {- "minLength": 1,- "pattern": "^[a-z0-9_-]+\\/[a-zA-Z0-9._:-]+$",- "type": "string"+ "models": {+ "anyOf": [+ {+ "properties": {+ "level": {+ "default": "medium",+ "description": "Quality/cost tier (auto). low = cheapest, for short, formulaic, no-reasoning jobs (lookups, FAQ bots); medium = balanced default, for multi-step but bounded work; high = top-tier, for long, branching, reasoning-heavy work. Resolved to a priority-ordered cross-provider list at session start.",+ "enum": ["low", "medium", "high"],+ "type": "string"+ },+ "mode": {+ "const": "auto",+ "type": "string"+ },+ "optimize_for": {+ "default": "cost",+ "description": "Session model stability vs. resilience. `cost` (default): the first turn picks a working model and PINS it for the whole session — keeps the provider's prompt cache warm (cache reads are ~0.1-0.5x of full input) and never fails over mid-session; if the pinned model is down the turn fails rather than re-reading the whole context cold on another provider. `availability`: fail over to the next model when the session's model fails — survives an outage at the cost of a one-time cold re-read. Prefer `cost` for long/expensive sessions, `availability` where uptime matters more than spend.",+ "enum": ["cost", "availability"],+ "type": "string"+ },+ "reasoning": {+ "description": "Reasoning/thinking effort budget. minimal = no deliberation (fastest, cheapest) … xhigh = maximal (research-grade, ~5-10x the per-turn cost). Omit for the provider/spec default.",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ "type": "string"+ }+ },+ "required": ["mode"],+ "type": "object"+ },+ {+ "properties": {+ "mode": {+ "const": "manual",+ "type": "string"+ },+ "models": {+ "description": "Explicit priority-ordered fallback list — the runner tries entries in order (primary first).",+ "items": {+ "properties": {+ "model": {+ "description": "Canonical model id, e.g. `anthropic/claude-sonnet-4-6` (see the agent-applications-models tool for served ids).",+ "minLength": 1,+ "pattern": "^[a-z0-9_-]+\\/[a-zA-Z0-9._:-]+$",+ "type": "string"+ },+ "reasoning": {+ "description": "Per-model reasoning effort override (else the spec default).",+ "enum": ["minimal", "low", "medium", "high", "xhigh"],+ "type": "string"+ }+ },+ "required": ["model"],+ "type": "object"+ },+ "minItems": 1,+ "type": "array"+ },+ "optimize_for": {+ "default": "cost",+ "description": "Session model stability vs. resilience. `cost` (default): pin the first working model for the whole session (warm prompt cache, no mid-session failover). `availability`: fail over down this list when the session's model fails (survives outages, re-reads context cold).",+ "enum": ["cost", "availability"],+ "type": "string"+ }+ },+ "required": ["mode", "models"],+ "type": "object"+ }+ ],+ "default": {+ "level": "medium",+ "mode": "auto",+ "optimize_for": "cost"+ },+ "description": "How this agent selects its model. `auto`: pick a quality/cost `level` and the platform resolves it to a maintained, priority-ordered, cross-provider list at runtime. `manual`: give an explicit priority-ordered `models` list (primary first). `optimize_for` governs how the chosen model is treated across the session's turns."},"reasoning": {"enum": ["minimal", "low", "medium", "high", "xhigh"],@@ -942,7 +1008,6 @@"type": "array"}},- "required": ["model"],"type": "object"}},