Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(tasks): single-source the model catalog and read it statically (#93153)

Vojta Bartoš7733b0b32250
diff --git a/.claude/rules/task-model-catalog.md b/.claude/rules/task-model-catalog.md
new file mode 100644
index 000000000000..d96b99922f9d
--- /dev/null
+++ b/.claude/rules/task-model-catalog.md
@@ -0,0 +1,21 @@
+---
+paths:
+ - 'products/tasks/backend/model_catalog.py'
+ - 'products/tasks/scripts/build_model_catalog.py'
+ - 'products/tasks/frontend/modelCatalog.generated.ts'
+ - 'products/desktop/packages/shared/src/model-catalog.generated.ts'
+---
+
+`products/tasks/backend/model_catalog.py` is the single definition of a task run's triple: runtime adapter, model, and reasoning effort.
+The web composer and the desktop app each read a checked-in TypeScript projection of it, and the backend validates runs against the module itself.
+
+After changing the catalog, run `hogli build:task-model-catalog` and commit both regenerated files.
+The command needs no dev stack and takes well under a second, so run it rather than reasoning about whether the output moved.
+
+Never hand-edit `products/tasks/frontend/modelCatalog.generated.ts` or `products/desktop/packages/shared/src/model-catalog.generated.ts`.
+A test re-renders both and compares them byte for byte, so an edit that the generator would not produce fails CI rather than shipping.
+
+Adding a model means one row in `MODELS`. Two things do not follow from that row and are worth checking:
+
+- A model gated behind a feature flag also needs an entry in `MODEL_ACCESS_FLAGS` (`products/tasks/backend/constants.py`), which is where the server re-checks entitlement. A picker hiding a model is a convenience, not a gate.
+- The catalog names the harness that drives a model. The LLM gateway reports `owned_by`, which names whoever serves it — `cloudflare` and `baseten` for the vendor-served models — so routing a model by its owner puts it on the wrong adapter or drops it entirely.
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 185da4342fa5..8448fcfdab15 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -532,7 +532,14 @@ jobs:
- 'products/*/frontend/generated/**/*'
- 'services/mcp/src/generated/**/*'
- 'services/mcp/src/api/generated.ts'
- # Generation tooling - changes here could affect output
+ # Task run model catalog: one Python module projected into a
+ # checked-in .generated.ts per workspace. Only the outputs are
+ # named — neither sits in a generated/ directory, and the
+ # desktop one is under products/desktop, which the backend
+ # filter excludes. The catalog and its generator are .py under
+ # products/, so the backend filter already catches both.
+ - 'products/tasks/frontend/modelCatalog.generated.ts'
+ - 'products/desktop/packages/shared/src/model-catalog.generated.ts'
- 'tools/openapi-codegen/**/*'
- 'services/mcp/scripts/lib/**'
- 'frontend/bin/generate-openapi-types.mjs'
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index fcce59dd90ab..f81ea1f8129e 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -375,7 +375,14 @@ jobs:
- 'products/*/frontend/generated/**/*'
- 'services/mcp/src/generated/**/*'
- 'services/mcp/src/api/generated.ts'
- # Generation tooling - changes here could affect output
+ # Task run model catalog: one Python module projected into a
+ # checked-in .generated.ts per workspace. Only the outputs are
+ # named — neither sits in a generated/ directory, and the
+ # desktop one is under products/desktop, which the backend
+ # filter excludes. The catalog and its generator are .py under
+ # products/, so the backend filter already catches both.
+ - 'products/tasks/frontend/modelCatalog.generated.ts'
+ - 'products/desktop/packages/shared/src/model-catalog.generated.ts'
- 'tools/openapi-codegen/**/*'
- 'services/mcp/scripts/lib/**'
- 'frontend/bin/generate-openapi-types.mjs'
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index 2720e2b8f322..0148b7475dfc 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -118,6 +118,7 @@
"posthog/templates/**/*",
"common/hogvm/typescript/src/stl/bytecode.ts",
"common/hogvm/__tests__/__snapshots__/*",
+ "products/**/tests/__snapshots__/**/*",
"common/hogql_parser/build_wasm/",
"common/hogql_parser/build/",
"common/hogql_parser/dist/",
diff --git a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts
index 4b1d440a384c..e0ac0c668dc0 100644
--- a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts
+++ b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts
@@ -18,7 +18,6 @@ describe('taskAgentDefaultsLogic', () => {
200,
{ ai_run_preferences: myPreferences, resolved_ai_run_defaults: null },
],
- '/api/projects/:team_id/tasks/models/': () => [200, { models: [] }],
},
post: {
'/api/projects/:team_id/tasks/@me/config/': async ({ request }) => {
diff --git a/hogli.yaml b/hogli.yaml
index 210ff4ab82c5..ed27e0becc3b 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -551,6 +551,11 @@ build:
bin_script: build-mcp-oauth-scopes.py
description: Generate OAUTH_SCOPES_SUPPORTED for the MCP protected-resource
metadata from posthog/scopes.py
+ build:task-model-catalog:
+ cmd: python products/tasks/scripts/build_model_catalog.py
+ description: Generate the web and desktop views of the task run model catalog
+ (runtime adapter, model, reasoning effort) from
+ products/tasks/backend/model_catalog.py
build:openapi-cli-agent-scopes:
cmd: pnpm --filter=@posthog/mcp run generate-cli-agent-scopes
description: Generate the CLI `agent` login use-case scope list from the MCP
@@ -568,6 +573,7 @@ build:
- build:openapi-mcp
- build:openapi-mcp-tools
- build:openapi-mcp-scopes
+ - build:task-model-catalog
- build:openapi-cli-agent-scopes
- build:openapi-exec-docs
description: 'Generate OpenAPI schema and TypeScript types from the backend.
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/models.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/models.test.ts
index 8918dd1bea21..33abb3032fea 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/models.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/models.test.ts
@@ -64,15 +64,15 @@ describe("model capability flags", () => {
{
modelId: "claude-opus-4-5",
oneMContext: false,
- effort: false,
+ effort: true,
xhighEffort: false,
mcpInjection: true,
},
{
modelId: "claude-opus-4-6",
oneMContext: false,
- effort: false,
- xhighEffort: false,
+ effort: true,
+ xhighEffort: true,
mcpInjection: true,
},
{
@@ -178,9 +178,10 @@ describe("resolveEffortForModel", () => {
["claude-sonnet-5", undefined, "high"],
["@cf/zai-org/glm-5.2", undefined, "high"],
["zai-org/glm-5.3", undefined, "high"],
+ ["claude-opus-4-6", undefined, "high"],
// Models without effort support stay unset (SDK disables thinking).
["claude-haiku-4-5", undefined, undefined],
- ["claude-opus-4-6", undefined, undefined],
+ ["moonshotai/kimi-k3", undefined, undefined],
// An explicit choice is always honored, including on adaptive-only models.
["claude-opus-4-8", "low", "low"],
["claude-fable-5", "max", "max"],
@@ -196,15 +197,19 @@ describe("resolveEffortForModel", () => {
describe("getEffortOptions", () => {
it("returns null for models without effort support", () => {
expect(getEffortOptions("claude-haiku-4-5")).toBeNull();
- expect(getEffortOptions("claude-opus-4-6")).toBeNull();
+ // Named by the catalog, but with no effort control at all.
+ expect(getEffortOptions("moonshotai/kimi-k3")).toBeNull();
});
it.each([
["claude-sonnet-4-6", ["low", "medium", "high"]],
+ ["claude-opus-4-6", ["low", "medium", "high", "xhigh", "max"]],
["claude-opus-4-7", ["low", "medium", "high", "xhigh", "max", "ultracode"]],
["@cf/zai-org/glm-5.2", ["high", "max"]],
["zai-org/glm-5.3", ["high", "max"]],
["zai-org/glm-5.3-flash", ["high", "max"]],
+ // A provider-qualified id resolves to the same model as the bare one.
+ ["anthropic/claude-sonnet-4-6", ["low", "medium", "high"]],
])("returns the exact effort levels for %s", (modelId, expected) => {
expect(getEffortOptions(modelId)?.map((o) => o.value)).toEqual(expected);
});
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/models.ts b/products/desktop/packages/agent/src/adapters/claude/session/models.ts
index fe98fb41a9c0..a277da1cde7a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/models.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/models.ts
@@ -1,11 +1,17 @@
import {
DEFAULT_OPTION_META_KEY,
OPTION_DOCS_URL_META_KEY,
+ supports1MContext,
+ supportsFastMode,
} from "@posthog/shared";
import {
EFFORT_LEVEL_DOCS_URLS,
EFFORT_LEVEL_LABELS,
} from "@posthog/shared/domain-types";
+import {
+ normalizeModelId,
+ reasoningEffortsForModel,
+} from "@posthog/shared/model-catalog";
import type { EffortLevel } from "../types";
export const DEFAULT_MODEL = "opus";
@@ -41,19 +47,7 @@ export function rerootedModelOptions(
return { model: modelId, fallbackModel };
}
-const MODELS_WITH_1M_CONTEXT = new Set([
- "claude-opus-4-7",
- "claude-opus-4-8",
- "claude-opus-5",
- "claude-sonnet-4-6",
- "claude-sonnet-5",
- "claude-fable-5",
- "claude-fable-5-1",
-]);
-
-export function supports1MContext(modelId: string): boolean {
- return MODELS_WITH_1M_CONTEXT.has(modelId);
-}
+export { supports1MContext, supportsFastMode };
export const CONTEXT_WINDOW_1M_BETA = "context-1m-2025-08-07";
export const CONTEXT_WINDOW_200K_TOKENS = 200_000;
@@ -74,32 +68,12 @@ export function getContextWindowOptions(
];
}
-const STANDARD_EFFORT_LEVELS: readonly EffortLevel[] = [
- "low",
- "medium",
- "high",
-];
-const EXTENDED_EFFORT_LEVELS: readonly EffortLevel[] = [
- ...STANDARD_EFFORT_LEVELS,
- "xhigh",
- "max",
- "ultracode",
-];
-const MODEL_EFFORT_LEVELS: Readonly<Record<string, readonly EffortLevel[]>> = {
- "claude-opus-4-7": EXTENDED_EFFORT_LEVELS,
- "claude-opus-4-8": EXTENDED_EFFORT_LEVELS,
- "claude-opus-5": EXTENDED_EFFORT_LEVELS,
- "claude-sonnet-4-6": STANDARD_EFFORT_LEVELS,
- "claude-sonnet-5": EXTENDED_EFFORT_LEVELS,
- "claude-fable-5": EXTENDED_EFFORT_LEVELS,
- "claude-fable-5-1": EXTENDED_EFFORT_LEVELS,
- "@cf/zai-org/glm-5.2": ["high", "max"],
- "zai-org/glm-5.3": ["high", "max"],
- "zai-org/glm-5.3-flash": ["high", "max"],
-};
+function effortLevelsFor(modelId: string): readonly EffortLevel[] {
+ return reasoningEffortsForModel("claude", modelId);
+}
export function supportsEffort(modelId: string): boolean {
- return MODEL_EFFORT_LEVELS[modelId] !== undefined;
+ return effortLevelsFor(modelId).length > 0;
}
export function resolveEffortForModel(
@@ -111,7 +85,7 @@ export function resolveEffortForModel(
}
export function supportsXhighEffort(modelId: string): boolean {
- return MODEL_EFFORT_LEVELS[modelId]?.includes("xhigh") ?? false;
+ return effortLevelsFor(modelId).includes("xhigh");
}
const MODELS_TO_EXCLUDE_MCP_TOOLS = new Set(["claude-haiku-4-5"]);
@@ -120,16 +94,6 @@ export function supportsMcpInjection(modelId: string): boolean {
return !MODELS_TO_EXCLUDE_MCP_TOOLS.has(modelId);
}
-const MODELS_WITH_FAST_MODE = new Set([
- "claude-opus-4-7",
- "claude-opus-4-8",
- "claude-opus-5",
-]);
-
-export function supportsFastMode(modelId: string): boolean {
- return MODELS_WITH_FAST_MODE.has(modelId);
-}
-
export function getFastModeOptions(
modelId: string,
): { value: string; name: string }[] | null {
@@ -162,15 +126,16 @@ function effortOptionMeta(
return Object.keys(meta).length > 0 ? meta : undefined;
}
+/** Null rather than an empty list for a model with no effort control, so the caller
+ * renders no dropdown instead of an empty one. */
export function getEffortOptions(modelId: string): EffortOption[] | null {
- const levels = MODEL_EFFORT_LEVELS[modelId];
- return (
- levels?.map((value) => ({
- value,
- name: EFFORT_LEVEL_LABELS[value],
- _meta: effortOptionMeta(value),
- })) ?? null
- );
+ const levels = effortLevelsFor(modelId);
+ if (levels.length === 0) return null;
+ return levels.map((value) => ({
+ value,
+ name: EFFORT_LEVEL_LABELS[value],
+ _meta: effortOptionMeta(value),
+ }));
}
// Model alias resolution — lets callers use human-friendly aliases like
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/models.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/models.test.ts
index 45d59a2148e7..d361ca851d1b 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/models.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/models.test.ts
@@ -4,8 +4,6 @@ import {
formatCodexModelName,
getReasoningEffortOptions,
modelIdFromConfigOptions,
- supportsMaxEffort,
- supportsXhighEffort,
} from "./models";
describe("formatCodexModelName", () => {
@@ -51,24 +49,6 @@ describe("getReasoningEffortOptions", () => {
});
});
-describe("supportsXhighEffort", () => {
- it("is true for current GPT families and false for other models", () => {
- expect(supportsXhighEffort("gpt-6-astra")).toBe(true);
- expect(supportsXhighEffort("gpt-5.5-codex")).toBe(true);
- expect(supportsXhighEffort("GPT-5.5")).toBe(true);
- expect(supportsXhighEffort("gpt-5.3-codex")).toBe(false);
- });
-});
-
-describe("supportsMaxEffort", () => {
- it("is true for current GPT families with Max support", () => {
- expect(supportsMaxEffort("gpt-6-astra")).toBe(true);
- expect(supportsMaxEffort("gpt-5.6-sol")).toBe(true);
- expect(supportsMaxEffort("GPT-5.6-LUNA")).toBe(true);
- expect(supportsMaxEffort("gpt-5.5")).toBe(false);
- });
-});
-
describe("modelIdFromConfigOptions", () => {
const modelOption = (currentValue: unknown): SessionConfigOption =>
({
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/models.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/models.ts
index 8026ba5804ff..1cceab0b41eb 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/models.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/models.ts
@@ -5,6 +5,7 @@ import type {
} from "@agentclientprotocol/sdk";
import { DEFAULT_OPTION_META_KEY } from "@posthog/shared";
import { EFFORT_LEVEL_LABELS } from "@posthog/shared/domain-types";
+import { reasoningEffortsForModel } from "@posthog/shared/model-catalog";
interface ReasoningEffortOption {
value: string;
@@ -14,44 +15,18 @@ interface ReasoningEffortOption {
// "high" is the effort this app starts codex sessions with (see the preview
// config and workspace-server defaults), so the picker badges it as default.
-const CODEX_REASONING_EFFORT_OPTIONS: ReasoningEffortOption[] = [
- { value: "low", name: EFFORT_LEVEL_LABELS.low },
- { value: "medium", name: EFFORT_LEVEL_LABELS.medium },
- {
- value: "high",
- name: EFFORT_LEVEL_LABELS.high,
- _meta: { [DEFAULT_OPTION_META_KEY]: true },
- },
-];
-
-// OpenAI's `reasoning_effort` exposes an "extra high" tier on the gpt-5.5,
-// gpt-5.6, and gpt-6-astra families. GPT-5.6 and GPT-6 Astra also support the
-// "max" tier. Older models top out at "high".
-export function supportsXhighEffort(modelId: string): boolean {
- const id = modelId.toLowerCase();
- return (
- id.includes("gpt-5.5") ||
- id.includes("gpt-5.6") ||
- id.includes("gpt-6-astra")
- );
-}
-
-export function supportsMaxEffort(modelId: string): boolean {
- const id = modelId.toLowerCase();
- return id.includes("gpt-5.6") || id.includes("gpt-6-astra");
-}
+const DEFAULT_CODEX_EFFORT = "high";
export function getReasoningEffortOptions(
modelId: string,
): ReasoningEffortOption[] {
- const options = [...CODEX_REASONING_EFFORT_OPTIONS];
- if (supportsXhighEffort(modelId)) {
- options.push({ value: "xhigh", name: EFFORT_LEVEL_LABELS.xhigh });
- }
- if (supportsMaxEffort(modelId)) {
- options.push({ value: "max", name: EFFORT_LEVEL_LABELS.max });
- }
- return options;
+ return reasoningEffortsForModel("codex", modelId).map((value) => ({
+ value,
+ name: EFFORT_LEVEL_LABELS[value],
+ ...(value === DEFAULT_CODEX_EFFORT
+ ? { _meta: { [DEFAULT_OPTION_META_KEY]: true } }
+ : {}),
+ }));
}
export function formatCodexModelName(value: string): string {
diff --git a/products/desktop/packages/shared/package.json b/products/desktop/packages/shared/package.json
index c7d2ae4296af..4b112a1a59da 100644
--- a/products/desktop/packages/shared/package.json
+++ b/products/desktop/packages/shared/package.json
@@ -24,6 +24,10 @@
"types": "./dist/domain-types.d.ts",
"import": "./dist/domain-types.js"
},
+ "./model-catalog": {
+ "types": "./dist/model-catalog.d.ts",
+ "import": "./dist/model-catalog.js"
+ },
"./types": {
"types": "./dist/types.d.ts",
"import": "./dist/types.js"
diff --git a/products/desktop/packages/shared/src/cloud-task-models.ts b/products/desktop/packages/shared/src/cloud-task-models.ts
index fe13de083358..e8ccc46d4c19 100644
--- a/products/desktop/packages/shared/src/cloud-task-models.ts
+++ b/products/desktop/packages/shared/src/cloud-task-models.ts
@@ -1,6 +1,7 @@
import type { Adapter } from "./adapter";
import { getCustomCloud, isCustomCloudHost } from "./custom-cloud";
import { CODEX_MODE_PRESETS } from "./execution-modes";
+import { labelForModel } from "./model-catalog";
import {
customModelMeta,
modelHarnessMeta,
@@ -298,12 +299,10 @@ function formatProviderModelName(modelId: string): string {
return [head, ...tail].join(" ");
}
-const MODEL_DISPLAY_NAMES: Readonly<Record<string, string>> = {
- "deepseek-ai/deepseek-v4-flash-0731": "DeepSeek V4 Flash",
-};
-
export function formatGatewayModelName(model: GatewayModel): string {
- const displayName = MODEL_DISPLAY_NAMES[model.id];
+ // The catalog names the models whose derived name reads wrong, so web and desktop show
+ // the same string for them; everything else still goes through the formatters below.
+ const displayName = labelForModel(model.id);
if (displayName) {
return displayName;
}
diff --git a/products/desktop/packages/shared/src/model-catalog.generated.ts b/products/desktop/packages/shared/src/model-catalog.generated.ts
new file mode 100644
index 000000000000..0c4d103b7a68
--- /dev/null
+++ b/products/desktop/packages/shared/src/model-catalog.generated.ts
@@ -0,0 +1,227 @@
+// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from
+// products/tasks/backend/model_catalog.py.
+// Regenerate with `hogli build:task-model-catalog`. Do not edit.
+//
+// The single definition of a task agent run's triple: runtime adapter,
+// model, and reasoning effort. The backend validates a run against this
+// same data, so a picker built on this file can only offer a selection
+// the API will accept.
+
+export type RuntimeAdapter = "claude" | "codex";
+
+/** Thinking depths, shallowest first. */
+export type ReasoningEffort =
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "ultracode";
+
+export const REASONING_EFFORTS: readonly ReasoningEffort[] = [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode",
+];
+
+/** A value for each runtime adapter. */
+export type ByRuntimeAdapter<T> = Record<RuntimeAdapter, T>;
+
+/** Efforts per adapter, absent where the adapter has no fallback. */
+type FallbackEfforts = Partial<ByRuntimeAdapter<readonly ReasoningEffort[]>>;
+
+export interface CatalogModel {
+ id: string;
+ runtimeAdapter: RuntimeAdapter;
+ /** Empty for a model with no effort control: render no dropdown. */
+ reasoningEfforts: readonly ReasoningEffort[];
+ /** What a picker shows. Resolved when this file is generated, so every
+ surface names a model the same way without carrying a formatter. */
+ label: string;
+ /** Feature flag a person needs before a picker offers this model. Absent
+ means generally available. Governs display only — the server decides
+ whether a run may use it. */
+ accessFlag?: string;
+}
+
+/** Which vendor API each runtime adapter speaks. */
+export const PROVIDER_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {
+ claude: "anthropic",
+ codex: "openai",
+};
+
+export const RUNTIME_ADAPTERS: readonly RuntimeAdapter[] = ["claude", "codex"];
+
+export const MODELS: readonly CatalogModel[] = [
+ {
+ id: "@cf/zai-org/glm-5.2",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["high", "max"],
+ label: "GLM-5.2",
+ accessFlag: "posthog-code-glm-model",
+ },
+ {
+ id: "zai-org/glm-5.3",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["high", "max"],
+ label: "GLM-5.3",
+ accessFlag: "posthog-code-glm-53-model",
+ },
+ {
+ id: "zai-org/glm-5.3-flash",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["high", "max"],
+ label: "GLM-5.3 Flash",
+ accessFlag: "posthog-code-glm-53-flash-model",
+ },
+ {
+ id: "moonshotai/kimi-k3",
+ runtimeAdapter: "claude",
+ reasoningEfforts: [],
+ label: "Kimi K3",
+ accessFlag: "tasks-kimi-k3",
+ },
+ {
+ id: "deepseek-ai/deepseek-v4-flash-0731",
+ runtimeAdapter: "claude",
+ reasoningEfforts: [],
+ label: "DeepSeek V4 Flash",
+ accessFlag: "posthog-code-deepseek-model",
+ },
+ {
+ id: "claude-opus-4-5",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high"],
+ label: "Claude Opus 4.5",
+ },
+ {
+ id: "claude-opus-4-6",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ label: "Claude Opus 4.6",
+ },
+ {
+ id: "claude-opus-4-7",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Opus 4.7",
+ },
+ {
+ id: "claude-opus-4-8",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Opus 4.8",
+ },
+ {
+ id: "claude-opus-5",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Opus 5",
+ },
+ {
+ id: "claude-fable-5",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Fable 5",
+ },
+ {
+ id: "claude-fable-5-1",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Fable 5.1",
+ },
+ {
+ id: "claude-sonnet-5",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ label: "Claude Sonnet 5",
+ },
+ {
+ id: "claude-sonnet-4-6",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["low", "medium", "high"],
+ label: "Claude Sonnet 4.6",
+ },
+ {
+ id: "gpt-5",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high"],
+ label: "GPT-5",
+ },
+ {
+ id: "gpt-5.5",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high", "xhigh"],
+ label: "GPT-5.5",
+ },
+ {
+ id: "gpt-5.6-sol",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ label: "GPT-5.6 Sol",
+ },
+ {
+ id: "gpt-5.6-terra",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ label: "GPT-5.6 Terra",
+ },
+ {
+ id: "gpt-5.6-luna",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ label: "GPT-5.6 Luna",
+ },
+ {
+ id: "gpt-6-astra",
+ runtimeAdapter: "codex",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ label: "GPT-6 Astra",
+ },
+];
+
+/** The model a run uses when it pins none. */
+export const DEFAULT_MODEL_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {
+ claude: "claude-sonnet-5",
+ codex: "gpt-5",
+};
+
+export interface ModelFamily {
+ runtimeAdapter: RuntimeAdapter;
+ prefix: string;
+ reasoningEfforts: readonly ReasoningEffort[];
+}
+
+// Depths a whole family exposes, used when no exact id matches. OpenAI ships
+// vendor-flavoured variants the gateway never lists (`gpt-5.5-codex`), and a
+// local session can drive one. The longest matching prefix wins, so the
+// declaration order below is free.
+export const FAMILY_REASONING_EFFORTS: readonly ModelFamily[] = [
+ {
+ runtimeAdapter: "codex",
+ prefix: "gpt-6-astra",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ },
+ {
+ runtimeAdapter: "codex",
+ prefix: "gpt-5.6",
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
+ },
+ {
+ runtimeAdapter: "codex",
+ prefix: "gpt-5.5",
+ reasoningEfforts: ["low", "medium", "high", "xhigh"],
+ },
+];
+
+// What a runtime accepts for a model neither an id nor a family claims.
+// Codex passes any `gpt-*` identifier through, so an id the gateway starts
+// serving before it is listed here still runs. Claude is absent on
+// purpose: an unnamed model there yields no efforts, which is what makes
+// validation reject it.
+export const FALLBACK_REASONING_EFFORTS: FallbackEfforts = {
+ codex: ["low", "medium", "high"],
+};
diff --git a/products/desktop/packages/shared/src/model-catalog.ts b/products/desktop/packages/shared/src/model-catalog.ts
new file mode 100644
index 000000000000..c05e6675dc4b
--- /dev/null
+++ b/products/desktop/packages/shared/src/model-catalog.ts
@@ -0,0 +1,89 @@
+import type { Adapter } from "./adapter";
+import {
+ FALLBACK_REASONING_EFFORTS,
+ FAMILY_REASONING_EFFORTS,
+ MODELS,
+ PROVIDER_BY_RUNTIME_ADAPTER,
+ type ReasoningEffort,
+} from "./model-catalog.generated";
+
+export {
+ type CatalogModel,
+ DEFAULT_MODEL_BY_RUNTIME_ADAPTER,
+ MODELS,
+ PROVIDER_BY_RUNTIME_ADAPTER,
+ REASONING_EFFORTS,
+ type ReasoningEffort,
+ RUNTIME_ADAPTERS,
+ type RuntimeAdapter,
+} from "./model-catalog.generated";
+
+/**
+ * The form a model id is looked up under. The gateway serves some models both bare and
+ * provider-qualified (`openai/gpt-5.6-sol`) and a picker may hand back either, so folding
+ * the two together is what stops one model from having two answers. Only the provider
+ * prefixes the catalog knows are stripped, leaving ids that carry a slash of their own
+ * (`@cf/zai-org/glm-5.2`) intact.
+ */
+export function normalizeModelId(modelId: string): string {
+ const normalized = modelId.trim().toLowerCase();
+ for (const provider of Object.values(PROVIDER_BY_RUNTIME_ADAPTER)) {
+ if (normalized.startsWith(`${provider}/`)) {
+ return normalized.slice(provider.length + 1);
+ }
+ }
+ return normalized;
+}
+
+/**
+ * The efforts this model may run at, empty when it takes no effort at all.
+ *
+ * Resolved in three steps: the exact id, then the family it belongs to, then what the
+ * adapter accepts generally. Codex passes any `gpt-*` identifier through, so a newly
+ * served id still runs, while Claude has no fallback and yields nothing — which is what
+ * makes the backend reject it. Mirrors `reasoning_efforts_for` in
+ * products/tasks/backend/model_catalog.py, so a selection this offers is one a run can
+ * actually use.
+ */
+export function reasoningEffortsForModel(
+ adapter: Adapter,
+ modelId: string,
+): readonly ReasoningEffort[] {
+ const normalized = normalizeModelId(modelId);
+ const model = MODELS.find(
+ (candidate) =>
+ candidate.runtimeAdapter === adapter && candidate.id === normalized,
+ );
+ if (model) return model.reasoningEfforts;
+ // Longest matching prefix wins, so the table's declaration order is free.
+ const family = FAMILY_REASONING_EFFORTS.filter(
+ (candidate) =>
+ candidate.runtimeAdapter === adapter &&
+ normalized.startsWith(candidate.prefix),
+ ).sort((a, b) => b.prefix.length - a.prefix.length)[0];
+ return family?.reasoningEfforts ?? FALLBACK_REASONING_EFFORTS[adapter] ?? [];
+}
+
+/**
+ * The name the catalog pins for a model, or `undefined` to let the caller format the id.
+ *
+ * Only the ids whose derived name reads wrong carry one, so a caller keeps its formatter
+ * for everything else. Mirrors `label_for_model` in
+ * products/tasks/backend/model_catalog.py, so both surfaces name a model identically.
+ */
+/**
+ * The feature flag a person needs before a picker offers this model, or `undefined` when
+ * it is generally available.
+ *
+ * Governs display only. The server decides whether a run may use the model, so a stale
+ * projection can hide a model a person may use, never the other way round.
+ */
+export function accessFlagForModel(modelId: string): string | undefined {
+ const normalized = normalizeModelId(modelId);
+ return MODELS.find((candidate) => candidate.id === normalized)?.accessFlag;
+}
+
+export function labelForModel(modelId: string): string | undefined {
+ const normalized = normalizeModelId(modelId);
+ return MODELS.find((candidate) => candidate.id === normalized)?.label;
+}
diff --git a/products/desktop/packages/shared/src/reasoning-effort.ts b/products/desktop/packages/shared/src/reasoning-effort.ts
index 2f42f7cb0d90..2d50a8c866c1 100644
--- a/products/desktop/packages/shared/src/reasoning-effort.ts
+++ b/products/desktop/packages/shared/src/reasoning-effort.ts
@@ -1,5 +1,6 @@
import type { Adapter } from "./adapter";
import { EFFORT_LEVEL_LABELS, type EffortLevel } from "./domain-types";
+import { normalizeModelId, reasoningEffortsForModel } from "./model-catalog";
export type SupportedReasoningEffort = EffortLevel;
@@ -10,70 +11,15 @@ export interface ReasoningEffortOption {
name: string;
}
-const BASE_OPTIONS: ReasoningEffortOption[] = [
- { value: "low", name: "Low" },
- { value: "medium", name: "Medium" },
- { value: "high", name: "High" },
-];
-
-const STANDARD_EFFORTS: readonly SupportedReasoningEffort[] = [
- "low",
- "medium",
- "high",
-];
-const EXTENDED_EFFORTS: readonly SupportedReasoningEffort[] = [
- ...STANDARD_EFFORTS,
- "xhigh",
- "max",
- "ultracode",
-];
-
-const CLAUDE_MODEL_EFFORTS: Readonly<
- Record<string, readonly SupportedReasoningEffort[]>
-> = {
- "claude-opus-4-7": EXTENDED_EFFORTS,
- "claude-opus-4-8": EXTENDED_EFFORTS,
- "claude-sonnet-4-6": STANDARD_EFFORTS,
- "claude-sonnet-5": EXTENDED_EFFORTS,
- "claude-fable-5": EXTENDED_EFFORTS,
- "claude-fable-5-1": EXTENDED_EFFORTS,
- "@cf/zai-org/glm-5.2": ["high", "max"],
- "zai-org/glm-5.3": ["high", "max"],
- "zai-org/glm-5.3-flash": ["high", "max"],
- "claude-opus-5": EXTENDED_EFFORTS,
-};
-
+/** Null rather than an empty list for a model with no effort control, so the
+ * caller renders no dropdown instead of an empty one. */
export function getReasoningEffortOptions(
adapter: Adapter,
modelId: string,
): ReasoningEffortOption[] | null {
- if (adapter === "claude") {
- const efforts = CLAUDE_MODEL_EFFORTS[modelId];
- return (
- efforts?.map((value) => ({ value, name: EFFORT_LEVEL_LABELS[value] })) ??
- null
- );
- }
-
- const options = [...BASE_OPTIONS];
- const normalizedModelId = modelId.toLowerCase();
- const supportsXhigh =
- normalizedModelId.includes("gpt-5.5") ||
- normalizedModelId.includes("gpt-5.6") ||
- normalizedModelId.includes("gpt-6-astra");
-
- if (supportsXhigh) {
- options.push({ value: "xhigh", name: "Extra High" });
- }
- if (
- adapter === "codex" &&
- (normalizedModelId.includes("gpt-5.6") ||
- normalizedModelId.includes("gpt-6-astra"))
- ) {
- options.push({ value: "max", name: "Max" });
- }
-
- return options;
+ const efforts = reasoningEffortsForModel(adapter, modelId);
+ if (efforts.length === 0) return null;
+ return efforts.map((value) => ({ value, name: EFFORT_LEVEL_LABELS[value] }));
}
export function isSupportedReasoningEffort(
@@ -131,8 +77,10 @@ const MODELS_WITH_1M_CONTEXT = new Set([
"claude-fable-5-1",
]);
+// Normalized like the effort lookup above: the gateway serves some ids provider-qualified,
+// and a raw check here would silently drop the model to 200k.
export function supports1MContext(modelId: string): boolean {
- return MODELS_WITH_1M_CONTEXT.has(modelId);
+ return MODELS_WITH_1M_CONTEXT.has(normalizeModelId(modelId));
}
const MODELS_WITH_FAST_MODE = new Set([
@@ -142,5 +90,5 @@ const MODELS_WITH_FAST_MODE = new Set([
]);
export function supportsFastMode(modelId: string): boolean {
- return MODELS_WITH_FAST_MODE.has(modelId);
+ return MODELS_WITH_FAST_MODE.has(normalizeModelId(modelId));
}
diff --git a/products/desktop/packages/shared/tsup.config.ts b/products/desktop/packages/shared/tsup.config.ts
index d178bd88816a..6de68d283487 100644
--- a/products/desktop/packages/shared/tsup.config.ts
+++ b/products/desktop/packages/shared/tsup.config.ts
@@ -11,6 +11,7 @@ export default defineConfig({
"src/domain-types.ts",
"src/hoggies.ts",
"src/mcp-sandbox-proxy.ts",
+ "src/model-catalog.ts",
"src/posthog-property-headers.ts",
"src/product-engineer-prompt.ts",
"src/quick-ask-shortcuts.ts",
diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
index f806a1ec42a6..aee81a30a03e 100644
--- a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
+++ b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx
@@ -63,11 +63,7 @@ export function LoopModelFields({
() => [
{ value: DEFAULT_MODEL_VALUE, label: "Default (recommended)" },
...loopModelOptions(adapter, configOptions, {
- glmEnabled: modelFlags.glm,
- glm53Enabled: modelFlags.glm53,
- glm53FlashEnabled: modelFlags.glm53Flash,
- kimiEnabled: modelFlags.kimi,
- deepseekEnabled: modelFlags.deepseek,
+ flags: modelFlags,
pinnedModel: model,
}),
],
diff --git a/products/desktop/packages/ui/src/features/loops/loopModels.test.ts b/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
index d06bf46a488f..530d0b095e66 100644
--- a/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopModels.test.ts
@@ -3,8 +3,17 @@ import type {
SessionConfigSelectOptions,
} from "@agentclientprotocol/sdk";
import type { LoopSchemas } from "@posthog/api-client/loops";
-import { restrictedModelMeta } from "@posthog/shared";
+import {
+ DEEPSEEK_MODEL_FLAG,
+ GLM_MODEL_FLAG,
+ GLM53_FLASH_MODEL_FLAG,
+ GLM53_MODEL_FLAG,
+ KIMI_MODEL_FLAG,
+ restrictedModelMeta,
+} from "@posthog/shared";
+import { MODELS } from "@posthog/shared/model-catalog";
import { describe, expect, it } from "vitest";
+import type { ModelRolloutFlags } from "../sessions/modelOptionFilters";
import {
clampLoopReasoningEffort,
LOOP_DEFAULT_MODELS,
@@ -27,6 +36,23 @@ function modelConfigOption(
];
}
+/** The flag record the picker reads, from the friendlier names these cases are written in. */
+function rolloutFlags(on: {
+ glm?: boolean;
+ glm53?: boolean;
+ glm53Flash?: boolean;
+ kimi?: boolean;
+ deepseek?: boolean;
+}): ModelRolloutFlags {
+ return {
+ [GLM_MODEL_FLAG]: on.glm ?? false,
+ [GLM53_MODEL_FLAG]: on.glm53 ?? false,
+ [GLM53_FLASH_MODEL_FLAG]: on.glm53Flash ?? false,
+ [KIMI_MODEL_FLAG]: on.kimi ?? false,
+ [DEEPSEEK_MODEL_FLAG]: on.deepseek ?? false,
+ };
+}
+
const claudeOptions = modelConfigOption([
{ value: "claude-sonnet-5", name: "Claude Sonnet 5" },
{ value: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
@@ -36,7 +62,7 @@ describe("loopModelOptions", () => {
it("includes GPT-6 Astra in the offline Codex fallback", () => {
expect(
loopModelOptions("codex", [], {
- glmEnabled: false,
+ flags: rolloutFlags({ glm: false }),
pinnedModel: "",
}),
).toContainEqual({ value: "gpt-6-astra", label: "GPT-6 Astra" });
@@ -45,7 +71,7 @@ describe("loopModelOptions", () => {
it("maps served model options to value/label pairs", () => {
expect(
loopModelOptions("claude", claudeOptions, {
- glmEnabled: true,
+ flags: rolloutFlags({ glm: true }),
pinnedModel: "",
}),
).toEqual([
@@ -64,7 +90,7 @@ describe("loopModelOptions", () => {
]);
expect(
loopModelOptions("claude", grouped, {
- glmEnabled: true,
+ flags: rolloutFlags({ glm: true }),
pinnedModel: "",
}),
).toEqual([{ value: "claude-sonnet-5", label: "Claude Sonnet 5" }]);
@@ -81,7 +107,7 @@ describe("loopModelOptions", () => {
]);
expect(
loopModelOptions("claude", withRestricted, {
- glmEnabled: true,
+ flags: rolloutFlags({ glm: true }),
pinnedModel: "",
}),
).toEqual([{ value: "claude-sonnet-5", label: "Claude Sonnet 5" }]);
@@ -108,7 +134,7 @@ describe("loopModelOptions", () => {
},
])("$name", ({ glmEnabled, pinnedModel, expectedValues }) => {
const values = loopModelOptions("claude", claudeOptions, {
- glmEnabled,
+ flags: rolloutFlags({ glm: glmEnabled }),
pinnedModel,
}).map((option) => option.value);
expect(values).toEqual(expectedValues);
@@ -117,19 +143,19 @@ describe("loopModelOptions", () => {
it("keeps a pinned model that the catalog no longer serves", () => {
expect(
loopModelOptions("claude", claudeOptions, {
- glmEnabled: true,
- pinnedModel: "claude-opus-4-6",
+ flags: rolloutFlags({ glm: true }),
+ pinnedModel: "claude-opus-4-1",
}),
- ).toContainEqual({ value: "claude-opus-4-6", label: "claude-opus-4-6" });
+ ).toContainEqual({ value: "claude-opus-4-1", label: "Claude Opus 4.1" });
});
it.each([
{
- flags: { glm53Enabled: true },
+ flags: rolloutFlags({ glm53: true }),
expected: [{ value: "zai-org/glm-5.3", label: "GLM-5.3" }],
},
{
- flags: { glm53FlashEnabled: true },
+ flags: rolloutFlags({ glm53Flash: true }),
expected: [{ value: "zai-org/glm-5.3-flash", label: "GLM-5.3 Flash" }],
},
])("gates each GLM 5.3 variant independently", ({ flags, expected }) => {
@@ -140,11 +166,7 @@ describe("loopModelOptions", () => {
]);
expect(
- loopModelOptions("claude", options, {
- glmEnabled: false,
- pinnedModel: "",
- ...flags,
- }),
+ loopModelOptions("claude", options, { flags, pinnedModel: "" }),
).toEqual(expected);
});
@@ -177,8 +199,7 @@ describe("loopModelOptions", () => {
]);
const values = loopModelOptions("claude", options, {
- glmEnabled: true,
- deepseekEnabled,
+ flags: rolloutFlags({ glm: true, deepseek: deepseekEnabled }),
pinnedModel,
}).map((option) => option.value);
expect(values).toEqual(expectedValues);
@@ -228,12 +249,35 @@ describe("loopModelOptions", () => {
},
])("$name", ({ adapter, glm53Enabled, expectedValues }) => {
const values = loopModelOptions(adapter, [], {
- glmEnabled: true,
- glm53Enabled,
+ flags: rolloutFlags({ glm: true, glm53: glm53Enabled }),
pinnedModel: "",
}).map((option) => option.value);
expect(values).toEqual(expectedValues);
});
+
+ // The loops serializer rejects a model the catalog no longer serves, so a retired id
+ // in the fallback list is a save the user cannot make. The cases above assert the
+ // fallback against hardcoded ids, so only this notices a catalog removal.
+ it("every fallback model is one the catalog still serves", () => {
+ for (const adapter of ["claude", "codex"] as const) {
+ const served = MODELS.filter((m) => m.runtimeAdapter === adapter).map(
+ (m) => m.id,
+ );
+ const fallback = loopModelOptions(adapter, [], {
+ flags: rolloutFlags({
+ glm: true,
+ glm53: true,
+ glm53Flash: true,
+ kimi: true,
+ deepseek: true,
+ }),
+ pinnedModel: "",
+ })
+ .map((o) => o.value)
+ .filter((v) => v !== "");
+ expect(served).toEqual(expect.arrayContaining(fallback));
+ }
+ });
});
describe("LOOP_DEFAULT_MODELS", () => {
diff --git a/products/desktop/packages/ui/src/features/loops/loopModels.ts b/products/desktop/packages/ui/src/features/loops/loopModels.ts
index 401efcf792ef..87c174b11900 100644
--- a/products/desktop/packages/ui/src/features/loops/loopModels.ts
+++ b/products/desktop/packages/ui/src/features/loops/loopModels.ts
@@ -3,64 +3,99 @@ import { getReasoningEffortOptions } from "@posthog/agent/adapters/reasoning-eff
import type { LoopSchemas } from "@posthog/api-client/loops";
import {
flattenSelectOptions,
- isDeepseekModelId,
+ formatModelId,
isDefaultSelectOption,
- isGlm53FlashModelId,
- isGlm53ModelId,
- isGlmModelId,
isRestrictedModelOption,
selectOptionDocsUrl,
} from "@posthog/shared";
+import {
+ accessFlagForModel,
+ DEFAULT_MODEL_BY_RUNTIME_ADAPTER,
+ labelForModel,
+} from "@posthog/shared/model-catalog";
+import type { ModelRolloutFlags } from "../sessions/modelOptionFilters";
export interface LoopModelOption {
value: string;
label: string;
}
-// Mirrors DEFAULT_MODEL_BY_RUNTIME_ADAPTER in posthog's
-// products/tasks/backend/temporal/process_task/utils.py: the model a loop
-// fires with when none is pinned, and the one the serializer validates a
-// blank-model loop's reasoning effort against.
+// The name the catalog resolved for a model when it was generated, falling back to the
+// same formatter the served list uses. Every surface names a model this way, so one model
+// reads the same offline as it does online, and an id the catalog dropped still reads as
+// a name rather than as an id.
+function catalogLabel(id: string): string {
+ return labelForModel(id) ?? formatModelId(id);
+}
+
+// The model a loop fires with when none is pinned, and the one the serializer
+// validates a blank-model loop's reasoning effort against. Both the id and its
+// name come from the shared catalog, so neither can disagree with what the
+// backend applies.
export const LOOP_DEFAULT_MODELS: Record<
LoopSchemas.LoopRuntimeAdapterEnum,
{ id: string; label: string }
> = {
- claude: { id: "claude-sonnet-5", label: "Claude Sonnet 5" },
- codex: { id: "gpt-5", label: "GPT-5" },
+ claude: {
+ id: DEFAULT_MODEL_BY_RUNTIME_ADAPTER.claude,
+ label: catalogLabel(DEFAULT_MODEL_BY_RUNTIME_ADAPTER.claude),
+ },
+ codex: {
+ id: DEFAULT_MODEL_BY_RUNTIME_ADAPTER.codex,
+ label: catalogLabel(DEFAULT_MODEL_BY_RUNTIME_ADAPTER.codex),
+ },
};
-function isKimiModelId(modelId: string): boolean {
- return modelId === "moonshotai/kimi-k3";
-}
-
// Served-catalog stand-in while the preview config loads or when the request
-// fails, so the picker never collapses to "Default" alone. Matches the
-// backend's per-adapter catalogs in process_task/utils.py minus client-blocked
-// models; the served catalog stays authoritative once it arrives.
-const FALLBACK_MODEL_OPTIONS: Record<
+// fails, so the picker never collapses to "Default" alone. The served catalog is
+// authoritative once it arrives.
+//
+// The ids are a deliberate subset, not the whole catalog: an offline picker offers
+// what someone should reach for without a network, which is fewer models than the
+// catalog serves. `everyFallbackModelIsServedByTheCatalog` in the tests holds the
+// subset to models the loops serializer still accepts.
+const FALLBACK_MODEL_IDS: Record<
LoopSchemas.LoopRuntimeAdapterEnum,
- LoopModelOption[]
+ readonly string[]
> = {
claude: [
- { value: "claude-opus-4-8", label: "Claude Opus 4.8" },
- { value: "claude-opus-5", label: "Claude Opus 5" },
- { value: "claude-sonnet-5", label: "Claude Sonnet 5" },
- { value: "claude-fable-5", label: "Claude Fable 5" },
- { value: "claude-fable-5-1", label: "Claude Fable 5.1" },
- { value: "zai-org/glm-5.3", label: "GLM-5.3" },
- { value: "zai-org/glm-5.3-flash", label: "GLM-5.3 Flash" },
- { value: "moonshotai/kimi-k3", label: "Kimi K3" },
+ "claude-opus-4-8",
+ "claude-opus-5",
+ "claude-sonnet-5",
+ "claude-fable-5",
+ "claude-fable-5-1",
+ "zai-org/glm-5.3",
+ "zai-org/glm-5.3-flash",
+ "moonshotai/kimi-k3",
],
codex: [
- { value: "gpt-5", label: "GPT-5" },
- { value: "gpt-5.5", label: "GPT-5.5" },
- { value: "gpt-5.6-sol", label: "GPT-5.6 Sol" },
- { value: "gpt-5.6-terra", label: "GPT-5.6 Terra" },
- { value: "gpt-5.6-luna", label: "GPT-5.6 Luna" },
- { value: "gpt-6-astra", label: "GPT-6 Astra" },
+ "gpt-5",
+ "gpt-5.5",
+ "gpt-5.6-sol",
+ "gpt-5.6-terra",
+ "gpt-5.6-luna",
+ "gpt-6-astra",
],
};
+// Named from the catalog, so a model does not change label when the preview config drops.
+const FALLBACK_MODEL_OPTIONS: Record<
+ LoopSchemas.LoopRuntimeAdapterEnum,
+ LoopModelOption[]
+> = {
+ claude: fallbackOptionsFor("claude"),
+ codex: fallbackOptionsFor("codex"),
+};
+
+function fallbackOptionsFor(
+ adapter: LoopSchemas.LoopRuntimeAdapterEnum,
+): LoopModelOption[] {
+ return FALLBACK_MODEL_IDS[adapter].map((id) => ({
+ value: id,
+ label: catalogLabel(id),
+ }));
+}
+
/** The model a loop's runs use, for display: the pinned id, or the adapter's
* loop default (which differs from the live-session default the
* ReportModelResolver serves, so it can't be resolved from there). */
@@ -82,21 +117,7 @@ export function formatLoopModel(
export function loopModelOptions(
adapter: LoopSchemas.LoopRuntimeAdapterEnum,
configOptions: SessionConfigOption[],
- {
- glmEnabled,
- glm53Enabled,
- glm53FlashEnabled,
- kimiEnabled,
- deepseekEnabled,
- pinnedModel,
- }: {
- glmEnabled: boolean;
- glm53Enabled?: boolean;
- glm53FlashEnabled?: boolean;
- kimiEnabled?: boolean;
- deepseekEnabled?: boolean;
- pinnedModel: string;
- },
+ { flags, pinnedModel }: { flags: ModelRolloutFlags; pinnedModel: string },
): LoopModelOption[] {
const modelOption = configOptions.find(
(option) => option.category === "model" || option.id === "model",
@@ -110,31 +131,19 @@ export function loopModelOptions(
label: option.name ?? option.value,
}))
: [];
- const options = (served.length > 0 ? served : FALLBACK_MODEL_OPTIONS[adapter])
- .filter(
- (option) =>
- (isGlm53FlashModelId(option.value)
- ? glm53FlashEnabled
- : isGlm53ModelId(option.value)
- ? glm53Enabled
- : glmEnabled) ||
- option.value === pinnedModel ||
- !isGlmModelId(option.value),
- )
- .filter(
- (option) =>
- kimiEnabled ||
- option.value === pinnedModel ||
- !isKimiModelId(option.value),
- )
- .filter(
- (option) =>
- deepseekEnabled ||
- option.value === pinnedModel ||
- !isDeepseekModelId(option.value),
- );
+ // A gated model the person cannot reach is dropped, except the one this loop already
+ // pins — removing that would silently change which model the loop runs.
+ const options = (
+ served.length > 0 ? served : FALLBACK_MODEL_OPTIONS[adapter]
+ ).filter((option) => {
+ if (option.value === pinnedModel) {
+ return true;
+ }
+ const flag = accessFlagForModel(option.value);
+ return flag === undefined || flags[flag];
+ });
if (pinnedModel && !options.some((option) => option.value === pinnedModel)) {
- options.push({ value: pinnedModel, label: pinnedModel });
+ options.push({ value: pinnedModel, label: catalogLabel(pinnedModel) });
}
return options;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
index f1665a2ae45f..8e295e512931 100644
--- a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.test.ts
@@ -1,4 +1,11 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import {
+ DEEPSEEK_MODEL_FLAG,
+ GLM_MODEL_FLAG,
+ GLM53_FLASH_MODEL_FLAG,
+ GLM53_MODEL_FLAG,
+ KIMI_MODEL_FLAG,
+} from "@posthog/shared";
import { describe, expect, it } from "vitest";
import {
type ModelRolloutFlags,
@@ -7,27 +14,29 @@ import {
} from "./modelOptionFilters";
describe("modelOptionFilters", () => {
- const rolloutModels: {
- flag: keyof ModelRolloutFlags;
- id: string;
- name: string;
- }[] = [
+ // The flag beside each id is the one the catalog records for it, so a case fails if the
+ // two ever disagree about which flag gates the model.
+ const rolloutModels: { flag: string; id: string; name: string }[] = [
{
- flag: "deepseek",
+ flag: DEEPSEEK_MODEL_FLAG,
id: "deepseek-ai/deepseek-v4-flash-0731",
name: "DeepSeek V4 Flash",
},
- { flag: "glm", id: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
- { flag: "glm53", id: "zai-org/glm-5.3", name: "GLM-5.3" },
- { flag: "glm53Flash", id: "zai-org/glm-5.3-flash", name: "GLM-5.3 Flash" },
- { flag: "kimi", id: "moonshotai/kimi-k3", name: "Kimi K3" },
+ { flag: GLM_MODEL_FLAG, id: "@cf/zai-org/glm-5.2", name: "GLM-5.2" },
+ { flag: GLM53_MODEL_FLAG, id: "zai-org/glm-5.3", name: "GLM-5.3" },
+ {
+ flag: GLM53_FLASH_MODEL_FLAG,
+ id: "zai-org/glm-5.3-flash",
+ name: "GLM-5.3 Flash",
+ },
+ { flag: KIMI_MODEL_FLAG, id: "moonshotai/kimi-k3", name: "Kimi K3" },
];
const enabledFlags: ModelRolloutFlags = {
- deepseek: true,
- glm: true,
- glm53: true,
- glm53Flash: true,
- kimi: true,
+ [DEEPSEEK_MODEL_FLAG]: true,
+ [GLM_MODEL_FLAG]: true,
+ [GLM53_MODEL_FLAG]: true,
+ [GLM53_FLASH_MODEL_FLAG]: true,
+ [KIMI_MODEL_FLAG]: true,
};
it.each(rolloutModels)(
@@ -73,7 +82,10 @@ describe("modelOptionFilters", () => {
};
expect(
- stripDisabledModelOption(option, { ...enabledFlags, kimi: false }),
+ stripDisabledModelOption(option, {
+ ...enabledFlags,
+ [KIMI_MODEL_FLAG]: false,
+ }),
).toMatchObject({
currentValue: "claude-opus-5",
options: [{ group: "anthropic" }],
diff --git a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.ts b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.ts
index 71229b39511e..869cb4a9a141 100644
--- a/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.ts
+++ b/products/desktop/packages/ui/src/features/sessions/modelOptionFilters.ts
@@ -1,34 +1,16 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
-import {
- isDeepseekModelId,
- isGlm53FlashModelId,
- isGlm53ModelId,
- isGlmModelId,
- isSelectGroup,
-} from "@posthog/shared";
+import { isSelectGroup } from "@posthog/shared";
+import { accessFlagForModel } from "@posthog/shared/model-catalog";
-const isKimiModelId = (modelId: string): boolean =>
- modelId === "moonshotai/kimi-k3";
-
-export interface ModelRolloutFlags {
- deepseek: boolean;
- glm: boolean;
- glm53: boolean;
- glm53Flash: boolean;
- kimi: boolean;
-}
+/** Whether each model access flag is on for this person, keyed by flag. */
+export type ModelRolloutFlags = Record<string, boolean>;
+// The catalog says which flag a model needs, so a newly gated model is filtered by adding
+// its `access_flag` there rather than by adding a predicate and a branch here. A model the
+// catalog does not gate is offered to everyone.
function isModelDisabled(modelId: string, flags: ModelRolloutFlags): boolean {
- return (
- (!flags.deepseek && isDeepseekModelId(modelId)) ||
- (!flags.glm53 && isGlm53ModelId(modelId)) ||
- (!flags.glm53Flash && isGlm53FlashModelId(modelId)) ||
- (!flags.glm &&
- isGlmModelId(modelId) &&
- !isGlm53ModelId(modelId) &&
- !isGlm53FlashModelId(modelId)) ||
- (!flags.kimi && isKimiModelId(modelId))
- );
+ const flag = accessFlagForModel(modelId);
+ return flag !== undefined && !flags[flag];
}
function stripModelOptions(
diff --git a/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts b/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
index aa7bc48e3ac1..3595d6a531e4 100644
--- a/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
+++ b/products/desktop/packages/ui/src/features/sessions/useModelRolloutFlags.ts
@@ -21,8 +21,16 @@ export function useModelRolloutFlags(): ModelRolloutFlags {
const glm53 = useFeatureFlag(GLM53_MODEL_FLAG, dev);
const glm53Flash = useFeatureFlag(GLM53_FLASH_MODEL_FLAG, dev);
const kimi = useFeatureFlag(KIMI_MODEL_FLAG, dev);
+ // Keyed by flag, so a model's `accessFlag` from the catalog reads straight off this
+ // rather than each caller knowing which named boolean belongs to which model.
return useMemo(
- () => ({ deepseek, glm, glm53, glm53Flash, kimi }),
+ () => ({
+ [DEEPSEEK_MODEL_FLAG]: deepseek,
+ [GLM_MODEL_FLAG]: glm,
+ [GLM53_MODEL_FLAG]: glm53,
+ [GLM53_FLASH_MODEL_FLAG]: glm53Flash,
+ [KIMI_MODEL_FLAG]: kimi,
+ }),
[deepseek, glm, glm53, glm53Flash, kimi],
);
}
diff --git a/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
index 6a14bb38048f..2cd9882559e4 100644
--- a/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/modelCatalogueLogic.test.ts
@@ -1,45 +1,25 @@
-import { expectLogic } from 'kea-test-utils'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { FALLBACK_MODEL_CHOICES } from '../utils/composerModels'
+import { MODELS } from 'products/tasks/frontend/modelCatalog.generated'
+
import { modelCatalogueLogic } from './modelCatalogueLogic'
describe('modelCatalogueLogic', () => {
- const MODELS = [
- {
- runtime_adapter: 'claude' as const,
- model: 'claude-opus-4-8',
- display_name: 'Claude Opus 4.8',
- supported_efforts: ['low' as const, 'high' as const],
- },
- {
- runtime_adapter: 'codex' as const,
- model: 'gpt-5.6-luna',
- display_name: 'GPT-5.6 Luna',
- supported_efforts: ['low' as const, 'high' as const],
- },
- ]
-
let logic: ReturnType<typeof modelCatalogueLogic.build>
- function useCatalogueMocks(models: typeof MODELS | 'error'): void {
- useMocks({
- get: {
- '/api/projects/:team_id/tasks/models/': () =>
- models === 'error' ? [500, { detail: 'gateway down' }] : [200, { models }],
- },
- })
- }
+ const GATED = MODELS.filter((model) => model.accessFlag)
+ const UNGATED = MODELS.filter((model) => !model.accessFlag)
- function mount(): void {
+ function mountWithFlags(flags: string[]): void {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags(flags, Object.fromEntries(flags.map((flag) => [flag, true])))
logic = modelCatalogueLogic()
logic.mount()
}
beforeEach(() => {
- localStorage.clear()
initKeaTests()
})
@@ -47,40 +27,45 @@ describe('modelCatalogueLogic', () => {
logic?.unmount()
})
- it('serves the fetched catalogue and keeps it for the next mount', async () => {
- useCatalogueMocks(MODELS)
- mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess']).toMatchValues({ catalogue: MODELS })
-
- // Remounting renders the stored catalogue right away rather than the built-in stand-in, so the
- // picker doesn't briefly lose the models it was showing a moment ago.
- logic.unmount()
- useCatalogueMocks('error')
- mount()
- expect(logic.values.catalogue).toEqual(MODELS)
+ it('offers every catalog model under the name the catalog gives it', () => {
+ mountWithFlags(GATED.map((model) => model.accessFlag as string))
+
+ expect(logic.values.catalogue.map((choice) => [choice.model, choice.display_name])).toEqual(
+ MODELS.map((model) => [model.id, model.label])
+ )
+ })
+
+ // A staged model is a picker offering the run API would reject, so it stays hidden until
+ // the person holds its flag. The API is still the gate — this only stops us offering it.
+ it('hides a model whose access flag the person does not hold', () => {
+ expect(GATED.length).toBeGreaterThan(0)
+ mountWithFlags([])
+
+ const offered = logic.values.catalogue.map((choice) => choice.model)
+ expect(offered).toEqual(UNGATED.map((model) => model.id))
+ })
+
+ it('reveals only the gated model whose flag is on', () => {
+ const [first] = GATED
+ mountWithFlags([first.accessFlag as string])
+
+ const offered = logic.values.catalogue.map((choice) => choice.model)
+ expect(offered).toContain(first.id)
+ for (const model of GATED.filter((candidate) => candidate.id !== first.id)) {
+ expect(offered).not.toContain(model.id)
+ }
})
- // A failed revalidation must not cost the models we already had — the built-in list is only a
- // stand-in for having nothing at all.
- it.each([['error' as const], [[] as typeof MODELS]])(
- 'keeps the stored catalogue when the refetch answers with %s',
- async (response) => {
- useCatalogueMocks(MODELS)
- mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess'])
- logic.unmount()
-
- useCatalogueMocks(response)
- mount()
- await expectLogic(logic).toDispatchActions(['loadCatalogueSuccess']).toMatchValues({ catalogue: MODELS })
+ // An empty effort list is an answer, not missing metadata: the picker renders such a model with no
+ // effort dropdown, and a run must not send an effort for it. Filling the gap with a default would
+ // offer efforts the backend rejects.
+ it('keeps the effort list empty for a model with no effort control', () => {
+ const withoutEfforts = MODELS.filter((model) => model.reasoningEfforts.length === 0)
+ expect(withoutEfforts.length).toBeGreaterThan(0)
+ mountWithFlags(GATED.map((model) => model.accessFlag as string))
+
+ for (const model of withoutEfforts) {
+ expect(logic.values.catalogue.find((choice) => choice.model === model.id)?.supported_efforts).toEqual([])
}
- )
-
- it('falls back to the built-in list when nothing has ever been fetched', async () => {
- useCatalogueMocks('error')
- mount()
- await expectLogic(logic)
- .toDispatchActions(['loadCatalogueSuccess'])
- .toMatchValues({ catalogue: FALLBACK_MODEL_CHOICES })
})
})
diff --git a/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts b/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts
index e8f30d3d43b2..e875615e42be 100644
--- a/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts
+++ b/products/posthog_ai/frontend/logics/modelCatalogueLogic.ts
@@ -1,116 +1,74 @@
-import { MakeLogicType, afterMount, connect, kea, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
+import { MakeLogicType, connect, kea, path, selectors } from 'kea'
-import { projectLogic } from 'scenes/projectLogic'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { tasksModelsRetrieve } from 'products/tasks/frontend/generated/api'
-import { ModelChoiceApi } from 'products/tasks/frontend/generated/api.schemas'
+import {
+ ModelChoiceApi,
+ ReasoningEffortEnumApi,
+ RuntimeAdapterEnumApi,
+} from 'products/tasks/frontend/generated/api.schemas'
+import { MODELS } from 'products/tasks/frontend/modelCatalog.generated'
-import { FALLBACK_MODEL_CHOICES } from '../utils/composerModels'
+// The catalog and these enums are generated from the same Python definitions, so the casts
+// restate what codegen already guarantees.
+const CATALOGUE: ModelChoiceApi[] = MODELS.map((model) => ({
+ runtime_adapter: model.runtimeAdapter as RuntimeAdapterEnumApi,
+ model: model.id,
+ display_name: model.label,
+ supported_efforts: [...model.reasoningEfforts] as ReasoningEffortEnumApi[],
+}))
-const CATALOGUE_STORAGE_KEY = 'posthog_ai_model_catalogue'
+// The flag a model needs before the picker offers it, from the same catalog row. Display
+// only: the run API rejects a model the person may not use, whatever the picker showed.
+const ACCESS_FLAG_BY_MODEL: Record<string, string> = Object.fromEntries(
+ MODELS.filter((model) => model.accessFlag).map((model) => [model.id, model.accessFlag as string])
+)
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface modelCatalogueLogicValues {
- currentProjectId: number | null // projectLogic
- cachedCatalogue: ModelChoiceApi[] | null
+ featureFlags: FeatureFlagsSet // featureFlagLogic
catalogue: ModelChoiceApi[]
- fetchedCatalogue: ModelChoiceApi[] | null
- fetchedCatalogueLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface modelCatalogueLogicActions {
- loadCatalogue: () => any
- loadCatalogueFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadCatalogueSuccess: (
- fetchedCatalogue: ModelChoiceApi[] | null,
- payload?: any
- ) => {
- fetchedCatalogue: ModelChoiceApi[] | null
- payload?: any
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface modelCatalogueLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- catalogue: (
- fetchedCatalogue: ModelChoiceApi[] | null,
- cachedCatalogue: ModelChoiceApi[] | null
- ) => ModelChoiceApi[]
+ catalogue: (featureFlags: FeatureFlagsSet) => ModelChoiceApi[]
}
}
export type modelCatalogueLogicType = MakeLogicType<
modelCatalogueLogicValues,
- modelCatalogueLogicActions,
+ {},
Record<string, any>,
modelCatalogueLogicMeta
>
/**
- * The models a task run may use, fetched from the tasks API rather than hardcoded — the endpoint derives it from the
- * live LLM gateway catalogue, so a newly released model reaches the composer without a frontend change.
+ * The models a task run may use, read from the generated model catalog.
*
- * Served stale-while-revalidate: the last catalogue seen is kept in local storage and rendered immediately, while a
- * fresh one is fetched in the background. Whatever the fetch can't answer — no project, an unreachable gateway (the
- * endpoint answers with an empty list), a failed request — leaves the last known catalogue in place, and a small
- * built-in list stands in until there is one, so the model dropdown is never empty and never briefly loses the models
- * it showed a moment ago.
+ * The catalog is the same definition the backend validates a run against, so the composer can only offer a selection
+ * the API accepts. Baking it in rather than fetching it means the model dropdown is populated on first render, with no
+ * request to wait on and nothing to fall back to when one fails. A model reaches the composer when the catalog is
+ * regenerated, which is also what ships it to the backend and the desktop app.
*/
export const modelCatalogueLogic = kea<modelCatalogueLogicType>([
path(['products', 'posthog_ai', 'frontend', 'logics', 'modelCatalogueLogic']),
connect(() => ({
- values: [projectLogic, ['currentProjectId']],
+ values: [featureFlagLogic, ['featureFlags']],
})),
- loaders(({ values }) => ({
- fetchedCatalogue: [
- null as ModelChoiceApi[] | null,
- {
- loadCatalogue: async (): Promise<ModelChoiceApi[] | null> => {
- if (values.currentProjectId == null) {
- return null
- }
- try {
- const response = await tasksModelsRetrieve(String(values.currentProjectId))
- // An empty list means the gateway is unreachable, not that no model exists.
- return response.models.length ? response.models : null
- } catch {
- return null
- }
- },
- },
- ],
- })),
-
- reducers({
- cachedCatalogue: [
- null as ModelChoiceApi[] | null,
- { persist: true, storageKey: CATALOGUE_STORAGE_KEY },
- {
- loadCatalogueSuccess: (state, { fetchedCatalogue }) => fetchedCatalogue ?? state,
- },
- ],
- }),
-
selectors({
catalogue: [
- (s) => [s.fetchedCatalogue, s.cachedCatalogue],
- (fetched: ModelChoiceApi[] | null, cached: ModelChoiceApi[] | null): ModelChoiceApi[] =>
- fetched ?? cached ?? FALLBACK_MODEL_CHOICES,
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): ModelChoiceApi[] =>
+ CATALOGUE.filter((choice) => {
+ // The catalog names the flag, so it is a plain string rather than a `FeatureFlagKey`.
+ // Listing these keys in `FEATURE_FLAGS` too would restore the duplication the catalog removes.
+ const flag = ACCESS_FLAG_BY_MODEL[choice.model] as keyof FeatureFlagsSet | undefined
+ return !flag || !!featureFlags[flag]
+ }),
],
}),
-
- afterMount(({ actions }) => {
- actions.loadCatalogue()
- }),
])
diff --git a/products/posthog_ai/frontend/utils/composerModels.test.ts b/products/posthog_ai/frontend/utils/composerModels.test.ts
index 5ca1a9b66664..a0bdb28d76d0 100644
--- a/products/posthog_ai/frontend/utils/composerModels.test.ts
+++ b/products/posthog_ai/frontend/utils/composerModels.test.ts
@@ -10,6 +10,9 @@ import {
import {
buildRunCreateRequest,
getCapabilityLadder,
+ getEffortsForModel,
+ getModelLabel,
+ getRuntimeAdapterForModel,
listRuntimeAdapters,
modelsForRuntimeAdapter,
} from './composerModels'
@@ -54,6 +57,27 @@ describe('composerModels', () => {
})
})
+ // The gateway serves some models provider-qualified, so a run or workflow config can hold either spelling.
+ // The backend and the desktop app both fold them onto the bare id; without this the web alone reads a stored
+ // `anthropic/...` run as an unknown model — raw id for a name, and the generic effort floor.
+ it.each([
+ ['anthropic/claude-opus-4-8', 'Claude Opus 4.8'],
+ ['openai/gpt-5.6-luna', 'GPT-5.6 Luna'],
+ ])('resolves the provider-qualified id %s like the bare one', (qualified, expectedLabel) => {
+ const bare = qualified.split('/')[1]
+ expect(getModelLabel(CATALOGUE, qualified)).toBe(expectedLabel)
+ expect(getEffortsForModel(CATALOGUE, qualified)).toEqual(getEffortsForModel(CATALOGUE, bare))
+ expect(
+ buildRunCreateRequest(
+ CATALOGUE,
+ qualified,
+ ReasoningEffortEnumApi.High,
+ InitialPermissionModeEnumApi.Auto as PermissionMode,
+ {}
+ )
+ ).toMatchObject({ runtime_adapter: getRuntimeAdapterForModel(CATALOGUE, bare) })
+ })
+
// A model absent from the catalogue (still loading, or retired from the gateway) must still produce a
// sendable request rather than an undefined adapter.
it('falls back to the claude adapter for an unknown model', () => {
diff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.ts
index 0e34eb958db6..cedefd81e3fd 100644
--- a/products/posthog_ai/frontend/utils/composerModels.ts
+++ b/products/posthog_ai/frontend/utils/composerModels.ts
@@ -8,6 +8,8 @@ import {
RuntimeAdapterEnumApi,
TaskRunCreateRequestSchemaApi,
} from 'products/tasks/frontend/generated/api.schemas'
+import { normalizeModelId } from 'products/tasks/frontend/modelCatalog'
+import { DEFAULT_MODEL_BY_RUNTIME_ADAPTER } from 'products/tasks/frontend/modelCatalog.generated'
import { type PermissionMode, resolveModeForRuntimeAdapter } from './composerModes'
@@ -16,33 +18,15 @@ export interface ComposerEffortOption {
label: string
}
-// What a thinking model supports at minimum. Only reached for a model the catalogue hasn't described yet — while the
-// first fetch is in flight, or for a run started on a model since retired from the gateway.
+// What a thinking model supports at minimum. Only reached for a model the catalogue does not describe, which now means
+// a run started on a model since retired from the catalog.
const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = [
ReasoningEffortEnumApi.Low,
ReasoningEffortEnumApi.Medium,
ReasoningEffortEnumApi.High,
]
-// Used only when the tasks API can't answer: an unreachable LLM gateway makes the catalogue endpoint return an empty
-// list, and an empty model dropdown is worse than a stale one. The live catalogue is the source of truth — see
-// `modelCatalogueLogic`. Claude-only: without the catalogue we can't know a Codex model exists, and Claude is the default.
-export const FALLBACK_MODEL_CHOICES: ModelChoiceApi[] = [
- {
- runtime_adapter: RuntimeAdapterEnumApi.Claude,
- model: 'claude-sonnet-5',
- display_name: 'Claude Sonnet 5',
- supported_efforts: FALLBACK_EFFORTS,
- },
- {
- runtime_adapter: RuntimeAdapterEnumApi.Claude,
- model: 'claude-opus-5',
- display_name: 'Claude Opus 5',
- supported_efforts: FALLBACK_EFFORTS,
- },
-]
-
-export const DEFAULT_COMPOSER_MODEL = 'claude-sonnet-5'
+export const DEFAULT_COMPOSER_MODEL = DEFAULT_MODEL_BY_RUNTIME_ADAPTER.claude
export const DEFAULT_COMPOSER_EFFORT: ReasoningEffortEnumApi = ReasoningEffortEnumApi.High
const EFFORT_LABELS: Record<string, string> = {
@@ -54,11 +38,21 @@ const EFFORT_LABELS: Record<string, string> = {
[ReasoningEffortEnumApi.Ultracode]: 'Ultracode',
}
+// The catalogue is keyed by bare catalog ids, so a provider-qualified id is folded onto the model it names before
+// any lookup. A run stored as `anthropic/claude-opus-5` otherwise reads as an unknown model on this surface alone.
+function catalogueEntry(catalogue: ModelChoiceApi[], model: string | null | undefined): ModelChoiceApi | undefined {
+ if (!model) {
+ return undefined
+ }
+ const normalized = normalizeModelId(model)
+ return catalogue.find((option) => option.model === normalized)
+}
+
export function getEffortsForModel(
catalogue: ModelChoiceApi[],
model: string | null | undefined
): ComposerEffortOption[] {
- const efforts = catalogue.find((option) => option.model === model)?.supported_efforts ?? FALLBACK_EFFORTS
+ const efforts = catalogueEntry(catalogue, model)?.supported_efforts ?? FALLBACK_EFFORTS
return efforts.map((value) => ({ value, label: EFFORT_LABELS[value] ?? value }))
}
@@ -69,7 +63,7 @@ export function getRuntimeAdapterForModel(
catalogue: ModelChoiceApi[],
model: string | null | undefined
): RuntimeAdapterEnumApi {
- return catalogue.find((option) => option.model === model)?.runtime_adapter ?? RuntimeAdapterEnumApi.Claude
+ return catalogueEntry(catalogue, model)?.runtime_adapter ?? RuntimeAdapterEnumApi.Claude
}
// The harnesses the catalogue actually offers, in the order the models arrive. Derived rather than enumerated, so a
@@ -135,7 +129,7 @@ export function getRuntimeAdapterLabel(runtimeAdapter: string): string {
}
export function getModelLabel(catalogue: ModelChoiceApi[], model: string | null | undefined): string {
- return catalogue.find((option) => option.model === model)?.display_name ?? model ?? 'Model'
+ return catalogueEntry(catalogue, model)?.display_name ?? model ?? 'Model'
}
export function getEffortLabel(effort: string | null | undefined): string {
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 9c647fdc5329..4f13bf770f6d 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -462,12 +462,12 @@ path**: the Django side _sets_ the knobs and the `@posthog/agent` package _appli
entry in `REVIEW_ARMS_BY_TIER` (the executor kwargs exist for every single-turn stage).
- **The registry (source of truth for what's allowed)** — `products/tasks/backend/temporal/process_task/utils.py`,
re-exported framework-free from the facade `products/tasks/backend/facade/run_config.py` (import from the facade):
- `RuntimeAdapter` (`claude|codex`), `LLMProvider`, `ReasoningEffort`, `RUNTIME_PROVIDER_BY_ADAPTER`,
- `CLAUDE_REASONING_EFFORTS_BY_MODEL`, `CODEX_MODELS` + `CODEX_REASONING_EFFORTS` + the
- `CODEX_XHIGH/MAX_REASONING_MODELS` tiers (`gpt-5.5` caps at `xhigh`; the `gpt-5.6-*` models allow up to
- `max`), and the pure checks `get_provider_for_runtime_adapter` /
- `get_supported_reasoning_efforts` / `get_reasoning_effort_error`. A new model/effort must be added here or the combo
- is rejected. `test_constants.py` locks the ReviewHog combo to this registry at unit time.
+ `RuntimeAdapter` (`claude|codex`), `LLMProvider`, `ReasoningEffort`, `RUNTIME_PROVIDER_BY_ADAPTER`, and the pure
+ checks `get_provider_for_runtime_adapter` /
+ `get_supported_reasoning_efforts` / `get_reasoning_effort_error`. Which models exist and what efforts each takes
+ comes from `products/tasks/backend/model_catalog.py`, the one definition both the backend and the generated
+ TypeScript projections read. A new model/effort must be added there or the combo is rejected.
+ `test_constants.py` locks the ReviewHog combo to this registry at unit time.
- **Transport into the sandbox:** `Task._build_task` writes `extra_state[{runtime_adapter, provider, model,
reasoning_effort}]` → `get_task_processing_context` reads it back → `start_agent_server` →
`build_agent_runtime_env_prefix` (`logic/services/sandbox.py`) emits
@@ -494,11 +494,10 @@ an agent-side fix reaches reviews only once it is published and the image rebuil
(the local desktop path); the claude adapter's `resolveInitialModelId` fallback covers Claude but not the codex
reviewer arm — verify `$ai_model` **and `$ai_effort`** on the review generations whenever a pin changes.
-**Recipe — testing e.g. Sonnet.** Set `runtime_adapter = "claude"`, `model` a key in `CLAUDE_REASONING_EFFORTS_BY_MODEL`,
-and an effort that model supports; provider auto-derives to `anthropic`. For a new Codex model: `runtime_adapter =
-"codex"`, `model` in `CODEX_MODELS`, effort in `CODEX_REASONING_EFFORTS` (`xhigh`/`max` only for models in the
-`CODEX_XHIGH/MAX_REASONING_MODELS` tiers). A brand-new model/effort must be added to the registry on **both** sides
-(`utils.py` + `reasoning-effort.ts` / the gateway model list in `@posthog/agent`) or startup validation rejects it on one side.
+**Recipe — testing e.g. Sonnet.** Set `runtime_adapter = "claude"`, `model` to a catalog id, and an effort that model
+supports; provider auto-derives to `anthropic`. The same applies to a Codex model with `runtime_adapter = "codex"`.
+Every id and its efforts live in `model_catalog.py`; run `hogli build:task-model-catalog` after editing it, which
+updates the TypeScript projections the desktop app and the web composer read.
---
diff --git a/products/slack_app/backend/services/model_catalogue.py b/products/slack_app/backend/services/model_catalogue.py
index 35f9b6002578..5acbf1b104ae 100644
--- a/products/slack_app/backend/services/model_catalogue.py
+++ b/products/slack_app/backend/services/model_catalogue.py
@@ -12,44 +12,35 @@ against it. Neither may hardcode a model list.
from __future__ import annotations
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- # Importing this at runtime would execute `gateway_client`, pulling the Anthropic and OpenAI
- # SDKs onto slack_app's import path. It is only ever used as an annotation.
- from posthog.llm.gateway_client import Product
-
-
from products.tasks.backend.facade.model_catalogue import (
REASONING_EFFORT_DISPLAY_NAMES,
RUNTIME_ADAPTER_DISPLAY_NAMES,
ModelChoice,
RuntimeGroup,
- available_model_choices as _available_model_choices,
+ catalog_model_choices,
+ display_name_for_model,
filter_unsupported_effort,
- format_model_id,
group_by_runtime,
label_for,
runtime_adapter_for,
)
-SLACK_APP_GATEWAY_PRODUCT: Product = "slack_app"
-
def available_model_choices() -> tuple[ModelChoice, ...]:
"""Every model a Slack-triggered run may use.
- Empty when the gateway is unreachable — callers must treat that as "no choice to
- offer" rather than falling back to a hardcoded list, so a gateway outage can't route
- a run to a model the gateway would reject anyway.
+ Read from the catalog rather than the gateway. Slack asks only what the catalog
+ answers — whether a mention names a real model, which runtime drives it, and what
+ efforts it takes — so the list no longer depends on a network call that can come
+ back empty and leave a mention with nothing to match against.
"""
- return _available_model_choices(SLACK_APP_GATEWAY_PRODUCT)
+ return catalog_model_choices()
def describe_run_model(model: str | None, reasoning_effort: str | None) -> str:
"""Render the model a run is on, in one phrasing shared by the App Home card and
the progress message in the Slack thread."""
- label = format_model_id(model) if model else "—"
+ label = display_name_for_model(model) if model else "—"
if not reasoning_effort:
return f"*{label}*"
return f"*{label}* · Reasoning: *{label_for(reasoning_effort, REASONING_EFFORT_DISPLAY_NAMES)}*"
@@ -63,7 +54,7 @@ __all__ = [
"available_model_choices",
"describe_run_model",
"filter_unsupported_effort",
- "format_model_id",
+ "display_name_for_model",
"group_by_runtime",
"label_for",
"runtime_adapter_for",
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index 6b47e958d634..86e966eda7ca 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -40,7 +40,7 @@ from products.slack_app.backend.services.model_catalogue import (
RUNTIME_ADAPTER_DISPLAY_NAMES,
available_model_choices,
describe_run_model,
- format_model_id,
+ display_name_for_model,
group_by_runtime,
label_for,
)
@@ -631,7 +631,7 @@ def _active_model_blocks(
)
source_label = f"{run_defaults.source_label} in PostHog"
else:
- headline = f"Defaulting to {format_model_id(SLACK_DEFAULT_MODEL)}. Pick your own settings to override."
+ headline = f"Defaulting to {display_name_for_model(SLACK_DEFAULT_MODEL)}. Pick your own settings to override."
source_label = source.label
blocks: list[dict] = [
@@ -1296,7 +1296,7 @@ def _bar(value: int, peak: int, width: int = _STATS_BAR_WIDTH) -> str:
def _stats_model_label(usage: ModelUsage) -> str:
"""Display label for a model, truncated so the bar column stays aligned."""
- label = format_model_id(usage.model)
+ label = display_name_for_model(usage.model)
return _truncate(label, _STATS_COLUMN_LABEL_CHARS)
@@ -1325,7 +1325,7 @@ def _row_summary(row: SlackSettings | None) -> str:
if not row or not row.runtime_adapter or not row.model:
return "_(none)_"
parts = [
- f"*Model:* {format_model_id(row.model)}",
+ f"*Model:* {display_name_for_model(row.model)}",
f"*Runtime:* {label_for(row.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}",
]
if row.reasoning_effort:
diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.py
index 214a5ab62a98..d72877979664 100644
--- a/products/slack_app/backend/tests/services/test_run_preferences.py
+++ b/products/slack_app/backend/tests/services/test_run_preferences.py
@@ -8,7 +8,7 @@ from products.slack_app.backend.services.model_catalogue import (
ModelChoice,
available_model_choices,
describe_run_model,
- format_model_id,
+ display_name_for_model,
)
from products.slack_app.backend.services.run_preferences import (
SLACK_DEFAULT_MODEL,
@@ -226,24 +226,26 @@ class TestFormatModelId:
("gpt-5-mini", "GPT-5 Mini"),
# A provider-prefixed id drops the prefix before naming.
("openai/gpt-5.5", "GPT-5.5"),
+ # A vendor-served id derives badly, so the catalog names it and that name wins.
+ ("@cf/zai-org/glm-5.2", "GLM-5.2"),
],
)
def test_names_every_family_without_a_lookup_table(self, model_id, expected):
- assert format_model_id(model_id) == expected
+ assert display_name_for_model(model_id) == expected
class TestAvailableModelChoices:
- def test_drops_providers_we_cannot_route(self):
- """The gateway serves models under providers the tasks product has no runtime
- for; offering one would produce a run the gateway rejects."""
- from products.tasks.backend.facade.model_catalogue import GatewayModel
-
- gateway = (
- GatewayModel(id="claude-fable-5", owned_by="anthropic", context_window=200000),
- GatewayModel(id="titan-express", owned_by="bedrock", context_window=8000),
- )
+ def test_reads_the_catalog_rather_than_the_gateway(self):
+ """Slack asks only what the catalog answers, so a gateway outage must not leave a
+ mention with nothing to match its model against."""
+ # Fails the call rather than emptying it: returning `()` would pass whether or not
+ # Slack still reaches the gateway, which is the whole claim under test.
with patch(
"products.tasks.backend.logic.services.model_catalogue.list_gateway_models",
- return_value=gateway,
+ side_effect=AssertionError("Slack must not reach the gateway for its model list"),
):
- assert [c.model for c in available_model_choices()] == ["claude-fable-5"]
+ choices = available_model_choices()
+
+ models = {c.model for c in choices}
+ assert {"claude-sonnet-5", "gpt-5.6-sol", "zai-org/glm-5.3"} <= models
+ assert all(c.label and c.runtime_adapter for c in choices)
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 5051dd0186ba..83635ba20c4f 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -5,6 +5,8 @@ from typing import Any, Literal, get_args
import posthoganalytics
+from products.tasks.backend import model_catalog
+
# Canonical PR/CI snapshot vocabulary, as produced by the GitHub integration's
# pull-request snapshot (`_map_pr_state` / `_map_ci_status`) and persisted on
# ``TaskRun.output`` (``pr_state`` / ``ci_status``) for the task list filters.
@@ -79,28 +81,18 @@ DEV_STACK_PREVIEW_STATE_KEY = "dev_stack_preview"
DEV_STACK_PREVIEW_FEATURE_FLAG = "tasks-dev-stack-preview"
DEV_STACK_PREVIEW_PORT = 8020
-# Models a caller may only select while the paired flag is enabled for them. The Desktop
-# pickers already hide these client-side (`products/desktop/packages/shared/src/flags.ts`),
-# but a picker is a convenience rather than a gate: a stored per-task model preference, an
-# older client, or a direct API call all reach the write paths without consulting a flag, so
-# entitlement is re-checked server-side. Keys are the model ids callers send.
-MODEL_ACCESS_FLAGS: dict[str, str] = {
- "moonshotai/kimi-k3": "tasks-kimi-k3",
- "deepseek-ai/deepseek-v4-flash-0731": "posthog-code-deepseek-model",
- "zai-org/glm-5.3": "posthog-code-glm-53-model",
- "zai-org/glm-5.3-flash": "posthog-code-glm-53-flash-model",
-}
-
def get_required_model_flag(model: str | None) -> str | None:
- """The feature flag a caller needs to select `model`, or None when it's generally available."""
+ """The feature flag a caller needs to select `model`, or None when it's generally available.
+
+ Read from the catalog, which is also what the pickers project into TypeScript, so a
+ model cannot be offered on one surface and gated on another. The lookup folds a
+ provider-qualified id onto the model it names, so a gate matching raw strings cannot
+ read `anthropic/zai-org/glm-5.3` as an unknown model and skip the check.
+ """
if not model:
return None
- normalized = model.strip().lower()
- for gated_model, flag_key in MODEL_ACCESS_FLAGS.items():
- if gated_model.lower() == normalized:
- return flag_key
- return None
+ return model_catalog.access_flag_for_model(model)
def _decode_vm_sandbox_payload(payload: object) -> object:
diff --git a/products/tasks/backend/facade/model_catalogue.py b/products/tasks/backend/facade/model_catalogue.py
index 2a6b1ce1a05c..283b03c58fdc 100644
--- a/products/tasks/backend/facade/model_catalogue.py
+++ b/products/tasks/backend/facade/model_catalogue.py
@@ -15,8 +15,9 @@ from products.tasks.backend.logic.services.model_catalogue import (
ModelChoice,
RuntimeGroup,
available_model_choices,
+ catalog_model_choices,
+ display_name_for_model,
filter_unsupported_effort,
- format_model_id,
group_by_runtime,
label_for,
runtime_adapter_for,
@@ -30,8 +31,9 @@ __all__ = [
"ModelChoice",
"RuntimeGroup",
"available_model_choices",
+ "catalog_model_choices",
+ "display_name_for_model",
"filter_unsupported_effort",
- "format_model_id",
"group_by_runtime",
"label_for",
"runtime_adapter_for",
diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.py
index 79abe6b5ca38..79863a7a1ed3 100644
--- a/products/tasks/backend/facade/run_config.py
+++ b/products/tasks/backend/facade/run_config.py
@@ -14,7 +14,6 @@ from products.tasks.backend.constants import (
ALL_INITIAL_PERMISSION_MODE_CHOICES,
CODEX_INITIAL_PERMISSION_MODE_CHOICES,
INITIAL_PERMISSION_MODE_CHOICES,
- MODEL_ACCESS_FLAGS,
InitialPermissionMode,
get_required_model_flag,
)
@@ -43,6 +42,7 @@ from products.tasks.backend.temporal.process_task.utils import (
get_runtime_adapter_for_model,
get_supported_reasoning_efforts,
parse_run_state,
+ runtime_adapter_serves_model,
validate_model_selection,
)
@@ -66,7 +66,6 @@ __all__ = [
"INITIAL_PERMISSION_MODE_CHOICES",
"WARMABLE_ORIGIN_PRODUCTS",
"InitialPermissionMode",
- "MODEL_ACCESS_FLAGS",
"PUBLIC_REASONING_EFFORTS",
"GitHubCredentialSource",
"LLMProvider",
@@ -81,6 +80,7 @@ __all__ = [
"get_default_model_for_runtime_adapter",
"get_model_access_error",
"get_models_for_runtime_adapter",
+ "runtime_adapter_serves_model",
"get_provider_for_runtime_adapter",
"get_reasoning_effort_error",
"get_required_model_flag",
diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.py
index f53824594378..c67b9b4e1342 100644
--- a/products/tasks/backend/feature_flags.py
+++ b/products/tasks/backend/feature_flags.py
@@ -153,7 +153,7 @@ def is_agent_otel_telemetry_enabled(*, distinct_id: str, organization_id: str) -
def get_model_access_error(model: str | None, *, distinct_id: str | None) -> str | None:
"""Reject a gated model the caller isn't entitled to; `None` when the selection is allowed.
- Fail-closed on purpose. Only a model in `MODEL_ACCESS_FLAGS` reaches an evaluation at all,
+ Fail-closed on purpose. Only a model the catalog gives an `access_flag` reaches an evaluation at all,
so an evaluation outage withholds a preview model from everyone rather than opening it to
everyone — the opposite trade to the telemetry flags above, because this one decides spend.
"""
diff --git a/products/tasks/backend/logic/services/model_catalogue.py b/products/tasks/backend/logic/services/model_catalogue.py
index 5c98ac488d38..909fba7f864a 100644
--- a/products/tasks/backend/logic/services/model_catalogue.py
+++ b/products/tasks/backend/logic/services/model_catalogue.py
@@ -18,7 +18,6 @@ can't make every interaction wait the full timeout.
from __future__ import annotations
-import re
from dataclasses import dataclass
from functools import lru_cache
from typing import TYPE_CHECKING
@@ -27,6 +26,9 @@ from django.core.cache import cache
import structlog
+from products.tasks.backend import model_catalog
+from products.tasks.backend.model_catalog import display_name_for_model # noqa: F401 — re-exported
+
if TYPE_CHECKING:
from posthog.llm.gateway_client import Product
@@ -41,9 +43,9 @@ _CACHE_TTL_SECONDS = 30 * 60
_NEGATIVE_CACHE_TTL_SECONDS = 30
_FETCH_TIMEOUT_SECONDS = 3.0
-# Runtime + effort labels are UI strings with no run-config equivalent. Model display
-# labels are computed from the model id on the fly via `format_model_id` so we never
-# have to hand-maintain a model→label map.
+# Runtime + effort labels are UI strings with no run-config equivalent. A model's display
+# name is resolved by `display_name_for_model`, so a new model names itself and the catalog
+# overrides that only for the ids the derivation gets wrong.
RUNTIME_ADAPTER_DISPLAY_NAMES: dict[str, str] = {
"claude": "Claude (Anthropic)",
"codex": "Codex (OpenAI)",
@@ -58,9 +60,6 @@ REASONING_EFFORT_DISPLAY_NAMES: dict[str, str] = {
"ultracode": "Ultracode",
}
-# Vendor initialisms that must not be title-cased into "Gpt".
-_MODEL_ACRONYMS: dict[str, str] = {"gpt": "GPT", "glm": "GLM"}
-
@dataclass(frozen=True)
class GatewayModel:
@@ -179,20 +178,44 @@ def available_model_choices(product: Product) -> tuple[ModelChoice, ...]:
by_provider = _runtime_adapter_by_provider()
choices = []
for model in list_gateway_models(product):
- runtime_adapter = by_provider.get(model.owned_by)
+ # The catalog names the harness that drives a model; `owned_by` names whoever
+ # serves it, which for the vendor-served models is `cloudflare`/`baseten`/the
+ # vendor org and says nothing about the harness. Falling back to the provider
+ # keeps an unlisted `gpt-*` working and still drops a provider we cannot route.
+ runtime_adapter = runtime_adapter_for(model.id) or by_provider.get(model.owned_by)
if runtime_adapter is None:
continue
choices.append(
ModelChoice(
runtime_adapter=runtime_adapter,
model=model.id,
- label=format_model_id(model.id),
+ label=model_catalog.display_name_for_model(model.id),
supported_efforts=tuple(e.value for e in get_supported_reasoning_efforts(runtime_adapter, model.id)),
)
)
return tuple(choices)
+@lru_cache(maxsize=1)
+def catalog_model_choices() -> tuple[ModelChoice, ...]:
+ """Every model the catalog serves, without asking the gateway.
+
+ The gateway answers one question the catalog cannot — which models it is serving
+ right now — and a caller that only needs to recognise a model and read what it
+ supports is asking the catalog's questions, not that one. Those callers take this
+ and stay off the network.
+ """
+ return tuple(
+ ModelChoice(
+ runtime_adapter=entry.runtime_adapter,
+ model=entry.id,
+ label=model_catalog.display_name_for_model(entry.id),
+ supported_efforts=entry.reasoning_efforts,
+ )
+ for entry in model_catalog.MODELS
+ )
+
+
def runtime_adapter_for(model: str | None) -> str | None:
"""Which runtime drives this model, per the static run-config map.
@@ -215,13 +238,11 @@ def filter_unsupported_effort(runtime_adapter: str | None, model: str | None, ef
The single answer to "is this effort legal for this pair" — every stored-preference
resolver routes through it.
"""
- from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — see `available_model_choices`
- get_supported_reasoning_efforts,
- )
-
- if not effort:
+ # A missing adapter or model supports nothing: an unknown model must not inherit the
+ # adapter's fallback ladder and quietly keep an effort the run would be rejected for.
+ if not effort or not runtime_adapter or not model:
return None
- return effort if effort in {e.value for e in get_supported_reasoning_efforts(runtime_adapter, model)} else None
+ return effort if effort in model_catalog.reasoning_efforts_for(runtime_adapter, model) else None
@lru_cache(maxsize=1)
@@ -246,37 +267,6 @@ def _runtime_adapter_by_provider() -> dict[str, str]:
return by_provider
-def format_model_id(model_id: str) -> str:
- """Turn a gateway model id into a display name: `Claude Opus 4.8`, `GPT-5.6 Sol`.
-
- Every family goes through the same rules — strip the provider prefix, glue a version
- onto a leading acronym, title-case the rest — so a new model is named without anyone
- touching a lookup table.
- """
- clean = model_id
- for provider in _runtime_adapter_by_provider():
- if clean.startswith(f"{provider}/"):
- clean = clean[len(provider) + 1 :]
- break
-
- # Collapse `4-8` into `4.8` so version components survive the dash split.
- words = re.split(r"[-_]", re.sub(r"(\d)-(\d)", r"\1.\2", clean))
- acronym = _MODEL_ACRONYMS.get(words[0].lower())
- if acronym is None:
- return " ".join(_titled(word) for word in words)
- # `gpt` + `5.6` reads as `GPT-5.6`, the way the vendor writes it, with any remaining
- # qualifier ("sol", "codex", "mini") as its own word.
- head = f"{acronym}-{words[1]}" if len(words) > 1 else acronym
- return " ".join([head, *(_titled(word) for word in words[2:])])
-
-
-def _titled(word: str) -> str:
- """Capitalise a name part, leaving bare version numbers alone."""
- if re.fullmatch(r"[0-9.]+", word):
- return word
- return word[:1].upper() + word[1:].lower()
-
-
def label_for(value: str | None, mapping: dict[str, str]) -> str:
"""Display name for a stored value, falling back to the value itself."""
if not value:
@@ -292,8 +282,9 @@ __all__ = [
"ModelChoice",
"RuntimeGroup",
"available_model_choices",
+ "catalog_model_choices",
+ "display_name_for_model",
"filter_unsupported_effort",
- "format_model_id",
"group_by_runtime",
"label_for",
"list_gateway_models",
diff --git a/products/tasks/backend/model_catalog.py b/products/tasks/backend/model_catalog.py
new file mode 100644
index 000000000000..32a7ad1ee6f3
--- /dev/null
+++ b/products/tasks/backend/model_catalog.py
@@ -0,0 +1,294 @@
+"""The models a task agent run may use, and what each one supports.
+
+This module is the single definition of the run triple — runtime adapter, model, and
+reasoning effort — together with the model each adapter falls back to when a run pins
+none. Every surface that offers or validates a selection derives from here:
+
+- the backend, through ``products.tasks.backend.temporal.process_task.utils``;
+- the web composer and settings, through ``products/tasks/frontend/modelCatalog.generated.ts``;
+- the desktop app and its agent, through ``@posthog/shared/model-catalog``.
+
+Both TypeScript projections are emitted by ``products/tasks/scripts/build_model_catalog.py`` and are
+checked for drift by the same CI job that guards the generated OpenAPI types, so a model
+ships by editing this file and nothing else.
+
+Keep this module free of Django and of anything outside the standard library. The
+generator loads it by filesystem path with ``runpy``, which bypasses ``posthog``'s package
+import and the Celery and settings machinery behind it.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+CLAUDE = "claude"
+CODEX = "codex"
+
+ANTHROPIC = "anthropic"
+OPENAI = "openai"
+
+# Which vendor API a runtime adapter speaks. The adapter drives the harness; the provider
+# tells the agent server and the LLM gateway how to route.
+PROVIDER_BY_RUNTIME_ADAPTER: dict[str, str] = {
+ CLAUDE: ANTHROPIC,
+ CODEX: OPENAI,
+}
+
+LOW = "low"
+MEDIUM = "medium"
+HIGH = "high"
+XHIGH = "xhigh"
+MAX = "max"
+ULTRACODE = "ultracode"
+
+# Every tier any model exposes, shallowest first. A consumer renders an effort ladder from
+# this, so a new tier reaches both projections by being added here and nowhere else.
+REASONING_EFFORTS: tuple[str, ...] = (LOW, MEDIUM, HIGH, XHIGH, MAX, ULTRACODE)
+
+_STANDARD = (LOW, MEDIUM, HIGH)
+_THROUGH_MAX = (*_STANDARD, XHIGH, MAX)
+_EXTENDED = (*_THROUGH_MAX, ULTRACODE)
+# The GLM family exposes two thinking depths rather than the full ladder.
+_GLM = (HIGH, MAX)
+_NO_EFFORT: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class CatalogModel:
+ """One model a run may use.
+
+ ``reasoning_efforts`` is empty for a model with no effort control. That is an answer,
+ not missing metadata: a picker renders such a model without an effort dropdown, and a
+ run must not send an effort for it.
+
+ ``label`` is set only where deriving the name from the id gets it wrong. Each surface
+ formats an id it has no label for, and those formatters disagree on vendor-qualified
+ ids, so a model whose name matters is named here once instead of in each picker.
+
+ ``access_flag`` names the feature flag a person needs before a picker offers the model,
+ and ``None`` means generally available. It decides what a picker *shows*: this file is
+ checked in and the desktop app auto-updates into it, so it is readable by anyone and can
+ be stale. Whether a run may actually use the model stays a server question, answered by
+ ``get_model_access_error`` on every write path.
+ """
+
+ id: str
+ runtime_adapter: str
+ reasoning_efforts: tuple[str, ...]
+ label: str | None = None
+ access_flag: str | None = None
+
+
+MODELS: tuple[CatalogModel, ...] = (
+ # GLM 5.2 is Cloudflare-served and driven through the `claude` adapter: the LLM gateway
+ # exposes it over its Anthropic-Messages surface and translates the `@cf/` id upstream,
+ # so the `anthropic` provider is the intended routing rather than a direct Anthropic call.
+ CatalogModel("@cf/zai-org/glm-5.2", CLAUDE, _GLM, label="GLM-5.2", access_flag="posthog-code-glm-model"),
+ CatalogModel("zai-org/glm-5.3", CLAUDE, _GLM, label="GLM-5.3", access_flag="posthog-code-glm-53-model"),
+ CatalogModel(
+ "zai-org/glm-5.3-flash", CLAUDE, _GLM, label="GLM-5.3 Flash", access_flag="posthog-code-glm-53-flash-model"
+ ),
+ CatalogModel("moonshotai/kimi-k3", CLAUDE, _NO_EFFORT, label="Kimi K3", access_flag="tasks-kimi-k3"),
+ CatalogModel(
+ "deepseek-ai/deepseek-v4-flash-0731",
+ CLAUDE,
+ _NO_EFFORT,
+ label="DeepSeek V4 Flash",
+ access_flag="posthog-code-deepseek-model",
+ ),
+ CatalogModel("claude-opus-4-5", CLAUDE, _STANDARD),
+ CatalogModel("claude-opus-4-6", CLAUDE, _THROUGH_MAX),
+ CatalogModel("claude-opus-4-7", CLAUDE, _EXTENDED),
+ CatalogModel("claude-opus-4-8", CLAUDE, _EXTENDED),
+ CatalogModel("claude-opus-5", CLAUDE, _EXTENDED),
+ CatalogModel("claude-fable-5", CLAUDE, _EXTENDED),
+ CatalogModel("claude-fable-5-1", CLAUDE, _EXTENDED),
+ CatalogModel("claude-sonnet-5", CLAUDE, _EXTENDED),
+ CatalogModel("claude-sonnet-4-6", CLAUDE, _STANDARD),
+ CatalogModel("gpt-5", CODEX, _STANDARD),
+ CatalogModel("gpt-5.5", CODEX, (*_STANDARD, XHIGH)),
+ CatalogModel("gpt-5.6-sol", CODEX, _THROUGH_MAX),
+ CatalogModel("gpt-5.6-terra", CODEX, _THROUGH_MAX),
+ CatalogModel("gpt-5.6-luna", CODEX, _THROUGH_MAX),
+ CatalogModel("gpt-6-astra", CODEX, _THROUGH_MAX),
+)
+
+# Depths a whole model family exposes, used when no exact id matches. OpenAI ships
+# vendor-flavoured variants the gateway never lists (`gpt-5.5-codex`), and a desktop session
+# running against the user's own subscription can drive one, so the tier a family supports has
+# to answer for those too. The longest matching prefix wins, so declaration order is free.
+FAMILY_REASONING_EFFORTS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
+ (CODEX, "gpt-6-astra", _THROUGH_MAX),
+ (CODEX, "gpt-5.6", _THROUGH_MAX),
+ (CODEX, "gpt-5.5", (*_STANDARD, XHIGH)),
+)
+
+# What a runtime accepts for a model neither an id nor a family claims. Codex passes any
+# `gpt-*` identifier through to the runtime, so an id the gateway starts serving before it is
+# listed here still runs, at the depths every Codex model supports. Claude is absent on
+# purpose: an unnamed model there yields no efforts, which is what makes validation reject one.
+FALLBACK_REASONING_EFFORTS_BY_RUNTIME_ADAPTER: dict[str, tuple[str, ...]] = {
+ CODEX: _STANDARD,
+}
+
+# Applied when a run or a loop leaves the model unset: blank means "let PostHog pick", so the
+# choice can improve without rewriting anything stored.
+DEFAULT_MODEL_BY_RUNTIME_ADAPTER: dict[str, str] = {
+ CLAUDE: "claude-sonnet-5",
+ CODEX: "gpt-5",
+}
+
+
+RUNTIME_ADAPTERS: tuple[str, ...] = tuple(PROVIDER_BY_RUNTIME_ADAPTER)
+
+# The catalog keyed the two ways it gets read. Built once from MODELS, which stays the
+# only place a model is written down.
+_MODEL_BY_ID: dict[str, CatalogModel] = {model.id: model for model in MODELS}
+_MODEL_IDS_BY_RUNTIME_ADAPTER: dict[str, tuple[str, ...]] = {
+ adapter: tuple(model.id for model in MODELS if model.runtime_adapter == adapter) for adapter in RUNTIME_ADAPTERS
+}
+
+
+def models_for_runtime_adapter(runtime_adapter: str) -> tuple[str, ...]:
+ """The model ids one adapter drives, in catalog order."""
+ return _MODEL_IDS_BY_RUNTIME_ADAPTER.get(runtime_adapter, ())
+
+
+def runtime_adapter_for_model(model_id: str | None) -> str | None:
+ """Which adapter drives this model, whichever spelling the caller sends.
+
+ ``None`` when the catalog lists no adapter for it. The adapter is a property of the
+ model rather than an independent choice, so deriving it is what keeps a
+ ``(runtime_adapter, model)`` pair from disagreeing with itself.
+ """
+ if not model_id:
+ return None
+ model = _MODEL_BY_ID.get(normalize_model_id(model_id))
+ return model.runtime_adapter if model else None
+
+
+def serves_model(runtime_adapter: str, model_id: str | None) -> bool:
+ """Whether this adapter drives the model, whichever spelling the caller sends.
+
+ Resolving the id rather than testing it against ``models_for_runtime_adapter``, whose
+ entries are raw catalog ids: the gateway serves some models provider-qualified, so an
+ allowlist built that way rejects a spelling every resolver here accepts.
+ """
+ return runtime_adapter_for_model(model_id) == runtime_adapter
+
+
+def normalize_model_id(model_id: str) -> str:
+ """The form a model id is looked up under.
+
+ The LLM gateway serves some models both bare and provider-qualified
+ (``openai/gpt-5.6-sol``), and a picker may hand back either. Folding the two together
+ is what stops the same model from having two answers depending on which surface asked.
+ Only the provider prefixes this catalog knows are stripped, so ids that carry a slash
+ of their own (``@cf/zai-org/glm-5.2``) survive intact.
+ """
+ normalized = model_id.strip().lower()
+ for provider in PROVIDER_BY_RUNTIME_ADAPTER.values():
+ prefix = f"{provider}/"
+ if normalized.startswith(prefix):
+ return normalized[len(prefix) :]
+ return normalized
+
+
+def access_flag_for_model(model_id: str) -> str | None:
+ """The feature flag a person needs before a picker offers this model, or ``None``."""
+ model = _MODEL_BY_ID.get(normalize_model_id(model_id))
+ return model.access_flag if model else None
+
+
+def label_for_model(model_id: str) -> str | None:
+ """The name this catalog pins for a model id, or ``None`` to let the caller derive one."""
+ model = _MODEL_BY_ID.get(normalize_model_id(model_id))
+ return model.label if model else None
+
+
+_MODEL_ACRONYMS: dict[str, str] = {"gpt": "GPT", "glm": "GLM"}
+
+
+def _titled(word: str) -> str:
+ """Capitalise a name part, leaving bare version numbers alone."""
+ if re.fullmatch(r"[0-9.]+", word):
+ return word
+ return word[:1].upper() + word[1:].lower()
+
+
+def format_model_id(model_id: str) -> str:
+ """Turn a gateway model id into a display name: `Claude Opus 4.8`, `GPT-5.6 Sol`.
+
+ Every family goes through the same rules — strip the provider prefix, glue a version
+ onto a leading acronym, title-case the rest — so a new model is named without anyone
+ touching a lookup table.
+ """
+ # Collapse `4-8` into `4.8` so version components survive the dash split.
+ clean = re.sub(r"(\d)-(\d)", r"\1.\2", normalize_model_id(model_id))
+ words = re.split(r"[-_]", clean)
+ acronym = _MODEL_ACRONYMS.get(words[0].lower())
+ if acronym is None:
+ return " ".join(_titled(word) for word in words)
+ # `gpt` + `5.6` reads as `GPT-5.6`, the way the vendor writes it, with any remaining
+ # qualifier ("sol", "codex", "mini") as its own word.
+ head = f"{acronym}-{words[1]}" if len(words) > 1 else acronym
+ return " ".join([head, *(_titled(word) for word in words[2:])])
+
+
+def display_name_for_model(model_id: str) -> str:
+ """The name a picker shows for a model.
+
+ The catalog's own name where it pins one, and the name derived from the id everywhere
+ else. Every surface resolves a display name through here, so a model reads the same in
+ the web composer, the Slack picker, and the desktop app.
+ """
+ normalized = normalize_model_id(model_id)
+ model = _MODEL_BY_ID.get(normalized)
+ return (model.label if model else None) or format_model_id(normalized)
+
+
+def reasoning_efforts_for(runtime_adapter: str, model_id: str) -> tuple[str, ...]:
+ """The efforts this model may run at, empty when it takes no effort at all.
+
+ Resolved in three steps: the exact id, then the family it belongs to, then what the
+ adapter accepts generally. Codex passes any ``gpt-*`` identifier through, so a newly
+ served id still runs, while Claude has no fallback and yields nothing — which is what
+ makes validation reject it.
+ """
+ normalized = normalize_model_id(model_id)
+ exact = _MODEL_BY_ID.get(normalized)
+ if exact and exact.runtime_adapter == runtime_adapter:
+ return exact.reasoning_efforts
+ families = [
+ (prefix, efforts)
+ for adapter, prefix, efforts in FAMILY_REASONING_EFFORTS
+ if adapter == runtime_adapter and normalized.startswith(prefix)
+ ]
+ if families:
+ return max(families, key=lambda family: len(family[0]))[1]
+ return FALLBACK_REASONING_EFFORTS_BY_RUNTIME_ADAPTER.get(runtime_adapter, ())
+
+
+__all__ = [
+ "ANTHROPIC",
+ "CLAUDE",
+ "CODEX",
+ "DEFAULT_MODEL_BY_RUNTIME_ADAPTER",
+ "FALLBACK_REASONING_EFFORTS_BY_RUNTIME_ADAPTER",
+ "MODELS",
+ "OPENAI",
+ "PROVIDER_BY_RUNTIME_ADAPTER",
+ "REASONING_EFFORTS",
+ "access_flag_for_model",
+ "RUNTIME_ADAPTERS",
+ "CatalogModel",
+ "label_for_model",
+ "models_for_runtime_adapter",
+ "normalize_model_id",
+ "display_name_for_model",
+ "format_model_id",
+ "reasoning_efforts_for",
+ "runtime_adapter_for_model",
+ "serves_model",
+]
diff --git a/products/tasks/backend/presentation/serializers_loops.py b/products/tasks/backend/presentation/serializers_loops.py
index 835a72ec7b39..2eccc4dd879c 100644
--- a/products/tasks/backend/presentation/serializers_loops.py
+++ b/products/tasks/backend/presentation/serializers_loops.py
@@ -30,6 +30,7 @@ from products.tasks.backend.facade.run_config import (
get_model_access_error,
get_models_for_runtime_adapter,
get_reasoning_effort_error,
+ runtime_adapter_serves_model,
)
from products.tasks.backend.presentation.serializers import (
TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES,
@@ -544,7 +545,7 @@ class LoopWriteSerializer(serializers.Serializer):
model = attrs.get("model")
if runtime_adapter is not None and model:
allowed_models = get_models_for_runtime_adapter(runtime_adapter)
- if allowed_models and model not in allowed_models:
+ if allowed_models and not runtime_adapter_serves_model(runtime_adapter, model):
raise serializers.ValidationError(
{"model": f"'{model}' is not a supported model for runtime_adapter '{runtime_adapter}'."}
)
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 98a9b691107f..80f06a1f9816 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -18,6 +18,7 @@ from posthog.models.user_integration import ReauthorizationRequired, UserGitHubI
from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopes
from products.mcp_store.backend.facade.api import get_installations_for_sandbox
+from products.tasks.backend import model_catalog
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
CODEX_INITIAL_PERMISSION_MODE_CHOICES,
@@ -104,13 +105,11 @@ class ReasoningEffort(StrEnum):
ULTRACODE = "ultracode"
-PUBLIC_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
+# Derived, not restated: this is the tuple the run serializers build their effort choices
+# from, so a tier added to the catalog and not here would have every picker offering a
+# depth the API rejects.
+PUBLIC_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = tuple(
+ ReasoningEffort(effort) for effort in model_catalog.REASONING_EFFORTS
)
@@ -118,125 +117,11 @@ CONTEXT_WINDOW_CHOICES: tuple[str, ...] = ("200k", "1m")
RUNTIME_PROVIDER_BY_ADAPTER: dict[RuntimeAdapter, LLMProvider] = {
- RuntimeAdapter.CLAUDE: LLMProvider.ANTHROPIC,
- RuntimeAdapter.CODEX: LLMProvider.OPENAI,
+ RuntimeAdapter(adapter): LLMProvider(provider)
+ for adapter, provider in model_catalog.PROVIDER_BY_RUNTIME_ADAPTER.items()
}
-CLAUDE_REASONING_EFFORTS_BY_MODEL: dict[str, tuple[ReasoningEffort, ...]] = {
- # GLM 5.2 is a Cloudflare-served model driven through the `claude` runtime adapter: the LLM
- # gateway exposes it over its Anthropic-Messages surface and translates the `@cf/` id upstream,
- # so the derived `provider="anthropic"` is the intended routing, not a direct Anthropic call.
- "@cf/zai-org/glm-5.2": (
- ReasoningEffort.HIGH,
- ReasoningEffort.MAX,
- ),
- "zai-org/glm-5.3": (
- ReasoningEffort.HIGH,
- ReasoningEffort.MAX,
- ),
- "zai-org/glm-5.3-flash": (
- ReasoningEffort.HIGH,
- ReasoningEffort.MAX,
- ),
- "moonshotai/kimi-k3": (),
- "claude-opus-4-5": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ),
- "claude-opus-4-6": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ),
- "claude-opus-4-7": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-opus-4-8": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-opus-5": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-fable-5": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-fable-5-1": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-sonnet-5": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ReasoningEffort.XHIGH,
- ReasoningEffort.MAX,
- ReasoningEffort.ULTRACODE,
- ),
- "claude-sonnet-4-6": (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
- ),
-}
-
-CODEX_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = (
- ReasoningEffort.LOW,
- ReasoningEffort.MEDIUM,
- ReasoningEffort.HIGH,
-)
-CODEX_XHIGH_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = (
- *CODEX_REASONING_EFFORTS,
- ReasoningEffort.XHIGH,
-)
-CODEX_MAX_REASONING_EFFORTS: tuple[ReasoningEffort, ...] = (
- *CODEX_XHIGH_REASONING_EFFORTS,
- ReasoningEffort.MAX,
-)
-CODEX_XHIGH_REASONING_MODELS: frozenset[str] = frozenset({"gpt-5.5"})
-CODEX_MAX_REASONING_MODELS: frozenset[str] = frozenset({"gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-6-astra"})
-
-# Canonical list of Codex models. The runtime technically accepts any
-# `gpt-*` identifier passed through, but only models on this list are
-# considered tested and surfaced in pickers. Extend when a new Codex model
-# ships.
-CODEX_MODELS: tuple[str, ...] = (
- "gpt-5",
- "gpt-5.5",
- "gpt-5.6-sol",
- "gpt-5.6-terra",
- "gpt-5.6-luna",
- "gpt-6-astra",
-)
-
-
def get_models_for_runtime_adapter(runtime_adapter: RuntimeAdapter | str | None) -> tuple[str, ...]:
"""Return the canonical model identifiers the given runtime adapter exposes.
@@ -247,20 +132,25 @@ def get_models_for_runtime_adapter(runtime_adapter: RuntimeAdapter | str | None)
if runtime_adapter is None:
return ()
adapter_value = runtime_adapter.value if isinstance(runtime_adapter, RuntimeAdapter) else runtime_adapter
- if adapter_value == RuntimeAdapter.CLAUDE.value:
- return tuple(CLAUDE_REASONING_EFFORTS_BY_MODEL.keys())
- if adapter_value == RuntimeAdapter.CODEX.value:
- return CODEX_MODELS
- return ()
-
-
-# Applied at fire time when a loop leaves its model unset ("" / None): a blank
-# model means "let PostHog pick", so defaults can improve without rewriting
-# stored loops. Mirrored by LOOP_DEFAULT_MODELS in posthog-code's loops UI.
-DEFAULT_MODEL_BY_RUNTIME_ADAPTER: dict[str, str] = {
- RuntimeAdapter.CLAUDE.value: "claude-sonnet-5",
- RuntimeAdapter.CODEX.value: "gpt-5",
-}
+ return model_catalog.models_for_runtime_adapter(adapter_value)
+
+
+def runtime_adapter_serves_model(runtime_adapter: RuntimeAdapter | str | None, model: str | None) -> bool:
+ """Whether the adapter drives the model, whichever spelling the caller sends.
+
+ An allowlist wants this rather than membership of `get_models_for_runtime_adapter`,
+ which holds canonical ids and so rejects the provider-qualified spelling the gateway
+ also serves and every resolver here accepts.
+ """
+ if runtime_adapter is None:
+ return False
+ adapter_value = runtime_adapter.value if isinstance(runtime_adapter, RuntimeAdapter) else runtime_adapter
+ return model_catalog.serves_model(adapter_value, model)
+
+
+# Applied at fire time when a run or loop leaves its model unset ("" / None): a blank
+# model means "let PostHog pick", so defaults can improve without rewriting stored loops.
+DEFAULT_MODEL_BY_RUNTIME_ADAPTER: dict[str, str] = dict(model_catalog.DEFAULT_MODEL_BY_RUNTIME_ADAPTER)
def get_default_model_for_runtime_adapter(runtime_adapter: RuntimeAdapter | str | None) -> str | None:
@@ -338,17 +228,7 @@ def get_supported_reasoning_efforts(
return ()
adapter_value = runtime_adapter.value if isinstance(runtime_adapter, RuntimeAdapter) else runtime_adapter
- if adapter_value == RuntimeAdapter.CLAUDE.value:
- return CLAUDE_REASONING_EFFORTS_BY_MODEL.get(model, ())
- if adapter_value == RuntimeAdapter.CODEX.value:
- normalized_model = model.lower()
- if normalized_model in CODEX_MAX_REASONING_MODELS:
- return CODEX_MAX_REASONING_EFFORTS
- if normalized_model in CODEX_XHIGH_REASONING_MODELS:
- return CODEX_XHIGH_REASONING_EFFORTS
- return CODEX_REASONING_EFFORTS
-
- return ()
+ return tuple(ReasoningEffort(effort) for effort in model_catalog.reasoning_efforts_for(adapter_value, model))
def get_reasoning_effort_error(
@@ -379,14 +259,8 @@ def get_runtime_adapter_for_model(model: str | None) -> RuntimeAdapter | None:
deriving it is what lets callers reject a `(runtime_adapter, model)` pair that
disagrees with itself. `None` when no adapter claims the model.
"""
- if not model:
- return None
-
- normalized = model.strip().lower()
- for adapter in RuntimeAdapter:
- if any(known.lower() == normalized for known in get_models_for_runtime_adapter(adapter)):
- return adapter
- return None
+ adapter = model_catalog.runtime_adapter_for_model(model)
+ return RuntimeAdapter(adapter) if adapter else None
def validate_model_selection(
diff --git a/products/tasks/backend/tests/__snapshots__/test_model_catalog/test_every_model_resolves_to_the_recorded_triple.json b/products/tasks/backend/tests/__snapshots__/test_model_catalog/test_every_model_resolves_to_the_recorded_triple.json
new file mode 100644
index 000000000000..479e2d53f7c6
--- /dev/null
+++ b/products/tasks/backend/tests/__snapshots__/test_model_catalog/test_every_model_resolves_to_the_recorded_triple.json
@@ -0,0 +1,182 @@
+{
+ "model_families": [
+ {
+ "prefix": "gpt-6-astra",
+ "reasoning_efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "runtime_adapter": "codex"
+ },
+ {
+ "prefix": "gpt-5.6",
+ "reasoning_efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "runtime_adapter": "codex"
+ },
+ {
+ "prefix": "gpt-5.5",
+ "reasoning_efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "runtime_adapter": "codex"
+ }
+ ],
+ "reasoning_efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "runtime_adapters": {
+ "claude": {
+ "default_model": "claude-sonnet-5",
+ "fallback_reasoning_efforts": [],
+ "models": {
+ "@cf/zai-org/glm-5.2": [
+ "high",
+ "max"
+ ],
+ "claude-fable-5": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "claude-fable-5-1": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "claude-opus-4-5": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "claude-opus-4-6": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "claude-opus-4-7": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "claude-opus-4-8": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "claude-opus-5": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "claude-sonnet-4-6": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "claude-sonnet-5": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode"
+ ],
+ "deepseek-ai/deepseek-v4-flash-0731": [],
+ "moonshotai/kimi-k3": [],
+ "zai-org/glm-5.3": [
+ "high",
+ "max"
+ ],
+ "zai-org/glm-5.3-flash": [
+ "high",
+ "max"
+ ]
+ },
+ "provider": "anthropic"
+ },
+ "codex": {
+ "default_model": "gpt-5",
+ "fallback_reasoning_efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "models": {
+ "gpt-5": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "gpt-5.5": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "gpt-5.6-luna": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "gpt-5.6-sol": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "gpt-5.6-terra": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "gpt-6-astra": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ]
+ },
+ "provider": "openai"
+ }
+ }
+}
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index fcd8f5cd7eff..d36660856356 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -3710,9 +3710,15 @@ class TestTaskAPI(BaseTaskAPITest):
("glm_5_2_max", "claude", "@cf/zai-org/glm-5.2", "max", "anthropic"),
]
)
+ # GLM 5.2 is gated, and this case is about the metadata a run persists rather than about
+ # entitlement, so the flag is granted here and gating is covered in `test_feature_flags`.
+ @patch(
+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",
+ side_effect=lambda flag, *args, **kwargs: flag == "posthog-code-glm-model",
+ )
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_runtime_metadata(
- self, _case_name, runtime_adapter, model, reasoning_effort, provider, mock_workflow
+ self, _case_name, runtime_adapter, model, reasoning_effort, provider, mock_workflow, _mock_flag
):
task = self.create_task()
diff --git a/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.py
index c77ebefc93e4..cfdbd6d8fd99 100644
--- a/products/tasks/backend/tests/test_feature_flags.py
+++ b/products/tasks/backend/tests/test_feature_flags.py
@@ -56,7 +56,7 @@ class TestIsDevStackImageBakeEnabled:
class TestGetModelAccessError:
@pytest.mark.parametrize(
"model",
- ["claude-sonnet-5", "gpt-5.6-luna", "@cf/zai-org/glm-5.2", "", None],
+ ["claude-sonnet-5", "gpt-5.6-luna", "", None],
)
def test_ungated_model_is_allowed_without_consulting_the_flag(self, model):
with (
@@ -76,6 +76,9 @@ class TestGetModelAccessError:
("moonshotai/kimi-k3", "tasks-kimi-k3"),
(" MoonshotAI/Kimi-K3 ", "tasks-kimi-k3"),
("deepseek-ai/deepseek-v4-flash-0731", "posthog-code-deepseek-model"),
+ # Gated on the desktop app before this was one definition, and ungated on the
+ # server, so the same model was reachable through the web composer and the API.
+ ("@cf/zai-org/glm-5.2", "posthog-code-glm-model"),
("zai-org/glm-5.3", "posthog-code-glm-53-model"),
("zai-org/glm-5.3-flash", "posthog-code-glm-53-flash-model"),
],
diff --git a/products/tasks/backend/tests/test_loops_api.py b/products/tasks/backend/tests/test_loops_api.py
index 9cacb241b3e5..7b60f96dc1cd 100644
--- a/products/tasks/backend/tests/test_loops_api.py
+++ b/products/tasks/backend/tests/test_loops_api.py
@@ -115,8 +115,14 @@ class LoopCRUDAPITest(LoopsAPITestCase):
("model_outside_the_adapter_catalog", "claude", "openai/gpt-5.6-sol", None, status.HTTP_400_BAD_REQUEST),
]
)
+ # GLM 5.2 is gated, and these cases are about model/effort validation rather than
+ # entitlement, so the flag is granted here and gating is covered in `test_feature_flags`.
+ @patch(
+ "products.tasks.backend.presentation.serializers_loops.get_model_access_error",
+ return_value=None,
+ )
def test_create_validates_model_and_reasoning_effort(
- self, _name, runtime_adapter, model, reasoning_effort, expected_status
+ self, _name, runtime_adapter, model, reasoning_effort, expected_status, _mock_flag
):
payload = self._valid_loop_payload(
runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort
diff --git a/products/tasks/backend/tests/test_model_catalog.py b/products/tasks/backend/tests/test_model_catalog.py
new file mode 100644
index 000000000000..c3cd6008eaac
--- /dev/null
+++ b/products/tasks/backend/tests/test_model_catalog.py
@@ -0,0 +1,188 @@
+import sys
+import importlib.util
+from pathlib import Path
+from typing import Any
+
+import pytest
+from unittest.mock import patch
+
+from syrupy.extensions.json import JSONSnapshotExtension
+
+from products.tasks.backend import model_catalog
+from products.tasks.backend.constants import get_required_model_flag
+from products.tasks.backend.facade.model_catalogue import GatewayModel, available_model_choices
+from products.tasks.backend.temporal.process_task.utils import ReasoningEffort, RuntimeAdapter
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+GENERATOR = REPO_ROOT / "products" / "tasks" / "scripts" / "build_model_catalog.py"
+
+
+def _load_generator():
+ name = "build_task_model_catalog"
+ spec = importlib.util.spec_from_file_location(name, GENERATOR)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ # Registered before execution because @dataclass resolves annotations through
+ # sys.modules[cls.__module__], which is unset for a module loaded by path alone.
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def _resolved_catalog() -> dict[str, Any]:
+ """The catalog as data, read back through the public resolver rather than the tables.
+
+ Every value here is what a caller actually gets, so the snapshot moves when resolution
+ changes even if the literals did not.
+ """
+ return {
+ "reasoning_efforts": list(model_catalog.REASONING_EFFORTS),
+ "runtime_adapters": {
+ adapter: {
+ "provider": model_catalog.PROVIDER_BY_RUNTIME_ADAPTER[adapter],
+ "default_model": model_catalog.DEFAULT_MODEL_BY_RUNTIME_ADAPTER[adapter],
+ "fallback_reasoning_efforts": list(
+ model_catalog.FALLBACK_REASONING_EFFORTS_BY_RUNTIME_ADAPTER.get(adapter, ())
+ ),
+ "models": {
+ model_id: list(model_catalog.reasoning_efforts_for(adapter, model_id))
+ for model_id in model_catalog.models_for_runtime_adapter(adapter)
+ },
+ }
+ for adapter in model_catalog.RUNTIME_ADAPTERS
+ },
+ "model_families": [
+ {"runtime_adapter": adapter, "prefix": prefix, "reasoning_efforts": list(efforts)}
+ for adapter, prefix, efforts in model_catalog.FAMILY_REASONING_EFFORTS
+ ],
+ }
+
+
+def test_every_model_resolves_to_the_recorded_triple(snapshot) -> None:
+ # The parametrized cases below pin the resolution rules; this pins the whole answer for
+ # every model at once, so a change to a shared effort tuple, a default, or a provider
+ # lands in review as a readable data diff instead of one line of Python.
+ # Refresh with: pytest products/tasks/backend/tests/test_model_catalog.py --snapshot-update
+ assert _resolved_catalog() == snapshot(extension_class=JSONSnapshotExtension)
+
+
[email protected]("output,style", [("WEB_OUTPUT", "OXFMT"), ("DESKTOP_OUTPUT", "BIOME")], ids=["web", "desktop"])
+def test_checked_in_projection_is_what_the_generator_emits(output: str, style: str) -> None:
+ generator = _load_generator()
+ expected = generator.render(vars(model_catalog), getattr(generator, style))
+
+ path: Path = getattr(generator, output)
+ assert path.exists(), f"{path} is missing — run `hogli build:task-model-catalog`"
+ assert path.read_text() == expected, (
+ f"{path.relative_to(REPO_ROOT)} is stale. The catalog changed without regenerating, so this "
+ f"surface would offer a selection the backend rejects. Run `hogli build:task-model-catalog`."
+ )
+
+
+def test_every_runtime_adapter_has_catalog_models() -> None:
+ for adapter in RuntimeAdapter:
+ assert model_catalog.models_for_runtime_adapter(adapter.value), (
+ f"runtime adapter '{adapter.value}' has no models in the catalog, so every picker "
+ f"and validator would treat it as serving nothing"
+ )
+
+
+def test_every_catalog_effort_is_a_known_reasoning_effort() -> None:
+ known = {effort.value for effort in ReasoningEffort}
+ used = {effort for entry in model_catalog.MODELS for effort in entry.reasoning_efforts}
+ assert used <= known, f"catalog names efforts the ReasoningEffort enum lacks: {sorted(used - known)}"
+
+
+ "adapter,model,expected",
+ [
+ ("claude", "claude-sonnet-4-6", ("low", "medium", "high")),
+ ("claude", "moonshotai/kimi-k3", ()),
+ ("claude", "claude-imaginary-9", ()),
+ ("claude", "anthropic/claude-sonnet-4-6", ("low", "medium", "high")),
+ ("codex", "GPT-5.5", ("low", "medium", "high", "xhigh")),
+ ("codex", "gpt-5.5-codex", ("low", "medium", "high", "xhigh")),
+ ("codex", "gpt-9", ("low", "medium", "high")),
+ ("codex", "gpt-5.6-sol", ("low", "medium", "high", "xhigh", "max")),
+ ],
+ ids=[
+ "exact_id",
+ "no_effort_control",
+ "unknown_claude_model_has_no_fallback",
+ "provider_qualified_id",
+ "uppercase_id",
+ "codex_family_variant",
+ "unknown_codex_model_falls_back",
+ "exact_id_beats_family",
+ ],
+)
+def test_efforts_resolve_by_id_then_family_then_adapter(adapter: str, model: str, expected: tuple[str, ...]) -> None:
+ assert model_catalog.reasoning_efforts_for(adapter, model) == expected
+
+
+def test_default_model_is_one_the_catalog_serves() -> None:
+ for adapter, model in model_catalog.DEFAULT_MODEL_BY_RUNTIME_ADAPTER.items():
+ assert model in model_catalog.models_for_runtime_adapter(adapter), (
+ f"the default model for '{adapter}' is not in its catalog, so a run that pins no model "
+ f"would resolve to one validation rejects"
+ )
+
+
+def test_labels_are_set_only_where_the_derived_name_is_wrong() -> None:
+ # A pin that the formatter would produce anyway is dead weight that outlives the
+ # formatter improving, so assert the property rather than restating the six strings.
+ for entry in model_catalog.MODELS:
+ if entry.label is None:
+ continue
+ assert entry.label != model_catalog.format_model_id(entry.id), (
+ f"'{entry.id}' pins the label the formatter already derives; drop the pin"
+ )
+
+
+class TestAvailableModelChoices:
+ """The gateway-backed list the `/tasks/models` endpoint serves. Slack and the web read
+ the catalog directly, so this path is the only one still asking what is served now."""
+
+ def test_drops_providers_we_cannot_route(self) -> None:
+ gateway = (
+ GatewayModel(id="claude-fable-5", owned_by="anthropic", context_window=200000),
+ GatewayModel(id="titan-express", owned_by="bedrock", context_window=8000),
+ )
+ with patch(
+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",
+ return_value=gateway,
+ ):
+ assert [c.model for c in available_model_choices("posthog_code")] == ["claude-fable-5"]
+
+ def test_keeps_vendor_served_models_the_catalog_routes(self) -> None:
+ # The gateway owns these under the party serving them, not the harness that drives
+ # them, so routing on the owner alone dropped every one from the web picker.
+ gateway = (
+ GatewayModel(id="deepseek-ai/deepseek-v4-flash-0731", owned_by="baseten", context_window=128000),
+ GatewayModel(id="zai-org/glm-5.3-flash", owned_by="cloudflare", context_window=128000),
+ GatewayModel(id="moonshotai/kimi-k3", owned_by="moonshotai", context_window=128000),
+ )
+ with patch(
+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",
+ return_value=gateway,
+ ):
+ choices = available_model_choices("posthog_code")
+
+ assert [c.model for c in choices] == [m.id for m in gateway]
+ assert {c.runtime_adapter for c in choices} == {"claude"}
+ assert [c.label for c in choices] == ["DeepSeek V4 Flash", "GLM-5.3 Flash", "Kimi K3"]
+
+
+def test_every_gated_model_resolves_to_its_catalog_flag() -> None:
+ # The gate and the pickers read one field now, so this fails if a row gains an
+ # access_flag the entitlement check cannot see, whichever spelling the caller sends.
+ gated = [model for model in model_catalog.MODELS if model.access_flag]
+ assert gated, "the catalog gates no model, so this guard proves nothing"
+
+ for model in gated:
+ assert get_required_model_flag(model.id) == model.access_flag
+ assert get_required_model_flag(f"anthropic/{model.id}") == model.access_flag
+
+ for model in model_catalog.MODELS:
+ if model.access_flag is None:
+ assert get_required_model_flag(model.id) is None
diff --git a/products/tasks/backend/tests/test_model_selection.py b/products/tasks/backend/tests/test_model_selection.py
index 2e1211e16838..73cc22ec8857 100644
--- a/products/tasks/backend/tests/test_model_selection.py
+++ b/products/tasks/backend/tests/test_model_selection.py
@@ -2,9 +2,11 @@ import pytest
from django.core.exceptions import ValidationError
+from products.tasks.backend.constants import get_required_model_flag
from products.tasks.backend.temporal.process_task.utils import (
RuntimeAdapter,
get_runtime_adapter_for_model,
+ runtime_adapter_serves_model,
validate_model_selection,
)
@@ -16,6 +18,10 @@ from products.tasks.backend.temporal.process_task.utils import (
("CLAUDE-SONNET-5", RuntimeAdapter.CLAUDE),
("gpt-5.6-sol", RuntimeAdapter.CODEX),
("gpt-6-astra", RuntimeAdapter.CODEX),
+ # The gateway serves some models provider-qualified and a picker hands back either
+ # spelling, so both resolve to the adapter the bare id does.
+ ("anthropic/claude-sonnet-5", RuntimeAdapter.CLAUDE),
+ ("openai/gpt-5.6-sol", RuntimeAdapter.CODEX),
("some-model-nobody-serves", None),
(None, None),
],
@@ -53,3 +59,45 @@ def test_valid_selections_pass(runtime_adapter, model, reasoning_effort) -> None
def test_invalid_selections_raise(runtime_adapter, model, reasoning_effort, expected_message) -> None:
with pytest.raises(ValidationError, match=expected_message):
validate_model_selection(runtime_adapter, model, reasoning_effort)
+
+
+ "model,expected_flag",
+ [
+ ("zai-org/glm-5.3", "posthog-code-glm-53-model"),
+ ("anthropic/zai-org/glm-5.3", "posthog-code-glm-53-model"),
+ ("ANTHROPIC/ZAI-ORG/GLM-5.3", "posthog-code-glm-53-model"),
+ ("claude-opus-5", None),
+ ],
+ ids=["canonical", "provider_qualified", "mixed_case", "ungated"],
+)
+def test_gated_model_is_gated_in_every_spelling(model: str, expected_flag: str | None) -> None:
+ # Every resolver folds a provider-qualified id onto the model it names, so a gate that
+ # missed that spelling would skip the entitlement check on an id the rest of the stack
+ # already treats as the gated one.
+ assert get_required_model_flag(model) == expected_flag
+
+
+ "adapter,model,expected",
+ [
+ ("codex", "gpt-5.6-sol", True),
+ ("codex", "openai/gpt-5.6-sol", True),
+ ("claude", "anthropic/claude-opus-5", True),
+ ("codex", "claude-opus-5", False),
+ ("codex", "some-model-nobody-serves", False),
+ ("codex", None, False),
+ ],
+ ids=[
+ "canonical",
+ "provider_qualified",
+ "provider_qualified_claude",
+ "wrong_adapter",
+ "unserved",
+ "no_model",
+ ],
+)
+def test_allowlist_accepts_the_spellings_the_resolvers_accept(adapter: str, model: str | None, expected: bool) -> None:
+ # The loops serializer rejects anything this call rejects, so a spelling the gateway
+ # serves and the pickers offer has to pass here or the save 400s.
+ assert runtime_adapter_serves_model(adapter, model) is expected
diff --git a/products/tasks/frontend/components/TaskModelPicker/CyclotronJobInputTaskModel.tsx b/products/tasks/frontend/components/TaskModelPicker/CyclotronJobInputTaskModel.tsx
index cf7e6d25eb61..a9579aba02c9 100644
--- a/products/tasks/frontend/components/TaskModelPicker/CyclotronJobInputTaskModel.tsx
+++ b/products/tasks/frontend/components/TaskModelPicker/CyclotronJobInputTaskModel.tsx
@@ -1,66 +1,60 @@
-import { useValues } from 'kea'
-
import { LemonSelect } from '@posthog/lemon-ui'
import type { CustomInputRendererProps } from 'lib/components/CyclotronJob/customInputRenderers'
-import { taskModelPickerLogic } from './taskModelPickerLogic'
+import { normalizeModelId } from 'products/tasks/frontend/modelCatalog'
+import { MODELS } from 'products/tasks/frontend/modelCatalog.generated'
type TaskModelValue = { model: string; reasoning_effort?: string }
-export default function CyclotronJobInputTaskModel({ value, onChange }: CustomInputRendererProps): JSX.Element {
- const { models, modelsLoading } = useValues(taskModelPickerLogic)
+const MODEL_OPTIONS = MODELS.map((model) => ({ value: model.id, label: model.label }))
+const EFFORTS_BY_MODEL = new Map<string, readonly string[]>(MODELS.map((model) => [model.id, model.reasoningEfforts]))
+export default function CyclotronJobInputTaskModel({ value, onChange }: CustomInputRendererProps): JSX.Element {
const selected: Partial<TaskModelValue> = value ?? {}
- const selectedChoice = models.find((choice) => choice.model === selected.model)
- const efforts = selectedChoice?.supported_efforts ?? []
+ // Folded onto the bare catalog id so a value stored as `openai/gpt-5.6-sol` selects the option it names and
+ // offers that model's efforts, rather than matching no option and rendering blank.
+ const selectedModel = selected.model ? normalizeModelId(selected.model) : null
+ const efforts = (selectedModel && EFFORTS_BY_MODEL.get(selectedModel)) || []
- const modelOptions = models.map((choice) => ({ value: choice.model, label: choice.display_name }))
- // A stored model that has since left the catalogue still needs to render as itself, not as blank.
- if (selected.model && !selectedChoice) {
- modelOptions.push({ value: selected.model, label: selected.model })
+ const modelOptions = [...MODEL_OPTIONS]
+ // A stored model that has since left the catalog still needs to render as itself, not as blank.
+ if (selectedModel && !EFFORTS_BY_MODEL.has(selectedModel)) {
+ modelOptions.push({ value: selectedModel, label: selectedModel })
}
return (
<div className="flex gap-2">
<LemonSelect
className="flex-1"
- placeholder={modelsLoading ? 'Loading models...' : 'Default model'}
+ placeholder="Default model"
allowClear
- disabledReason={
- !modelsLoading && models.length === 0 && !selected.model
- ? 'Model list is unavailable right now. The task will use the default model.'
- : undefined
- }
- value={selected.model ?? null}
+ value={selectedModel}
options={modelOptions}
onChange={(model) => {
if (!model) {
onChange(null)
return
}
- const choice = models.find((c) => c.model === model)
- const supported = choice?.supported_efforts ?? []
// Keep the chosen effort across a model switch when the new model supports it;
// otherwise drop it so the server applies that model's default.
+ const supported = EFFORTS_BY_MODEL.get(model) ?? []
const effort =
- selected.reasoning_effort && (supported as string[]).includes(selected.reasoning_effort)
+ selected.reasoning_effort && supported.includes(selected.reasoning_effort)
? selected.reasoning_effort
: undefined
onChange(effort ? { model, reasoning_effort: effort } : { model })
}}
data-attr="task-model-picker-model"
/>
- {efforts.length > 0 && (
+ {selectedModel && efforts.length > 0 && (
<LemonSelect
placeholder="Default effort"
allowClear
value={selected.reasoning_effort ?? null}
options={efforts.map((effort) => ({ value: effort, label: effort }))}
onChange={(effort) =>
- onChange(
- effort ? { model: selected.model, reasoning_effort: effort } : { model: selected.model }
- )
+ onChange(effort ? { model: selectedModel, reasoning_effort: effort } : { model: selectedModel })
}
data-attr="task-model-picker-effort"
/>
diff --git a/products/tasks/frontend/components/TaskModelPicker/taskModelPickerLogic.ts b/products/tasks/frontend/components/TaskModelPicker/taskModelPickerLogic.ts
deleted file mode 100644
index f7f0c12f26bf..000000000000
--- a/products/tasks/frontend/components/TaskModelPicker/taskModelPickerLogic.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { MakeLogicType, afterMount, connect, kea, path } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { projectLogic } from 'scenes/projectLogic'
-
-import { tasksModelsRetrieve } from 'products/tasks/frontend/generated/api'
-import type { ModelChoiceApi } from 'products/tasks/frontend/generated/api.schemas'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface taskModelPickerLogicValues {
- currentProjectId: number | null // projectLogic
- models: ModelChoiceApi[]
- modelsLoading: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface taskModelPickerLogicActions {
- loadModels: () => any
- loadModelsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadModelsSuccess: (
- models: ModelChoiceApi[],
- payload?: any
- ) => {
- models: ModelChoiceApi[]
- payload?: any
- }
-}
-
-export type taskModelPickerLogicType = MakeLogicType<taskModelPickerLogicValues, taskModelPickerLogicActions>
-
-export const taskModelPickerLogic = kea<taskModelPickerLogicType>([
- path(['products', 'tasks', 'frontend', 'components', 'TaskModelPicker', 'taskModelPickerLogic']),
- connect(() => ({
- values: [projectLogic, ['currentProjectId']],
- })),
- loaders(({ values }) => ({
- models: [
- [] as ModelChoiceApi[],
- {
- loadModels: async (): Promise<ModelChoiceApi[]> => {
- const response = await tasksModelsRetrieve(String(values.currentProjectId))
- return response.models
- },
- },
- ],
- })),
- afterMount(({ actions }) => {
- actions.loadModels()
- }),
-])
diff --git a/products/tasks/frontend/modelCatalog.generated.ts b/products/tasks/frontend/modelCatalog.generated.ts
new file mode 100644
index 000000000000..a9564bfc62cd
--- /dev/null
+++ b/products/tasks/frontend/modelCatalog.generated.ts
@@ -0,0 +1,214 @@
+// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from
+// products/tasks/backend/model_catalog.py.
+// Regenerate with `hogli build:task-model-catalog`. Do not edit.
+//
+// The single definition of a task agent run's triple: runtime adapter,
+// model, and reasoning effort. The backend validates a run against this
+// same data, so a picker built on this file can only offer a selection
+// the API will accept.
+
+export type RuntimeAdapter = 'claude' | 'codex'
+
+/** Thinking depths, shallowest first. */
+export type ReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultracode'
+
+export const REASONING_EFFORTS: readonly ReasoningEffort[] = ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode']
+
+/** A value for each runtime adapter. */
+export type ByRuntimeAdapter<T> = Record<RuntimeAdapter, T>
+
+/** Efforts per adapter, absent where the adapter has no fallback. */
+type FallbackEfforts = Partial<ByRuntimeAdapter<readonly ReasoningEffort[]>>
+
+export interface CatalogModel {
+ id: string
+ runtimeAdapter: RuntimeAdapter
+ /** Empty for a model with no effort control: render no dropdown. */
+ reasoningEfforts: readonly ReasoningEffort[]
+ /** What a picker shows. Resolved when this file is generated, so every
+ surface names a model the same way without carrying a formatter. */
+ label: string
+ /** Feature flag a person needs before a picker offers this model. Absent
+ means generally available. Governs display only — the server decides
+ whether a run may use it. */
+ accessFlag?: string
+}
+
+/** Which vendor API each runtime adapter speaks. */
+export const PROVIDER_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {
+ claude: 'anthropic',
+ codex: 'openai',
+}
+
+export const RUNTIME_ADAPTERS: readonly RuntimeAdapter[] = ['claude', 'codex']
+
+export const MODELS: readonly CatalogModel[] = [
+ {
+ id: '@cf/zai-org/glm-5.2',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['high', 'max'],
+ label: 'GLM-5.2',
+ accessFlag: 'posthog-code-glm-model',
+ },
+ {
+ id: 'zai-org/glm-5.3',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['high', 'max'],
+ label: 'GLM-5.3',
+ accessFlag: 'posthog-code-glm-53-model',
+ },
+ {
+ id: 'zai-org/glm-5.3-flash',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['high', 'max'],
+ label: 'GLM-5.3 Flash',
+ accessFlag: 'posthog-code-glm-53-flash-model',
+ },
+ {
+ id: 'moonshotai/kimi-k3',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: [],
+ label: 'Kimi K3',
+ accessFlag: 'tasks-kimi-k3',
+ },
+ {
+ id: 'deepseek-ai/deepseek-v4-flash-0731',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: [],
+ label: 'DeepSeek V4 Flash',
+ accessFlag: 'posthog-code-deepseek-model',
+ },
+ {
+ id: 'claude-opus-4-5',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high'],
+ label: 'Claude Opus 4.5',
+ },
+ {
+ id: 'claude-opus-4-6',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ label: 'Claude Opus 4.6',
+ },
+ {
+ id: 'claude-opus-4-7',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Opus 4.7',
+ },
+ {
+ id: 'claude-opus-4-8',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Opus 4.8',
+ },
+ {
+ id: 'claude-opus-5',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Opus 5',
+ },
+ {
+ id: 'claude-fable-5',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Fable 5',
+ },
+ {
+ id: 'claude-fable-5-1',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Fable 5.1',
+ },
+ {
+ id: 'claude-sonnet-5',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'],
+ label: 'Claude Sonnet 5',
+ },
+ {
+ id: 'claude-sonnet-4-6',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['low', 'medium', 'high'],
+ label: 'Claude Sonnet 4.6',
+ },
+ {
+ id: 'gpt-5',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high'],
+ label: 'GPT-5',
+ },
+ {
+ id: 'gpt-5.5',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh'],
+ label: 'GPT-5.5',
+ },
+ {
+ id: 'gpt-5.6-sol',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ label: 'GPT-5.6 Sol',
+ },
+ {
+ id: 'gpt-5.6-terra',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ label: 'GPT-5.6 Terra',
+ },
+ {
+ id: 'gpt-5.6-luna',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ label: 'GPT-5.6 Luna',
+ },
+ {
+ id: 'gpt-6-astra',
+ runtimeAdapter: 'codex',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ label: 'GPT-6 Astra',
+ },
+]
+
+/** The model a run uses when it pins none. */
+export const DEFAULT_MODEL_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {
+ claude: 'claude-sonnet-5',
+ codex: 'gpt-5',
+}
+
+export interface ModelFamily {
+ runtimeAdapter: RuntimeAdapter
+ prefix: string
+ reasoningEfforts: readonly ReasoningEffort[]
+}
+
+// Depths a whole family exposes, used when no exact id matches. OpenAI ships
+// vendor-flavoured variants the gateway never lists (`gpt-5.5-codex`), and a
+// local session can drive one. The longest matching prefix wins, so the
+// declaration order below is free.
+export const FAMILY_REASONING_EFFORTS: readonly ModelFamily[] = [
+ {
+ runtimeAdapter: 'codex',
+ prefix: 'gpt-6-astra',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ },
+ {
+ runtimeAdapter: 'codex',
+ prefix: 'gpt-5.6',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ },
+ {
+ runtimeAdapter: 'codex',
+ prefix: 'gpt-5.5',
+ reasoningEfforts: ['low', 'medium', 'high', 'xhigh'],
+ },
+]
+
+// What a runtime accepts for a model neither an id nor a family claims.
+// Codex passes any `gpt-*` identifier through, so an id the gateway starts
+// serving before it is listed here still runs. Claude is absent on
+// purpose: an unnamed model there yields no efforts, which is what makes
+// validation reject it.
+export const FALLBACK_REASONING_EFFORTS: FallbackEfforts = {
+ codex: ['low', 'medium', 'high'],
+}
diff --git a/products/tasks/frontend/modelCatalog.ts b/products/tasks/frontend/modelCatalog.ts
new file mode 100644
index 000000000000..109564ad7c36
--- /dev/null
+++ b/products/tasks/frontend/modelCatalog.ts
@@ -0,0 +1,23 @@
+import { PROVIDER_BY_RUNTIME_ADAPTER } from './modelCatalog.generated'
+
+/**
+ * The form a model id is looked up under.
+ *
+ * The LLM gateway serves some models both bare and provider-qualified (`openai/gpt-5.6-sol`), and a stored run or
+ * workflow config may carry either. Folding the two together is what stops one model from having two answers
+ * depending on which surface asked. Only the provider prefixes this catalog knows are stripped, so ids that carry a
+ * slash of their own (`@cf/zai-org/glm-5.2`) survive intact.
+ *
+ * The hand-written half of the catalog, kept beside the generated data the way the desktop app keeps
+ * `model-catalog.ts` — the generator emits data only, so each language writes the lookup once.
+ */
+export function normalizeModelId(modelId: string): string {
+ const normalized = modelId.trim().toLowerCase()
+ for (const provider of Object.values(PROVIDER_BY_RUNTIME_ADAPTER)) {
+ const prefix = `${provider}/`
+ if (normalized.startsWith(prefix)) {
+ return normalized.slice(prefix.length)
+ }
+ }
+ return normalized
+}
diff --git a/products/tasks/scripts/build_model_catalog.py b/products/tasks/scripts/build_model_catalog.py
new file mode 100755
index 000000000000..b3a45456c33f
--- /dev/null
+++ b/products/tasks/scripts/build_model_catalog.py
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+"""Project the task run model catalog into TypeScript for the web app and the desktop app.
+
+Same pattern as ``bin/build-mcp-oauth-scopes.py``: a codegen script that reads a pure-data
+Python module and writes a checked-in ``*.generated.ts``, so the Python module stays the
+single authority and the TypeScript sides are projections of it. It lives beside the
+catalog it projects rather than in ``bin/``, since only this product reads or writes it —
+the same placement as ``products/posthog_ai/scripts/build_skills.py``.
+
+Two files come out of one template because the two workspaces run different formatters —
+the web app runs oxfmt (four spaces, single quotes, no semicolons, 120 columns) and the
+desktop app runs Biome (two spaces, double quotes, semicolons, 80 columns). Each file is
+emitted in the shape its own formatter would produce, so a later ``pnpm format`` never
+turns generated output into a diff. Objects are written one property per line, which both
+formatters preserve regardless of width; arrays and unions are wrapped against the target
+width, because both formatters collapse those whenever they fit.
+
+Emitting that shape rather than shelling out to each formatter is a deliberate trade. It
+costs a small amount of formatter emulation here, and it buys a ``render()`` whose output
+is byte-exact, which is what lets the drift test compare the checked-in files against this
+module with no Node in the loop. ``check_fits`` is the guard on that bargain: a line the
+target formatter would rewrap fails the build instead of drifting silently.
+
+Only data is generated. The lookup built on it lives in
+``products/desktop/packages/shared/src/model-catalog.ts`` and, for Python, in the source
+module itself — behavior stays hand-written and tested, while the table that actually
+changes has one home.
+
+Run via hogli: `hogli build:task-model-catalog` (also runs as part of `build:openapi`).
+See `hogli.yaml`.
+"""
+# ruff: noqa: T201
+
+from __future__ import annotations
+
+import sys
+import runpy
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+CATALOG_PY = REPO_ROOT / "products" / "tasks" / "backend" / "model_catalog.py"
+WEB_OUTPUT = REPO_ROOT / "products" / "tasks" / "frontend" / "modelCatalog.generated.ts"
+DESKTOP_OUTPUT = REPO_ROOT / "products" / "desktop" / "packages" / "shared" / "src" / "model-catalog.generated.ts"
+
+HEADER = """// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from
+// products/tasks/backend/model_catalog.py.
+// Regenerate with `hogli build:task-model-catalog`. Do not edit.
+//
+// The single definition of a task agent run's triple: runtime adapter,
+// model, and reasoning effort. The backend validates a run against this
+// same data, so a picker built on this file can only offer a selection
+// the API will accept."""
+
+
+@dataclass(frozen=True)
+class Style:
+ """How one workspace's formatter wants generated TypeScript to look."""
+
+ indent: str
+ quote: str
+ semi: str
+ width: int
+
+ def s(self, value: str) -> str:
+ """A string literal. Catalog values are lowercase ids: letters, digits, `-./@` only."""
+ if self.quote in value or "\\" in value:
+ raise RuntimeError(f"unexpected character in catalog value: {value!r}")
+ return f"{self.quote}{value}{self.quote}"
+
+ def array(self, values: tuple[str, ...], *, prefix: str, suffix: str, depth: int) -> str:
+ """An array literal, wrapped one item per line when the single-line form is too wide."""
+ pad = self.indent * depth
+ items = [self.s(value) for value in values]
+ single = f"{pad}{prefix}[{', '.join(items)}]{suffix}"
+ if len(single) <= self.width:
+ return single
+ inner = "".join(f"{pad}{self.indent}{item},\n" for item in items)
+ return f"{pad}{prefix}[\n{inner}{pad}]{suffix}"
+
+ def union(self, values: tuple[str, ...], *, prefix: str) -> str:
+ """A string-literal union, broken onto leading-pipe lines when too wide."""
+ items = [self.s(value) for value in values]
+ single = f"{prefix}{' | '.join(items)}{self.semi}"
+ if len(single) <= self.width:
+ return single
+ broken = "".join(f"{self.indent}| {item}\n" for item in items)
+ return f"{prefix.rstrip()}\n{broken.rstrip()}{self.semi}"
+
+
+OXFMT = Style(indent=" " * 4, quote="'", semi="", width=120)
+BIOME = Style(indent=" " * 2, quote='"', semi=";", width=80)
+
+
+def render(catalog: dict[str, Any], style: Style) -> str:
+ i, semi = style.indent, style.semi
+ adapters: tuple[str, ...] = catalog["RUNTIME_ADAPTERS"]
+ providers: dict[str, str] = catalog["PROVIDER_BY_RUNTIME_ADAPTER"]
+ defaults: dict[str, str] = catalog["DEFAULT_MODEL_BY_RUNTIME_ADAPTER"]
+ fallbacks: dict[str, tuple[str, ...]] = catalog["FALLBACK_REASONING_EFFORTS_BY_RUNTIME_ADAPTER"]
+ families: tuple[tuple[str, str, tuple[str, ...]], ...] = catalog["FAMILY_REASONING_EFFORTS"]
+ models: tuple[Any, ...] = catalog["MODELS"]
+ efforts: tuple[str, ...] = catalog["REASONING_EFFORTS"]
+ display_name = catalog["display_name_for_model"]
+
+ def model_entry(model: Any) -> str:
+ return "\n".join(
+ [
+ f"{i}{{",
+ f"{i}{i}id: {style.s(model.id)},",
+ f"{i}{i}runtimeAdapter: {style.s(model.runtime_adapter)},",
+ style.array(model.reasoning_efforts, prefix="reasoningEfforts: ", suffix=",", depth=2),
+ f"{i}{i}label: {style.s(display_name(model.id))},",
+ *([f"{i}{i}accessFlag: {style.s(model.access_flag)},"] if model.access_flag else []),
+ f"{i}}},",
+ ]
+ )
+
+ model_entries = "\n".join(model_entry(model) for model in models)
+ provider_entries = "\n".join(f"{i}{adapter}: {style.s(providers[adapter])}," for adapter in adapters)
+ default_entries = "\n".join(f"{i}{adapter}: {style.s(defaults[adapter])}," for adapter in adapters)
+ fallback_entries = "\n".join(
+ style.array(fallbacks[adapter], prefix=f"{adapter}: ", suffix=",", depth=1)
+ for adapter in adapters
+ if adapter in fallbacks
+ )
+ family_entries = "\n".join(
+ f"{i}{{\n"
+ f"{i}{i}runtimeAdapter: {style.s(adapter)},\n"
+ f"{i}{i}prefix: {style.s(prefix)},\n"
+ f"{style.array(family_efforts, prefix='reasoningEfforts: ', suffix=',', depth=2)}\n"
+ f"{i}}},"
+ for adapter, prefix, family_efforts in families
+ )
+
+ return f"""{HEADER}
+
+{style.union(adapters, prefix="export type RuntimeAdapter = ")}
+
+/** Thinking depths, shallowest first. */
+{style.union(efforts, prefix="export type ReasoningEffort = ")}
+
+{style.array(efforts, prefix="export const REASONING_EFFORTS: readonly ReasoningEffort[] = ", suffix=semi, depth=0)}
+
+/** A value for each runtime adapter. */
+export type ByRuntimeAdapter<T> = Record<RuntimeAdapter, T>{semi}
+
+/** Efforts per adapter, absent where the adapter has no fallback. */
+type FallbackEfforts = Partial<ByRuntimeAdapter<readonly ReasoningEffort[]>>{semi}
+
+export interface CatalogModel {{
+{i}id: string{semi}
+{i}runtimeAdapter: RuntimeAdapter{semi}
+{i}/** Empty for a model with no effort control: render no dropdown. */
+{i}reasoningEfforts: readonly ReasoningEffort[]{semi}
+{i}/** What a picker shows. Resolved when this file is generated, so every
+{i} surface names a model the same way without carrying a formatter. */
+{i}label: string{semi}
+{i}/** Feature flag a person needs before a picker offers this model. Absent
+{i} means generally available. Governs display only — the server decides
+{i} whether a run may use it. */
+{i}accessFlag?: string{semi}
+}}
+
+/** Which vendor API each runtime adapter speaks. */
+export const PROVIDER_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {{
+{provider_entries}
+}}{semi}
+
+{style.array(adapters, prefix="export const RUNTIME_ADAPTERS: readonly RuntimeAdapter[] = ", suffix=semi, depth=0)}
+
+export const MODELS: readonly CatalogModel[] = [
+{model_entries}
+]{semi}
+
+/** The model a run uses when it pins none. */
+export const DEFAULT_MODEL_BY_RUNTIME_ADAPTER: ByRuntimeAdapter<string> = {{
+{default_entries}
+}}{semi}
+
+export interface ModelFamily {{
+{i}runtimeAdapter: RuntimeAdapter{semi}
+{i}prefix: string{semi}
+{i}reasoningEfforts: readonly ReasoningEffort[]{semi}
+}}
+
+// Depths a whole family exposes, used when no exact id matches. OpenAI ships
+// vendor-flavoured variants the gateway never lists (`gpt-5.5-codex`), and a
+// local session can drive one. The longest matching prefix wins, so the
+// declaration order below is free.
+export const FAMILY_REASONING_EFFORTS: readonly ModelFamily[] = [
+{family_entries}
+]{semi}
+
+// What a runtime accepts for a model neither an id nor a family claims.
+// Codex passes any `gpt-*` identifier through, so an id the gateway starts
+// serving before it is listed here still runs. Claude is absent on
+// purpose: an unnamed model there yields no efforts, which is what makes
+// validation reject it.
+export const FALLBACK_REASONING_EFFORTS: FallbackEfforts = {{
+{fallback_entries}
+}}{semi}
+"""
+
+
+def check_fits(rendered: str, style: Style, output: Path) -> None:
+ """Fail on a line the target formatter would rewrap.
+
+ Every line here is already in the shape its formatter produces, which is what keeps a
+ ``pnpm format`` run from turning generated output into a diff. A model id long enough
+ to push a line past the column limit breaks that quietly, so it stops the build
+ instead — the fix is to shorten the emitted shape, not to accept the drift.
+ """
+ too_long = [line for line in rendered.splitlines() if len(line) > style.width]
+ if too_long:
+ raise RuntimeError(
+ f"{output.name}: {len(too_long)} line(s) exceed {style.width} columns and would be "
+ f"rewrapped by the formatter, e.g.\n {too_long[0]}"
+ )
+
+
+def main() -> int:
+ # runpy.run_path loads the module by filesystem path, bypassing the import machinery and
+ # therefore products/__init__.py and the Django settings behind it. Anything
+ # model_catalog.py cannot satisfy from the standard library raises here, failing loudly.
+ catalog = runpy.run_path(str(CATALOG_PY))
+ model_count = len(catalog["MODELS"])
+
+ for output, style in ((WEB_OUTPUT, OXFMT), (DESKTOP_OUTPUT, BIOME)):
+ rendered = render(catalog, style)
+ check_fits(rendered, style, output)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ if output.exists() and output.read_text() == rendered:
+ print(f"{output.relative_to(REPO_ROOT)} already up to date ({model_count} models)")
+ continue
+ output.write_text(rendered)
+ print(f"wrote {output.relative_to(REPO_ROOT)} ({model_count} models)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())