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.

fix(tasks): resume runs pinned to the cloudflare glm id through the go gateway (#122180)

Alessandro Pogliaghid23f59fb8b64
diff --git a/packages/agent/packages/agent-contracts/src/model-catalog.generated.ts b/packages/agent/packages/agent-contracts/src/model-catalog.generated.ts
index 9bbdd9f5c61c..aefcb8047ec9 100644
--- a/packages/agent/packages/agent-contracts/src/model-catalog.generated.ts
+++ b/packages/agent/packages/agent-contracts/src/model-catalog.generated.ts
@@ -160,6 +160,19 @@ export const MODELS: readonly CatalogModel[] = [
costSummary: "Input $1.40 · Output $4.40 per 1M tokens",
retired: true,
},
+ {
+ id: "zai-org/glm-5.2",
+ runtimeAdapter: "claude",
+ reasoningEfforts: ["high", "max"],
+ label: "GLM-5.2",
+ cost: {
+ inputPerMtok: 1.4,
+ outputPerMtok: 4.4,
+ },
+ costMultiplier: "≈0.57×",
+ costSummary: "Input $1.40 · Output $4.40 per 1M tokens",
+ retired: true,
+ },
{
id: "zai-org/glm-5.3",
runtimeAdapter: "claude",
diff --git a/packages/agent/packages/agent/src/adapters/base-acp-agent.ts b/packages/agent/packages/agent/src/adapters/base-acp-agent.ts
index 8ba08511d61e..1a3d1302f895 100644
--- a/packages/agent/packages/agent/src/adapters/base-acp-agent.ts
+++ b/packages/agent/packages/agent/src/adapters/base-acp-agent.ts
@@ -19,6 +19,7 @@ import type {
import {
customModelMeta,
isAnthropicModelId,
+ isRetiredModel,
restrictedModelMeta,
} from "@posthog/agent-contracts";
import {
@@ -195,7 +196,10 @@ export abstract class BaseAcpAgent implements Agent {
const rejectedByGateway = this.gatewayModels.some(
(model) => model.id === currentModelId,
);
- if (rejectedByGateway || isServedModelId(currentModelId)) {
+ if (
+ !isRetiredModel(currentModelId) &&
+ (rejectedByGateway || isServedModelId(currentModelId))
+ ) {
const fallbackOption =
options.find((option) => option.value === DEFAULT_GATEWAY_MODEL) ??
options.find((option) => option._meta === undefined);
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
index 5b5c67954268..b94dd1baf194 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts
@@ -379,6 +379,42 @@ describe("ClaudeAcpAgent session creation", () => {
},
);
+ it.each([
+ { isAiGateway: true, expectedSetModel: "zai-org/glm-5.2" },
+ { isAiGateway: false, expectedSetModel: "@cf/zai-org/glm-5.2" },
+ ])(
+ "resumes a run stored on @cf/zai-org/glm-5.2 as $expectedSetModel when isAiGateway is $isAiGateway",
+ async ({ isAiGateway, expectedSetModel }) => {
+ vi.mocked(fetchGatewayModels).mockResolvedValueOnce([]);
+ const client = {
+ sessionUpdate: vi.fn().mockResolvedValue(undefined),
+ extNotification: vi.fn().mockResolvedValue(undefined),
+ } as unknown as AgentSideConnection;
+ const agent = new ClaudeAcpAgent(client, {
+ gatewayEnv: {
+ anthropicBaseUrl: "http://gateway.test",
+ anthropicAuthToken: "token",
+ openaiBaseUrl: "http://gateway.test/v1",
+ openaiApiKey: "token",
+ isAiGateway,
+ },
+ });
+
+ const response = await agent.resumeSession({
+ sessionId: "0197a000-0000-7000-8000-000000000021",
+ cwd,
+ mcpServers: [],
+ _meta: { taskRunId: "run-glm", model: "@cf/zai-org/glm-5.2" },
+ });
+
+ expect(createdQueries).toHaveLength(1);
+ expect(createdQueries[0].setModel).toHaveBeenCalledWith(expectedSetModel);
+ expect(getModelConfigOption(response)?.currentValue).toBe(
+ expectedSetModel,
+ );
+ },
+ );
+
// The shared claude settings file is cross-session state: the session's own
// pick must win over it, with the file only as a fallback.
it.each([
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
index b07f15c38c68..720a14574170 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
@@ -78,6 +78,7 @@ import { PostHogAPIClient } from "../../posthog-api";
import type { PostHogAPIConfig } from "../../types";
import { text } from "../../utils/acp-content";
import { unreachable, withAbort, withTimeout } from "../../utils/common";
+import { modelIdForGatewayRoute } from "../../utils/gateway";
import { Logger } from "../../utils/logger";
import { Pushable } from "../../utils/streams";
import { BaseAcpAgent } from "../base-acp-agent";
@@ -2829,13 +2830,17 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
: [o as { value: string; name?: string; description?: string }],
)
: [];
- let validValue = allValues.find((o) => o.value === params.value);
+ const requestedValue =
+ params.configId === "model"
+ ? this.routedModelId(params.value)
+ : params.value;
+ let validValue = allValues.find((o) => o.value === requestedValue);
// For model options, fall back to alias resolution when exact match fails.
// This lets callers use human-friendly aliases like "opus" or "sonnet"
// instead of full model IDs like "claude-opus-4-8".
if (!validValue && params.configId === "model") {
- const resolved = resolveModelPreference(params.value, allValues);
+ const resolved = resolveModelPreference(requestedValue, allValues);
if (resolved) {
validValue = allValues.find((o) => o.value === resolved);
}
@@ -3018,6 +3023,13 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
}
+ private routedModelId<T extends string | undefined>(model: T): T {
+ return modelIdForGatewayRoute(
+ model,
+ this.options?.gatewayEnv?.isAiGateway ?? false,
+ );
+ }
+
private startupFailure(
step:
| "initialization"
@@ -3143,8 +3155,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
// The session's explicit pick outranks the shared claude settings file:
// that file is cross-session state and must only ever be a fallback.
- const earlyModelId =
- meta?.model || settingsManager.getSettings().model || "";
+ const earlyModelId = this.routedModelId(
+ meta?.model || settingsManager.getSettings().model || "",
+ );
// Register the in-process general local-tools MCP server. Tools self-gate
// via the registry (e.g. signed-commit is cloud-only and needs a GH token),
@@ -3378,8 +3391,9 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
this.session = session;
this.sessionId = sessionId;
- const requestedModel =
- meta?.model || settingsManager.getSettings().model || undefined;
+ const requestedModel = this.routedModelId(
+ meta?.model || settingsManager.getSettings().model || undefined,
+ );
if (isResume) {
const resumeStartedAt = Date.now();
@@ -3539,10 +3553,12 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
}
- const resolvedModelId = resolveInitialModelId(modelOptions, [
- meta?.model,
- settingsManager.getSettings().model,
- ]);
+ const resolvedModelId = resolveInitialModelId(
+ modelOptions,
+ [meta?.model, settingsManager.getSettings().model].map((model) =>
+ this.routedModelId(model),
+ ),
+ );
modelOptions.currentModelId = resolvedModelId;
session.modelId = resolvedModelId;
session.lastContextWindowSize =
diff --git a/packages/agent/packages/agent/src/adapters/claude/session/options.ts b/packages/agent/packages/agent/src/adapters/claude/session/options.ts
index 38b986aabdb4..b23e863baa1d 100644
--- a/packages/agent/packages/agent/src/adapters/claude/session/options.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/session/options.ts
@@ -90,6 +90,7 @@ export type GatewayEnv = {
openaiCustomHeaders?: Record<string, string>;
/** PostHog project ID used to build the gateway project-scope header. */
posthogProjectId?: string;
+ isAiGateway?: boolean;
};
export interface BuildOptionsParams {
diff --git a/packages/agent/packages/agent/src/server/gateway-env.test.ts b/packages/agent/packages/agent/src/server/gateway-env.test.ts
new file mode 100644
index 000000000000..71e0513801f8
--- /dev/null
+++ b/packages/agent/packages/agent/src/server/gateway-env.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Logger } from "../utils/logger";
+import { buildGatewayEnv } from "./gateway-env";
+
+const ENV_KEYS = [
+ "LLM_GATEWAY_URL",
+ "AI_GATEWAY_URL",
+ "AI_GATEWAY_PRODUCTS",
+ "AI_GATEWAY_PRODUCT",
+ "AI_GATEWAY_AI_STAGE",
+ "AI_GATEWAY_TOKEN",
+];
+
+const config = {
+ apiKey: "oauth-token",
+ apiUrl: "https://us.posthog.com",
+ projectId: 7,
+};
+
+function logger(): Logger {
+ return {
+ warn: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ error: vi.fn(),
+ } as never;
+}
+
+describe("buildGatewayEnv", () => {
+ const saved: Record<string, string | undefined> = {};
+
+ beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved[key] = process.env[key];
+ delete process.env[key];
+ }
+ });
+
+ afterEach(() => {
+ for (const key of ENV_KEYS) {
+ if (saved[key] === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = saved[key];
+ }
+ }
+ });
+
+ // Without this flag the Claude adapter keeps `@cf/` ids, which Go refuses.
+ it.each([
+ {
+ route: "Go with a minted token",
+ env: {
+ AI_GATEWAY_URL: "https://ai-gateway.us.posthog.com/v1",
+ AI_GATEWAY_PRODUCTS: "posthog_code",
+ AI_GATEWAY_PRODUCT: "posthog_code",
+ AI_GATEWAY_TOKEN: "phe_run",
+ },
+ expected: true,
+ },
+ {
+ route: "Go without a minted token",
+ env: {
+ AI_GATEWAY_URL: "https://ai-gateway.us.posthog.com/v1",
+ AI_GATEWAY_PRODUCTS: "posthog_code",
+ AI_GATEWAY_PRODUCT: "posthog_code",
+ },
+ expected: false,
+ },
+ {
+ route: "the legacy gateway",
+ env: {
+ LLM_GATEWAY_URL: "https://gateway.us.posthog.com",
+ AI_GATEWAY_TOKEN: "phe_run",
+ },
+ expected: false,
+ },
+ ])("sets isAiGateway to $expected on $route", ({ env, expected }) => {
+ Object.assign(process.env, env);
+ const gatewayEnv = buildGatewayEnv(config, {}, logger());
+
+ expect(gatewayEnv.isAiGateway).toBe(expected);
+ expect(gatewayEnv.anthropicAuthToken).toBe(
+ expected ? "phe_run" : "oauth-token",
+ );
+ });
+});
diff --git a/packages/agent/packages/agent/src/server/gateway-env.ts b/packages/agent/packages/agent/src/server/gateway-env.ts
index 188325db91e3..a7e82cac53c4 100644
--- a/packages/agent/packages/agent/src/server/gateway-env.ts
+++ b/packages/agent/packages/agent/src/server/gateway-env.ts
@@ -11,6 +11,7 @@ import {
import type { GatewayEnv } from "../adapters/claude/session/options";
import type { Task } from "../types";
import {
+ modelIdForGatewayRoute,
resolveGatewayProduct,
resolveGatewayTarget,
resolveLlmGatewayUrl,
@@ -202,17 +203,10 @@ export function buildGatewayEnv(
anthropicCustomHeaders: customHeaders,
openaiCustomHeaders,
posthogProjectId: String(projectId),
+ isAiGateway,
};
}
-// Go serves GLM under its bare id and has no `@cf/` alias.
-export function piModelIdForRoute<T extends string | undefined>(
- model: T,
- isAiGateway: boolean,
-): T {
- return (isAiGateway ? model?.replace(/^@cf\//, "") : model) as T;
-}
-
export interface PiProviderRoute {
apiKey: string;
baseUrl: string;
@@ -258,7 +252,7 @@ export function buildPiProviderRoute(
}),
...buildPosthogSessionHeaderRecord(taskId),
},
- model: piModelIdForRoute(model, true),
+ model: modelIdForGatewayRoute(model, true),
isAiGateway: true,
};
}
diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.ts
index c2b7049f104c..56d93d9354bf 100644
--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts
+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts
@@ -58,13 +58,10 @@ import {
import { PostHogAPIClient } from "../posthog-api";
import { attachmentFilePath } from "../utils/attachments";
import { createEventIdSource } from "../utils/event-id";
+import { modelIdForGatewayRoute } from "../utils/gateway";
import { Logger } from "../utils/logger";
import { TaskRunEventStreamSender } from "./event-stream-sender";
-import {
- buildPiProviderRoute,
- type PiProviderRoute,
- piModelIdForRoute,
-} from "./gateway-env";
+import { buildPiProviderRoute, type PiProviderRoute } from "./gateway-env";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
import { readRunLaunch } from "./launch/run-launch";
import { createRtkSavingsNotification } from "./rtk-savings";
@@ -1124,7 +1121,7 @@ export class PiAgentServer {
? {
type: "set_model",
provider: "posthog",
- modelId: piModelIdForRoute(
+ modelId: modelIdForGatewayRoute(
value,
session.providerRoute.isAiGateway,
),
diff --git a/packages/agent/packages/agent/src/utils/gateway.ts b/packages/agent/packages/agent/src/utils/gateway.ts
index 6917babd86b5..572d02153379 100644
--- a/packages/agent/packages/agent/src/utils/gateway.ts
+++ b/packages/agent/packages/agent/src/utils/gateway.ts
@@ -251,3 +251,10 @@ export function resolveGatewayTarget({
aiStage: effectiveStage,
};
}
+
+export function modelIdForGatewayRoute<T extends string | undefined>(
+ model: T,
+ isAiGateway: boolean,
+): T {
+ return (isAiGateway ? model?.replace(/^@cf\//, "") : model) as T;
+}
diff --git a/products/tasks/backend/logic/services/gateway_model_pin.py b/products/tasks/backend/logic/services/gateway_model_pin.py
index 94bec0bcd28a..b4f293f4e7bc 100644
--- a/products/tasks/backend/logic/services/gateway_model_pin.py
+++ b/products/tasks/backend/logic/services/gateway_model_pin.py
@@ -14,6 +14,8 @@ SDK_IMPLICIT_MODELS: tuple[str, ...] = ("claude-haiku-4-5", "claude-sonnet-4-5")
_GATEWAY_RESTRICTED_MODEL_PRODUCTS: dict[str, frozenset[str]] = {
"deepseek-ai/deepseek-v4-flash-0731": frozenset({"posthog_code", "review_hog"}),
"deepseek-ai/deepseek-v4.1-flash-1017-fast": frozenset({"posthog_code", "review_hog", "signals_scout"}),
+ # Excluded from every first-party pin; posthog_code admits it through DESKTOP_AGENT_MODELS.
+ "zai-org/glm-5.2": frozenset({"posthog_code"}),
"zai-org/glm-5.3": frozenset({"posthog_code", "review_hog"}),
"zai-org/glm-5.3-flash": frozenset({"posthog_code", "review_hog"}),
}
@@ -32,9 +34,6 @@ def _first_party_pin(product: str) -> list[str]:
# Ids the legacy gateway serves to PostHog Desktop that the catalog lacks; older app builds call them.
_DESKTOP_LEGACY_MODELS: tuple[str, ...] = ("gpt-5.4", "gpt-5.3-codex", "gpt-5.2", "gpt-5-mini")
-# Go has no `@cf/` alias, so a run stored on `@cf/zai-org/glm-5.2` calls Go under the bare id.
-_GO_SPELLINGS: tuple[str, ...] = ("zai-org/glm-5.2",)
-
def gateway_pin(models: list[str]) -> list[str]:
return [model for model in models if not model.startswith("@cf/")]
@@ -42,7 +41,7 @@ def gateway_pin(models: list[str]) -> list[str]:
# Every model a PostHog Desktop session or cloud run may call, slash ids included. Go picks the provider.
DESKTOP_AGENT_MODELS: list[str] = list(
- dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS), *_DESKTOP_LEGACY_MODELS, *_GO_SPELLINGS])
+ dict.fromkeys([*SDK_IMPLICIT_MODELS, *(model.id for model in MODELS), *_DESKTOP_LEGACY_MODELS])
)
# The Go gateway refuses a pin longer than this at mint.
MAX_GATEWAY_PIN_LENGTH = 32
diff --git a/products/tasks/backend/model_catalog.py b/products/tasks/backend/model_catalog.py
index 9a35688944f4..da6b8aad8708 100644
--- a/products/tasks/backend/model_catalog.py
+++ b/products/tasks/backend/model_catalog.py
@@ -187,6 +187,7 @@ MODELS: tuple[CatalogModel, ...] = (
# 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", cost=_GLM_COST, retired=True),
+ CatalogModel("zai-org/glm-5.2", CLAUDE, _GLM, label="GLM-5.2", cost=_GLM_COST, retired=True),
CatalogModel("zai-org/glm-5.3", CLAUDE, _GLM, label="GLM-5.3", cost=_GLM_COST),
CatalogModel("zai-org/glm-5.3-flash", CLAUDE, _GLM, label="GLM-5.3 Flash", cost=_GLM_FLASH_COST),
CatalogModel("moonshotai/kimi-k3", CLAUDE, _NO_EFFORT, label="Kimi K3", cost=_KIMI_COST),
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index ac262b04ab14..8de3f542c31f 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -309,6 +309,7 @@ class TestMintScopedToken:
pin = _PRODUCT_ALLOWED_MODELS[product]
assert len(pin) == len(set(pin))
expected = {model for model in registry if not model.startswith("@cf/")} | set(SDK_IMPLICIT_MODELS)
+ expected -= {"zai-org/glm-5.2"}
if product != "review_hog":
expected -= {
"deepseek-ai/deepseek-v4-flash-0731",
@@ -1267,7 +1268,7 @@ class TestSlackAppMint:
"zai-org/glm-5.3-flash",
}
assert reserved <= set(_PRODUCT_ALLOWED_MODELS["review_hog"])
- missing = routed - reserved - set(_PRODUCT_ALLOWED_MODELS["slack_app"])
+ missing = routed - reserved - {"zai-org/glm-5.2"} - set(_PRODUCT_ALLOWED_MODELS["slack_app"])
assert not missing, f"catalog models absent from the slack_app pin: {sorted(missing)}"
def test_ttl_covers_the_sandbox_lifetime(self, mint_settings):
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
index 9f7c05a2e7ee..e874ea36f3c2 100644
--- 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
@@ -315,6 +315,16 @@
"supports_1m_context": false,
"supports_fast_mode": false
},
+ "zai-org/glm-5.2": {
+ "cost_multiplier": "≈0.57×",
+ "offered": false,
+ "reasoning_efforts": [
+ "high",
+ "max"
+ ],
+ "supports_1m_context": false,
+ "supports_fast_mode": false
+ },
"zai-org/glm-5.3": {
"cost_multiplier": "≈0.57×",
"offered": true,
diff --git a/products/tasks/frontend/modelCatalog.generated.ts b/products/tasks/frontend/modelCatalog.generated.ts
index 24fbd77b9980..04fb75054c1b 100644
--- a/products/tasks/frontend/modelCatalog.generated.ts
+++ b/products/tasks/frontend/modelCatalog.generated.ts
@@ -147,6 +147,19 @@ export const MODELS: readonly CatalogModel[] = [
costSummary: 'Input $1.40 · Output $4.40 per 1M tokens',
retired: true,
},
+ {
+ id: 'zai-org/glm-5.2',
+ runtimeAdapter: 'claude',
+ reasoningEfforts: ['high', 'max'],
+ label: 'GLM-5.2',
+ cost: {
+ inputPerMtok: 1.4,
+ outputPerMtok: 4.4,
+ },
+ costMultiplier: '≈0.57×',
+ costSummary: 'Input $1.40 · Output $4.40 per 1M tokens',
+ retired: true,
+ },
{
id: 'zai-org/glm-5.3',
runtimeAdapter: 'claude',