:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): run cloud Codex tasks on your own ChatGPT plan (#97543)
Shy Alter247b9b1ad96a
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 520e91c31ab9..4931a18b2575 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4857,6 +4857,61 @@ export interface PaginatedUserGitHubIntegrationListResponseListApi {results: UserGitHubIntegrationListResponseApi[]}+/**+ * * `connected` - Connected+ * * `reauth_required` - Reauth Required+ * * `not_connected` - Not Connected+ */+export type CodexIntegrationStatusEnumApi =+ (typeof CodexIntegrationStatusEnumApi)[keyof typeof CodexIntegrationStatusEnumApi]++export const CodexIntegrationStatusEnumApi = {+ Connected: 'connected',+ ReauthRequired: 'reauth_required',+ NotConnected: 'not_connected',+} as const++export interface UserCodexIntegrationApi {+ /** `connected` when cloud runs can use the account; `reauth_required` when OpenAI rejected the refresh token and the user must log in and connect again; `not_connected` when no account is connected.+ *+ * * `connected` - Connected+ * * `reauth_required` - Reauth Required+ * * `not_connected` - Not Connected */+ status: CodexIntegrationStatusEnumApi+ /**+ * The ChatGPT plan type OpenAI reports for the account.+ * @nullable+ */+ plan_type?: string | null+ /**+ * The email of the connected ChatGPT account.+ * @nullable+ */+ email?: string | null+ /**+ * When the account was connected.+ * @nullable+ */+ connected_at?: string | null+}++export interface UserCodexAuthTokensApi {+ /** The ChatGPT access token (a JWT) from the `tokens` object of the Codex `auth.json`. */+ access_token: string+ /** The single-use ChatGPT refresh token from the same `tokens` object. */+ refresh_token: string+ /**+ * The OpenID id token from the same `tokens` object, when present. Used to read the account email.+ * @nullable+ */+ id_token?: string | null+}++export interface UserCodexConnectRequestApi {+ /** The `tokens` object of the `auth.json` that `codex login` wrote. PostHog refreshes the chain once, stores the rotated tokens, and refreshes them for cloud runs from then on. */+ tokens: UserCodexAuthTokensApi+}+export interface GitHubBranchesResponseApi {/** List of branch names */branches: string[]diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 5f77adcec07f..9c6e8af16a25 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -93,6 +93,8 @@ import type {UploadedMediaUploadStartedApi,UserApi,UserAuthSessionApi,+ UserCodexConnectRequestApi,+ UserCodexIntegrationApi,UserGitHubLinkStartRequestApi,UserGitHubLinkStartResponseApi,UserGitHubPrepareCallbackRequestApi,@@ -2767,6 +2769,60 @@ export const usersIntegrationsList = async (})}+export const getUsersIntegrationsCodexRetrieveUrl = (uuid: string) => {+ return `/api/users/${uuid}/integrations/codex/`+}++/**+ * `/api/users/@me/integrations/` — manage the user's personal GitHub integrations.+ * @summary Show the ChatGPT account connected for Codex cloud tasks+ */+export const usersIntegrationsCodexRetrieve = async (+ uuid: string,+ options?: RequestInit+): Promise<UserCodexIntegrationApi> => {+ return apiMutator<UserCodexIntegrationApi>(getUsersIntegrationsCodexRetrieveUrl(uuid), {+ ...options,+ method: 'GET',+ })+}++export const getUsersIntegrationsCodexCreateUrl = (uuid: string) => {+ return `/api/users/${uuid}/integrations/codex/`+}++/**+ * Submit the `tokens` object of the `auth.json` that `codex login` wrote on the user's machine. PostHog refreshes the chain once to prove it works, stores the rotated tokens encrypted, and from then on refreshes them for the user's Codex cloud runs. Only the owning user can connect. No response carries a token.+ * @summary Connect a ChatGPT account for Codex cloud tasks+ */+export const usersIntegrationsCodexCreate = async (+ uuid: string,+ userCodexConnectRequestApi: UserCodexConnectRequestApi,+ options?: RequestInit+): Promise<UserCodexIntegrationApi> => {+ return apiMutator<UserCodexIntegrationApi>(getUsersIntegrationsCodexCreateUrl(uuid), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(userCodexConnectRequestApi),+ })+}++export const getUsersIntegrationsCodexDestroyUrl = (uuid: string) => {+ return `/api/users/${uuid}/integrations/codex/`+}++/**+ * Revokes the refresh token at OpenAI and deletes the stored tokens. Idempotent.+ * @summary Disconnect the ChatGPT account used for Codex cloud tasks+ */+export const usersIntegrationsCodexDestroy = async (uuid: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getUsersIntegrationsCodexDestroyUrl(uuid), {+ ...options,+ method: 'DELETE',+ })+}+export const getUsersIntegrationsGithubDestroyUrl = (uuid: string, installationId: string) => {return `/api/users/${uuid}/integrations/github/${installationId}/`}diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex e224d2d32324..11c6db357838 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -1420,6 +1420,29 @@ export const UsersHedgehogConfigPartialUpdateBody = /* @__PURE__ */ zod.object({),})+/**+ * Submit the `tokens` object of the `auth.json` that `codex login` wrote on the user's machine. PostHog refreshes the chain once to prove it works, stores the rotated tokens encrypted, and from then on refreshes them for the user's Codex cloud runs. Only the owning user can connect. No response carries a token.+ * @summary Connect a ChatGPT account for Codex cloud tasks+ */+export const UsersIntegrationsCodexCreateBody = /* @__PURE__ */ zod.object({+ tokens: zod+ .object({+ access_token: zod+ .string()+ .describe('The ChatGPT access token (a JWT) from the `tokens` object of the Codex `auth.json`.'),+ refresh_token: zod.string().describe('The single-use ChatGPT refresh token from the same `tokens` object.'),+ id_token: zod+ .string()+ .nullish()+ .describe(+ 'The OpenID id token from the same `tokens` object, when present. Used to read the account email.'+ ),+ })+ .describe(+ 'The `tokens` object of the `auth.json` that `codex login` wrote. PostHog refreshes the chain once, stores the rotated tokens, and refreshes them for cloud runs from then on.'+ ),+})+/*** Seed personal GitHub manage callback state before opening installation settings on GitHub.*/diff --git a/posthog/admin/admins/integration_admin.py b/posthog/admin/admins/integration_admin.pyindex 8bacf3f06259..d2f77dcf4962 100644--- a/posthog/admin/admins/integration_admin.py+++ b/posthog/admin/admins/integration_admin.py@@ -51,6 +51,7 @@ class UserIntegrationAdmin(admin.ModelAdmin):search_fields = ("id", "integration_id", "user__email", "user__first_name", "user__last_name", "config")ordering = ("-created_at",)readonly_fields = ("id", "user", "created_at", "updated_at")+ exclude = ("sensitive_config",)@admin.register(OrganizationIntegration)diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex df55d11054fd..d7cc2f18ed9e 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -1,14 +1,22 @@+import jsonimport time+import uuid+import base64+from datetime import timedeltafrom typing import Anyfrom urllib.parse import parse_qs, urlencode, urlparsefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.core.cache import cachefrom django.test import override_settings+from django.utils import timezone+import requestsfrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.test import APIClientfrom posthog.api.github_callback.state import (load_authorize_state,@@ -23,6 +31,7 @@ from posthog.models.integration import (GitHubUserAuthorization,Integration,)+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.user_integration import (GitHubInstallRequest,ReauthorizationRequired,@@ -30,6 +39,7 @@ from posthog.models.user_integration import (UserIntegration,user_github_integration_from_installation,)+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEVdef _authorization(gh_id: int = 99, gh_login: str = "octocat") -> GitHubUserAuthorization:@@ -70,6 +80,30 @@ def _create_user_integration(user: User, **overrides) -> UserIntegration:return UserIntegration.objects.create(user=user, **defaults)+def _codex_jwt(claims: dict[str, Any]) -> str:+ def segment(value: dict[str, Any]) -> str:+ return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")++ return f"{segment({'alg': 'RS256'})}.{segment(claims)}.c2lnbmF0dXJl"+++def _codex_access_token() -> str:+ return _codex_jwt(+ {+ "exp": int(time.time()) + 3600,+ "https://api.openai.com/auth": {"chatgpt_account_id": "acct_1", "chatgpt_plan_type": "plus"},+ }+ )+++def _codex_refresh_body(refresh_token: str) -> dict[str, Any]:+ return {+ "access_token": _codex_access_token(),+ "refresh_token": refresh_token,+ "id_token": _codex_jwt({"email": "[email protected]"}),+ }++class TestUserIntegrationEndpoints(APIBaseTest):def test_list_returns_empty_when_no_integrations(self):response = self.client.get("/api/users/@me/integrations/")@@ -1632,3 +1666,167 @@ class TestUserIntegrationSlackEndpoints(APIBaseTest):format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class TestUserIntegrationCodexEndpoints(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag = patch("posthog.api.user_integration_codex.posthoganalytics.feature_enabled", return_value=True)+ self.flag_enabled = flag.start()+ self.addCleanup(flag.stop)+ cache.clear()++ def _sandbox_client(self) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Task sandbox",+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_sandbox_{uuid.uuid4().hex}",+ expires=timezone.now() + timedelta(hours=1),+ scope="user:read user:write",+ sandbox_task_id=uuid.uuid4(),+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.token}")+ return client++ def _openai_response(self, status_code: int, body: dict[str, Any]) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ return response++ def _connect(self) -> Any:+ with patch("requests.request", return_value=self._openai_response(200, _codex_refresh_body("rt_rotated"))):+ return self.client.post(+ "/api/users/@me/integrations/codex/",+ {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_submitted"}},+ format="json",+ )++ def test_codex_status_is_not_connected_before_connect(self):+ response = self.client.get("/api/users/@me/integrations/codex/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"status": "not_connected", "plan_type": None, "email": None, "connected_at": None}++ def test_connect_stores_the_chain_and_never_returns_a_token(self):+ response = self._connect()++ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["status"] == "connected"+ assert body["plan_type"] == "plus"+ assert "rt_" not in response.content.decode()+ assert "eyJ" not in response.content.decode()+ row = UserIntegration.objects.get(user=self.user, kind="codex")+ assert row.sensitive_config["refresh_token"] == "rt_rotated"+ assert self.client.get("/api/users/@me/integrations/codex/").json()["status"] == "connected"++ @parameterized.expand(+ [+ ("api_key_file", {"auth_mode": "apikey", "OPENAI_API_KEY": "sk-test"}, None),+ ("rejected_by_openai", None, (400, {"error": "invalid_grant"})),+ ]+ )+ def test_connect_rejects_an_unusable_credential_and_stores_nothing(self, _name, body, openai):+ payload = body or {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_dead"}}+ with patch("requests.request", return_value=self._openai_response(*openai) if openai else None):+ response = self.client.post("/api/users/@me/integrations/codex/", payload, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "tokens"+ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()++ def test_connect_reports_an_unreachable_openai_as_a_gateway_error(self):+ with patch("requests.request", side_effect=requests.ConnectionError("down")):+ response = self.client.post(+ "/api/users/@me/integrations/codex/",+ {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_submitted"}},+ format="json",+ )++ assert response.status_code == status.HTTP_502_BAD_GATEWAY+ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()++ def test_destroy_revokes_and_forgets_the_account(self):+ self._connect()++ with patch("requests.request", return_value=self._openai_response(200, {})) as request:+ response = self.client.delete("/api/users/@me/integrations/codex/")++ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert request.call_args.kwargs["json"]["token"] == "rt_rotated"+ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()+ assert self.client.delete("/api/users/@me/integrations/codex/").status_code == status.HTTP_204_NO_CONTENT++ @parameterized.expand([("connect", "post"), ("disconnect", "delete")])+ def test_sandbox_token_cannot_change_the_connection(self, _name, method):+ self._connect()++ with patch("requests.request") as request:+ response = getattr(self._sandbox_client(), method)(+ "/api/users/@me/integrations/codex/",+ {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_attacker"}},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ request.assert_not_called()+ assert (+ UserIntegration.objects.get(user=self.user, kind="codex").sensitive_config["refresh_token"] == "rt_rotated"+ )++ @parameterized.expand([("flag_off", False, None), ("flag_check_failed", None, RuntimeError("down"))])+ def test_connect_is_unavailable_without_the_flag(self, _name, enabled, error):+ self.flag_enabled.return_value = enabled+ self.flag_enabled.side_effect = error++ with patch("requests.request") as request:+ response = self.client.post(+ "/api/users/@me/integrations/codex/",+ {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_submitted"}},+ format="json",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+ request.assert_not_called()+ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()++ def test_connect_is_throttled_per_user(self):+ for _ in range(10):+ assert self._connect().status_code == status.HTTP_200_OK++ with patch("requests.request") as request:+ response = self.client.post(+ "/api/users/@me/integrations/codex/",+ {"tokens": {"access_token": _codex_access_token(), "refresh_token": "rt_submitted"}},+ format="json",+ )++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ request.assert_not_called()+ assert self.client.delete("/api/users/@me/integrations/codex/").status_code == status.HTTP_204_NO_CONTENT++ def test_another_user_cannot_read_or_remove_the_connection(self):+ self._connect()+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.force_login(other)++ assert (+ self.client.get(f"/api/users/{self.user.uuid}/integrations/codex/").status_code == status.HTTP_403_FORBIDDEN+ )+ assert (+ self.client.delete(f"/api/users/{self.user.uuid}/integrations/codex/").status_code+ == status.HTTP_403_FORBIDDEN+ )+ assert UserIntegration.objects.filter(user=self.user, kind="codex").exists()diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex 13db33a4c522..f92087f82af2 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -23,6 +23,7 @@ from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import BaseThrottlefrom posthog.api.github_callback import state as github_callback_statefrom posthog.api.github_callback.personal_state import list_user_github_app_installations@@ -45,6 +46,16 @@ from posthog.api.integration import (github_rate_limited_response,validate_github_repository_name,)+from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.user_integration_codex import (+ UserCodexConnectRequestSerializer,+ UserCodexIntegrationSerializer,+ connect_codex_integration,+ disconnect_codex_integration,+ ensure_codex_connect_enabled,+ ensure_not_sandbox_request,+ get_codex_integration,+)from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.exceptions_capture import capture_exception@@ -53,7 +64,7 @@ from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import Userfrom posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegrationfrom posthog.permissions import APIScopePermission, TimeSensitiveActionPermission-from posthog.rate_limit import UserAuthenticationThrottle+from posthog.rate_limit import CodexConnectUserThrottle, UserAuthenticationThrottlefrom posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled@@ -287,6 +298,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"github_branches","github_install_requests","slack_linkable",+ "codex",]scope_object_write_actions = ["create",@@ -301,6 +313,8 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"github_install_requests_destroy","slack_start","slack_destroy",+ "codex_connect",+ "codex_destroy",]authentication_classes = [OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication]@@ -310,6 +324,12 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):http_method_names = ["get", "post", "delete"]serializer_class = UserGitHubIntegrationItemSerializer+ def get_throttles(self) -> list[BaseThrottle]:+ throttles = super().get_throttles()+ if self.action == "codex_connect":+ throttles.append(CodexConnectUserThrottle())+ return throttles+def handle_exception(self, exc: Exception) -> Response:# Personal-GitHub actions (repos, branches, refresh) raise the same egress# GitHubRateLimitError as the team integration endpoints — same 429 mapping.@@ -838,6 +858,53 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):integration.delete()return Response(status=status.HTTP_204_NO_CONTENT)+ @extend_schema(+ summary="Show the ChatGPT account connected for Codex cloud tasks",+ responses={200: UserCodexIntegrationSerializer},+ )+ @action(methods=["GET"], detail=False, url_path="codex")+ def codex(self, request: Request, **_kwargs) -> Response:+ user = self._get_user()+ return Response(get_codex_integration(user))++ @validated_request(+ request_serializer=UserCodexConnectRequestSerializer,+ responses={+ 200: OpenApiResponse(response=UserCodexIntegrationSerializer, description="The account is connected."),+ 400: OpenApiResponse(description="The tokens are not usable, or OpenAI rejected the refresh token."),+ 403: OpenApiResponse(description="A cloud task sandbox token cannot connect an account."),+ 404: OpenApiResponse(description="ChatGPT plans for cloud tasks are not available to this user."),+ 502: OpenApiResponse(description="OpenAI could not be reached."),+ },+ summary="Connect a ChatGPT account for Codex cloud tasks",+ description=(+ "Submit the `tokens` object of the `auth.json` that `codex login` wrote on the user's machine. PostHog "+ "refreshes the chain once to prove it works, stores the rotated tokens encrypted, and from then on "+ "refreshes them for the user's Codex cloud runs. Only the owning user can connect. No response carries "+ "a token."+ ),+ )+ @codex.mapping.post+ def codex_connect(self, request: ValidatedRequest, **_kwargs) -> Response:+ ensure_not_sandbox_request(request)+ user = self._get_user()+ ensure_codex_connect_enabled(user)+ return connect_codex_integration(user, request.validated_data)++ @extend_schema(+ summary="Disconnect the ChatGPT account used for Codex cloud tasks",+ description="Revokes the refresh token at OpenAI and deletes the stored tokens. Idempotent.",+ responses={+ 204: OpenApiResponse(description="No account is connected any more."),+ 403: OpenApiResponse(description="A cloud task sandbox token cannot disconnect an account."),+ },+ )+ @codex.mapping.delete+ def codex_destroy(self, request: Request, **_kwargs) -> Response:+ ensure_not_sandbox_request(request)+ user = self._get_user()+ return disconnect_codex_integration(user)+def _resolve_team_for_github_start(user: User, request: Request):"""Resolve which team to use for team-level GitHub install discovery.diff --git a/posthog/api/user_integration_codex.py b/posthog/api/user_integration_codex.pynew file mode 100644index 000000000000..40e25893003d--- /dev/null+++ b/posthog/api/user_integration_codex.py@@ -0,0 +1,132 @@+import posthoganalytics+from rest_framework import exceptions, serializers, status+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.event_usage import report_user_action+from posthog.exceptions_capture import capture_exception+from posthog.models.integration.codex import (+ STATUS_NOT_CONNECTED,+ CodexAuthError,+ CodexIntegrationStatus,+ CodexReauthRequired,+ CodexUserIntegration,+ parse_codex_auth_json,+)+from posthog.models.user import User+from posthog.oauth_provenance import is_sandbox_oauth_request++from products.tasks.backend.facade.api import CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG+++class UserCodexAuthTokensSerializer(serializers.Serializer):+ access_token = serializers.CharField(+ write_only=True, help_text="The ChatGPT access token (a JWT) from the `tokens` object of the Codex `auth.json`."+ )+ refresh_token = serializers.CharField(+ write_only=True, help_text="The single-use ChatGPT refresh token from the same `tokens` object."+ )+ id_token = serializers.CharField(+ write_only=True,+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="The OpenID id token from the same `tokens` object, when present. Used to read the account email.",+ )+++class UserCodexConnectRequestSerializer(serializers.Serializer):+ tokens = UserCodexAuthTokensSerializer(+ help_text=(+ "The `tokens` object of the `auth.json` that `codex login` wrote. PostHog refreshes the chain once, "+ "stores the rotated tokens, and refreshes them for cloud runs from then on."+ )+ )+++class UserCodexIntegrationSerializer(serializers.Serializer):+ status = serializers.ChoiceField(+ choices=CodexIntegrationStatus.choices,+ help_text=(+ "`connected` when cloud runs can use the account; `reauth_required` when OpenAI rejected the refresh "+ "token and the user must log in and connect again; `not_connected` when no account is connected."+ ),+ )+ plan_type = serializers.CharField(+ required=False, allow_null=True, help_text="The ChatGPT plan type OpenAI reports for the account."+ )+ email = serializers.EmailField(+ required=False, allow_null=True, help_text="The email of the connected ChatGPT account."+ )+ connected_at = serializers.DateTimeField(+ required=False, allow_null=True, help_text="When the account was connected."+ )+++class OpenAIUnavailable(exceptions.APIException):+ status_code = status.HTTP_502_BAD_GATEWAY+ default_code = "openai_unavailable"+++def serialize_codex_integration(integration: CodexUserIntegration | None) -> dict[str, str | None]:+ if integration is None:+ return {"status": STATUS_NOT_CONNECTED, "plan_type": None, "email": None, "connected_at": None}+ return {+ "status": integration.status,+ "plan_type": integration.plan_type,+ "email": integration.email,+ "connected_at": integration.connected_at,+ }+++def ensure_not_sandbox_request(request: Request) -> None:+ if is_sandbox_oauth_request(request):+ raise exceptions.PermissionDenied("Cloud tasks cannot change the connected ChatGPT account.")+++def ensure_codex_connect_enabled(user: User) -> None:+ organization_id = str(user.current_organization_id)+ try:+ enabled = posthoganalytics.feature_enabled(+ CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ str(user.distinct_id),+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception as error:+ capture_exception(error)+ enabled = False+ if not enabled:+ raise exceptions.NotFound()+++def get_codex_integration(user: User) -> dict[str, str | None]:+ return serialize_codex_integration(CodexUserIntegration.for_user(user.id))+++def connect_codex_integration(user: User, data: object) -> Response:+ try:+ tokens = parse_codex_auth_json(data)+ except CodexAuthError as error:+ raise exceptions.ValidationError({"tokens": str(error)})+ try:+ integration = CodexUserIntegration.connect(user.id, tokens, source="user_integration_api")+ except CodexReauthRequired as error:+ report_user_action(user, "codex subscription connect failed", {"reason": "rejected_by_openai"})+ raise exceptions.ValidationError({"tokens": str(error)})+ except CodexAuthError as error:+ report_user_action(user, "codex subscription connect failed", {"reason": "openai_unreachable"})+ capture_exception(error)+ raise OpenAIUnavailable(str(error))+ report_user_action(user, "codex subscription connected", {"plan_type": integration.plan_type})+ return Response(serialize_codex_integration(integration))+++def disconnect_codex_integration(user: User) -> Response:+ integration = CodexUserIntegration.for_user(user.id)+ if integration is not None:+ integration.disconnect(source="user_integration_api")+ report_user_action(user, "codex subscription disconnected", {})+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/posthog/egress/openai_auth/README.md b/posthog/egress/openai_auth/README.mdnew file mode 100644index 000000000000..9cbd6437a373--- /dev/null+++ b/posthog/egress/openai_auth/README.md@@ -0,0 +1,37 @@+# OpenAI auth egress++Calls to the OpenAI auth server that refreshes and revokes ChatGPT OAuth tokens for the Codex CLI client.++## Identity++The constant scope `codex-client`.+Every request uses the one public Codex CLI OAuth client id, so there is no per-account identity to budget.+A per-user scope would put one label value per connected ChatGPT account on the counter.++## Budget++None: calls are recorded, never gated (`RecordedEgressClient`).+OpenAI documents no request limit for the OAuth token endpoint.+Add a gate only if OpenAI publishes a request limit for it.++## Lanes and callers++No lanes, because nothing is gated.+`posthog/models/integration/codex.py` is the caller.+It refreshes once when a user connects, once per cloud task run start when the access token is near expiry, and once more on demand when the Codex app-server reports a 401.+It revokes the refresh token when the user disconnects.++## Rate-limit headers++None documented, so the domain declares no gauges.+The counter is `openai_auth_api_requests_total`, labeled `scope, method, endpoint, status_code, source`.++## Auth++The refresh token of the connected ChatGPT account, sent in the request body with the public Codex client id.+No PostHog-owned credential.++## Sources++- The vendored Codex CLI binary (`@openai/codex`, `login/src/auth/manager.rs`): the token endpoint is `https://auth.openai.com/oauth/token`, the revoke endpoint is `https://auth.openai.com/oauth/revoke`, and the client id is `app_EMoamEEZ73f0CkXaXp7hrann`. The binary's refresh error messages name three permanent failures: an expired, an already used, and a revoked refresh token.+- [openai/codex login crate](https://github.com/openai/codex/tree/main/codex-rs/login): the refresh request is a JSON body with `client_id`, `grant_type=refresh_token`, `refresh_token` and `scope=openid profile email`; the response carries `id_token`, `access_token` and `refresh_token`. Unverified: the docs publish no request limit and no rate-limit header for this endpoint.diff --git a/posthog/egress/openai_auth/__init__.py b/posthog/egress/openai_auth/__init__.pynew file mode 100644index 000000000000..135a337f04f2--- /dev/null+++ b/posthog/egress/openai_auth/__init__.py@@ -0,0 +1,3 @@+from posthog.egress.openai_auth.transport import OPENAI_OAUTH_REVOKE_URL, OPENAI_OAUTH_TOKEN_URL, openai_auth_request++__all__ = ["OPENAI_OAUTH_REVOKE_URL", "OPENAI_OAUTH_TOKEN_URL", "openai_auth_request"]diff --git a/posthog/egress/openai_auth/observability.py b/posthog/egress/openai_auth/observability.pynew file mode 100644index 000000000000..04d9f35db8c9--- /dev/null+++ b/posthog/egress/openai_auth/observability.py@@ -0,0 +1,18 @@+"""OpenAI auth (ChatGPT OAuth) outbound request telemetry.++The token endpoint documents no rate-limit headers, so this domain declares no gauges.+"""++from prometheus_client import Counter++from posthog.egress.observability.observability import EgressMetrics, EgressObservability++openai_auth_egress = EgressObservability(+ EgressMetrics(+ request_counter=Counter(+ "openai_auth_api_requests",+ "Outbound OpenAI auth (ChatGPT OAuth token and revoke) requests.",+ labelnames=["scope", "method", "endpoint", "status_code", "source"],+ ),+ )+)diff --git a/posthog/egress/openai_auth/transport.py b/posthog/egress/openai_auth/transport.pynew file mode 100644index 000000000000..b93871245ee5--- /dev/null+++ b/posthog/egress/openai_auth/transport.py@@ -0,0 +1,49 @@+"""Recorded transport for the OpenAI auth server that issues ChatGPT OAuth tokens.++OpenAI publishes no request limit for its OAuth token endpoint, so these calls are recorded but not+gated. A refresh token is single use, so a caller never retries a refresh on its own; it reports the+failure and lets the user reconnect.+"""++from typing import Any++import requests++from posthog.egress.openai_auth.observability import openai_auth_egress+from posthog.egress.transport.transport import RecordedEgressClient++OPENAI_OAUTH_TOKEN_URL = "https://auth.openai.com/oauth/token"+OPENAI_OAUTH_REVOKE_URL = "https://auth.openai.com/oauth/revoke"+++class OpenAIAuthClient(RecordedEgressClient):+ observability = openai_auth_egress++ def _standard_headers(self) -> dict[str, str]:+ return {"Accept": "application/json"}+++_openai_auth_client = OpenAIAuthClient()+++def openai_auth_request(+ method: str,+ url: str,+ *,+ source: str,+ endpoint: str,+ timeout: float | tuple[float, float] | None = None,+ session: requests.Session | None = None,+ **kwargs: Any,+) -> requests.Response:+ # Every call goes out under the one Codex OAuth client id, so the identity is constant.+ return _openai_auth_client.request(+ method,+ url,+ source=source,+ scope="codex-client",+ endpoint=endpoint,+ timeout=timeout,+ session=session,+ **kwargs,+ )diff --git a/posthog/egress/test/test_openai_auth_transport.py b/posthog/egress/test/test_openai_auth_transport.pynew file mode 100644index 000000000000..70cd37531fcc--- /dev/null+++ b/posthog/egress/test/test_openai_auth_transport.py@@ -0,0 +1,49 @@+from unittest.mock import patch++from django.test import SimpleTestCase++import requests+from prometheus_client import REGISTRY++from posthog.egress.openai_auth.transport import OPENAI_OAUTH_TOKEN_URL, openai_auth_request+++def _openai_auth_samples() -> list:+ return [+ sample+ for metric in REGISTRY.collect()+ if metric.name.startswith("openai_auth_api")+ for sample in metric.samples+ ]+++def _request_count(status_code: str = "200") -> float:+ labels = {+ "scope": "codex-client",+ "method": "POST",+ "endpoint": "oauth/token",+ "status_code": status_code,+ "source": "test",+ }+ return REGISTRY.get_sample_value("openai_auth_api_requests_total", labels) or 0+++class TestOpenAIAuthTransport(SimpleTestCase):+ def test_request_is_recorded_under_the_constant_client_scope(self) -> None:+ response = requests.Response()+ response.status_code = 200+ before = _request_count()++ with patch("requests.request", return_value=response) as request:+ openai_auth_request(+ "POST",+ OPENAI_OAUTH_TOKEN_URL,+ source="test",+ endpoint="oauth/token",+ json={"refresh_token": "rt_secret", "grant_type": "refresh_token"},+ )++ assert request.call_args.kwargs["json"]["refresh_token"] == "rt_secret"+ assert request.call_args.kwargs["headers"]["Accept"] == "application/json"+ assert _request_count() == before + 1+ assert not any("rt_secret" in value for sample in _openai_auth_samples() for value in sample.labels.values())diff --git a/posthog/migrations/1379_userintegration_kind_callable_choices.py b/posthog/migrations/1379_userintegration_kind_callable_choices.pynew file mode 100644index 000000000000..ff1b364cd5fd--- /dev/null+++ b/posthog/migrations/1379_userintegration_kind_callable_choices.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-18 15:27++from django.db import migrations, models++import posthog.models.user_integration+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1378_expand_file_system_shortcut_ref"),+ ]++ operations = [+ migrations.AlterField(+ model_name="userintegration",+ name="kind",+ field=models.CharField(+ choices=posthog.models.user_integration.user_integration_kind_choices, max_length=32+ ),+ ),+ ]diff --git a/posthog/migrations/1380_unique_codex_user_integration.py b/posthog/migrations/1380_unique_codex_user_integration.pynew file mode 100644index 000000000000..8e727d5b667b--- /dev/null+++ b/posthog/migrations/1380_unique_codex_user_integration.py@@ -0,0 +1,28 @@+# Generated by Django 5.2.17 on 2026-09-22 16:09++from django.db import migrations, models+from django.db.backends.base.schema import BaseDatabaseSchemaEditor+from django.db.migrations.state import StateApps+++def require_unique_codex_accounts(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:+ integrations = apps.get_model("posthog", "UserIntegration")+ duplicates = (+ integrations.objects.using(schema_editor.connection.alias)+ .filter(kind="codex")+ .values("user_id")+ .annotate(account_count=models.Count("id"))+ .filter(account_count__gt=1)+ )+ if duplicates.exists():+ raise RuntimeError("Resolve duplicate Codex account records before applying this migration.")+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1379_userintegration_kind_callable_choices"),+ ]++ operations = [+ migrations.RunPython(require_unique_codex_accounts, migrations.RunPython.noop),+ ]diff --git a/posthog/migrations/1381_codex_user_integration_unique_index.py b/posthog/migrations/1381_codex_user_integration_unique_index.pynew file mode 100644index 000000000000..51e60bfacf15--- /dev/null+++ b/posthog/migrations/1381_codex_user_integration_unique_index.py@@ -0,0 +1,35 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("posthog", "1380_unique_codex_user_integration"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddConstraint(+ model_name="userintegration",+ constraint=models.UniqueConstraint(+ condition=models.Q(kind="codex"),+ fields=("user",),+ name="unique_codex_user_integration",+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="unique_codex_user_integration",+ table_name="posthog_user_integration",+ columns='("user_id")',+ unique=True,+ where="WHERE kind = 'codex'",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 37b094e57848..4ef2ce7ca55f 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1378_expand_file_system_shortcut_ref+1381_codex_user_integration_unique_indexdiff --git a/posthog/models/integration/codex.py b/posthog/models/integration/codex.pynew file mode 100644index 000000000000..d77467b18cba--- /dev/null+++ b/posthog/models/integration/codex.py@@ -0,0 +1,415 @@+"""ChatGPT plan credentials for Codex cloud tasks.++The user logs in once on their own machine with the Codex CLI. Desktop submits the `auth.json` that+the login wrote. From then on this module owns the refresh chain: it stores the tokens on the user's+`UserIntegration` row (kind=codex), refreshes the access token with the single-use refresh token, and+hands the access token to each cloud run. An access token can stay valid for several days, so a run can+keep it after the run ends. No route ever returns the refresh token.+"""++import json+import base64+import hashlib+from dataclasses import field+from datetime import UTC, datetime, timedelta+from typing import Any++from django.db import connection, models, transaction+from django.utils import timezone++import requests+import structlog++from posthog.dataclasses import frozen+from posthog.egress.openai_auth import OPENAI_OAUTH_REVOKE_URL, OPENAI_OAUTH_TOKEN_URL, openai_auth_request+from posthog.exceptions_capture import capture_exception+from posthog.models.user_integration import UserIntegration++logger = structlog.get_logger(__name__)++# The public OAuth client id of the Codex CLI. The tokens Desktop submits were issued to it, so refresh+# and revoke must name it too.+CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"+CODEX_OAUTH_SCOPE = "openid profile email"+OPENAI_AUTH_TIMEOUT_SECONDS = 15.0+# Refresh a little before the token expires so a run never starts with a token about to die.+ACCESS_TOKEN_REFRESH_MARGIN = timedelta(minutes=5)+# Codex access tokens carry `exp`; this is only the fallback when a token has none or one out of range.+DEFAULT_ACCESS_TOKEN_LIFETIME = timedelta(hours=1)+# OpenAI answers a rate-limited or timed-out refresh with these; the chain is still alive.+TRANSIENT_REFRESH_STATUS_CODES = frozenset({408, 425, 429})++CODEX_AUTH_CLAIM = "https://api.openai.com/auth"+CODEX_PROFILE_CLAIM = "https://api.openai.com/profile"+++class CodexIntegrationStatus(models.TextChoices):+ CONNECTED = "connected"+ REAUTH_REQUIRED = "reauth_required"+ NOT_CONNECTED = "not_connected"+++STATUS_CONNECTED = CodexIntegrationStatus.CONNECTED.value+STATUS_REAUTH_REQUIRED = CodexIntegrationStatus.REAUTH_REQUIRED.value+STATUS_NOT_CONNECTED = CodexIntegrationStatus.NOT_CONNECTED.value+++class CodexAuthError(Exception):+ """The submitted credential is not usable, or OpenAI could not be reached."""+++class CodexReauthRequired(CodexAuthError):+ """The refresh chain is dead. The user must log in again and reconnect."""+++@frozen+class CodexTokens:+ access_token: str = field(repr=False)+ refresh_token: str = field(repr=False)+ account_id: str+ plan_type: str | None+ email: str | None+ expires_at: datetime+++@frozen+class CodexAccessGrant:+ """What a cloud run gets: enough to sign in the Codex app-server, and nothing that lasts."""++ access_token: str = field(repr=False)+ account_id: str+ plan_type: str | None+ expires_at: datetime+ refreshed: bool+++def access_token_fingerprint(access_token: str) -> str:+ """The SHA-256 hex digest a run sends back to name the token Codex rejected, so the token itself never travels twice."""+ return hashlib.sha256(access_token.encode()).hexdigest()+++def decode_jwt_claims(token: str) -> dict[str, Any]:+ """Read the claims of a JWT without checking its signature. OpenAI verifies the token; we only read ids."""+ parts = token.split(".")+ if len(parts) != 3:+ raise CodexAuthError("The access token is not a JWT.")+ payload = parts[1]+ try:+ raw = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))+ claims = json.loads(raw)+ except (ValueError, UnicodeDecodeError) as error:+ raise CodexAuthError("The access token claims could not be decoded.") from error+ if not isinstance(claims, dict):+ raise CodexAuthError("The access token claims are not an object.")+ return claims+++def _optional_str(value: object) -> str | None:+ return value if isinstance(value, str) and value else None+++def _tokens_from_parts(access_token: str, refresh_token: str, id_token: str | None) -> CodexTokens:+ claims = decode_jwt_claims(access_token)+ auth_claims = claims.get(CODEX_AUTH_CLAIM)+ if not isinstance(auth_claims, dict):+ auth_claims = {}+ account_id = _optional_str(auth_claims.get("chatgpt_account_id"))+ if account_id is None:+ raise CodexAuthError("The access token has no ChatGPT account id.")+ expires_at = timezone.now() + DEFAULT_ACCESS_TOKEN_LIFETIME+ exp = claims.get("exp")+ if isinstance(exp, int | float) and not isinstance(exp, bool):+ try:+ expires_at = datetime.fromtimestamp(exp, tz=UTC)+ except (OverflowError, OSError, ValueError):+ pass++ email = None+ if id_token:+ try:+ email = _optional_str(decode_jwt_claims(id_token).get("email"))+ except CodexAuthError:+ pass+ if email is None:+ profile = claims.get(CODEX_PROFILE_CLAIM)+ if isinstance(profile, dict):+ email = _optional_str(profile.get("email"))++ return CodexTokens(+ access_token=access_token,+ refresh_token=refresh_token,+ account_id=account_id,+ plan_type=_optional_str(auth_claims.get("chatgpt_plan_type")),+ email=email,+ expires_at=expires_at,+ )+++def parse_codex_auth_json(raw: object) -> CodexTokens:+ """Read the `auth.json` that `codex login` writes: `{"tokens": {"access_token", "refresh_token", "id_token", ...}}`."""+ if not isinstance(raw, dict):+ raise CodexAuthError("The auth file is not a JSON object.")+ tokens = raw.get("tokens")+ if not isinstance(tokens, dict):+ raise CodexAuthError("The auth file has no tokens. Log in with ChatGPT, not with an API key.")+ access_token = _optional_str(tokens.get("access_token"))+ refresh_token = _optional_str(tokens.get("refresh_token"))+ if access_token is None or refresh_token is None:+ raise CodexAuthError("The auth file has no access token or no refresh token.")+ return _tokens_from_parts(access_token, refresh_token, _optional_str(tokens.get("id_token")))+++def _refresh_failure_code(response: requests.Response) -> str:+ try:+ body = response.json()+ except ValueError:+ return f"http_{response.status_code}"+ error = body.get("error") if isinstance(body, dict) else None+ if isinstance(error, dict):+ return _optional_str(error.get("code")) or _optional_str(error.get("type")) or f"http_{response.status_code}"+ return _optional_str(error) or f"http_{response.status_code}"+++def refresh_codex_tokens(refresh_token: str, *, source: str) -> CodexTokens:+ """Exchange the single-use refresh token for a new token set.++ A 4xx means the chain is dead, except the codes OpenAI uses for throttling and timeouts.+ """+ try:+ response = openai_auth_request(+ "POST",+ OPENAI_OAUTH_TOKEN_URL,+ source=source,+ endpoint="oauth/token",+ timeout=OPENAI_AUTH_TIMEOUT_SECONDS,+ json={+ "client_id": CODEX_OAUTH_CLIENT_ID,+ "grant_type": "refresh_token",+ "refresh_token": refresh_token,+ "scope": CODEX_OAUTH_SCOPE,+ },+ )+ except requests.RequestException as error:+ raise CodexAuthError("Could not reach OpenAI to refresh the ChatGPT token.") from error+ if response.status_code in TRANSIENT_REFRESH_STATUS_CODES:+ raise CodexAuthError(f"OpenAI returned {response.status_code} on refresh.")+ if 400 <= response.status_code < 500:+ code = _refresh_failure_code(response)+ raise CodexReauthRequired(f"OpenAI rejected the refresh token ({code}).")+ if not response.ok:+ raise CodexAuthError(f"OpenAI returned {response.status_code} on refresh.")+ try:+ body = response.json()+ except ValueError as error:+ raise CodexAuthError("OpenAI returned a refresh response that is not JSON.") from error+ access_token = _optional_str(body.get("access_token")) if isinstance(body, dict) else None+ if access_token is None:+ raise CodexAuthError("OpenAI returned no access token on refresh.")+ # OpenAI rotates the refresh token on every use; keep the old one only when the response has none.+ new_refresh_token = _optional_str(body.get("refresh_token")) or refresh_token+ return _tokens_from_parts(access_token, new_refresh_token, _optional_str(body.get("id_token")))+++def revoke_codex_refresh_token(refresh_token: str, *, source: str) -> None:+ """Best effort: end the device authorization the user made for PostHog. A failure is logged, not raised."""+ try:+ response = openai_auth_request(+ "POST",+ OPENAI_OAUTH_REVOKE_URL,+ source=source,+ endpoint="oauth/revoke",+ timeout=OPENAI_AUTH_TIMEOUT_SECONDS,+ json={"token": refresh_token, "token_type_hint": "refresh_token", "client_id": CODEX_OAUTH_CLIENT_ID},+ )+ except requests.RequestException as error:+ logger.warning("codex_refresh_token_revoke_failed", error=str(error))+ return+ if not response.ok:+ logger.warning("codex_refresh_token_revoke_rejected", status_code=response.status_code)+++class CodexUserIntegration:+ """The one `UserIntegration` row of kind=codex for a user."""++ KIND = UserIntegration.IntegrationKind.CODEX++ def __init__(self, integration: UserIntegration) -> None:+ self.integration = integration++ @classmethod+ def for_user(cls, user_id: int) -> "CodexUserIntegration | None":+ row = UserIntegration.objects.filter(user_id=user_id, kind=cls.KIND).first()+ return cls(row) if row is not None else None++ @classmethod+ def _lock_user(cls, user_id: int) -> None:+ # Row locks cannot protect the first connection because its record does not exist yet.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [user_id, "user_integration:codex"])++ @classmethod+ def connect(cls, user_id: int, tokens: CodexTokens, *, source: str) -> "CodexUserIntegration":+ """Store a submitted token set after one refresh.++ The refresh proves the chain is live, and it makes the server the current holder: the tokens+ in the file on the user's machine stop working by construction, whatever the client does.+ """+ with transaction.atomic():+ cls._lock_user(user_id)+ fresh = refresh_codex_tokens(tokens.refresh_token, source=source)+ now = timezone.now()+ row, _ = UserIntegration.objects.update_or_create(+ user_id=user_id,+ kind=cls.KIND,+ defaults={+ "integration_id": fresh.account_id,+ "config": {+ "plan_type": fresh.plan_type,+ "email": fresh.email,+ "status": STATUS_CONNECTED,+ "connected_at": now.isoformat(),+ "last_refreshed_at": now.isoformat(),+ },+ "sensitive_config": cls._sensitive_config(fresh),+ },+ )+ return cls(row)++ @classmethod+ def issue_access_grant(+ cls, user_id: int, *, rejected_access_token_sha256: str | None, source: str+ ) -> CodexAccessGrant:+ """The access token for a cloud run, refreshed under a row lock when expired or rejected.++ The refresh token is single use, so two runs of one user must not refresh at the same time.+ The row lock makes the second wait. A run that reports a rejected token names it by digest,+ so a token the first run already replaced is handed over as is instead of refreshed again.+ """+ reauth_error: CodexReauthRequired | None = None+ refreshed = False+ with transaction.atomic():+ cls._lock_user(user_id)+ row = UserIntegration.objects.select_for_update().filter(user_id=user_id, kind=cls.KIND).first()+ if row is None:+ raise CodexReauthRequired("No ChatGPT account is connected.")+ integration = cls(row)+ if integration.status != STATUS_CONNECTED:+ raise CodexReauthRequired("The ChatGPT account must be reconnected.")+ if integration._needs_refresh(rejected_access_token_sha256):+ try:+ integration._refresh(source=source)+ refreshed = True+ except CodexReauthRequired as error:+ integration._mark_reauth_required(str(error))+ reauth_error = error+ if reauth_error is not None:+ raise reauth_error+ return integration.access_grant(refreshed=refreshed)++ @property+ def status(self) -> str:+ return str(self.integration.config.get("status") or STATUS_REAUTH_REQUIRED)++ @property+ def plan_type(self) -> str | None:+ return _optional_str(self.integration.config.get("plan_type"))++ @property+ def email(self) -> str | None:+ return _optional_str(self.integration.config.get("email"))++ @property+ def connected_at(self) -> str | None:+ return _optional_str(self.integration.config.get("connected_at"))++ @property+ def account_id(self) -> str:+ return self.integration.integration_id++ def is_connected(self) -> bool:+ return self.status == STATUS_CONNECTED++ def access_grant(self, *, refreshed: bool) -> CodexAccessGrant:+ access_token = _optional_str(self.integration.sensitive_config.get("access_token"))+ if access_token is None:+ raise CodexReauthRequired("The ChatGPT account must be reconnected.")+ return CodexAccessGrant(+ access_token=access_token,+ account_id=self.account_id,+ plan_type=self.plan_type,+ expires_at=self._expires_at() or timezone.now(),+ refreshed=refreshed,+ )++ def _access_token_expired(self) -> bool:+ expires_at = self._expires_at()+ return expires_at is None or timezone.now() + ACCESS_TOKEN_REFRESH_MARGIN >= expires_at++ def disconnect(self, *, source: str) -> None:+ with transaction.atomic():+ self._lock_user(self.integration.user_id)+ current = self.for_user(self.integration.user_id)+ if current is None:+ return+ refresh_token = _optional_str(current.integration.sensitive_config.get("refresh_token"))+ if refresh_token is not None:+ revoke_codex_refresh_token(refresh_token, source=source)+ current.integration.delete()++ def _needs_refresh(self, rejected_access_token_sha256: str | None) -> bool:+ if self._access_token_expired():+ return True+ if rejected_access_token_sha256 is None:+ return False+ stored = _optional_str(self.integration.sensitive_config.get("access_token"))+ return stored is None or access_token_fingerprint(stored) == rejected_access_token_sha256++ def _refresh(self, *, source: str) -> None:+ refresh_token = _optional_str(self.integration.sensitive_config.get("refresh_token"))+ if refresh_token is None:+ raise CodexReauthRequired("The ChatGPT account has no refresh token.")+ try:+ fresh = refresh_codex_tokens(refresh_token, source=source)+ except CodexAuthError as error:+ if not isinstance(error, CodexReauthRequired):+ capture_exception(error)+ raise+ self.integration.sensitive_config = self._sensitive_config(fresh)+ self.integration.config = {+ **self.integration.config,+ "plan_type": fresh.plan_type or self.plan_type,+ "email": fresh.email or self.email,+ "last_refreshed_at": timezone.now().isoformat(),+ }+ self.integration.save(update_fields=["config", "sensitive_config"])++ def _mark_reauth_required(self, reason: str) -> None:+ # Drop the dead chain so nothing can retry it; keep the row so settings can show "Reconnect".+ self.integration.sensitive_config = {}+ self.integration.config = {+ **self.integration.config,+ "status": STATUS_REAUTH_REQUIRED,+ "reauth_reason": reason,+ }+ self.integration.save(update_fields=["config", "sensitive_config"])+ logger.warning("codex_subscription_reauth_required", user_id=self.integration.user_id, reason=reason)++ def _expires_at(self) -> datetime | None:+ return self._parse_datetime(self.integration.sensitive_config.get("access_token_expires_at"))++ @staticmethod+ def _parse_datetime(value: object) -> datetime | None:+ if not isinstance(value, str):+ return None+ try:+ return datetime.fromisoformat(value)+ except ValueError:+ return None++ @staticmethod+ def _sensitive_config(tokens: CodexTokens) -> dict[str, Any]:+ return {+ "access_token": tokens.access_token,+ "refresh_token": tokens.refresh_token,+ "access_token_expires_at": tokens.expires_at.isoformat(),+ }diff --git a/posthog/models/test/integration/test_codex.py b/posthog/models/test/integration/test_codex.pynew file mode 100644index 000000000000..41e1cee1857b--- /dev/null+++ b/posthog/models/test/integration/test_codex.py@@ -0,0 +1,259 @@+import json+import base64+from concurrent.futures import ThreadPoolExecutor+from dataclasses import replace+from datetime import UTC, datetime, timedelta+from threading import Barrier+from typing import Any++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import connections+from django.test import SimpleTestCase, TransactionTestCase++import requests+from parameterized import parameterized++from posthog.models.integration.codex import (+ CODEX_OAUTH_CLIENT_ID,+ STATUS_CONNECTED,+ STATUS_REAUTH_REQUIRED,+ CodexAuthError,+ CodexReauthRequired,+ CodexUserIntegration,+ access_token_fingerprint,+ parse_codex_auth_json,+)+from posthog.models.user import User+from posthog.models.user_integration import UserIntegration++FROZEN_NOW = datetime(2026, 3, 1, 12, 0, tzinfo=UTC)+++def _jwt(claims: dict[str, Any]) -> str:+ def segment(value: dict[str, Any]) -> str:+ return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")++ return f"{segment({'alg': 'RS256'})}.{segment(claims)}.c2lnbmF0dXJl"+++def _access_token(+ *, account_id: str = "acct_1", plan_type: str | None = "plus", expires_in: timedelta | None = None+) -> str:+ claims: dict[str, Any] = {"https://api.openai.com/auth": {"chatgpt_account_id": account_id}}+ if plan_type is not None:+ claims["https://api.openai.com/auth"]["chatgpt_plan_type"] = plan_type+ if expires_in is not None:+ claims["exp"] = int((FROZEN_NOW + expires_in).timestamp())+ return _jwt(claims)+++def _auth_json(+ access_token: str | None = None, *, id_token: str | None = _jwt({"email": "[email protected]"})+) -> dict[str, Any]:+ return {+ "auth_mode": "chatgpt",+ "tokens": {+ "access_token": access_token or _access_token(expires_in=timedelta(hours=1)),+ "refresh_token": "rt_submitted",+ "id_token": id_token,+ "account_id": "acct_1",+ },+ }+++def _openai_response(status_code: int, body: dict[str, Any]) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ return response+++def _refresh_ok(refresh_token: str = "rt_rotated", expires_in: timedelta = timedelta(hours=1)) -> requests.Response:+ return _openai_response(+ 200,+ {+ "access_token": _access_token(expires_in=expires_in),+ "refresh_token": refresh_token,+ "id_token": _jwt({"email": "[email protected]"}),+ },+ )+++class TestParseCodexAuthJson(SimpleTestCase):+ @time_machine.travel(FROZEN_NOW, tick=False)+ def test_reads_the_account_plan_email_and_expiry_from_the_tokens(self) -> None:+ tokens = parse_codex_auth_json(_auth_json(_access_token(expires_in=timedelta(minutes=30))))++ assert tokens.account_id == "acct_1"+ assert tokens.plan_type == "plus"+ assert tokens.email == "[email protected]"+ assert tokens.refresh_token == "rt_submitted"+ assert tokens.expires_at == FROZEN_NOW + timedelta(minutes=30)+ assert "rt_submitted" not in repr(tokens)++ @time_machine.travel(FROZEN_NOW, tick=False)+ def test_an_exp_out_of_range_falls_back_to_the_default_lifetime(self) -> None:+ claims: dict[str, Any] = {"https://api.openai.com/auth": {"chatgpt_account_id": "acct_1"}, "exp": 10**20}++ tokens = parse_codex_auth_json(_auth_json(_jwt(claims)))++ assert tokens.expires_at == FROZEN_NOW + timedelta(hours=1)++ @parameterized.expand(+ [+ ("api_key_login", {"auth_mode": "apikey", "OPENAI_API_KEY": "sk-test"}),+ ("missing_refresh_token", {"tokens": {"access_token": _access_token()}}),+ ("access_token_without_account", {"tokens": {"access_token": _jwt({"sub": "x"}), "refresh_token": "rt"}}),+ ("not_an_object", ["tokens"]),+ ]+ )+ def test_rejects_a_file_that_cannot_start_a_refresh_chain(self, _name: str, raw: object) -> None:+ with self.assertRaises(CodexAuthError):+ parse_codex_auth_json(raw)+++class TestCodexConcurrentConnections(TransactionTestCase):+ def test_concurrent_accounts_replace_one_user_record(self) -> None:+ user = User.objects.create(email="[email protected]", distinct_id="codex-concurrency")+ accounts = {+ account: replace(+ parse_codex_auth_json(_auth_json(_access_token(account_id=account))), refresh_token=account+ )+ for account in ("account-1", "account-2")+ }+ start = Barrier(2)++ def connect(account: str) -> None:+ try:+ start.wait(timeout=10)+ CodexUserIntegration.connect(user.id, accounts[account], source="test")+ finally:+ connections["default"].close()++ with patch(+ "posthog.models.integration.codex.refresh_codex_tokens", side_effect=lambda token, **kwargs: accounts[token]+ ):+ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [executor.submit(connect, account) for account in accounts]+ for future in futures:+ future.result(timeout=15)++ row = UserIntegration.objects.get(user=user, kind="codex")+ assert row.integration_id in accounts+ assert row.sensitive_config["refresh_token"] == row.integration_id+++class TestCodexUserIntegration(BaseTest):+ def _connect(self, response: requests.Response | None = None) -> CodexUserIntegration:+ with patch("requests.request", return_value=response or _refresh_ok()):+ return CodexUserIntegration.connect(self.user.id, parse_codex_auth_json(_auth_json()), source="test")++ def _stored_fingerprint(self) -> str:+ row = UserIntegration.objects.get(user=self.user, kind="codex")+ return access_token_fingerprint(row.sensitive_config["access_token"])++ @time_machine.travel(FROZEN_NOW, tick=False)+ def test_connect_refreshes_once_and_stores_only_the_rotated_chain(self) -> None:+ with patch("requests.request", return_value=_refresh_ok()) as request:+ integration = CodexUserIntegration.connect(self.user.id, parse_codex_auth_json(_auth_json()), source="test")++ assert request.call_args.kwargs["json"]["refresh_token"] == "rt_submitted"+ row = UserIntegration.objects.get(user=self.user, kind="codex")+ assert row.integration_id == "acct_1"+ assert row.sensitive_config["refresh_token"] == "rt_rotated"+ assert row.config["status"] == STATUS_CONNECTED+ assert integration.plan_type == "plus"+ assert integration.email == "[email protected]"++ @time_machine.travel(FROZEN_NOW, tick=False)+ def test_connect_refuses_a_chain_openai_rejects_and_stores_nothing(self) -> None:+ with patch(+ "requests.request", return_value=_openai_response(400, {"error": {"code": "refresh_token_expired"}})+ ):+ with self.assertRaises(CodexReauthRequired):+ CodexUserIntegration.connect(self.user.id, parse_codex_auth_json(_auth_json()), source="test")++ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()++ @parameterized.expand(+ [+ ("fresh_token_nothing_rejected", timedelta(hours=1), None, False),+ ("inside_refresh_margin", timedelta(minutes=4), None, True),+ ("the_stored_token_was_rejected", timedelta(hours=1), "stored", True),+ ("an_already_replaced_token_was_rejected", timedelta(hours=1), "other", False),+ ]+ )+ def test_issue_access_grant_refreshes_only_when_needed(+ self, _name: str, expires_in: timedelta, rejected: str | None, expect_refresh: bool+ ) -> None:+ with time_machine.travel(FROZEN_NOW, tick=False):+ self._connect(_refresh_ok(expires_in=expires_in))+ stored = UserIntegration.objects.get(user=self.user, kind="codex").sensitive_config["access_token"]+ rejected_sha256 = {None: None, "stored": access_token_fingerprint(stored), "other": "0" * 64}[rejected]+ with time_machine.travel(FROZEN_NOW + timedelta(seconds=10), tick=False):+ with patch("requests.request", return_value=_refresh_ok("rt_second")) as request:+ grant = CodexUserIntegration.issue_access_grant(+ self.user.id, rejected_access_token_sha256=rejected_sha256, source="test"+ )++ assert request.called is expect_refresh+ assert grant.refreshed is expect_refresh+ row = UserIntegration.objects.get(user=self.user, kind="codex")+ assert row.sensitive_config["refresh_token"] == ("rt_second" if expect_refresh else "rt_rotated")+ assert grant.access_token == row.sensitive_config["access_token"]+ assert grant.account_id == "acct_1"+ assert "access_token" not in repr(grant)++ def test_a_dead_refresh_chain_marks_the_row_for_reconnect_and_drops_the_tokens(self) -> None:+ with time_machine.travel(FROZEN_NOW, tick=False):+ self._connect()++ with time_machine.travel(FROZEN_NOW + timedelta(minutes=1), tick=False):+ with patch("requests.request", return_value=_openai_response(401, {"error": "invalid_grant"})):+ with self.assertRaises(CodexReauthRequired):+ CodexUserIntegration.issue_access_grant(+ self.user.id, rejected_access_token_sha256=self._stored_fingerprint(), source="test"+ )++ row = UserIntegration.objects.get(user=self.user, kind="codex")+ assert row.config["status"] == STATUS_REAUTH_REQUIRED+ assert row.sensitive_config == {}+ with patch("requests.request") as request:+ with self.assertRaises(CodexReauthRequired):+ CodexUserIntegration.issue_access_grant(self.user.id, rejected_access_token_sha256=None, source="test")+ assert not request.called++ @parameterized.expand([("server_error", 503), ("rate_limited", 429), ("request_timeout", 408)])+ def test_a_transient_error_on_refresh_keeps_the_chain_for_a_retry(self, _name: str, status_code: int) -> None:+ with time_machine.travel(FROZEN_NOW, tick=False):+ self._connect()++ with time_machine.travel(FROZEN_NOW + timedelta(minutes=1), tick=False):+ with patch("requests.request", return_value=_openai_response(status_code, {})):+ with self.assertRaises(CodexAuthError) as raised:+ CodexUserIntegration.issue_access_grant(+ self.user.id, rejected_access_token_sha256=self._stored_fingerprint(), source="test"+ )++ assert not isinstance(raised.exception, CodexReauthRequired)+ row = UserIntegration.objects.get(user=self.user, kind="codex")+ assert row.config["status"] == STATUS_CONNECTED+ assert row.sensitive_config["refresh_token"] == "rt_rotated"++ @time_machine.travel(FROZEN_NOW, tick=False)+ def test_disconnect_revokes_the_refresh_token_and_deletes_the_row(self) -> None:+ integration = self._connect()+ self._connect(_refresh_ok(refresh_token="rt_latest"))++ with patch("requests.request", return_value=_openai_response(200, {})) as request:+ integration.disconnect(source="test")++ assert request.call_args.kwargs["json"] == {+ "token": "rt_latest",+ "token_type_hint": "refresh_token",+ "client_id": CODEX_OAUTH_CLIENT_ID,+ }+ assert not UserIntegration.objects.filter(user=self.user, kind="codex").exists()diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex d050cb909f3b..96993d8a7406 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -5,6 +5,7 @@ from uuid import UUID, uuid4from django.conf import settingsfrom django.db import models+from django.utils.functional import Promiseimport requestsimport structlog@@ -33,6 +34,10 @@ _GITHUB_UNRECOVERABLE_REFRESH_ERRORS = {}+def user_integration_kind_choices() -> list[tuple[str, str | Promise]]:+ return list(UserIntegration.IntegrationKind.choices)++class UserIntegration(UUIDModel):"""User-scoped integration with an external service.@@ -64,6 +69,15 @@ class UserIntegration(UUIDModel):the most-recently-linked accessible row and warns when it sees morethan one match — see `find_linked_posthog_user`.+ Contents for Codex (ChatGPT plan for cloud tasks):+ - `integration_id` holds the ChatGPT account id from the access token claims+ - `config` holds {plan_type, email, status, connected_at}; `status` is+ "connected" or "reauth_required"+ - `sensitive_config` holds {access_token, refresh_token,+ access_token_expires_at}. The refresh token is single use, so every refresh+ stores the rotated token under a row lock. See `posthog.models.integration.codex`.+ - One row per user: Desktop replaces it on reconnect.+The `unique_together = ("user", "kind", "integration_id")` constraint onlyforbids the same PostHog user linking the same Slack workspace identitytwice (which would have to be a re-OAuth that `update_or_create` already@@ -75,13 +89,14 @@ class UserIntegration(UUIDModel):class IntegrationKind(models.TextChoices):GITHUB = "github"SLACK = "slack"+ CODEX = "codex"user = models.ForeignKey("posthog.User",on_delete=models.CASCADE,related_name="integrations",)- kind = models.CharField(max_length=32, choices=IntegrationKind.choices)+ kind = models.CharField(max_length=32, choices=user_integration_kind_choices)# The ID of the integration in the external system, same as on Integrationintegration_id = models.TextField()config = models.JSONField(default=dict)@@ -94,6 +109,11 @@ class UserIntegration(UUIDModel):class Meta:db_table = "posthog_user_integration"unique_together = [("user", "kind", "integration_id")]+ constraints = [+ models.UniqueConstraint(+ fields=["user"], condition=models.Q(kind="codex"), name="unique_codex_user_integration"+ ),+ ]indexes = [models.Index(fields=["kind", "integration_id"], name="user_integration_kind_extid"),]diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 8440a5a150e1..c92c78cb7b05 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -460,6 +460,11 @@ class PostHogAIAccessRequestIPThrottle(IPThrottle):rate = "1/day"+class CodexConnectUserThrottle(UserRateThrottle):+ scope = "codex_connect_user"+ rate = "10/hour"++class BurstRateThrottle(PersonalApiKeyRateThrottle):# Throttle class that's applied on all endpoints (except for capture + decide)# Intended to block quick bursts of requests, per projectdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex ddd5dccb5c9e..2f2533ee2d26 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -636,6 +636,8 @@ SPECTACULAR_SETTINGS = {# class would cross a product boundary, so the entry names the set centrally."RunStatusEnum": ["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],"RunEnvironmentEnum": ["local", "cloud"],+ # claude_model_access and codex_model_access carry the same pair.+ "ModelAccessEnum": ["posthog-gateway", "own-subscription"],"DiagnosticSeverityEnum": ["error", "warning"],"InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],"NotificationDestinationTypeEnum": ["slack", "webhook", "teams"],diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 318784828f19..b2a4e7eb034d 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -1,4 +1,4 @@-from collections.abc import Mapping+from collections.abc import Collection, Mappingfrom datetime import timedeltafrom typing import Any, Literal, TypedDict, castfrom uuid import UUID@@ -584,8 +584,13 @@ def create_oauth_access_token_for_user(include_slack_run_scope: bool = False,application: SandboxOAuthApplication = "array",sandbox_task_id: UUID | None = None,+ withhold_scopes: Collection[str] = (),) -> str:- resolved = resolve_scopes(scopes, include_internal_scopes=include_internal_scopes)+ resolved = [+ scope+ for scope in resolve_scopes(scopes, include_internal_scopes=include_internal_scopes)+ if scope not in withhold_scopes+ ]if include_mcp_builtin_agent_scope:# Provenance marker: the MCP Store uses it to deny the human/member# surface and route the agent through its explicit gateway grants. Itdiff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.pyindex 387723fbeeca..2f470792bad9 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -416,6 +416,18 @@ class TestCreateOAuthAccessTokenForUser(TestCase):with self.assertRaisesRegex(RuntimeError, "PostHog AI app not found"):create_oauth_access_token_for_user(user, team.id, application="posthog_ai")+ @override_settings(CLOUD_DEPLOYMENT="DEV")+ def test_withheld_scopes_are_dropped_after_internal_scopes_are_added(self) -> None:+ self._create_oauth_app(ARRAY_APP_CLIENT_ID_DEV, "Array Dev App")+ user, team = self._create_user_and_team()++ token = create_oauth_access_token_for_user(user, team.id, withhold_scopes=["llm_gateway:read"])++ scopes = set(OAuthAccessToken.objects.get(token=token).scope.split())+ assert "llm_gateway:read" not in scopes+ assert "internal_run:read" in scopes+ assert "task:write" in scopes+@override_settings(CLOUD_DEPLOYMENT="DEV")def test_built_in_agent_scope_is_added_without_narrowing_scopes(self) -> None:self._create_oauth_app(ARRAY_APP_CLIENT_ID_DEV, "Array Dev App")diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.tsindex 6f1fe6fe47ba..2d1ac3265c99 100644--- a/products/desktop/apps/code/src/renderer/desktop-services.ts+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts@@ -1,3 +1,8 @@+import { codexCloudAccountModule } from "@posthog/core/integrations/codexCloudAccount.module";+import {+ CODEX_CLOUD_ACCOUNT_HOST,+ type CodexCloudAccountHost,+} from "@posthog/core/integrations/codexCloudAccountService";import { SETTINGS_BACKUP_FILES } from "@posthog/platform/settings-backup-files";import { CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS } from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";// Desktop host service bindings live here as features move into packages.@@ -475,3 +480,21 @@ container.bind(SETTINGS_BACKUP_FILES).toConstantValue({open: () => hostTrpcClient.settingsBackup.open.mutate(),save: (input) => hostTrpcClient.settingsBackup.save.mutate(input),});++container.load(codexCloudAccountModule);+container+ .bind<CodexCloudAccountHost>(CODEX_CLOUD_ACCOUNT_HOST)+ .toConstantValue({+ prepare: (attemptId) =>+ hostTrpcClient.agent.codexCloudAuthTerminal.mutate({ attemptId }),+ read: (attemptId) =>+ hostTrpcClient.agent.codexCloudAuthFileRead.query({ attemptId }),+ remove: (attemptId) =>+ hostTrpcClient.agent.codexCloudAuthFileRemove.mutate({ attemptId }),+ finish: (attemptId) =>+ hostTrpcClient.agent.codexCloudAuthFinish.mutate({ attemptId }),+ cancel: async (attemptId) => {+ await hostTrpcClient.shell.destroy.mutate({ sessionId: attemptId });+ await hostTrpcClient.agent.codexCloudAuthFinish.mutate({ attemptId });+ },+ });diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.tsindex cf1f271fa6d3..027efb49ffe8 100644--- a/products/desktop/apps/code/src/renderer/di/bindings.ts+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts@@ -59,6 +59,10 @@ import {REPORT_MODEL_RESOLVER,type ReportModelResolver,} from "@posthog/core/inbox/identifiers";+import {+ CODEX_CLOUD_ACCOUNT_HOST,+ type CodexCloudAccountHost,+} from "@posthog/core/integrations/codexCloudAccountService";import {GITHUB_CONNECT_CLIENT as INTEGRATIONS_GITHUB_CONNECT_CLIENT,type GithubConnectClient as IntegrationsGithubConnectClient,@@ -303,6 +307,7 @@ import { TASK_SERVICE as RENDERER_TASK_SERVICE, TRPC_CLIENT } from "./tokens";* ContainerModules without typing their internal bindings).*/export interface RendererBindings {+ [CODEX_CLOUD_ACCOUNT_HOST]: CodexCloudAccountHost;[SETTINGS_BACKUP_FILES]: ISettingsBackupFiles;// --- di/container.ts ---[HOST_LOGGER]: HostLogger;diff --git a/products/desktop/docs/CLOUD-MCP-RELAY.md b/products/desktop/docs/CLOUD-MCP-RELAY.mdindex 53bf782dfe4c..5125e7c51171 100644--- a/products/desktop/docs/CLOUD-MCP-RELAY.md+++ b/products/desktop/docs/CLOUD-MCP-RELAY.md@@ -330,3 +330,69 @@ The task sandbox has the same credential boundary as GitHub runs. Code inside itA Claude setup token lasts longer than a GitHub token. Remove token does not revoke it or clear an active Claude process.Direct event uploads stay open by default. Local development closes each batch because local proxies can buffer an open request.++## ChatGPT subscription credentials++The Codex cloud subscription is under `posthog-code-codex-own-subscription-cloud`.+It does not use the credential relay. PostHog stores the ChatGPT login server-side, as it stores the GitHub login, and each cloud run gets a short-lived access token from PostHog.+Desktop deletes the local credential file after PostHog accepts the tokens, if cleanup succeeds. A failed upload or cleanup can leave the file behind. Desktop is not needed while a run is active. Tasks continue when Desktop is closed.+During connect, the tokens pass through the Desktop renderer process once: the host reads the file over tRPC and the renderer uploads it with the user's PostHog session. The renderer does not save the tokens. A cleanup warning identifies a local file that still needs deletion.++Users log in once from Settings > Harness > ChatGPT subscription > Cloud tasks.+Log in opens a dialog that runs `codex login --device-auth` in an embedded terminal, with `CODEX_HOME` set to `~/.codex-posthog`.+The bundled codex binary runs the login, so the flow does not depend on a `codex` on the user's PATH.+Desktop never reads `~/.codex`, so the user's own codex login is not affected.+A stale `~/.codex-posthog/auth.json` is deleted before the terminal starts, so a cancelled attempt cannot be connected later.+When the command exits 0, Desktop reads the file the login wrote, sends the tokens to `POST /api/users/@me/integrations/codex/`, and deletes the file after PostHog accepts them.+A failed connect keeps the file for another try. Desktop shows an error when the file is missing, is not JSON, or holds an API key login instead of ChatGPT tokens.+The host permits one login attempt at a time. File reads and cleanup require that attempt's ID.+Closing the dialog during an upload lets the upload and cleanup finish before another attempt can start.+An old attempt cannot delete a newer attempt's file.+PostHog refreshes the tokens once on connect, so the local copy is stale after that. The refresh token rotates and is single use.+One database record holds the user's Codex connection. Connect, refresh, and disconnect use the same per-user lock.+`GET` on the same path reports `not_connected`, `connected`, or `reauth_required`, with the plan type and account email. `DELETE` disconnects. No route returns a refresh token.++```mermaid+sequenceDiagram+ actor U as User+ participant D as Desktop+ participant T as In-app terminal+ participant P as PostHog+ participant O as OpenAI+ U->>D: Settings > Harness > Cloud tasks > Log in+ D->>T: codex login --device-auth, CODEX_HOME=~/.codex-posthog+ T-->>U: Device code and link+ U->>O: Approve in a browser+ O-->>T: Writes ~/.codex-posthog/auth.json+ T-->>D: Exit 0+ D->>D: Read auth.json+ D->>P: POST /api/users/@me/integrations/codex/+ P->>O: Refresh once+ O-->>P: New access token + rotated refresh token+ P->>P: Store the pair encrypted on the user+ P-->>D: connected (email, plan)+ D->>D: Delete auth.json+ U->>D: Disconnect, later+ D->>P: DELETE /api/users/@me/integrations/codex/+ P->>O: Revoke the refresh token+ P->>P: Delete the row+```++PostHog stores the tokens in an encrypted `UserIntegration` row of kind `codex`, owned by the user, not by a project.+It refreshes the access token against OpenAI on demand and keeps only one refresh in flight per user.+When OpenAI rejects the refresh token, the row moves to `reauth_required`, and Desktop asks the user to log in and connect again.+Desktop checks the account state before each Codex cloud start or resume that uses the plan.++Each subscription run gets a run-scoped secret. The worker writes it to a file that the sandbox command opens on file descriptor 3 and deletes before the agent server starts.+The agent server reads descriptor 3 once. The secret is absent from the environment, the command arguments, and the filesystem after that.+The agent server calls `POST /api/projects/{team}/tasks/{task_id}/runs/{run_id}/subscription_token/` with the secret in `X-Task-Run-Token`.+The endpoint accepts only that secret for that run, together with the sandbox identity, and returns an access token, the workspace id, and the plan type.+The general sandbox token alone cannot obtain a ChatGPT token. Code that runs inside the sandbox as a tool does not receive descriptor 3.+The sandbox tries to set `kernel.yama.ptrace_scope=1` so a tool process cannot read the agent server memory. This is best effort: the write fails where `/proc/sys` is read-only, and the local Docker sandbox holds `CAP_SYS_PTRACE` for agentsh, which bypasses it. Code running in the sandbox can obtain access tokens for the run's lifetime in any case, because the Codex process holds one.++Codex signs in with `chatgptAuthTokens`, which keeps the token in memory and writes no auth file.+On a 401 codex asks the agent server for a fresh token and waits ten seconds. The agent server calls the endpoint with the digest of the rejected token, and PostHog refreshes before it answers unless it already holds a newer token.+The run fails at the `subscription_token` phase when PostHog reports `reauth_required` or when OpenAI is unreachable. Desktop shows a retryable error for an OpenAI outage and asks for a new login when the chain is dead.+Subscription runs do not use a warm sandbox, because a warm sandbox started before the plan choice holds no run secret.+Codex tokens are JSON Web Tokens, so logs and events redact anything with that shape.+Sandbox compute still uses PostHog credits.diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.tsindex 1331379bae8b..4a686b043296 100644--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts@@ -247,6 +247,7 @@ function createCodexConnection(config: AcpConnectionConfig): AcpConnection {apiKey: codexOptions.apiKey,codexHome: codexOptions.codexHome,useMachineAuth: codexOptions.useMachineAuth,+ useChatgptAuthTokens: Boolean(codexOptions.chatgptAuthTokens),developerInstructions: codexOptions.developerInstructions,httpHeaders: codexOptions.httpHeaders,configOverrides: codexOptions.configOverrides,@@ -258,6 +259,8 @@ function createCodexConnection(config: AcpConnectionConfig): AcpConnection {gatewayModels: config.codexModels,processCallbacks: config.processCallbacks,onStructuredOutput: config.onStructuredOutput,+ chatgptAuthTokens: codexOptions.chatgptAuthTokens,+ refreshChatgptAuthTokens: codexOptions.refreshChatgptAuthTokens,logger: config.logger?.child("CodexAppServerAgent"),});return agent;diff --git a/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts b/products/desktop/packages/agent/src/adapters/claude/subscription-login.tsindex f33bf6d00d89..7f61ee0e5f15 100644--- a/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts+++ b/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts@@ -1,5 +1,6 @@import { spawn } from "node:child_process";import { existsSync } from "node:fs";+import { shellQuote } from "../../utils/shell-quote";import {applyMachineClaudeAuth,type MachineClaudeAuth,@@ -13,13 +14,6 @@ export interface ClaudeAuthTerminalCommand {env: { set: Record<string, string>; unset: string[] };}-function shellQuote(value: string): string {- if (process.platform === "win32") {- return `"${value.replaceAll('"', '\\"')}"`;- }- return `'${value.replaceAll("'", `'\\''`)}'`;-}-export function claudeAuthTerminalCommand(action: ClaudeAuthAction,claudeCliPath: string,diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.tsindex e34497eab824..ca6922552c51 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts@@ -2379,6 +2379,34 @@ describe("CodexAppServerAgent", () => {stub.emit("turn/completed", { turn: { status: "completed" } });});+ it("reports a failed ChatGPT token refresh as the turn's cause instead of Codex's generic code", async () => {+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client } = makeFakeClient();+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ refreshChatgptAuthTokens: () =>+ Promise.reject(new Error("Your ChatGPT login stopped working.")),+ rpcFactory: stub.factory,+ });++ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "go" }],+ } as unknown as PromptRequest);+ await expect(+ stub.invokeRequest("account/chatgptAuthTokens/refresh", {}),+ ).rejects.toThrow("Your ChatGPT login stopped working.");+ stub.emit("error", {+ willRetry: false,+ error: { message: "auth refresh request failed: code=-32000" },+ });++ await expect(done).rejects.toThrow(+ "The agent stopped before completing this request: Your ChatGPT login stopped working.",+ );+ });+it("rejects the prompt on a non-retried error notification", async () => {const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });const { client } = makeFakeClient();diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.tsindex 837938e1ce97..1f2a68bb5aa2 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts@@ -104,6 +104,7 @@ import {SessionConfigState,} from "./session-config";import {+ type ChatgptAuthTokens,type CodexAppServerProcess,type CodexAppServerProcessOptions,spawnCodexAppServerProcess,@@ -284,6 +285,8 @@ export interface CodexAppServerAgentOptions {processCallbacks?: ProcessSpawnedCallback;logger?: Logger;onStructuredOutput?: (output: Record<string, unknown>) => Promise<void>;+ chatgptAuthTokens?: ChatgptAuthTokens;+ refreshChatgptAuthTokens?: () => Promise<ChatgptAuthTokens>;/** Test seam: build the JSON-RPC client (defaults to spawning the process). */rpcFactory?: (handlers: AppServerClientHandlers) => AppServerRpc;}@@ -310,6 +313,9 @@ export class CodexAppServerAgent extends BaseAcpAgent {private readonly developerInstructions?: string;private readonly contextWiki?: ContextWikiEnv;private readonly gatewayConfigured: boolean;+ private readonly chatgptAuthTokens?: ChatgptAuthTokens;+ private readonly refreshChatgptAuthTokens?: () => Promise<ChatgptAuthTokens>;+ private chatgptAuthRefreshFailure?: string;private threadId?: string;/** JSON schema constraining the final message; set per session via `_meta`. */private jsonSchema?: Record<string, unknown>;@@ -380,6 +386,8 @@ export class CodexAppServerAgent extends BaseAcpAgent {this.developerInstructions = options.processOptions.developerInstructions;this.contextWiki = options.processOptions.contextWiki;this.gatewayConfigured = Boolean(options.processOptions.apiBaseUrl);+ this.chatgptAuthTokens = options.chatgptAuthTokens;+ this.refreshChatgptAuthTokens = options.refreshChatgptAuthTokens;const handlers: AppServerClientHandlers = {logger: this.logger,@@ -423,6 +431,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {capabilities: { experimentalApi: true, requestAttestation: false },});this.rpc.notify(APP_SERVER_NOTIFICATIONS.INITIALIZED, {});+ await this.loginWithChatgptAuthTokens();return {protocolVersion: request.protocolVersion,agentCapabilities: {@@ -1743,8 +1752,11 @@ export class CodexAppServerAgent extends BaseAcpAgent {if (turn?.status === "failed") {// codex reports the terminal cause on the completion itself. Prefer it// over the last retry message, which can be stale or never arrived.+ const refreshFailure = this.chatgptAuthRefreshFailure;+ this.chatgptAuthRefreshFailure = undefined;const terminalCause =- typeof turn.error?.message === "string" ? turn.error.message : "";+ refreshFailure ??+ (typeof turn.error?.message === "string" ? turn.error.message : "");this.deferFailedTurnFinalization(turn?.id,this.turns.currentGeneration,@@ -1780,7 +1792,11 @@ export class CodexAppServerAgent extends BaseAcpAgent {if (turnId && turnId !== this.turns.activeTurnId) {return;}- const message = typeof error?.message === "string" ? error.message : "";+ const refreshFailure = this.chatgptAuthRefreshFailure;+ if (willRetry === false) this.chatgptAuthRefreshFailure = undefined;+ const message =+ refreshFailure ??+ (typeof error?.message === "string" ? error.message : "");// Keep the newest cause even while codex retries: when the retries run out the// turn dies through `turn/completed`, which carries no error text of its own.// Bind it to the turn so a later steered turn cannot inherit this cause.@@ -2349,10 +2365,46 @@ export class CodexAppServerAgent extends BaseAcpAgent {* string is rejected); richer ones (AskUserQuestion / permission profile / elicitation) go* to `handleServerRequest`. Whatever we return is sent back as the JSON-RPC result.*/+ /** Codex forces memory-only storage in this mode, so no auth file is written. */+ private async loginWithChatgptAuthTokens(): Promise<void> {+ if (!this.chatgptAuthTokens) return;+ await this.rpc.request(APP_SERVER_METHODS.ACCOUNT_LOGIN_START, {+ type: "chatgptAuthTokens",+ accessToken: this.chatgptAuthTokens.accessToken,+ chatgptAccountId: this.chatgptAuthTokens.chatgptAccountId,+ chatgptPlanType: this.chatgptAuthTokens.chatgptPlanType,+ });+ this.logger.info("Codex signed in with the run's ChatGPT access token", {+ hasAccountId: Boolean(this.chatgptAuthTokens.chatgptAccountId),+ planType: this.chatgptAuthTokens.chatgptPlanType,+ });+ }++ private async handleChatgptAuthTokensRefresh(): Promise<ChatgptAuthTokens> {+ if (!this.refreshChatgptAuthTokens) {+ throw new Error("No ChatGPT token refresh is configured for this run.");+ }+ try {+ const tokens = await this.refreshChatgptAuthTokens();+ // Never include the cause: a token refresh error can carry the token.+ if (!tokens.accessToken) {+ throw new Error("PostHog returned no ChatGPT access token.");+ }+ return tokens;+ } catch (error) {+ this.chatgptAuthRefreshFailure =+ error instanceof Error ? error.message : String(error);+ throw error;+ }+ }+private async handleApproval(method: string,params: unknown,): Promise<unknown> {+ if (method === APP_SERVER_REQUESTS.CHATGPT_AUTH_TOKENS_REFRESH) {+ return await this.handleChatgptAuthTokensRefresh();+ }const richer = await handleServerRequest(method, params, this.client, {sessionId: this.sessionId,logger: this.logger,diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.tsindex 651e4045ef26..01febc90e9c0 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts@@ -73,8 +73,12 @@ export const APP_SERVER_REQUESTS = {TOOL_USER_INPUT: "item/tool/requestUserInput",PERMISSIONS_APPROVAL: "item/permissions/requestApproval",MCP_ELICITATION: "mcpServer/elicitation/request",+ CHATGPT_AUTH_TOKENS_REFRESH: "account/chatgptAuthTokens/refresh",} as const;+/** Codex fails the turn if the host does not answer a refresh in this time. */+export const CHATGPT_AUTH_TOKENS_REFRESH_TIMEOUT_MS = 10_000;+/** JSON-RPC ids are `string | number` per the codex schema (`RequestId.ts`). */export type RequestId = string | number;diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.tsindex 551b62272767..c19924e09943 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts@@ -9,6 +9,12 @@ import {import type { ProcessSpawnedCallback } from "../../types";import { Logger } from "../../utils/logger";+export interface ChatgptAuthTokens {+ accessToken: string;+ chatgptAccountId?: string;+ chatgptPlanType?: string;+}+/*** Host-facing codex options passed through `createAcpConnection`'s* `codexOptions`. The connection layer maps these onto@@ -42,6 +48,8 @@ export interface CodexOptions {binaryPath?: string;codexHome?: string;useMachineAuth?: boolean;+ chatgptAuthTokens?: ChatgptAuthTokens;+ refreshChatgptAuthTokens?: () => Promise<ChatgptAuthTokens>;/** Extra codex `-c key=value` config overrides. */configOverrides?: Record<string, string | number>;/**@@ -61,6 +69,8 @@ export interface CodexAppServerProcessOptions {apiKey?: string;codexHome?: string;useMachineAuth?: boolean;+ /** Pins the ChatGPT login so an ambient API key cannot take over. */+ useChatgptAuthTokens?: boolean;/** Guidance appended to Codex's base prompt via `developer_instructions`. */developerInstructions?: string;/**@@ -160,7 +170,7 @@ export function buildAppServerArgs(args.push("-c", `otel.trace_exporter="none"`);args.push("-c", "otel.log_user_prompt=false");- if (options.useMachineAuth) {+ if (options.useMachineAuth || options.useChatgptAuthTokens) {args.push("-c", `model_provider="openai"`);args.push("-c", `forced_login_method="chatgpt"`);args.push("-c", `history.persistence="none"`);diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.tsindex 3105fc3d17ac..e1e7c7c8d1bc 100644--- a/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts@@ -1,5 +1,6 @@import type { ProcessSpawnedCallback } from "../../types";import type { Logger } from "../../utils/logger";+import { shellQuote } from "../../utils/shell-quote";import {nodeReadableToWebReadable,nodeWritableToWebWritable,@@ -36,6 +37,21 @@ export interface CodexLoginSession {cancel: () => Promise<void>;}+export interface CodexAuthTerminalCommand {+ command: string;+ env: { set: Record<string, string>; unset: string[] };+}++export function codexCloudAuthTerminalCommand(+ binaryPath: string,+ codexHome: string,+): CodexAuthTerminalCommand {+ return {+ command: [binaryPath, "login", "--device-auth"].map(shellQuote).join(" "),+ env: { set: { CODEX_HOME: codexHome }, unset: [] },+ };+}+export interface CodexLoginStatus {loggedIn: boolean;email?: string;diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex b42ac99ada4e..86919d0a85b5 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -436,4 +436,112 @@ describe("PostHogAPIClient", () => {).rejects.toThrow("Failed to sync task session: [504] Gateway Timeout");expect(mockFetch).toHaveBeenCalledOnce();});++ it.each([+ new TypeError("fetch failed"),+ new DOMException("The request timed out", "TimeoutError"),+ ])("classifies a token transport failure as retryable: %s", async (error) => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ mockFetch.mockRejectedValueOnce(error);++ await expect(+ client.requestCodexSubscriptionToken(+ "task-1",+ "run-1",+ "run-token",+ null,+ 5_000,+ ),+ ).rejects.toMatchObject({+ name: "CodexSubscriptionTokenError",+ code: "request_failed",+ });+ });++ it("asks the run's subscription_token endpoint with the fd 3 run token", async () => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ const grant = {+ access_token: "chatgpt-access",+ account_id: "acct-1",+ plan_type: "plus",+ expires_at: "2030-01-01T00:00:00Z",+ };+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: vi.fn().mockResolvedValue(grant),+ });++ await expect(+ client.requestCodexSubscriptionToken(+ "task-1",+ "run-1",+ "run-token",+ "a".repeat(64),+ 5_000,+ ),+ ).resolves.toEqual(grant);++ expect(mockFetch).toHaveBeenLastCalledWith(+ "https://app.posthog.com/api/projects/7/tasks/task-1/runs/run-1/subscription_token/",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ rejected_access_token_sha256: "a".repeat(64),+ }),+ }),+ );+ const request = mockFetch.mock.calls.at(-1)?.[1] as RequestInit;+ expect((request.headers as Headers).get("X-Task-Run-Token")).toBe(+ "run-token",+ );+ });++ it.each([+ [409, { code: "reauth_required", error: "Reconnect." }, "reauth_required"],+ [+ 502,+ { code: "openai_unavailable", error: "No answer." },+ "openai_unavailable",+ ],+ [403, {}, "forbidden"],+ [500, {}, "request_failed"],+ ])(+ "maps a %s from subscription_token to the %s error code",+ async (status, body, code) => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status,+ statusText: "Error",+ json: vi.fn().mockResolvedValue(body),+ });++ await expect(+ client.requestCodexSubscriptionToken(+ "task-1",+ "run-1",+ "run-token",+ null,+ 5_000,+ ),+ ).rejects.toMatchObject({+ name: "CodexSubscriptionTokenError",+ code,+ status,+ });+ },+ );});diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex cecd5433816d..09946ff0f2a1 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -24,6 +24,30 @@ export interface TaskSessionStorageAccess {content_sha256: string | null;}+export interface CodexSubscriptionAccessGrant {+ access_token: string;+ account_id: string;+ plan_type: string | null;+ expires_at: string;+}++export type CodexSubscriptionTokenErrorCode =+ | "reauth_required"+ | "openai_unavailable"+ | "forbidden"+ | "request_failed";++export class CodexSubscriptionTokenError extends Error {+ constructor(+ readonly code: CodexSubscriptionTokenErrorCode,+ readonly status: number,+ message: string,+ ) {+ super(message);+ this.name = "CodexSubscriptionTokenError";+ }+}+export class PostHogAPIError extends Error {constructor(message: string,@@ -291,6 +315,60 @@ export class PostHogAPIClient {return result.content_sha256;}+ /**+ * A short-lived ChatGPT access token for a run on the owner's own plan. The+ * run token from fd 3 proves the caller is this run's agent-server; the+ * refresh token never leaves the server. `force` asks for a new token even+ * when the stored one has not expired, for when Codex rejected the last one.+ */+ async requestCodexSubscriptionToken(+ taskId: string,+ runId: string,+ runToken: string,+ rejectedAccessTokenSha256: string | null,+ timeoutMs: number,+ ): Promise<CodexSubscriptionAccessGrant> {+ const teamId = this.getTeamId();+ const response = await this.performRequestWithRetry(+ `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/subscription_token/`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-Task-Run-Token": runToken,+ },+ body: JSON.stringify({+ rejected_access_token_sha256: rejectedAccessTokenSha256,+ }),+ signal: AbortSignal.timeout(timeoutMs),+ },+ ).catch(() => {+ throw new CodexSubscriptionTokenError(+ "request_failed",+ 0,+ "Could not reach PostHog to get a ChatGPT token. Try the task again.",+ );+ });+ if (response.ok) {+ return (await response.json()) as CodexSubscriptionAccessGrant;+ }+ const body = (await response.json().catch(() => ({}))) as {+ code?: string;+ error?: string;+ };+ const code: CodexSubscriptionTokenErrorCode =+ body.code === "reauth_required" || body.code === "openai_unavailable"+ ? body.code+ : response.status === 403 || response.status === 404+ ? "forbidden"+ : "request_failed";+ throw new CodexSubscriptionTokenError(+ code,+ response.status,+ `Failed to get a ChatGPT token: [${response.status}] ${body.error ?? response.statusText}`,+ );+ }+async appendTaskRunLog(taskId: string,runId: string,diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex ee72f393df5f..a078dac91e67 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -82,6 +82,7 @@ import {} from "../adapters/claude/session/jsonl-hydration";import type { GatewayEnv } from "../adapters/claude/session/options";import { codexKeyMatchesMcpServerName } from "../adapters/codex-app-server/mcp-config";+import type { ChatgptAuthTokens } from "../adapters/codex-app-server/spawn";import { hasCodexThreadState } from "../adapters/codex-app-server/thread-state";import { mergeUsage } from "../adapters/codex-app-server/usage-tracker";import {@@ -96,7 +97,7 @@ import type { PermissionMode } from "../execution-mode";import { DEFAULT_CODEX_MODEL, fetchGatewayModels } from "../gateway-models";import { OtelRunTelemetry } from "../otel-telemetry";import { configurePersistentAgentState } from "../persistent-agent-state";-import { PostHogAPIClient } from "../posthog-api";+import { CodexSubscriptionTokenError, PostHogAPIClient } from "../posthog-api";import {findPrUrls,type OwnedBranch,@@ -130,6 +131,10 @@ import {normalizeCloudPromptContent,promptBlocksToText,} from "./cloud-prompt";+import {+ CodexSubscriptionTokenClient,+ codexSubscriptionRefreshFailureMessage,+} from "./codex-subscription-token";import { CredentialRelay, CredentialRelayError } from "./credential-relay";import { TaskRunEventStreamSender } from "./event-stream-sender";import {@@ -336,6 +341,21 @@ export interface PreparedInitialTaskMessage {action: "wait" | "idle" | "resume" | "initial";}+export const CODEX_SUBSCRIPTION_TOKEN_MISSING_MESSAGE =+ "This run could not get a ChatGPT token. Open Desktop, go to Settings > Harness, and connect your ChatGPT account again. Then start the task again.";++/** How a run that cannot get its plan credential reports the failure, per adapter. */+const SUBSCRIPTION_TOKEN_FAILURE = {+ claude: {+ phase: "credential_relay",+ message: CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE,+ },+ codex: {+ phase: "subscription_token",+ message: CODEX_SUBSCRIPTION_TOKEN_MISSING_MESSAGE,+ },+} as const;+function hiddenTextBlock(text: string): ContentBlock {return {type: "text",@@ -593,6 +613,7 @@ export class AgentServer {private readonly posthogExecPermissionRegex: RegExp;private readonly posthogExecPermissionRegexSource: string;private mcpRelayServer: McpRelayServer | null = null;+ private codexTokenClient: CodexSubscriptionTokenClient | null = null;private readonly credentialRelay = new CredentialRelay({emitEvent: (event) => this.broadcastEvent(event),});@@ -1171,8 +1192,9 @@ export class AgentServer {if (error instanceof CredentialRelayError && error.code === "cancelled")return;const errorMessage = redactSecrets(- error instanceof CredentialRelayError- ? CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE+ error instanceof CredentialRelayError ||+ error instanceof CodexSubscriptionTokenError+ ? SUBSCRIPTION_TOKEN_FAILURE[this.subscriptionAdapter()].message: describeFatalError(error),);this.logger.error("Fatal agent-server error; marking run failed", error);@@ -1231,11 +1253,48 @@ export class AgentServer {}}- private async reportClaudeSubscriptionTokenMissing(+ private subscriptionAdapter(): "claude" | "codex" {+ return this.getRuntimeAdapter() === "codex" ? "codex" : "claude";+ }++ private async refreshCodexSubscriptionTokens(): Promise<ChatgptAuthTokens> {+ try {+ return await this.codexSubscriptionTokens().refresh();+ } catch (error) {+ const code =+ error instanceof CodexSubscriptionTokenError ? error.code : "unknown";+ this.logger.warn("ChatGPT token refresh failed", { code });+ throw new Error(codexSubscriptionRefreshFailureMessage(error));+ }+ }++ private codexSubscriptionTokens(): CodexSubscriptionTokenClient {+ if (!this.codexTokenClient) {+ if (!this.config.codexRunToken) {+ throw new CodexSubscriptionTokenError(+ "forbidden",+ 0,+ "This run has no ChatGPT run token.",+ );+ }+ this.codexTokenClient = new CodexSubscriptionTokenClient({+ posthogAPI: this.posthogAPI,+ taskId: this.config.taskId,+ runId: this.config.runId,+ runToken: this.config.codexRunToken,+ logger: this.logger.child("CodexSubscriptionToken"),+ });+ }+ return this.codexTokenClient;+ }++ private async reportSubscriptionTokenMissing(+ adapter: "claude" | "codex",reason: string,): Promise<void> {- this.initializationFailureCode = "claude_credential_unavailable";- this.logger.warn("claude_credential_unavailable");+ const failure = SUBSCRIPTION_TOKEN_FAILURE[adapter];+ this.initializationFailureCode = `${adapter}_credential_unavailable`;+ this.logger.warn(this.initializationFailureCode);try {this.broadcastEvent({type: "notification",@@ -1245,9 +1304,9 @@ export class AgentServer {method: POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED,params: {runtimeAdapter: this.getRuntimeAdapter(),- initializationPhase: "credential_relay",+ initializationPhase: failure.phase,reason,- message: CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE,+ message: failure.message,},},});@@ -1857,8 +1916,11 @@ export class AgentServer {} catch (error) {if (this.shutdownController.signal.aborted) throw error;this.bootTracker.markFailed();- if (error instanceof CredentialRelayError) {- this.initializationFailureCode = "claude_credential_unavailable";+ if (+ error instanceof CredentialRelayError ||+ error instanceof CodexSubscriptionTokenError+ ) {+ this.initializationFailureCode = `${this.subscriptionAdapter()}_credential_unavailable`;}const telemetry = this.initializingTelemetry;telemetry?.append(payload.run_id, {@@ -2137,7 +2199,28 @@ export class AgentServer {if (this.shutdownController.signal.aborted) throw error;const reason = error instanceof Error ? error.message : String(error);this.logger.warn("Claude subscription token relay failed", { reason });- await this.reportClaudeSubscriptionTokenMissing(reason);+ await this.reportSubscriptionTokenMissing("claude", reason);+ throw error;+ }+ }++ let codexSubscriptionTokens: ChatgptAuthTokens | null = null;+ if (+ this.config.codexModelAccess === "own-subscription" &&+ runtimeAdapter === "codex"+ ) {+ try {+ codexSubscriptionTokens = await this.codexSubscriptionTokens().get();+ } catch (error) {+ if (this.shutdownController.signal.aborted) throw error;+ const reason =+ error instanceof CodexSubscriptionTokenError+ ? error.code+ : error instanceof Error+ ? error.message+ : String(error);+ this.logger.warn("ChatGPT token request failed", { reason });+ await this.reportSubscriptionTokenMissing("codex", reason);throw error;}}@@ -2166,7 +2249,10 @@ export class AgentServer {runtimeAdapter === "codex"? {cwd: this.config.repositoryPath ?? "/tmp/workspace",- ...codexAuthFromGatewayEnv(gatewayEnv),+ // Routing a plan run through the gateway would bill us as well.+ ...(codexSubscriptionTokens+ ? {}+ : codexAuthFromGatewayEnv(gatewayEnv)),// Bundled-binary hint for the native codex CLI: the codex// binary itself, or any file in its directory. Set in the// sandbox image (POSTHOG_CODEX_BINARY_PATH); when unset the@@ -2185,7 +2271,13 @@ export class AgentServer {: undefined,serviceTier: this.config.serviceTier,developerInstructions: codexInstructions,- httpHeaders: gatewayEnv.openaiCustomHeaders,+ httpHeaders: codexSubscriptionTokens+ ? undefined+ : gatewayEnv.openaiCustomHeaders,+ chatgptAuthTokens: codexSubscriptionTokens ?? undefined,+ refreshChatgptAuthTokens: codexSubscriptionTokens+ ? () => this.refreshCodexSubscriptionTokens()+ : undefined,}: undefined,onStructuredOutput: async (output) => {diff --git a/products/desktop/packages/agent/src/server/bin.ts b/products/desktop/packages/agent/src/server/bin.tsindex 79bd9d3dad24..187df01d8386 100644--- a/products/desktop/packages/agent/src/server/bin.ts+++ b/products/desktop/packages/agent/src/server/bin.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import { closeSync, readFileSync } from "node:fs";import { fileURLToPath } from "node:url";import { DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE } from "@posthog/harness/extensions/posthog-mcp-policy";import { EFFORT_LEVELS, SERVICE_TIERS } from "@posthog/shared/domain-types";@@ -83,6 +84,32 @@ const envSchema = z.object({const program = new Command();+const CODEX_RUN_TOKEN_FD = 3;++/**+ * The launcher opens the run token on fd 3 (`exec 3< file`) and deletes the+ * file before this process starts, so the token exists only here. Read it once+ * and close the descriptor before anything else can be spawned.+ */+function readCodexRunToken(): string {+ let token = "";+ try {+ token = readFileSync(CODEX_RUN_TOKEN_FD, "utf8").trim();+ } catch {+ token = "";+ } finally {+ try {+ closeSync(CODEX_RUN_TOKEN_FD);+ } catch {+ // Already closed or never opened; nothing to release.+ }+ }+ if (!token) {+ program.error("--codexSubscription requires the run token on fd 3");+ }+ return token;+}+function parseBooleanOption(raw: string | undefined,flag: string,@@ -145,6 +172,10 @@ program).option("--repositoryPath <path>", "Path to the repository").option("--claudeSubscription", "Use a relayed Claude subscription token")+ .option(+ "--codexSubscription",+ "Run on the owner's ChatGPT plan; the run token arrives on fd 3",+ ).option("--repoReadyFile <path>","Sentinel file; session creation blocks until it exists (set while cloning concurrently)",@@ -197,6 +228,16 @@ program) {program.error("--claudeSubscription requires the Claude runtime");}+ if (+ options.codexSubscription &&+ (env.POSTHOG_AGENT_RUNTIME === "pi" ||+ env.POSTHOG_CODE_RUNTIME_ADAPTER !== "codex")+ ) {+ program.error("--codexSubscription requires the Codex runtime");+ }+ const codexRunToken = options.codexSubscription+ ? readCodexRunToken()+ : undefined;delete process.env.POSTHOG_AGENT_LAUNCH_STARTED_AT_MS;// The telemetry token is only ever consumed here (into the server config);@@ -299,6 +340,10 @@ programclaudeModelAccess: options.claudeSubscription? "own-subscription": "posthog-gateway",+ codexModelAccess: options.codexSubscription+ ? "own-subscription"+ : "posthog-gateway",+ codexRunToken,reasoningEffort: env.POSTHOG_CODE_REASONING_EFFORT,serviceTier: env.POSTHOG_CODE_SERVICE_TIER,contextWindow: env.POSTHOG_CODE_CONTEXT_WINDOW,diff --git a/products/desktop/packages/agent/src/server/codex-subscription-token.test.ts b/products/desktop/packages/agent/src/server/codex-subscription-token.test.tsnew file mode 100644index 000000000000..bf757482ad10--- /dev/null+++ b/products/desktop/packages/agent/src/server/codex-subscription-token.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it, vi } from "vitest";+import {+ type CodexSubscriptionAccessGrant,+ CodexSubscriptionTokenError,+} from "../posthog-api";+import {+ accessTokenFingerprint,+ CODEX_SUBSCRIPTION_REFRESH_FAILED_MESSAGES,+ CODEX_TOKEN_REFRESH_MARGIN_MS,+ CodexSubscriptionTokenClient,+ codexSubscriptionRefreshFailureMessage,+} from "./codex-subscription-token";++const START = Date.parse("2030-01-01T00:00:00Z");+const HOUR_MS = 60 * 60_000;++function grant(+ accessToken: string,+ expiresAt: number,+): CodexSubscriptionAccessGrant {+ return {+ access_token: accessToken,+ account_id: "acct-1",+ plan_type: "plus",+ expires_at: new Date(expiresAt).toISOString(),+ };+}++function createClient(now: { value: number }) {+ const requestCodexSubscriptionToken = vi.fn();+ const client = new CodexSubscriptionTokenClient({+ posthogAPI: { requestCodexSubscriptionToken },+ taskId: "task-1",+ runId: "run-1",+ runToken: "run-token",+ now: () => now.value,+ });+ return { client, requestCodexSubscriptionToken };+}++describe("CodexSubscriptionTokenClient", () => {+ it("maps the grant for codex and reuses it until the refresh margin", async () => {+ const now = { value: START };+ const { client, requestCodexSubscriptionToken } = createClient(now);+ requestCodexSubscriptionToken.mockResolvedValueOnce(+ grant("access-1", START + HOUR_MS),+ );++ await expect(client.get()).resolves.toEqual({+ accessToken: "access-1",+ chatgptAccountId: "acct-1",+ chatgptPlanType: "plus",+ });+ expect(requestCodexSubscriptionToken).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ "run-token",+ null,+ expect.any(Number),+ );++ now.value = START + HOUR_MS - CODEX_TOKEN_REFRESH_MARGIN_MS - 1;+ await client.get();+ expect(requestCodexSubscriptionToken).toHaveBeenCalledTimes(1);++ requestCodexSubscriptionToken.mockResolvedValueOnce(+ grant("access-2", START + 2 * HOUR_MS),+ );+ now.value = START + HOUR_MS - CODEX_TOKEN_REFRESH_MARGIN_MS;+ await expect(client.get()).resolves.toMatchObject({+ accessToken: "access-2",+ });+ expect(requestCodexSubscriptionToken).toHaveBeenCalledTimes(2);+ });++ it("names the rejected token by digest and adopts whatever the server answers", async () => {+ const now = { value: START };+ const { client, requestCodexSubscriptionToken } = createClient(now);+ requestCodexSubscriptionToken+ .mockResolvedValueOnce(grant("access-1", START + HOUR_MS))+ .mockResolvedValueOnce(grant("access-2", START + 2 * HOUR_MS))+ .mockResolvedValueOnce(grant("access-2", START + 2 * HOUR_MS));+ await client.get();++ await expect(client.refresh()).resolves.toMatchObject({+ accessToken: "access-2",+ });+ expect(requestCodexSubscriptionToken).toHaveBeenLastCalledWith(+ "task-1",+ "run-1",+ "run-token",+ accessTokenFingerprint("access-1"),+ expect.any(Number),+ );++ await client.refresh();+ expect(requestCodexSubscriptionToken).toHaveBeenLastCalledWith(+ "task-1",+ "run-1",+ "run-token",+ accessTokenFingerprint("access-2"),+ expect.any(Number),+ );+ expect(requestCodexSubscriptionToken).toHaveBeenCalledTimes(3);+ });++ it("shares one in-flight request between concurrent callers", async () => {+ const now = { value: START };+ const { client, requestCodexSubscriptionToken } = createClient(now);+ let release: (value: CodexSubscriptionAccessGrant) => void = () => {};+ requestCodexSubscriptionToken.mockReturnValueOnce(+ new Promise<CodexSubscriptionAccessGrant>((resolve) => {+ release = resolve;+ }),+ );++ const first = client.get();+ const second = client.refresh();+ release(grant("access-1", START + HOUR_MS));++ await expect(Promise.all([first, second])).resolves.toEqual([+ expect.objectContaining({ accessToken: "access-1" }),+ expect.objectContaining({ accessToken: "access-1" }),+ ]);+ expect(requestCodexSubscriptionToken).toHaveBeenCalledTimes(1);+ });++ it("names the settings page when the refresh chain is dead, and never echoes the cause", () => {+ const dead = new CodexSubscriptionTokenError(+ "reauth_required",+ 409,+ "Failed to get a ChatGPT token: [409] secret-bearing detail",+ );+ expect(codexSubscriptionRefreshFailureMessage(dead)).toBe(+ CODEX_SUBSCRIPTION_REFRESH_FAILED_MESSAGES.reauth_required,+ );+ expect(codexSubscriptionRefreshFailureMessage(dead)).not.toContain(+ "secret-bearing",+ );+ expect(+ codexSubscriptionRefreshFailureMessage(new Error("socket hang up")),+ ).toBe(CODEX_SUBSCRIPTION_REFRESH_FAILED_MESSAGES.request_failed);+ });+});diff --git a/products/desktop/packages/agent/src/server/codex-subscription-token.ts b/products/desktop/packages/agent/src/server/codex-subscription-token.tsnew file mode 100644index 000000000000..6e174c523f25--- /dev/null+++ b/products/desktop/packages/agent/src/server/codex-subscription-token.ts@@ -0,0 +1,129 @@+import { createHash } from "node:crypto";+import { CHATGPT_AUTH_TOKENS_REFRESH_TIMEOUT_MS } from "../adapters/codex-app-server/protocol";+import type { ChatgptAuthTokens } from "../adapters/codex-app-server/spawn";+import {+ CodexSubscriptionTokenError,+ type CodexSubscriptionTokenErrorCode,+ type PostHogAPIClient,+} from "../posthog-api";+import type { Logger } from "../utils/logger";++/** Ask for a new token this long before the cached one expires. */+export const CODEX_TOKEN_REFRESH_MARGIN_MS = 60_000;+/** Codex fails the turn if its refresh request is not answered in 10 s. */+export const CODEX_TOKEN_REQUEST_TIMEOUT_MS =+ CHATGPT_AUTH_TOKENS_REFRESH_TIMEOUT_MS - 1_000;++export interface CodexSubscriptionTokenClientOptions {+ posthogAPI: Pick<PostHogAPIClient, "requestCodexSubscriptionToken">;+ taskId: string;+ runId: string;+ runToken: string;+ logger?: Logger;+ now?: () => number;+}++interface CachedGrant {+ tokens: ChatgptAuthTokens;+ expiresAt: number;+}++export const CODEX_SUBSCRIPTION_REFRESH_FAILED_MESSAGES: Record<+ CodexSubscriptionTokenErrorCode,+ string+> = {+ reauth_required:+ "Your ChatGPT login stopped working. Open Desktop, go to Settings > Harness, log in to ChatGPT again, then start the task again.",+ openai_unavailable:+ "OpenAI did not answer the ChatGPT token refresh. Try again in a few minutes.",+ forbidden:+ "This run could not get a new ChatGPT token. Start the task again.",+ request_failed:+ "This run could not get a new ChatGPT token. Start the task again.",+};++export function codexSubscriptionRefreshFailureMessage(error: unknown): string {+ const code: CodexSubscriptionTokenErrorCode =+ error instanceof CodexSubscriptionTokenError+ ? error.code+ : "request_failed";+ return CODEX_SUBSCRIPTION_REFRESH_FAILED_MESSAGES[code];+}++export function accessTokenFingerprint(accessToken: string): string {+ return createHash("sha256").update(accessToken).digest("hex");+}++/**+ * Hands the Codex app-server ChatGPT access tokens for a run on the owner's own+ * plan. The server holds the refresh token and mints a short-lived access+ * token per request; this client only caches the current one and refreshes it+ * before it expires, or when Codex rejects it. A rejection names the rejected+ * token by digest, so the server refreshes once however many runs report it.+ */+export class CodexSubscriptionTokenClient {+ private cached: CachedGrant | null = null;+ private inFlight: Promise<ChatgptAuthTokens> | null = null;+ private readonly now: () => number;++ constructor(private readonly options: CodexSubscriptionTokenClientOptions) {+ this.now = options.now ?? Date.now;+ }++ async get(): Promise<ChatgptAuthTokens> {+ if (+ this.cached &&+ this.cached.expiresAt - CODEX_TOKEN_REFRESH_MARGIN_MS > this.now()+ ) {+ return this.cached.tokens;+ }+ return this.fetch(null);+ }++ /** Codex rejected the current token; the server replaces it, or hands back a newer one it already minted. */+ async refresh(): Promise<ChatgptAuthTokens> {+ const rejected = this.cached+ ? accessTokenFingerprint(this.cached.tokens.accessToken)+ : null;+ return this.fetch(rejected);+ }++ private fetch(+ rejectedAccessTokenSha256: string | null,+ ): Promise<ChatgptAuthTokens> {+ if (this.inFlight) return this.inFlight;+ const request = this.request(rejectedAccessTokenSha256).finally(() => {+ this.inFlight = null;+ });+ this.inFlight = request;+ return request;+ }++ private async request(+ rejectedAccessTokenSha256: string | null,+ ): Promise<ChatgptAuthTokens> {+ const grant = await this.options.posthogAPI.requestCodexSubscriptionToken(+ this.options.taskId,+ this.options.runId,+ this.options.runToken,+ rejectedAccessTokenSha256,+ CODEX_TOKEN_REQUEST_TIMEOUT_MS,+ );+ const tokens: ChatgptAuthTokens = {+ accessToken: grant.access_token,+ chatgptAccountId: grant.account_id,+ chatgptPlanType: grant.plan_type ?? undefined,+ };+ const expiresAt = Date.parse(grant.expires_at);+ this.cached = {+ tokens,+ expiresAt: Number.isNaN(expiresAt) ? this.now() : expiresAt,+ };+ this.options.logger?.info("Fetched a ChatGPT access token for this run", {+ afterRejection: rejectedAccessTokenSha256 !== null,+ planType: tokens.chatgptPlanType,+ expiresAt: grant.expires_at,+ });+ return tokens;+ }+}diff --git a/products/desktop/packages/agent/src/server/types.ts b/products/desktop/packages/agent/src/server/types.tsindex 23eac6ab94bf..6351a454081c 100644--- a/products/desktop/packages/agent/src/server/types.ts+++ b/products/desktop/packages/agent/src/server/types.ts@@ -60,6 +60,9 @@ export interface AgentServerConfig {runtimeAdapter?: Adapter;model?: string;claudeModelAccess?: "posthog-gateway" | "own-subscription";+ codexModelAccess?: "posthog-gateway" | "own-subscription";+ /** Run-scoped secret for the run's ChatGPT token endpoint; read once from fd 3 at boot. */+ codexRunToken?: string;reasoningEffort?: EffortLevel | "off" | "minimal";/*** Codex-only OpenAI service tier for the run's turns. "flex" is the cheaper,diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts b/products/desktop/packages/agent/src/utils/redact-secrets.test.tsindex a9c1758776d9..1360897b7088 100644--- a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts+++ b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts@@ -83,6 +83,12 @@ describe("redactSecrets", () => {},);+ it("redacts every segment of a JWT", () => {+ const jwt = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhY2N0XzEifQ.c2lnbmF0dXJl";+ expect(redactSecrets(`Bearer ${jwt} ok`)).toBe("Bearer [REDACTED] ok");+ expect(redactSecrets(`Bearer ${jwt}. ok`)).toBe("Bearer [REDACTED]. ok");+ });+it.each(headerCases)("redacts a %s", (_shape, server, expected) => {expect(redactSecrets({diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.ts b/products/desktop/packages/agent/src/utils/redact-secrets.tsindex a70b4008b3ff..d204c402d5a7 100644--- a/products/desktop/packages/agent/src/utils/redact-secrets.ts+++ b/products/desktop/packages/agent/src/utils/redact-secrets.ts@@ -17,9 +17,17 @@ function tokenSource(rule: TokenRule, repeat: "+" | "*"): string {const RULES: CompiledRule[] = TOKEN_RULES.map((rule) => ({head: new RegExp(tokenSource(rule, "*"), "g"),- tail: new RegExp(`^${rule.body.source}+`),+ tail: new RegExp(`^${rule.body.source}*`),}));+// A JWT body contains dots, so a match can end in sentence punctuation. The dots belong to+// the token only when more of it follows; at the end of a chunk that is not yet known.+const TRAILING_DOTS = /\.+$/;++function trailingDots(match: string): string {+ return TRAILING_DOTS.exec(match)?.[0] ?? "";+}+const TOKEN = new RegExp(TOKEN_RULES.map((rule) => tokenSource(rule, "+")).join("|"),"g",@@ -54,7 +62,8 @@ export function redactSecrets(value: string): string;export function redactSecrets(value: string | undefined): string | undefined;export function redactSecrets(value: unknown): unknown;export function redactSecrets(value: unknown): unknown {- if (typeof value === "string") return value.replace(TOKEN, REDACTED);+ if (typeof value === "string")+ return value.replace(TOKEN, (match) => REDACTED + trailingDots(match));if (Array.isArray(value)) return value.map(redactSecrets);if (value instanceof Error)return {@@ -126,6 +135,7 @@ export class SecretEventRedactor {private pending: TextEvent | null = null;private active: CompiledRule | null = null;private chunkKind: string | null = null;+ private heldDots = 0;redact(event: Record<string, unknown>): Record<string, unknown>[] {const events: Record<string, unknown>[] = [];@@ -142,25 +152,38 @@ export class SecretEventRedactor {return events;}const previous = this.pending;- let text =- (previous?.notification.params.update.content.text ?? "") +- event.notification.params.update.content.text;+ const previousText =+ previous?.notification.params.update.content.text ?? "";+ let text = previousText + event.notification.params.update.content.text;this.pending = null;+ let heldDots = 0;if (this.active) {- text = text.replace(this.active.tail, "");- if (text.length > 0) this.active = null;+ // The held dots of the previous chunk are part of the continuation.+ const start = previousText.length - this.heldDots;+ const rest = text.slice(start);+ const match = this.active.tail.exec(rest)?.[0] ?? "";+ const dots = trailingDots(match);+ const remainder = rest.slice(match.length - dots.length);+ text = text.slice(0, start) + remainder;+ if (remainder === dots) heldDots = dots.length;+ else if (remainder.length > 0) this.active = null;}for (const rule of RULES) {text = text.replace(rule.head,(match, offset: number, source: string) => {- if (offset + match.length === source.length) this.active = rule;- return REDACTED;+ const dots = trailingDots(match);+ if (offset + match.length === source.length) {+ this.active = rule;+ heldDots = dots.length;+ }+ return REDACTED + dots;},);}const redacted = redactSecrets(withText(event, text)) as TextEvent;- const held = this.active ? 0 : partialPrefixLength(text);+ const held = this.active ? heldDots : partialPrefixLength(text);+ this.heldDots = this.active ? heldDots : 0;if (held > 0) {if (previous) {events.push(withText(previous, text.slice(0, -held)));diff --git a/products/desktop/packages/agent/src/utils/secret-rules.ts b/products/desktop/packages/agent/src/utils/secret-rules.tsindex 9794f5b5ce38..c056af09f391 100644--- a/products/desktop/packages/agent/src/utils/secret-rules.ts+++ b/products/desktop/packages/agent/src/utils/secret-rules.ts@@ -37,6 +37,12 @@ export const TOKEN_RULES: TokenRule[] = [prefix: "phx_",body: URL_SAFE_BODY,},+ {+ // A ChatGPT access token is a JWT; "eyJ" is base64 for the opening of its JSON header.+ label: "jwt",+ prefix: "eyJ",+ body: /[A-Za-z0-9_.-]/,+ },];export const SECRET_HEADERS: string[] = [diff --git a/products/desktop/packages/agent/src/utils/shell-quote.ts b/products/desktop/packages/agent/src/utils/shell-quote.tsnew file mode 100644index 000000000000..9c5a754b4604--- /dev/null+++ b/products/desktop/packages/agent/src/utils/shell-quote.ts@@ -0,0 +1,6 @@+export function shellQuote(value: string): string {+ if (process.platform === "win32") {+ return `"${value.replaceAll('"', '\\"')}"`;+ }+ return `'${value.replaceAll("'", `'\\''`)}'`;+}diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex ff50c973f8d6..8331b3d0ccc4 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -476,6 +476,26 @@ export type Evaluation = Schemas.Evaluation;export type GithubInstallationStatus = "connected" | "unavailable";+export type CodexIntegrationStatus =+ | "not_connected"+ | "connected"+ | "reauth_required";++/** `GET /api/users/@me/integrations/codex/`: the ChatGPT account PostHog holds for the user's cloud Codex runs. */+export interface UserCodexIntegration {+ status: CodexIntegrationStatus;+ plan_type: string | null;+ email: string | null;+ connected_at: string | null;+}++/** The `tokens` object of the `auth.json` that `codex login` writes. */+export interface CodexAuthTokens {+ access_token: string;+ refresh_token: string;+ id_token?: string | null;+}+export interface UserGitHubIntegration {id: string;kind: "github";@@ -1106,6 +1126,7 @@ export interface CloudRunOptions {/** Only false is sent: opts the run out of rtk command-output compression. */rtkEnabled?: boolean;claudeModelAccess?: ModelAccess;+ codexModelAccess?: ModelAccess;runSource?: CloudRunSource;signalReportId?: string;initialPermissionMode?: ExecutionMode;@@ -1259,6 +1280,9 @@ function buildCloudRunRequestBody(if (!options?.piRuntime && options?.claudeModelAccess) {body.claude_model_access = options.claudeModelAccess;}+ if (!options?.piRuntime && options?.codexModelAccess) {+ body.codex_model_access = options.codexModelAccess;+ }if (options?.runSource) {body.run_source = options.runSource;}@@ -2114,6 +2138,65 @@ export class PostHogAPIClient {}}+ async getCodexUserIntegration(): Promise<UserCodexIntegration> {+ const urlPath = `/api/users/@me/integrations/codex/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const response = await this.api.fetcher.fetch({+ method: "get",+ url,+ path: urlPath,+ });+ if (!response.ok) {+ throw new Error(+ `Failed to fetch the ChatGPT account: ${response.statusText}`,+ );+ }+ return (await response.json()) as UserCodexIntegration;+ }++ /**+ * `POST /api/users/@me/integrations/codex/`. PostHog refreshes the chain once and keeps+ * the rotated tokens, so the local `auth.json` is stale after this call.+ */+ async connectCodexUserIntegration(+ tokens: CodexAuthTokens,+ ): Promise<UserCodexIntegration> {+ const urlPath = `/api/users/@me/integrations/codex/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const response = await this.api.fetcher.fetch({+ method: "post",+ url,+ path: urlPath,+ overrides: { body: JSON.stringify({ tokens }) },+ });+ if (!response.ok) {+ const err = (await response.json().catch(() => ({}))) as {+ detail?: unknown;+ };+ throw new Error(+ typeof err.detail === "string"+ ? err.detail+ : `Failed to connect the ChatGPT account: ${response.statusText}`,+ );+ }+ return (await response.json()) as UserCodexIntegration;+ }++ async disconnectCodexUserIntegration(): Promise<void> {+ const urlPath = `/api/users/@me/integrations/codex/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const response = await this.api.fetcher.fetch({+ method: "delete",+ url,+ path: urlPath,+ });+ if (!response.ok && response.status !== 404) {+ throw new Error(+ `Failed to disconnect the ChatGPT account: ${response.statusText}`,+ );+ }+ }+/** `GET /api/users/@me/integrations/github/install_requests/`: installs waiting on a GitHub org owner. */async getGithubInstallRequests(): Promise<GithubInstallRequestsResponse> {const urlPath = `/api/users/@me/integrations/github/install_requests/`;diff --git a/products/desktop/packages/core/src/integrations/codexCloudAccount.module.ts b/products/desktop/packages/core/src/integrations/codexCloudAccount.module.tsnew file mode 100644index 000000000000..e83037a03fdc--- /dev/null+++ b/products/desktop/packages/core/src/integrations/codexCloudAccount.module.ts@@ -0,0 +1,11 @@+import { ContainerModule } from "inversify";+import {+ CODEX_CLOUD_ACCOUNT_SERVICE,+ CodexCloudAccountService,+} from "./codexCloudAccountService";++export const codexCloudAccountModule = new ContainerModule(({ bind }) => {+ bind(CODEX_CLOUD_ACCOUNT_SERVICE)+ .to(CodexCloudAccountService)+ .inSingletonScope();+});diff --git a/products/desktop/packages/core/src/integrations/codexCloudAccountService.test.ts b/products/desktop/packages/core/src/integrations/codexCloudAccountService.test.tsnew file mode 100644index 000000000000..1c22aa13d89c--- /dev/null+++ b/products/desktop/packages/core/src/integrations/codexCloudAccountService.test.ts@@ -0,0 +1,145 @@+import type { UserCodexIntegration } from "@posthog/api-client/posthog-client";+import { describe, expect, it, vi } from "vitest";+import {+ CodexCloudAccountService,+ type CodexCloudTerminal,+} from "./codexCloudAccountService";++const tokens = {+ access_token: "access-example",+ refresh_token: "refresh-example",+ id_token: null,+};++const connected: UserCodexIntegration = {+ status: "connected",+ plan_type: "plus",+ email: "[email protected]",+ connected_at: "2026-01-01T00:00:00Z",+};++describe("connectCodexCloudAccount", () => {+ it("waits for preparation before it cancels the login", async () => {+ let prepared!: (terminal: CodexCloudTerminal) => void;+ const preparation = new Promise<CodexCloudTerminal>((resolve) => {+ prepared = resolve;+ });+ const host = {+ prepare: vi.fn().mockReturnValue(preparation),+ finish: vi.fn(),+ cancel: vi.fn().mockResolvedValue(undefined),+ read: vi.fn(),+ remove: vi.fn(),+ };+ const service = new CodexCloudAccountService(host);+ const login = service.begin("attempt-1");+ const cancel = service.cancel("attempt-1");+ expect(host.cancel).not.toHaveBeenCalled();+ prepared({+ command: "codex",+ cwd: "/tmp",+ additionalEnv: {},+ unsetEnv: [],+ });+ await login;+ await cancel;+ expect(host.cancel).toHaveBeenCalledWith("attempt-1");+ await service.begin("attempt-2");+ });++ it("removes the local login file only after PostHog accepted the tokens", async () => {+ let finishUpload!: (value: UserCodexIntegration) => void;+ const upload = new Promise<UserCodexIntegration>((resolve) => {+ finishUpload = resolve;+ });+ const client = {+ connectCodexUserIntegration: vi.fn().mockReturnValue(upload),+ };+ const host = {+ prepare: vi.fn().mockResolvedValue({+ command: "codex",+ cwd: "/tmp",+ additionalEnv: {},+ unsetEnv: [],+ }),+ finish: vi.fn().mockResolvedValue(undefined),+ cancel: vi.fn().mockResolvedValue(undefined),+ read: vi.fn().mockResolvedValue(tokens),+ remove: vi.fn().mockResolvedValue(undefined),+ };++ const service = new CodexCloudAccountService(host);+ await service.begin("attempt-1");+ const connection = service.connect("attempt-1", client);+ const cancelled = service.cancel("attempt-1");+ await expect(service.begin("attempt-2")).rejects.toThrow("in progress");+ expect(service.connect("attempt-1", client)).toBe(connection);+ expect(host.remove).not.toHaveBeenCalled();+ finishUpload(connected);+ await expect(connection).resolves.toEqual({+ integration: connected,+ staleFileError: null,+ });++ expect(client.connectCodexUserIntegration).toHaveBeenCalledWith(tokens);+ await cancelled;+ expect(host.remove).toHaveBeenCalledWith("attempt-1");+ await service.begin("attempt-2");+ await service.cancel("attempt-1");+ expect(host.cancel).not.toHaveBeenCalled();+ await service.cancel("attempt-2");+ });++ it("reports a connect that left the stale file behind as connected", async () => {+ const client = {+ connectCodexUserIntegration: vi.fn().mockResolvedValue(connected),+ };+ const host = {+ prepare: vi.fn().mockResolvedValue({+ command: "codex",+ cwd: "/tmp",+ additionalEnv: {},+ unsetEnv: [],+ }),+ finish: vi.fn().mockResolvedValue(undefined),+ cancel: vi.fn().mockResolvedValue(undefined),+ read: vi.fn().mockResolvedValue(tokens),+ remove: vi.fn().mockRejectedValue(new Error("EACCES")),+ };++ const service = new CodexCloudAccountService(host);+ await service.begin("attempt-1");+ await expect(service.connect("attempt-1", client)).resolves.toEqual({+ integration: connected,+ staleFileError: new Error("EACCES"),+ });+ });++ it("keeps the local login file when PostHog rejects the tokens", async () => {+ const client = {+ connectCodexUserIntegration: vi+ .fn()+ .mockRejectedValue(new Error("OpenAI rejected the login")),+ };+ const host = {+ prepare: vi.fn().mockResolvedValue({+ command: "codex",+ cwd: "/tmp",+ additionalEnv: {},+ unsetEnv: [],+ }),+ finish: vi.fn().mockResolvedValue(undefined),+ cancel: vi.fn().mockResolvedValue(undefined),+ read: vi.fn().mockResolvedValue(tokens),+ remove: vi.fn().mockResolvedValue(undefined),+ };++ const service = new CodexCloudAccountService(host);+ await service.begin("attempt-1");+ await expect(service.connect("attempt-1", client)).rejects.toThrow(+ "OpenAI rejected the login",+ );++ expect(host.remove).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/core/src/integrations/codexCloudAccountService.ts b/products/desktop/packages/core/src/integrations/codexCloudAccountService.tsnew file mode 100644index 000000000000..b9a29e73cc75--- /dev/null+++ b/products/desktop/packages/core/src/integrations/codexCloudAccountService.ts@@ -0,0 +1,121 @@+import type {+ CodexAuthTokens,+ PostHogAPIClient,+ UserCodexIntegration,+} from "@posthog/api-client/posthog-client";+import { inject, injectable } from "inversify";++export const CODEX_CLOUD_ACCOUNT_HOST = Symbol.for(+ "posthog.core.codexCloudAccountHost",+);+export const CODEX_CLOUD_ACCOUNT_SERVICE = Symbol.for(+ "posthog.core.codexCloudAccountService",+);++export interface CodexCloudTerminal {+ command: string;+ cwd: string;+ additionalEnv: Record<string, string>;+ unsetEnv: string[];+}++export interface CodexCloudAccountHost {+ prepare(attemptId: string): Promise<CodexCloudTerminal>;+ read(attemptId: string): Promise<CodexAuthTokens>;+ remove(attemptId: string): Promise<void>;+ finish(attemptId: string): Promise<void>;+ cancel(attemptId: string): Promise<void>;+}++export interface CodexCloudConnectResult {+ integration: UserCodexIntegration;+ /** A failed cleanup does not undo the accepted connection. */+ staleFileError: Error | null;+}++@injectable()+export class CodexCloudAccountService {+ private attemptId: string | null = null;+ private preparation: Promise<CodexCloudTerminal> | null = null;+ private connection: Promise<CodexCloudConnectResult> | null = null;++ constructor(+ @inject(CODEX_CLOUD_ACCOUNT_HOST)+ private readonly host: CodexCloudAccountHost,+ ) {}++ async begin(attemptId: string): Promise<CodexCloudTerminal> {+ if (this.attemptId !== null) {+ throw new Error(+ "Another ChatGPT login is in progress. Wait for it to finish.",+ );+ }+ this.attemptId = attemptId;+ this.preparation = this.host.prepare(attemptId);+ try {+ return await this.preparation;+ } catch (error) {+ this.attemptId = null;+ throw error;+ } finally {+ this.preparation = null;+ }+ }++ connect(+ attemptId: string,+ client: Pick<PostHogAPIClient, "connectCodexUserIntegration">,+ ): Promise<CodexCloudConnectResult> {+ if (this.attemptId !== attemptId) {+ return Promise.reject(+ new Error("This ChatGPT login attempt is no longer active."),+ );+ }+ if (this.connection) return this.connection;+ this.connection = this.upload(attemptId, client).finally(() => {+ this.attemptId = null;+ this.connection = null;+ });+ return this.connection;+ }++ async cancel(attemptId: string): Promise<void> {+ await this.preparation?.catch(() => undefined);+ if (this.attemptId !== attemptId) return;+ // The upload can rotate tokens, so closing the view must not interrupt its cleanup.+ if (this.connection) {+ await this.connection.catch(() => undefined);+ return;+ }+ await this.host.cancel(attemptId);+ if (this.attemptId === attemptId) this.attemptId = null;+ }++ private async upload(+ attemptId: string,+ client: Pick<PostHogAPIClient, "connectCodexUserIntegration">,+ ): Promise<CodexCloudConnectResult> {+ let integration: UserCodexIntegration;+ try {+ const tokens = await this.host.read(attemptId);+ integration = await client.connectCodexUserIntegration(tokens);+ } catch (error) {+ await this.host.finish(attemptId);+ throw error;+ }+ let staleFileError: Error | null = null;+ try {+ await this.host.remove(attemptId);+ } catch (error) {+ staleFileError =+ error instanceof Error ? error : new Error(String(error));+ }+ try {+ await this.host.finish(attemptId);+ } catch (error) {+ staleFileError ??=+ error instanceof Error ? error : new Error(String(error));+ }+ return { integration, staleFileError };+ }+}diff --git a/products/desktop/packages/core/src/sessions/cloudModelAccess.ts b/products/desktop/packages/core/src/sessions/cloudModelAccess.tsnew file mode 100644index 000000000000..a22e88ab498a--- /dev/null+++ b/products/desktop/packages/core/src/sessions/cloudModelAccess.ts@@ -0,0 +1,31 @@+import type { Adapter, ModelAccess } from "@posthog/shared";++export type CloudModelAccess =+ | { kind: "posthog-gateway" }+ | { kind: "own-subscription"; adapter: Adapter };++export function cloudModelAccessFromState(+ state: Record<string, unknown>,+): CloudModelAccess {+ const claude = state.claude_model_access === "own-subscription";+ const codex = state.codex_model_access === "own-subscription";+ if (claude && codex)+ throw new Error("Select only one subscription for this run.");+ if (!claude && !codex) return { kind: "posthog-gateway" };+ const adapter = codex ? "codex" : "claude";+ if ((state.runtime_adapter ?? "claude") !== adapter) {+ throw new Error(+ `The ${adapter} subscription requires the ${adapter} runtime.`,+ );+ }+ return { kind: "own-subscription", adapter };+}++export function cloudAccessFor(+ access: CloudModelAccess,+ adapter: Adapter,+): ModelAccess {+ return access.kind === "own-subscription" && access.adapter === adapter+ ? "own-subscription"+ : "posthog-gateway";+}diff --git a/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts b/products/desktop/packages/core/src/sessions/cloudRunOptions.test.tsindex 8d2729570131..028f0475662f 100644--- a/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts+++ b/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts@@ -1,6 +1,7 @@import type { AgentSession } from "@posthog/shared";import type { TaskRun } from "@posthog/shared/domain-types";import { describe, expect, it } from "vitest";+import { cloudAccessFor, cloudModelAccessFromState } from "./cloudModelAccess";import {getCloudPrAuthorshipMode,getCloudRunSource,@@ -9,6 +10,34 @@ import {} from "./cloudRunOptions";describe("getCloudPrAuthorshipMode", () => {+ it.each([+ [{}, "posthog-gateway", "posthog-gateway"],+ [+ { claude_model_access: "own-subscription" },+ "own-subscription",+ "posthog-gateway",+ ],+ [+ { runtime_adapter: "codex", codex_model_access: "own-subscription" },+ "posthog-gateway",+ "own-subscription",+ ],+ ])("decodes legacy model access %s", (state, claude, codex) => {+ const access = cloudModelAccessFromState(state);+ expect(cloudAccessFor(access, "claude")).toBe(claude);+ expect(cloudAccessFor(access, "codex")).toBe(codex);+ });++ it.each([+ {+ claude_model_access: "own-subscription",+ codex_model_access: "own-subscription",+ },+ { runtime_adapter: "claude", codex_model_access: "own-subscription" },+ ])("rejects incompatible model access %s", (state) => {+ expect(() => cloudModelAccessFromState(state)).toThrow();+ });+it("honors an explicit user/bot mode", () => {expect(getCloudPrAuthorshipMode({ pr_authorship_mode: "bot" })).toBe("bot");expect(getCloudPrAuthorshipMode({ pr_authorship_mode: "user" })).toBe(diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 9cba555e7e92..70813a4e7dd9 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -97,6 +97,11 @@ import type {} from "./cloudArtifactIdentifiers";import { classifyCloudLogAppend } from "./cloudLogGap";import { CloudLogGapReconciler } from "./cloudLogGapReconciler";+import {+ type CloudModelAccess,+ cloudAccessFor,+ cloudModelAccessFromState,+} from "./cloudModelAccess";import { CloudRunIdleTracker } from "./cloudRunIdleTracker";import {type CloudRuntimeOptions,@@ -528,6 +533,8 @@ export interface SessionServiceDeps {claudeModelAccess?: ModelAccess;claudeCloudSubscriptionOn?: boolean;claudeCloudSubscriptionEnabled?: boolean;+ codexCloudSubscriptionOn?: boolean;+ codexCloudSubscriptionEnabled?: boolean;};usageLimit: { show: (...args: any[]) => any };readonly addDirectoryDialog: { open: boolean };@@ -5461,7 +5468,8 @@ export class SessionService {});runtimeOptions = getCloudRuntimeOptions(session, previousRun);- if (previousState.claude_model_access === "own-subscription") {+ const previousAccess = cloudModelAccessFromState(previousState);+ if (previousAccess.kind === "own-subscription") {if (session.isTaskAuthor === false) {const task = await authCredentials.client.getTask(session.taskId);if (task.channel) {@@ -5470,7 +5478,10 @@ export class SessionService {);}}- await this.resolveClaudeCloudModelAccess("own-subscription");+ await this.resolveCloudModelAccess(+ previousAccess.adapter,+ "own-subscription",+ );}const artifactIds = await this.d.h.uploadTaskStagedAttachments(authCredentials.client,@@ -5491,10 +5502,8 @@ export class SessionService {reasoningLevel: runtimeOptions.reasoningLevel,initialPermissionMode: runtimeOptions.initialPermissionMode,resumeFromRunId: session.taskRunId,- claudeModelAccess:- previousState.claude_model_access === "own-subscription"- ? "own-subscription"- : undefined,+ claudeModelAccess: cloudAccessFor(previousAccess, "claude"),+ codexModelAccess: cloudAccessFor(previousAccess, "codex"),pendingUserMessage: transport.messageText,pendingUserArtifactIds:artifactIds.length > 0 ? artifactIds : undefined,@@ -5509,7 +5518,8 @@ export class SessionService {},);if (- previousState.claude_model_access === "own-subscription" &&+ previousAccess.kind === "own-subscription" &&+ previousAccess.adapter === "claude" &&updatedTask.latest_run?.id) {try {@@ -6753,27 +6763,46 @@ export class SessionService {});}- async resolveClaudeCloudModelAccess(+ async resolveCloudModelAccess(+ adapter: Adapter,requested?: ModelAccess,- ): Promise<ModelAccess> {+ ): Promise<CloudModelAccess> {const access =requested ??- (this.d.settings.claudeCloudSubscriptionOn+ (this.d.settings[`${adapter}CloudSubscriptionOn`]? "own-subscription": "posthog-gateway");- if (access === "own-subscription") {- if (!this.d.settings.claudeCloudSubscriptionEnabled) {+ if (access === "posthog-gateway") return { kind: access };+ if (!this.d.settings[`${adapter}CloudSubscriptionEnabled`]) {+ const plan = adapter === "claude" ? "Claude" : "ChatGPT";+ throw new Error(+ `${plan} plan billing is unavailable for cloud tasks. Try again later.`,+ );+ }+ if (adapter === "claude") {+ if (!(await this.d.trpc.claudeSubscriptionToken.has.query())) {throw new Error(- "Claude plan billing is unavailable for cloud tasks. Try again later.",+ "Save a Claude token in Settings > Harness before you start or resume this task.",);}- if (!(await this.d.trpc.claudeSubscriptionToken.has.query())) {+ } else {+ const authStatus = await this.getAuthCredentialsStatus();+ if (authStatus.kind !== "ready")+ throw new Error("Authentication required for cloud commands");+ const integration =+ await authStatus.auth.client.getCodexUserIntegration();+ if (integration.status === "reauth_required") {throw new Error(- "Save a Claude token in Settings > Harness before you start or resume this task.",+ "Your ChatGPT account needs a new login. Connect it again in Settings > Harness before you start or resume this task.",+ );+ }+ if (integration.status !== "connected") {+ throw new Error(+ "Connect your ChatGPT account in Settings > Harness before you start or resume this task.",);}}- return access;+ return { kind: access, adapter };}async designateClaudeSubscription(@@ -6811,13 +6840,19 @@ export class SessionService {) {this.d.store.setTaskStarting?.(taskId, taskRunId);}- const claudeModelAccess =- runState?.claude_model_access === "own-subscription" ||- runState?.claude_model_access === "posthog-gateway"- ? runState.claude_model_access+ const modelAccessOf = (value: unknown): ModelAccess | undefined =>+ value === "own-subscription" || value === "posthog-gateway"+ ? value: undefined;- if (claudeModelAccess && watchedSession?.taskRunId === taskRunId) {- this.d.store.updateSession(taskRunId, { claudeModelAccess });+ const claudeModelAccess = modelAccessOf(runState?.claude_model_access);+ const codexModelAccess = modelAccessOf(runState?.codex_model_access);+ if (watchedSession?.taskRunId === taskRunId) {+ if (claudeModelAccess) {+ this.d.store.updateSession(taskRunId, { claudeModelAccess });+ }+ if (codexModelAccess) {+ this.d.store.updateSession(taskRunId, { codexModelAccess });+ }}const persistedConfigOptions = this.d.getPersistedConfigOptions(taskRunId);const persistedAdapter = this.d.adapterStore.getAdapter(taskRunId);@@ -8975,12 +9010,18 @@ export class SessionService {if (entry.type !== "notification") continue;const notification = entry.notification as {method?: string;- params?: { initializationPhase?: string; message?: string };+ params?: {+ initializationPhase?: string;+ message?: string;+ reason?: string;+ };};if (- notification.method === POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED &&- notification.params?.initializationPhase === "credential_relay"+ notification.method !== POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED) {+ continue;+ }+ if (notification.params?.initializationPhase === "credential_relay") {this.d.store.updateSession(taskRunId, {status: "error",errorTitle: "Claude token unavailable",@@ -8989,6 +9030,25 @@ export class SessionService {errorRetryable: false,isPromptPending: false,});+ } else if (+ notification.params?.initializationPhase === "subscription_token"+ ) {+ // OpenAI outages and network failures pass; only a dead login or a run that lost its+ // grant needs the user to reconnect.+ const transient =+ notification.params?.reason === "openai_unavailable" ||+ notification.params?.reason === "request_failed";+ this.d.store.updateSession(taskRunId, {+ status: "error",+ errorTitle: transient+ ? "ChatGPT token request failed"+ : "ChatGPT account unavailable",+ errorMessage: transient+ ? "PostHog could not get a ChatGPT token for this run. Start the task again in a few minutes."+ : "Connect your ChatGPT account again in Settings > Harness. Then start the task again.",+ errorRetryable: transient,+ isPromptPending: false,+ });}}}diff --git a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.tsindex 49c3814f40e6..f08376848765 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts@@ -15,6 +15,7 @@ export interface CreateTaskRunClientOptions {branch?: string | null;adapter?: Adapter;claudeModelAccess?: ModelAccess;+ codexModelAccess?: ModelAccess;piRuntime?: boolean;model?: string;reasoningLevel?: string;diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.tsindex b400876da410..aad1fefcec1c 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts@@ -105,6 +105,9 @@ export class TaskCreationSaga extends Saga<const claudeCloudModelAccess = isPiRuntime? undefined: input.claudeCloudModelAccess;+ const codexCloudModelAccess = isPiRuntime+ ? undefined+ : input.codexCloudModelAccess;const folderPromise =!taskId && input.repoPath? this.resolveFolder(input.repoPath)@@ -118,7 +121,8 @@ export class TaskCreationSaga extends Saga<!isPiRuntime &&!taskId &&input.workspaceMode === "cloud" &&- claudeCloudModelAccess !== "own-subscription"+ claudeCloudModelAccess !== "own-subscription" &&+ codexCloudModelAccess !== "own-subscription"? await this.prepareWarmActivation(input): null;@@ -443,6 +447,7 @@ export class TaskCreationSaga extends Saga<adapter: cloudAdapter,...(isPiRuntime ? { piRuntime: true } : {}),claudeModelAccess: claudeCloudModelAccess,+ codexModelAccess: codexCloudModelAccess,model: input.model,reasoningLevel: input.reasoningLevel,contextWindow: isPiRuntime ? undefined : input.contextWindow,@@ -868,7 +873,8 @@ export class TaskCreationSaga extends Saga<const canActivateWarmRun =input.runtime !== "pi" &&!warmPayload?.suppressWarmReuse &&- input.claudeCloudModelAccess !== "own-subscription";+ input.claudeCloudModelAccess !== "own-subscription" &&+ input.codexCloudModelAccess !== "own-subscription";const result = await this.deps.posthogClient.createTask({description,naming_source: namingSource,diff --git a/products/desktop/packages/core/src/task-detail/taskInput.ts b/products/desktop/packages/core/src/task-detail/taskInput.tsindex ee39ddaeab3e..3a6a69055ac5 100644--- a/products/desktop/packages/core/src/task-detail/taskInput.ts+++ b/products/desktop/packages/core/src/task-detail/taskInput.ts@@ -25,6 +25,7 @@ export interface PrepareTaskInputOptions {codexModelAccess?: ModelAccess;claudeModelAccess?: ModelAccess;claudeCloudModelAccess?: ModelAccess;+ codexCloudModelAccess?: ModelAccess;runtime?: AgentRuntime;model?: string;reasoningLevel?: string;@@ -77,6 +78,7 @@ export function prepareTaskInput(codexModelAccess: options.codexModelAccess,claudeModelAccess: options.claudeModelAccess,claudeCloudModelAccess: options.claudeCloudModelAccess,+ codexCloudModelAccess: options.codexCloudModelAccess,runtime,model: options.model,reasoningLevel: options.reasoningLevel,diff --git a/products/desktop/packages/core/src/task-detail/taskService.test.ts b/products/desktop/packages/core/src/task-detail/taskService.test.tsindex 1eab889146cc..1c3230baecc2 100644--- a/products/desktop/packages/core/src/task-detail/taskService.test.ts+++ b/products/desktop/packages/core/src/task-detail/taskService.test.ts@@ -187,14 +187,20 @@ describe("TaskService.createTask validation", () => {{ runtime: "acp" as const, adapter: "codex" as const, blocked: false },{ runtime: "pi" as const, adapter: "claude" as const, blocked: false },{ runtime: "acp" as const, adapter: "claude" as const, blocked: true },+ { runtime: "acp" as const, adapter: "codex" as const, blocked: true },])(- "checks Claude billing before cloud creation for %s",+ "checks subscription billing before cloud creation for %s",async ({ runtime, adapter, blocked }) => {- const resolveClaudeCloudModelAccess = vi+ const resolveCloudModelAccess = vi.fn()- .mockImplementation(async () => {- if (blocked) throw new Error("Save a Claude token first.");- return "own-subscription";+ .mockImplementation(async (selectedAdapter) => {+ if (blocked)+ throw new Error(+ selectedAdapter === "claude"+ ? "Save a Claude token first."+ : "Connect your ChatGPT account first.",+ );+ return { kind: "own-subscription", adapter: selectedAdapter };});const run = vi.spyOn(TaskCreationSaga.prototype, "run")@@ -205,7 +211,7 @@ describe("TaskService.createTask validation", () => {});try {const result = await makeService({- resolveClaudeCloudModelAccess,+ resolveCloudModelAccess,}).createTask({content: "Check the build",@@ -220,15 +226,31 @@ describe("TaskService.createTask validation", () => {expect(run).not.toHaveBeenCalled();expect(result).toMatchObject({success: false,- error: "Save a Claude token first.",+ error:+ adapter === "claude"+ ? "Save a Claude token first."+ : "Connect your ChatGPT account first.",});- } else if (runtime === "acp" && adapter === "claude") {+ } else if (runtime === "pi") {+ expect(resolveCloudModelAccess).not.toHaveBeenCalled();+ expect(run.mock.calls[0][0].claudeCloudModelAccess).toBeUndefined();+ expect(run.mock.calls[0][0].codexCloudModelAccess).toBeUndefined();+ } else if (adapter === "claude") {+ expect(resolveCloudModelAccess).toHaveBeenCalledWith(+ "claude",+ undefined,+ );expect(run.mock.calls[0][0].claudeCloudModelAccess).toBe("own-subscription",);} else {- expect(resolveClaudeCloudModelAccess).not.toHaveBeenCalled();- expect(run.mock.calls[0][0].claudeCloudModelAccess).toBeUndefined();+ expect(resolveCloudModelAccess).toHaveBeenCalledWith(+ "codex",+ undefined,+ );+ expect(run.mock.calls[0][0].codexCloudModelAccess).toBe(+ "own-subscription",+ );}} finally {run.mockRestore();diff --git a/products/desktop/packages/core/src/task-detail/taskService.ts b/products/desktop/packages/core/src/task-detail/taskService.tsindex d75351d69371..c7add9a2299f 100644--- a/products/desktop/packages/core/src/task-detail/taskService.ts+++ b/products/desktop/packages/core/src/task-detail/taskService.ts@@ -2,6 +2,7 @@ import {CLOUD_USAGE_LIMIT_ERROR_MESSAGE,type TaskSessionStorageAccess,} from "@posthog/api-client/posthog-client";+import { cloudAccessFor } from "@posthog/core/sessions/cloudModelAccess";import {SESSION_SERVICE,type SessionService,@@ -153,18 +154,19 @@ export class TaskService {}}- if (- input.workspaceMode === "cloud" &&- input.runtime !== "pi" &&- (input.adapter ?? "claude") === "claude"- ) {+ if (input.workspaceMode === "cloud" && input.runtime !== "pi") {+ const adapter = input.adapter ?? "claude";try {+ const access = await this.sessionService.resolveCloudModelAccess(+ adapter,+ adapter === "claude"+ ? input.claudeCloudModelAccess+ : input.codexCloudModelAccess,+ );input = {...input,- claudeCloudModelAccess:- await this.sessionService.resolveClaudeCloudModelAccess(- input.claudeCloudModelAccess,- ),+ claudeCloudModelAccess: cloudAccessFor(access, "claude"),+ codexCloudModelAccess: cloudAccessFor(access, "codex"),};} catch (error) {return {@@ -173,7 +175,7 @@ export class TaskService {error:error instanceof Error? error.message- : "Could not check Claude plan billing.",+ : "Could not check subscription billing.",};}}diff --git a/products/desktop/packages/host-router/src/routers/agent.router.ts b/products/desktop/packages/host-router/src/routers/agent.router.tsindex 8c4129d1993b..dc029226aa38 100644--- a/products/desktop/packages/host-router/src/routers/agent.router.ts+++ b/products/desktop/packages/host-router/src/routers/agent.router.ts@@ -6,12 +6,14 @@ import type { AgentService } from "@posthog/workspace-server/services/agent/agenimport { AGENT_SERVICE } from "@posthog/workspace-server/services/agent/identifiers";import {AgentServiceEvent,+ authTerminalOutput,cancelPermissionInput,cancelPromptInput,cancelSessionInput,claudeAuthTerminalInput,- claudeAuthTerminalOutput,claudeSubscriptionStatusOutput,+ codexCloudAuthAttemptInput,+ codexCloudAuthTokensOutput,codexSubscriptionLoginOutput,codexSubscriptionStatusOutput,getPiModelCatalogInput,@@ -107,7 +109,7 @@ export const agentRouter = router({claudeAuthTerminal: publicProcedure.input(claudeAuthTerminalInput)- .output(claudeAuthTerminalOutput)+ .output(authTerminalOutput).query(({ ctx, input }) =>ctx.container.get<AgentService>(AGENT_SERVICE)@@ -122,6 +124,40 @@ export const agentRouter = router({.startCodexSubscriptionLogin(),),+ codexCloudAuthTerminal: publicProcedure+ .input(codexCloudAuthAttemptInput)+ .output(authTerminalOutput)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<AgentService>(AGENT_SERVICE)+ .getCodexCloudAuthTerminal(input.attemptId),+ ),++ codexCloudAuthFileRead: publicProcedure+ .input(codexCloudAuthAttemptInput)+ .output(codexCloudAuthTokensOutput)+ .query(({ ctx, input }) =>+ ctx.container+ .get<AgentService>(AGENT_SERVICE)+ .readCodexCloudAuthFile(input.attemptId),+ ),++ codexCloudAuthFileRemove: publicProcedure+ .input(codexCloudAuthAttemptInput)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<AgentService>(AGENT_SERVICE)+ .removeCodexCloudAuthFile(input.attemptId),+ ),++ codexCloudAuthFinish: publicProcedure+ .input(codexCloudAuthAttemptInput)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<AgentService>(AGENT_SERVICE)+ .finishCodexCloudAuth(input.attemptId),+ ),+codexSubscriptionSignOut: publicProcedure.mutation(({ ctx }) =>ctx.container.get<AgentService>(AGENT_SERVICE).signOutCodexSubscription(),),diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 24ad69318186..19708799d996 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -1716,6 +1716,8 @@ export const ANALYTICS_EVENTS = {CLAUDE_SUBSCRIPTION_SIGNED_OUT: "Claude subscription signed out",CLAUDE_CLOUD_TOKEN_SAVED: "Claude cloud token saved",CLAUDE_CLOUD_TOKEN_REMOVED: "Claude cloud token removed",+ CODEX_CLOUD_ACCOUNT_CONNECTED: "Codex cloud account connected",+ CODEX_CLOUD_ACCOUNT_DISCONNECTED: "Codex cloud account disconnected",CLOUD_CREDENTIAL_RELAY: "Cloud credential relay",// Feedback events@@ -1927,6 +1929,8 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.SETTING_CHANGED]: SettingChangedProperties;[ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_SAVED]: never;[ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_REMOVED]: never;+ [ANALYTICS_EVENTS.CODEX_CLOUD_ACCOUNT_CONNECTED]: never;+ [ANALYTICS_EVENTS.CODEX_CLOUD_ACCOUNT_DISCONNECTED]: never;[ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY]: CloudCredentialRelayProperties;[ANALYTICS_EVENTS.CUSTOM_SOUND_ADDED]: CustomSoundAddedProperties;[ANALYTICS_EVENTS.SETTINGS_BACKUP_EXPORTED]: SettingsBackupExportProperties;diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.jsonindex 06c1cc11d15b..a4de55cd902f 100644--- a/products/desktop/packages/shared/src/feature-flag-keys.json+++ b/products/desktop/packages/shared/src/feature-flag-keys.json@@ -10,6 +10,7 @@"CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG": "posthog-code-claude-own-subscription-cloud","CLOUD_COMPUTE_BILLING_FLAG": "posthog-desktop-cloud-compute-billing","CODEX_OWN_SUBSCRIPTION_FLAG": "posthog-code-codex-own-subscription",+ "CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG": "posthog-code-codex-own-subscription-cloud","CONTEXT_LAYER_FLAG": "context-layer","CUSTOM_IMAGES_FEATURE_FLAG": "tasks-modal-vm-sandbox","DESKTOP_HOME_FLAG": "desktop-home-flag",diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex d5a4fe881cab..01fcc12d7ee4 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -38,6 +38,8 @@ export const FAST_MODE_FLAG = featureFlagKeys.FAST_MODE_FLAG;export const SPOKEN_NARRATION_FLAG = featureFlagKeys.SPOKEN_NARRATION_FLAG;export const CODEX_OWN_SUBSCRIPTION_FLAG =featureFlagKeys.CODEX_OWN_SUBSCRIPTION_FLAG;+export const CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG =+ featureFlagKeys.CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG;export const CLAUDE_OWN_SUBSCRIPTION_FLAG =featureFlagKeys.CLAUDE_OWN_SUBSCRIPTION_FLAG;export const CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG =diff --git a/products/desktop/packages/shared/src/task-creation-domain.ts b/products/desktop/packages/shared/src/task-creation-domain.tsindex ace250e44ffa..531cca99cadf 100644--- a/products/desktop/packages/shared/src/task-creation-domain.ts+++ b/products/desktop/packages/shared/src/task-creation-domain.ts@@ -40,6 +40,7 @@ export interface TaskCreationInput {codexModelAccess?: ModelAccess;claudeModelAccess?: ModelAccess;claudeCloudModelAccess?: ModelAccess;+ codexCloudModelAccess?: ModelAccess;runtime?: AgentRuntime;model?: string;reasoningLevel?: string;diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsxindex ef9f587a3248..e745704fa516 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx@@ -998,7 +998,7 @@ describe("ReasoningLevelSelector", () => {it.each([["claude", "Anthropic", /^Claude plan billing is unavailable/],- ["codex", "OpenAI", /^OpenAI billing only works/],+ ["codex", "OpenAI", /^ChatGPT plan billing is unavailable/],] as const)("disables the %s billing option for cloud tasks and names the reason",async (adapter, planLabel, reason) => {diff --git a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsxindex 191ce24a7338..7aa9395f253e 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx@@ -17,6 +17,7 @@ import {type WorkspaceModeForAccess,} from "@posthog/ui/features/settings/adapterSubscription";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/settings/subscriptionActions";const PROVIDER_LABEL: Record<Adapter, string> = {claude: "Anthropic",@@ -34,16 +35,11 @@ const LOGIN_NOTE: Record<Adapter, { link: string; rest: string }> = {},};-export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {- claude: "claude-login",- codex: "codex-login",-};-const CLOUD_ONLY_REASON: Record<Adapter, string> = {claude:"Claude plan billing is unavailable for cloud tasks. Try again later.",codex:- "OpenAI billing only works for local and worktree tasks. Cloud tasks always use PostHog.",+ "ChatGPT plan billing is unavailable for cloud tasks. Try again later.",};const TOOLTIP_DELAY_MS = 150;@@ -61,27 +57,40 @@ export function SubscriptionSubmenu({}: SubscriptionSubmenuProps): React.JSX.Element | null {const subscription = useAdapterSubscription(adapter);const cloudTask = workspaceMode === "cloud";- const cloudAvailable = adapter === "claude" && subscription.cloudFlagEnabled;- if (- cloudTask- ? !subscription.flagEnabled &&- !cloudAvailable &&- !subscription.cloudSubscriptionOn- : !subscription.flagEnabled- ) {+ const cloudAvailable = cloudTask && subscription.cloudFlagEnabled;+ const available = subscription.flagEnabled || cloudAvailable;+ if (!available) {return null;}+const providerLabel = PROVIDER_LABEL[adapter];- const value: ModelAccess = cloudTask+ const selected: ModelAccess = cloudTask? subscriptionModelAccess(subscription, "cloud"): subscription.subscriptionOn? "own-subscription": "posthog-gateway";+ const effective = subscriptionModelAccess(+ subscription,+ workspaceMode ?? "local",+ );const valueLabel =- subscriptionModelAccess(subscription, workspaceMode ?? "local") ===- "own-subscription"- ? providerLabel- : "PostHog";+ effective === "own-subscription" ? providerLabel : "PostHog";+ const providerLocked = cloudTask && !cloudAvailable;+ const showLoginNote =+ !cloudTask && subscription.subscriptionOn && !subscription.loggedIn;++ const selectAccess = (next: string): void => {+ const ownSubscription = next === "own-subscription";+ if (cloudTask) {+ subscription.setCloudSubscriptionOn(ownSubscription);+ return;+ }+ applyModelAccess(+ adapter,+ ownSubscription ? "own-subscription" : "posthog-gateway",+ subscription.loggedIn,+ );+ };return (<DropdownMenuSub>@@ -92,29 +101,14 @@ export function SubscriptionSubmenu({</span></DropdownMenuSubTrigger><DropdownMenuSubContent>- <DropdownMenuRadioGroup- value={value}- onValueChange={(next) =>- cloudTask && adapter === "claude"- ? subscription.setCloudSubscriptionOn?.(- next === "own-subscription",- )- : applyModelAccess(- adapter,- next === "own-subscription"- ? "own-subscription"- : "posthog-gateway",- subscription.loggedIn,- )- }- >+ <DropdownMenuRadioGroup value={selected} onValueChange={selectAccess}><DropdownMenuRadioItemvalue="posthog-gateway"closeOnClick={closeOnChange}>PostHog</DropdownMenuRadioItem>- {cloudTask && !cloudAvailable ? (+ {providerLocked ? (<TooltipProvider delay={TOOLTIP_DELAY_MS}><Tooltip disableHoverablePopup><TooltipTrigger render={<span className="flex" />}>@@ -141,27 +135,25 @@ export function SubscriptionSubmenu({</DropdownMenuRadioItem>)}</DropdownMenuRadioGroup>- {!cloudTask &&- subscription.subscriptionOn &&- !subscription.loggedIn && (- // A quiet inline note rather than a permanent menu row: it appears- // only once the provider option is picked without a confirmed- // login, and sessions keep running on PostHog until the login- // completes. Unknown status counts as not logged in, so the note- // stays reachable when the status check cannot run or is pending.- <div className="px-2 py-1.5 text-muted-foreground text-xs">- <button- type="button"- className="underline underline-offset-2 hover:text-foreground"- onClick={() =>- openSettings("harness", SUBSCRIPTION_LOGIN_ACTION[adapter])- }- >- {LOGIN_NOTE[adapter].link}- </button>- {LOGIN_NOTE[adapter].rest}- </div>- )}+ {showLoginNote && (+ // A quiet inline note rather than a permanent menu row: it appears+ // only once the provider option is picked without a confirmed+ // login, and sessions keep running on PostHog until the login+ // completes. Unknown status counts as not logged in, so the note+ // stays reachable when the status check cannot run or is pending.+ <div className="px-2 py-1.5 text-muted-foreground text-xs">+ <button+ type="button"+ className="underline underline-offset-2 hover:text-foreground"+ onClick={() =>+ openSettings("harness", SUBSCRIPTION_LOGIN_ACTION[adapter])+ }+ >+ {LOGIN_NOTE[adapter].link}+ </button>+ {LOGIN_NOTE[adapter].rest}+ </div>+ )}</DropdownMenuSubContent></DropdownMenuSub>);diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex ea6767b09ae1..f20aae25a7c7 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -7997,10 +7997,9 @@ describe("SessionService", () => {const service = getSessionService();mockFeatureFlags.isEnabled.mockReturnValue(true);if (tokenMissing)- vi.spyOn(- service,- "resolveClaudeCloudModelAccess",- ).mockRejectedValueOnce(new Error("Save a Claude token first."));+ vi.spyOn(service, "resolveCloudModelAccess").mockRejectedValueOnce(+ new Error("Save a Claude token first."),+ );mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(createMockSession({isCloud: true,diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.tsindex ab903c6df578..9ee38c851bab 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts@@ -25,6 +25,7 @@ import {type BedrockGatewayVariant,CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,CLAUDE_OWN_SUBSCRIPTION_FLAG,+ CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG,CODEX_OWN_SUBSCRIPTION_FLAG,SPOKEN_NARRATION_FLAG,} from "@posthog/shared";@@ -166,6 +167,9 @@ function buildSessionServiceDeps(): SessionServiceDeps {claudeCloudSubscriptionEnabled: featureFlags.isEnabled(CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,),+ codexCloudSubscriptionEnabled: featureFlags.isEnabled(+ CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG,+ ),customInstructions: getEffectiveCustomInstructions(state),spokenNarrationEnabled: shouldEnableSpokenNarration(state.spokenNotifications,diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.tsindex 83c339d639c8..ad79c64139c7 100644--- a/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts@@ -106,6 +106,7 @@ describe("adapter subscription gating", () => {loginState: "unknown",needsConnection: false,setSubscriptionOn: () => {},+ setCloudSubscriptionOn: () => {},},"cloud",),diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.tsindex 45bf53b26058..5e316b3f295b 100644--- a/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts@@ -4,6 +4,7 @@ import {ANALYTICS_EVENTS,CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,CLAUDE_OWN_SUBSCRIPTION_FLAG,+ CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG,CODEX_OWN_SUBSCRIPTION_FLAG,type ModelAccess,} from "@posthog/shared";@@ -28,26 +29,38 @@ export type WorkspaceModeForAccess = "local" | "worktree" | "cloud";interface AdapterSubscriptionSpec {flag: string;+ cloudFlag: string;settingName: string;+ cloudSettingName: string;statusProcedure: "claudeSubscriptionStatus" | "codexSubscriptionStatus";readAccess: (state: SettingsStore) => ModelAccess;writeAccess: (state: SettingsStore, next: ModelAccess) => void;+ readCloudOn: (state: SettingsStore) => boolean;+ writeCloudOn: (state: SettingsStore, next: boolean) => void;}const SPECS: Record<Adapter, AdapterSubscriptionSpec> = {claude: {flag: CLAUDE_OWN_SUBSCRIPTION_FLAG,+ cloudFlag: CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,settingName: "claude_model_access",+ cloudSettingName: "claude_cloud_subscription_on",statusProcedure: "claudeSubscriptionStatus",readAccess: (state) => state.claudeModelAccess,writeAccess: (state, next) => state.setClaudeModelAccess(next),+ readCloudOn: (state) => state.claudeCloudSubscriptionOn,+ writeCloudOn: (state, next) => state.setClaudeCloudSubscriptionOn(next),},codex: {flag: CODEX_OWN_SUBSCRIPTION_FLAG,+ cloudFlag: CODEX_OWN_SUBSCRIPTION_CLOUD_FLAG,settingName: "codex_model_access",+ cloudSettingName: "codex_cloud_subscription_on",statusProcedure: "codexSubscriptionStatus",readAccess: (state) => state.codexModelAccess,writeAccess: (state, next) => state.setCodexModelAccess(next),+ readCloudOn: (state) => state.codexCloudSubscriptionOn,+ writeCloudOn: (state, next) => state.setCodexCloudSubscriptionOn(next),},};@@ -113,13 +126,14 @@ export function applyModelAccess(registerAdapterSubscription(adapter, { access: next, connected });}-export function setClaudeCloudSubscriptionOn(next: boolean): void {+export function setCloudSubscriptionOn(adapter: Adapter, next: boolean): void {+ const spec = SPECS[adapter];const state = useSettingsStore.getState();- const previous = state.claudeCloudSubscriptionOn;+ const previous = spec.readCloudOn(state);if (previous === next) return;- state.setClaudeCloudSubscriptionOn(next);+ spec.writeCloudOn(state, next);track(ANALYTICS_EVENTS.SETTING_CHANGED, {- setting_name: "claude_cloud_subscription_on",+ setting_name: spec.cloudSettingName,old_value: previous,new_value: next,});@@ -160,9 +174,9 @@ function settingsHydrated(): Promise<void> {}export interface AdapterSubscription {- cloudFlagEnabled?: boolean;- cloudSubscriptionOn?: boolean;- setCloudSubscriptionOn?: (on: boolean) => void;+ cloudFlagEnabled: boolean;+ cloudSubscriptionOn: boolean;+ setCloudSubscriptionOn: (on: boolean) => void;flagEnabled: boolean;subscriptionOn: boolean;status: SubscriptionStatus | undefined;@@ -174,10 +188,8 @@ export interface AdapterSubscription {export function useAdapterSubscription(adapter: Adapter): AdapterSubscription {const spec = SPECS[adapter];- const cloudFlagEnabled = useFeatureFlag(CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG);- const cloudSubscriptionOn = useSettingsStore(- (state) => state.claudeCloudSubscriptionOn,- );+ const cloudFlagEnabled = useFeatureFlag(spec.cloudFlag);+ const cloudSubscriptionOn = useSettingsStore(spec.readCloudOn);const flagEnabled = useFeatureFlag(spec.flag) || import.meta.env.DEV;const modelAccess = useSettingsStore(spec.readAccess);const { localWorkspaces } = useHostCapabilities();@@ -199,10 +211,10 @@ export function useAdapterSubscription(adapter: Adapter): AdapterSubscription {const loginState = status?.loginState ?? "unknown";return {- cloudFlagEnabled:- adapter === "claude" && localWorkspaces && cloudFlagEnabled,- cloudSubscriptionOn: adapter === "claude" && cloudSubscriptionOn,- setCloudSubscriptionOn: setClaudeCloudSubscriptionOn,+ cloudFlagEnabled: localWorkspaces && cloudFlagEnabled,+ cloudSubscriptionOn:+ localWorkspaces && cloudFlagEnabled && cloudSubscriptionOn,+ setCloudSubscriptionOn: (on) => setCloudSubscriptionOn(adapter, on),flagEnabled,subscriptionOn,status,diff --git a/products/desktop/packages/ui/src/features/settings/codexCloudAccount.ts b/products/desktop/packages/ui/src/features/settings/codexCloudAccount.tsnew file mode 100644index 000000000000..2f34fa63297b--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/codexCloudAccount.ts@@ -0,0 +1,94 @@+import type { UserCodexIntegration } from "@posthog/api-client/posthog-client";+import {+ CODEX_CLOUD_ACCOUNT_SERVICE,+ type CodexCloudAccountService,+ type CodexCloudConnectResult,+} from "@posthog/core/integrations/codexCloudAccountService";+import { useServiceOptional } from "@posthog/di/react";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { toast } from "@posthog/ui/primitives/toast";+import { track } from "@posthog/ui/shell/analytics";+import {+ type UseMutationResult,+ type UseQueryResult,+ useMutation,+ useQuery,+ useQueryClient,+} from "@tanstack/react-query";++export const codexCloudAccountQueryKey = ["codex-cloud-account"] as const;++export function useCodexCloudAccount(): UseQueryResult<UserCodexIntegration> {+ const client = useOptionalAuthenticatedClient();+ return useQuery({+ queryKey: codexCloudAccountQueryKey,+ queryFn: () => {+ if (!client) throw new Error("Log in to PostHog first.");+ return client.getCodexUserIntegration();+ },+ enabled: !!client,+ retry: false,+ });+}++export function useCodexCloudAccountService(): CodexCloudAccountService | null {+ return useServiceOptional<CodexCloudAccountService>(+ CODEX_CLOUD_ACCOUNT_SERVICE,+ );+}++export function useConnectCodexCloudAccount(): UseMutationResult<+ CodexCloudConnectResult,+ Error,+ string+> {+ const client = useOptionalAuthenticatedClient();+ const service = useCodexCloudAccountService();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (attemptId) => {+ if (!client) throw new Error("Log in to PostHog first.");+ if (!service)+ throw new Error("ChatGPT login is unavailable on this device.");+ return service.connect(attemptId, client);+ },+ onSuccess: ({ integration, staleFileError }) => {+ queryClient.setQueryData(codexCloudAccountQueryKey, integration);+ track(ANALYTICS_EVENTS.CODEX_CLOUD_ACCOUNT_CONNECTED);+ if (staleFileError) {+ toast.warning("ChatGPT account connected", {+ description: `Desktop could not delete the old login file. Remove ~/.codex-posthog/auth.json by hand. ${staleFileError.message}`,+ });+ } else {+ toast.success("ChatGPT account connected");+ }+ },+ });+}++export function useDisconnectCodexCloudAccount(): UseMutationResult<+ void,+ Error,+ void+> {+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: () => {+ if (!client) throw new Error("Log in to PostHog first.");+ return client.disconnectCodexUserIntegration();+ },+ onSuccess: () => {+ queryClient.setQueryData<UserCodexIntegration>(+ codexCloudAccountQueryKey,+ {+ status: "not_connected",+ plan_type: null,+ email: null,+ connected_at: null,+ },+ );+ },+ });+}diff --git a/products/desktop/packages/ui/src/features/settings/components/AuthTerminalPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/AuthTerminalPanel.tsxnew file mode 100644index 000000000000..a9fd290bd12d--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/components/AuthTerminalPanel.tsx@@ -0,0 +1,85 @@+import { Terminal } from "@posthog/ui/features/terminal/Terminal";+import { useThemeStore } from "@posthog/ui/shell/themeStore";+import type { ReactElement } from "react";++export type AuthTerminalStatus = "running" | "checking" | "done" | "failed";++export interface AuthTerminalConfig {+ command: string;+ cwd: string;+ additionalEnv: Record<string, string>;+ unsetEnv: string[];+}++interface AuthTerminalPanelProps {+ sessionId: string;+ commandLabel: string;+ status: AuthTerminalStatus;+ terminal: AuthTerminalConfig;+ onExit: (exitCode?: number) => void;+}++const SURFACE = {+ dark: { body: "#131316", chrome: "#1c1c21", text: "#e6e6e6" },+ light: { body: "#f2f3ee", chrome: "#e7e9e1", text: "#3a4036" },+} as const;++const PILL: Record<AuthTerminalStatus, { dot: string; label: string }> = {+ running: {+ dot: "animate-pulse bg-(--amber-9) motion-reduce:animate-none",+ label: "Running",+ },+ checking: {+ dot: "animate-pulse bg-(--gray-9) motion-reduce:animate-none",+ label: "Checking",+ },+ done: { dot: "bg-(--green-9)", label: "Done" },+ failed: { dot: "bg-(--red-9)", label: "Failed" },+};++export function AuthTerminalPanel({+ sessionId,+ commandLabel,+ status,+ terminal,+ onExit,+}: AuthTerminalPanelProps): ReactElement {+ const isDarkMode = useThemeStore((state) => state.isDarkMode);+ const surface = isDarkMode ? SURFACE.dark : SURFACE.light;++ return (+ <div+ className="overflow-hidden rounded-(--radius-3) border border-border shadow-sm"+ style={{ backgroundColor: surface.body, color: surface.text }}+ >+ <div+ className="flex items-center justify-between border-black/10 border-b px-3 py-1.5"+ style={{ backgroundColor: surface.chrome }}+ >+ <span className="flex items-center gap-2 font-mono text-[11px] opacity-80">+ <span aria-hidden>❯</span>+ {commandLabel}+ </span>+ <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-wide opacity-70">+ <span+ className={`inline-block h-1.5 w-1.5 rounded-full ${PILL[status].dot}`}+ aria-hidden+ />+ {PILL[status].label}+ </span>+ </div>+ <div className="h-72">+ <Terminal+ sessionId={sessionId}+ persistenceKey={sessionId}+ cwd={terminal.cwd}+ command={terminal.command}+ additionalEnv={terminal.additionalEnv}+ unsetEnv={terminal.unsetEnv}+ sensitive+ onExit={onExit}+ />+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsxindex 8b68b31b43f8..5630b6fc2d2b 100644--- a/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx@@ -8,9 +8,11 @@ import {DialogHeader,DialogTitle,} from "@posthog/quill";+import {+ AuthTerminalPanel,+ type AuthTerminalStatus,+} from "@posthog/ui/features/settings/components/AuthTerminalPanel";import { destroyTerminalSession } from "@posthog/ui/features/terminal/destroyShellTerminal";-import { Terminal } from "@posthog/ui/features/terminal/Terminal";-import { useThemeStore } from "@posthog/ui/shell/themeStore";import { secureRandomString } from "@posthog/ui/utils/random";import { useQuery } from "@tanstack/react-query";import { type ReactElement, useCallback, useEffect, useState } from "react";@@ -23,11 +25,6 @@ interface ClaudeAuthTerminalDialogProps {onFinished: () => void;}-const SURFACE = {- dark: { body: "#131316", chrome: "#1c1c21", text: "#e6e6e6" },- light: { body: "#f2f3ee", chrome: "#e7e9e1", text: "#3a4036" },-} as const;-const COPY = {"setup-token": {title: "Create a Claude token",@@ -53,28 +50,12 @@ const COPY = {},} as const;-type Status = "running" | "checking" | "done" | "failed";--const PILL: Record<Status, { dot: string; label: string }> = {- running: {- dot: "animate-pulse bg-(--amber-9) motion-reduce:animate-none",- label: "Running",- },- checking: {- dot: "animate-pulse bg-(--gray-9) motion-reduce:animate-none",- label: "Checking",- },- done: { dot: "bg-(--green-9)", label: "Done" },- failed: { dot: "bg-(--red-9)", label: "Failed" },-};-export function ClaudeAuthTerminalDialog({action,onClose,onFinished,}: ClaudeAuthTerminalDialogProps): ReactElement {const hostTRPC = useHostTRPC();- const isDarkMode = useThemeStore((state) => state.isDarkMode);const [started, setStarted] = useState(action !== "logout");const {data: terminal,@@ -108,9 +89,8 @@ export function ClaudeAuthTerminalDialog({})();const copy = COPY[action];- const surface = isDarkMode ? SURFACE.dark : SURFACE.light;- const status = ((): Status => {+ const status = ((): AuthTerminalStatus => {if (terminalError) return "failed";if (!stopped) return "running";if (verified === undefined) return "checking";@@ -169,39 +149,13 @@ export function ClaudeAuthTerminalDialog({</span>) : null}{started && terminal ? (- <div- className="overflow-hidden rounded-(--radius-3) border border-(--gray-6) shadow-sm"- style={{ backgroundColor: surface.body, color: surface.text }}- >- <div- className="flex items-center justify-between border-black/10 border-b px-3 py-1.5"- style={{ backgroundColor: surface.chrome }}- >- <span className="flex items-center gap-2 font-mono text-[11px] opacity-80">- <span aria-hidden>❯</span>- {copy.command}- </span>- <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-wide opacity-70">- <span- className={`inline-block h-1.5 w-1.5 rounded-full ${PILL[status].dot}`}- aria-hidden- />- {PILL[status].label}- </span>- </div>- <div className="h-44">- <Terminal- sessionId={sessionId}- persistenceKey={sessionId}- cwd={terminal.cwd}- command={terminal.command}- additionalEnv={terminal.additionalEnv}- unsetEnv={terminal.unsetEnv}- sensitive- onExit={handleExit}- />- </div>- </div>+ <AuthTerminalPanel+ sessionId={sessionId}+ commandLabel={copy.command}+ status={status}+ terminal={terminal}+ onExit={handleExit}+ />) : null}</DialogBody><DialogFooter className="items-center justify-between gap-3">diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsxindex 68f63a823451..59e0db1587e2 100644--- a/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx@@ -1,7 +1,7 @@import { useServiceOptional } from "@posthog/di/react";import { Button, Input, Switch } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";-import { setClaudeCloudSubscriptionOn as setCloudSubscriptionOn } from "@posthog/ui/features/settings/adapterSubscription";+import { setCloudSubscriptionOn } from "@posthog/ui/features/settings/adapterSubscription";import {CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,type ClaudeSubscriptionTokenSettings,@@ -102,7 +102,7 @@ export function ClaudeCloudTokenSection({onCheckedChange={(checked) => {const next = checked === true;if (next === cloudSubscriptionOn) return;- setCloudSubscriptionOn(next);+ setCloudSubscriptionOn("claude", next);}}/></div>diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsxindex fd4ce9517a7f..83a140fc6aba 100644--- a/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx@@ -1,11 +1,11 @@import { useHostTRPC } from "@posthog/host-router/react";import { Button, Switch } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";-import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";import { useAdapterSubscription } from "@posthog/ui/features/settings/adapterSubscription";import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";+import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/settings/subscriptionActions";import { track } from "@posthog/ui/shell/analytics";import { registerAdapterSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";import { useQuery, useQueryClient } from "@tanstack/react-query";diff --git a/products/desktop/packages/ui/src/features/settings/sections/CodexCloudAuthTerminalDialog.tsx b/products/desktop/packages/ui/src/features/settings/sections/CodexCloudAuthTerminalDialog.tsxnew file mode 100644index 000000000000..49c313d1c0ed--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/CodexCloudAuthTerminalDialog.tsx@@ -0,0 +1,106 @@+import type { CodexCloudTerminal } from "@posthog/core/integrations/codexCloudAccountService";+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@posthog/quill";+import { useConnectCodexCloudAccount } from "@posthog/ui/features/settings/codexCloudAccount";+import {+ AuthTerminalPanel,+ type AuthTerminalStatus,+} from "@posthog/ui/features/settings/components/AuthTerminalPanel";+import { type ReactElement, useCallback, useState } from "react";++interface CodexCloudAuthTerminalDialogProps {+ onClose: () => void;+ sessionId: string;+ terminal: CodexCloudTerminal;+}++export function CodexCloudAuthTerminalDialog({+ onClose,+ sessionId,+ terminal,+}: CodexCloudAuthTerminalDialogProps): ReactElement {+ const connect = useConnectCodexCloudAccount();+ const [stopped, setStopped] = useState(false);+ const [connectError, setConnectError] = useState<string | null>(null);++ const connected = connect.isSuccess;++ const status = ((): AuthTerminalStatus => {+ if (connectError) return "failed";+ if (!stopped) return "running";+ if (connected) return "done";+ return "checking";+ })();++ const hint = ((): string => {+ if (connectError) return connectError;+ if (!stopped) return "Finish the login in this terminal.";+ if (connected)+ return "ChatGPT account connected. You can close this window.";+ return "Handing the login to PostHog.";+ })();++ const handleExit = useCallback(+ (code?: number) => {+ setStopped(true);+ if (code !== 0) {+ setConnectError(+ "The login did not complete. Read the output, then try again.",+ );+ return;+ }+ connect.mutate(sessionId, {+ onError: (error) => setConnectError(error.message),+ });+ },+ [connect.mutate, sessionId],+ );++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>Log in with ChatGPT</DialogTitle>+ </DialogHeader>+ <DialogBody className="flex flex-col gap-3">+ <p className="text-muted-foreground text-xs leading-relaxed">+ Follow the steps in this terminal. Desktop hands the login to+ PostHog when it finishes. This login is separate from your local+ codex login.+ </p>++ <AuthTerminalPanel+ sessionId={sessionId}+ commandLabel="codex login --device-auth"+ status={status}+ terminal={terminal}+ onExit={handleExit}+ />+ </DialogBody>+ <DialogFooter className="items-center justify-between gap-3">+ <span+ role={connectError ? "alert" : undefined}+ className="text-[11px] text-muted-foreground"+ >+ {hint}+ </span>+ <Button+ variant={connected ? "primary" : "outline"}+ size="sm"+ data-attr="codex-cloud-login-close"+ onClick={onClose}+ >+ {stopped ? "Close" : "Cancel"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/CodexCloudSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/CodexCloudSection.tsxnew file mode 100644index 000000000000..c1bf8b7726f1--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/CodexCloudSection.tsx@@ -0,0 +1,164 @@+import type { CodexCloudTerminal } from "@posthog/core/integrations/codexCloudAccountService";+import { Button, Switch } from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared";+import { setCloudSubscriptionOn } from "@posthog/ui/features/settings/adapterSubscription";+import {+ useCodexCloudAccount,+ useCodexCloudAccountService,+ useDisconnectCodexCloudAccount,+} from "@posthog/ui/features/settings/codexCloudAccount";+import { CodexCloudAuthTerminalDialog } from "@posthog/ui/features/settings/sections/CodexCloudAuthTerminalDialog";+import { destroyTerminalSession } from "@posthog/ui/features/terminal/destroyShellTerminal";+import { toast } from "@posthog/ui/primitives/toast";+import { track } from "@posthog/ui/shell/analytics";+import { secureRandomString } from "@posthog/ui/utils/random";+import { useMutation } from "@tanstack/react-query";+import {+ type ReactElement,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";++interface CodexCloudSectionProps {+ cloudSubscriptionOn: boolean;+}++export function CodexCloudSection({+ cloudSubscriptionOn,+}: CodexCloudSectionProps): ReactElement {+ const account = useCodexCloudAccount();+ const disconnect = useDisconnectCodexCloudAccount();+ const service = useCodexCloudAccountService();+ const activeAttempt = useRef<string | null>(null);+ const endAttempt = useCallback((): void => {+ const id = activeAttempt.current;+ activeAttempt.current = null;+ if (!id) return;+ destroyTerminalSession(id);+ void service+ ?.cancel(id)+ .catch((error: Error) => toast.error(error.message));+ }, [service]);+ useEffect(() => endAttempt, [endAttempt]);+ const [login, setLogin] = useState<{+ id: string;+ terminal: CodexCloudTerminal;+ } | null>(null);+ const start = useMutation({+ mutationFn: async () => {+ if (!service)+ throw new Error("ChatGPT login is unavailable on this device.");+ const id = `codex-cloud-login-${secureRandomString(7)}`;+ activeAttempt.current = id;+ return { id, terminal: await service.begin(id) };+ },+ onSuccess: (result) => {+ if (activeAttempt.current === result.id) setLogin(result);+ },+ onError: (error: Error) => {+ activeAttempt.current = null;+ toast.error(error.message);+ },+ });+ const closeLogin = (): void => {+ endAttempt();+ setLogin(null);+ };+ const pending = disconnect.isPending || start.isPending;+ const status = account.data?.status ?? "not_connected";++ const disconnectAccount = (): void => {+ if (pending) return;+ disconnect.mutate(undefined, {+ onSuccess: () => {+ track(ANALYTICS_EVENTS.CODEX_CLOUD_ACCOUNT_DISCONNECTED);+ toast.success("ChatGPT account disconnected");+ },+ onError: (error) =>+ toast.error("Cannot disconnect the ChatGPT account.", {+ description: error.message,+ }),+ });+ };++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <span className="font-medium text-xs">Cloud tasks</span>+ <Switch+ size="sm"+ aria-label="Use your ChatGPT plan for cloud tasks"+ data-attr="codex-cloud-subscription-toggle"+ checked={cloudSubscriptionOn}+ disabled={pending}+ onCheckedChange={(checked) => {+ const next = checked === true;+ if (next === cloudSubscriptionOn) return;+ setCloudSubscriptionOn("codex", next);+ }}+ />+ </div>+ <span className="text-muted-foreground text-xs">+ PostHog keeps your ChatGPT login and gives each cloud task a short-lived+ token. Tasks run when Desktop is closed. Compute is billed separately.+ </span>+ {account.isPending ? (+ <output className="text-muted-foreground text-xs">+ Checking account…+ </output>+ ) : account.isError ? (+ <span role="alert" className="text-muted-foreground text-xs">+ Cannot check the ChatGPT account. {account.error.message}+ </span>+ ) : status === "connected" ? (+ <span className="flex flex-wrap items-center gap-1.5 text-muted-foreground text-xs">+ <span+ className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-(--green-9)"+ aria-hidden+ />+ {account.data.email+ ? `Connected as ${account.data.email}`+ : "ChatGPT account connected"}+ {account.data.plan_type ? ` (${account.data.plan_type})` : null}+ <span aria-hidden>·</span>+ <button+ type="button"+ className="cursor-pointer hover:underline disabled:cursor-default"+ data-attr="codex-cloud-account-disconnect"+ disabled={pending}+ onClick={disconnectAccount}+ >+ {disconnect.isPending ? "Disconnecting…" : "Disconnect"}+ </button>+ </span>+ ) : (+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border p-3">+ <span className="text-muted-foreground text-xs">+ {status === "reauth_required"+ ? "Your ChatGPT login stopped working. Log in again to reconnect."+ : "Log in with ChatGPT. This login is separate from your local codex login."}+ </span>+ <Button+ type="button"+ variant="primary"+ size="sm"+ data-attr="codex-cloud-account-connect"+ disabled={pending}+ onClick={() => start.mutate()}+ >+ {status === "reauth_required" ? "Log in again" : "Log in"}+ </Button>+ </div>+ )}+ {login ? (+ <CodexCloudAuthTerminalDialog+ sessionId={login.id}+ terminal={login.terminal}+ onClose={closeLogin}+ />+ ) : null}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsxindex 7bf66291d9a6..f1566a35dc9d 100644--- a/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx@@ -1,13 +1,14 @@import { useHostTRPC } from "@posthog/host-router/react";import { Button, Switch } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";-import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";import {applyModelAccess,useAdapterSubscription,} from "@posthog/ui/features/settings/adapterSubscription";import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";+import { CodexCloudSection } from "@posthog/ui/features/settings/sections/CodexCloudSection";import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";+import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/settings/subscriptionActions";import { toast } from "@posthog/ui/primitives/toast";import { track } from "@posthog/ui/shell/analytics";import { openExternalUrl } from "@posthog/ui/shell/openExternal";@@ -31,6 +32,37 @@ function connectedAccountLabel(status: CodexAccountStatus | undefined): string {return `Connected as ${status.email}${plan}`;}+function ConnectedAccount({+ status,+ signingOut,+ onSignOut,+ className,+}: {+ status: CodexAccountStatus | undefined;+ signingOut: boolean;+ onSignOut: () => void;+ className?: string;+}): ReactElement {+ return (+ <span className={`flex items-center gap-1.5 ${className ?? ""}`}>+ <span+ className="inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-(--green-9)"+ aria-hidden+ />+ {connectedAccountLabel(status)}+ <span aria-hidden>·</span>+ <button+ type="button"+ className="cursor-pointer hover:underline"+ disabled={signingOut}+ onClick={onSignOut}+ >+ Sign out+ </button>+ </span>+ );+}+export function CodexSubscriptionSettings(): ReactElement | null {const subscription = useAdapterSubscription("codex");const hostTRPC = useHostTRPC();@@ -41,7 +73,7 @@ export function CodexSubscriptionSettings(): ReactElement | null {const statusQuery = hostTRPC.agent.codexSubscriptionStatus.queryOptions();const { data: status } = useQuery({...statusQuery,- enabled: subscription.flagEnabled,+ enabled: subscription.flagEnabled || subscription.cloudFlagEnabled,refetchInterval: (query) =>awaitingLogin && query.state.data?.loginState !== "logged-in"? 2000@@ -120,72 +152,115 @@ export function CodexSubscriptionSettings(): ReactElement | null {},});- if (!subscription.flagEnabled) {+ if (!subscription.flagEnabled && !subscription.cloudFlagEnabled) {return null;}- if (!loggedIn) {+ if (!subscription.cloudFlagEnabled) {+ if (!loggedIn) {+ return (+ <SettingsCardRow+ label="ChatGPT account"+ description={+ awaitingLogin+ ? "Finish signing in with your browser. This updates automatically"+ : "Connect to run local and worktree Codex sessions on your ChatGPT plan"+ }+ >+ <Button+ variant="outline"+ size="sm"+ loading={connecting}+ disabled={connecting}+ onClick={() => login.mutate()}+ >+ {connecting+ ? "Opening browser..."+ : awaitingLogin+ ? "Try again"+ : "Connect ChatGPT account"}+ </Button>+ </SettingsCardRow>+ );+ }+return (<SettingsCardRow- label="ChatGPT account"+ label="Use your ChatGPT subscription"description={- awaitingLogin- ? "Finish signing in with your browser. This updates automatically"- : "Connect to run local and worktree Codex sessions on your ChatGPT plan"+ <span className="flex flex-col gap-1">+ <span>+ Local and worktree Codex sessions run on your ChatGPT plan instead+ of PostHog credits. Cloud tasks always use PostHog credits+ </span>+ <ConnectedAccount+ status={status}+ signingOut={signOut.isPending}+ onSignOut={() => signOut.mutate()}+ />+ </span>}>- <Button- variant="outline"+ <Switchsize="sm"- loading={connecting}- disabled={connecting}- onClick={() => login.mutate()}- >- {connecting- ? "Opening browser..."- : awaitingLogin- ? "Try again"- : "Connect ChatGPT account"}- </Button>+ checked={subscription.subscriptionOn}+ onCheckedChange={(checked) =>+ subscription.setSubscriptionOn(checked === true)+ }+ /></SettingsCardRow>);}return (<SettingsCardRow- label="Use your ChatGPT subscription"- description={- <span className="flex flex-col gap-1">- <span>- Local and worktree Codex sessions run on your ChatGPT plan instead- of PostHog credits. Cloud tasks always use PostHog credits- </span>- <span className="flex items-center gap-1.5">- <span- className="inline-block h-1.5 w-1.5 rounded-full bg-(--green-9)"- aria-hidden- />- {connectedAccountLabel(status)}- <span aria-hidden>·</span>- <button- type="button"- className="cursor-pointer hover:underline"- disabled={signOut.isPending}- onClick={() => signOut.mutate()}- >- Sign out- </button>- </span>- </span>- }+ stacked+ label="ChatGPT subscription"+ description="Choose where to use your ChatGPT plan. Model use counts toward your plan limits.">- <Switch- size="sm"- checked={subscription.subscriptionOn}- onCheckedChange={(checked) =>- subscription.setSubscriptionOn(checked === true)- }- />+ <div className="flex flex-col gap-5 pt-2">+ {subscription.flagEnabled ? (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <span className="font-medium text-xs">Local tasks</span>+ {loggedIn ? (+ <Switch+ size="sm"+ aria-label="Use your ChatGPT plan for local tasks"+ checked={subscription.subscriptionOn}+ onCheckedChange={(checked) =>+ subscription.setSubscriptionOn(checked === true)+ }+ />+ ) : (+ <Button+ variant="outline"+ size="sm"+ loading={connecting}+ disabled={connecting}+ onClick={() => login.mutate()}+ >+ {connecting ? "Opening browser..." : "Connect in a browser"}+ </Button>+ )}+ </div>+ <span className="text-muted-foreground text-xs">+ Run local and worktree Codex sessions on your ChatGPT plan.+ </span>+ {loggedIn ? (+ <ConnectedAccount+ status={status}+ signingOut={signOut.isPending}+ onSignOut={() => signOut.mutate()}+ className="text-muted-foreground text-xs"+ />+ ) : null}+ </div>+ ) : null}+ <CodexCloudSection+ cloudSubscriptionOn={subscription.cloudSubscriptionOn}+ />+ </div></SettingsCardRow>);}diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.tsindex 20f266a55286..7ef44179e486 100644--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts@@ -299,6 +299,7 @@ export interface SettingsStore {codexModelAccess: ModelAccess;claudeModelAccess: ModelAccess;claudeCloudSubscriptionOn: boolean;+ codexCloudSubscriptionOn: boolean;setAllowBypassPermissions: (enabled: boolean) => void;setPreventSleepWhileRunning: (enabled: boolean) => void;setDebugLogsCloudRuns: (enabled: boolean) => void;@@ -308,6 +309,7 @@ export interface SettingsStore {setCodexModelAccess: (mode: ModelAccess) => void;setClaudeModelAccess: (mode: ModelAccess) => void;setClaudeCloudSubscriptionOn: (enabled: boolean) => void;+ setCodexCloudSubscriptionOn: (enabled: boolean) => void;// TerminalterminalFont: TerminalFont;@@ -587,6 +589,7 @@ export const useSettingsStore = create<SettingsStore>()(codexModelAccess: "posthog-gateway",claudeModelAccess: "posthog-gateway",claudeCloudSubscriptionOn: false,+ codexCloudSubscriptionOn: false,setAllowBypassPermissions: (enabled) =>set({ allowBypassPermissions: enabled }),setPreventSleepWhileRunning: (enabled) =>@@ -600,6 +603,8 @@ export const useSettingsStore = create<SettingsStore>()(setClaudeModelAccess: (mode) => set({ claudeModelAccess: mode }),setClaudeCloudSubscriptionOn: (enabled) =>set({ claudeCloudSubscriptionOn: enabled }),+ setCodexCloudSubscriptionOn: (enabled) =>+ set({ codexCloudSubscriptionOn: enabled }),// TerminalterminalFont: "berkeley-mono",@@ -755,6 +760,7 @@ export const useSettingsStore = create<SettingsStore>()(codexModelAccess: state.codexModelAccess,claudeModelAccess: state.claudeModelAccess,claudeCloudSubscriptionOn: state.claudeCloudSubscriptionOn,+ codexCloudSubscriptionOn: state.codexCloudSubscriptionOn,// TerminalterminalFont: state.terminalFont,diff --git a/products/desktop/packages/ui/src/features/settings/subscriptionActions.ts b/products/desktop/packages/ui/src/features/settings/subscriptionActions.tsnew file mode 100644index 000000000000..d9073ad9d4a5--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/subscriptionActions.ts@@ -0,0 +1,6 @@+import type { Adapter } from "@posthog/shared";++export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {+ claude: "claude-login",+ codex: "codex-login",+};diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsxindex 00e9b76b87f3..467acf655d0c 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx@@ -969,6 +969,7 @@ export function TaskInput({useWarmTask({claudeModelAccess: adapter === "claude" ? composerModelAccess : undefined,+ codexModelAccess: adapter === "codex" ? composerModelAccess : undefined,workspaceMode,selectedRepository: selectedCloudRepository,repositories: repoOptional ? taskRepositories : undefined,diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.tsindex cf837a964de4..d2a12e5426aa 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts@@ -486,6 +486,8 @@ export function useTaskCreation({claudeModelAccess,claudeCloudModelAccess:workspaceMode === "cloud" ? claudeModelAccess : undefined,+ codexCloudModelAccess:+ workspaceMode === "cloud" ? codexModelAccess : undefined,runtime,model,reasoningLevel,diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.tsindex 82cedc4eae25..49c242f10902 100644--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts@@ -21,6 +21,7 @@ const WARM_DEBOUNCE_MS = 600;export interface UseWarmTaskOptions {workspaceMode: WorkspaceMode;claudeModelAccess?: string;+ codexModelAccess?: string;selectedRepository?: string | null;repositories?: string[];githubIntegrationId?: number;@@ -39,6 +40,7 @@ export interface UseWarmTaskOptions {export function useWarmTask({workspaceMode,claudeModelAccess,+ codexModelAccess,selectedRepository,repositories,githubIntegrationId,@@ -87,7 +89,9 @@ export function useWarmTask({? (githubIntegrationId ?? null): null;const heldLeaseIsUnusable =- agentRuntime === "pi" || claudeModelAccess === "own-subscription";+ agentRuntime === "pi" ||+ claudeModelAccess === "own-subscription" ||+ codexModelAccess === "own-subscription";const eligible =enabled &&!heldLeaseIsUnusable &&diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.tsindex 7c54dac7f8d2..461df61c7663 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts@@ -1,3 +1,4 @@+import fs from "node:fs";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// --- Hoisted mocks ---@@ -161,6 +162,8 @@ vi.mock("./context-wiki", () => ({}));vi.mock("./codex-home", () => ({+ getCodexCloudHomeDir: vi.fn(() => "/mock/codex-cloud"),+ getCodexCloudAuthFilePath: vi.fn(() => "/mock/codex-cloud/auth.json"),cleanupCodexHome: vi.fn().mockResolvedValue(undefined),getCodexHomeDir: vi.fn(() => "/mock/codex-home"),prepareCodexHome: vi.fn().mockResolvedValue("/mock/codex-home"),@@ -325,6 +328,25 @@ describe("AgentService", () => {vi.unstubAllGlobals();});+ it("rejects old cleanup while a newer cloud login owns the file", async () => {+ vi.spyOn(fs.promises, "mkdir").mockResolvedValue(undefined);+ const remove = vi.spyOn(fs.promises, "rm").mockResolvedValue(undefined);+ await service.getCodexCloudAuthTerminal("attempt-1");+ await expect(+ service.getCodexCloudAuthTerminal("attempt-2"),+ ).rejects.toThrow("in progress");+ service.finishCodexCloudAuth("attempt-1");+ await service.getCodexCloudAuthTerminal("attempt-2");+ remove.mockClear();+ service.finishCodexCloudAuth("attempt-1");+ await expect(service.removeCodexCloudAuthFile("attempt-1")).rejects.toThrow(+ "no longer active",+ );+ expect(remove).not.toHaveBeenCalled();+ await service.removeCodexCloudAuthFile("attempt-2");+ expect(remove).toHaveBeenCalledOnce();+ });+describe("claude auth terminal", () => {it.each([{ action: "login" as const, expected: "'auth' 'login'" },diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex b5ae080b6c94..2ab8d248b2f3 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -29,6 +29,7 @@ import {} from "@posthog/agent/adapters/claude/subscription-login";import {type CodexLoginSession,+ codexCloudAuthTerminalCommand,hasCodexChatgptLogin,signOutCodexChatgpt,startCodexChatgptLogin,@@ -107,6 +108,8 @@ import { isScratchPath } from "../workspace/scratch";import type { AgentAuthAdapter, McpToolInstallations } from "./auth-adapter";import {cleanupCodexHome,+ getCodexCloudAuthFilePath,+ getCodexCloudHomeDir,getCodexHomeDir,prepareCodexHome,} from "./codex-home";@@ -129,10 +132,12 @@ import type {import {AgentServiceEvent,type AgentServiceEvents,- type ClaudeAuthTerminal,+ type AuthTerminal,type ClaudeSubscriptionStatus,+ type CodexCloudAuthTokens,type CodexSubscriptionStatus,type Credentials,+ codexCloudAuthTokensOutput,type EffortLevel,type InterruptReason,type PromptOutput,@@ -531,6 +536,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {private codexLogin?: CodexLoginSession;private codexAuthGeneration = 0;+ private codexCloudAttemptId: string | null = null;private claudeAuthGeneration = 0;async getCodexSubscriptionStatus(): Promise<CodexSubscriptionStatus> {@@ -559,9 +565,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {};}- async getClaudeAuthTerminal(- action: ClaudeAuthAction,- ): Promise<ClaudeAuthTerminal> {+ async getClaudeAuthTerminal(action: ClaudeAuthAction): Promise<AuthTerminal> {if (action === "logout") {await this.prepareClaudeAccountChange();}@@ -608,6 +612,43 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {return { authUrl: login.authUrl };}+ async getCodexCloudAuthTerminal(attemptId: string): Promise<AuthTerminal> {+ if (this.codexCloudAttemptId !== null) {+ throw new Error(+ "Another ChatGPT login is in progress. Wait for it to finish.",+ );+ }+ this.codexCloudAttemptId = attemptId;+ try {+ const codexHome = getCodexCloudHomeDir();+ await fs.promises.mkdir(codexHome, { recursive: true });+ await this.removeCodexCloudAuthFile(attemptId);+ const { command, env } = codexCloudAuthTerminalCommand(+ this.getCodexBinaryPath(),+ codexHome,+ );+ return {+ command,+ cwd: homedir(),+ additionalEnv: env.set,+ unsetEnv: env.unset,+ };+ } catch (error) {+ this.finishCodexCloudAuth(attemptId);+ throw error;+ }+ }++ finishCodexCloudAuth(attemptId: string): void {+ if (this.codexCloudAttemptId === attemptId) this.codexCloudAttemptId = null;+ }++ private requireCodexCloudAttempt(attemptId: string): void {+ if (this.codexCloudAttemptId !== attemptId) {+ throw new Error("This ChatGPT login attempt is no longer active.");+ }+ }+async signOutCodexSubscription(): Promise<void> {await this.prepareCodexAccountChange();await signOutCodexChatgpt({@@ -615,6 +656,50 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {});}+ /**+ * Reads the `auth.json` that `CODEX_HOME=~/.codex-posthog codex login` wrote,+ * so the user can hand its tokens to PostHog. Only the Desktop-only home is+ * read: the user's own `~/.codex` login stays on this machine.+ */+ async readCodexCloudAuthFile(+ attemptId: string,+ ): Promise<CodexCloudAuthTokens> {+ this.requireCodexCloudAttempt(attemptId);+ const authPath = getCodexCloudAuthFilePath();+ let raw: string;+ try {+ raw = await fs.promises.readFile(authPath, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {+ throw new Error(+ `No ChatGPT login found at ${authPath}. Run the login command first.`,+ );+ }+ throw error;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new Error(`The file at ${authPath} is not valid JSON.`);+ }+ const tokens = codexCloudAuthTokensOutput.safeParse(+ (parsed as { tokens?: unknown } | null)?.tokens,+ );+ if (!tokens.success) {+ throw new Error(+ `The file at ${authPath} has no ChatGPT tokens. Log in with ChatGPT, not with an API key.`,+ );+ }+ return tokens.data;+ }++ /** PostHog rotated the refresh token on connect, so the local copy is stale and only a liability. */+ async removeCodexCloudAuthFile(attemptId: string): Promise<void> {+ this.requireCodexCloudAttempt(attemptId);+ await fs.promises.rm(getCodexCloudAuthFilePath(), { force: true });+ }+private async prepareCodexAccountChange(): Promise<void> {this.codexAuthGeneration += 1;const currentLogin = this.codexLogin;diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.tsindex 63f6c7658333..0fac0c19a8b0 100644--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts@@ -9,6 +9,17 @@ import {} from "../skills/skill-discovery";import type { AgentScopedLogger } from "./ports";+/** The CODEX_HOME the user logs into for cloud runs. Separate from `~/.codex`, which stays local. */+export const CODEX_CLOUD_HOME_DIRNAME = ".codex-posthog";++export function getCodexCloudHomeDir(): string {+ return path.join(os.homedir(), CODEX_CLOUD_HOME_DIRNAME);+}++export function getCodexCloudAuthFilePath(): string {+ return path.join(getCodexCloudHomeDir(), "auth.json");+}+/*** Resolves a task run's private CODEX_HOME directory. Each run gets its own so* concurrent Codex sessions never share — and never race to rebuild — the samediff --git a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts b/products/desktop/packages/workspace-server/src/services/agent/schemas.tsindex 391a7b833655..7b574ab88865 100644--- a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts@@ -276,19 +276,35 @@ export const claudeAuthTerminalInput = z.object({action: z.enum(["login", "logout", "setup-token"]),});-export const claudeAuthTerminalOutput = z.object({+export const authTerminalOutput = z.object({command: z.string(),cwd: z.string(),additionalEnv: z.record(z.string(), z.string()),unsetEnv: z.array(z.string()),});-export type ClaudeAuthTerminal = z.infer<typeof claudeAuthTerminalOutput>;+export type AuthTerminal = z.infer<typeof authTerminalOutput>;++export const codexCloudAuthAttemptInput = z.object({+ attemptId: z.string().min(1),+});export const codexSubscriptionLoginOutput = z.object({authUrl: z.string(),});+/**+ * The `tokens` object of the `auth.json` that `codex login` writes into the+ * Desktop-only `~/.codex-posthog` home. Never the user's own `~/.codex`.+ */+export const codexCloudAuthTokensOutput = z.object({+ access_token: z.string().min(1),+ refresh_token: z.string().min(1),+ id_token: z.string().nullable().optional(),+});++export type CodexCloudAuthTokens = z.infer<typeof codexCloudAuthTokensOutput>;+// Set config option input (for Codex reasoning level, etc.)export const setConfigOptionInput = z.object({sessionId: z.string(),diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 1352d021ab9b..8c1599a0c482 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -222,6 +222,11 @@ TASK_SIGNALS_CLONING_BLOBLESS_FEATURE_FLAG = "task-signals-cloning-blobless"RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"BENJAMIN_FEATURE_FLAG = "task-cloud-run-benjamin-plus"CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-claude-own-subscription-cloud"+CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-codex-own-subscription-cloud"+# The plan name a person reads when a subscription run is refused. Every layer that gates,+# refuses, or explains one of these runs takes the name from here.+SUBSCRIPTION_PLAN_NAMES: dict[str, str] = {"claude": "Claude plan", "codex": "ChatGPT plan"}+CODEX_SUBSCRIPTION_EGRESS_DOMAINS: tuple[str, ...] = ("chatgpt.com",)# Gates whether long-running process_task runs continue-as-new to bound history/replay cost.CONTINUE_AS_NEW_FEATURE_FLAG = "tasks-cloud-run-continue-as-new"PR_BABYSIT_SNAPSHOT_FEATURE_FLAG = "tasks-pr-babysit-snapshot"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2033e58347c3..04430616900c 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -50,6 +50,7 @@ from posthog.event_usage import groupsfrom posthog.ingress.contracts import WebhookDeliveryfrom posthog.models import Team, Userfrom posthog.models.integration import Integration+from posthog.models.integration.codex import CodexAccessGrant, CodexAuthError, CodexReauthRequired, CodexUserIntegrationfrom posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPEfrom posthog.utils import absolute_uri@@ -69,6 +70,7 @@ from products.tasks.backend.constants import (ANALYSIS_TARGET_RUN_ID_STATE_KEY,ANALYSIS_TARGET_TASK_ID_STATE_KEY,CI_STATUSES as CI_STATUSES, # re-exported for presentation+ CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG as CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,DEV_STACK_PREVIEW_PORT,DEV_STACK_PREVIEW_STATE_KEY,GITHUB_PR_URL_PREFIX as GITHUB_PR_URL_PREFIX, # re-exported for signals billing@@ -79,6 +81,7 @@ from products.tasks.backend.constants import (RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,SANDBOX_REPOSITORIES_ROOT,SERVER_OWNED_RESUME_STATE_KEYS,+ SUBSCRIPTION_PLAN_NAMES,TASK_ANALYSIS_ACTIVITIES_STATE_KEY,TASK_ANALYSIS_FEATURE_FLAG,TASK_SESSION_MAX_SIZE_BYTES,@@ -95,6 +98,7 @@ from products.tasks.backend.feature_flags import (from products.tasks.backend.github_repository_access import (inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,)+from products.tasks.backend.logic.model_access import InvalidModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, pinned_run_allows_modelfrom products.tasks.backend.logic.services.image_builder import (ensure_image_builder_task,@@ -218,6 +222,7 @@ __all__ = ["apply_task_run_model_config","task_run_model_outside_gateway_pin","ensure_task_run_session",+ "ensure_subscription_owner","beacon_task_presence","bootstrap_task_run","SANDBOX_REPOSITORIES_ROOT",@@ -478,6 +483,8 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset("benjamin_enabled","claude_model_access","claude_subscription_user_id",+ "codex_model_access",+ "codex_subscription_user_id","context_window","custom_image_id","fast_mode",@@ -2583,6 +2590,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("service_tier","claude_model_access","claude_subscription_user_id",+ "codex_model_access",+ "codex_subscription_user_id","rtk_effective","benjamin_effective","usage_metrics_recorded",@@ -3558,6 +3567,17 @@ def _delete_task_session_object(task_session_id: UUID, object_storage_key: str))+def ensure_subscription_owner(state: dict[str, Any] | None, actor_user_id: int | None) -> None:+ """Refuse anyone but the owner of the plan a run bills to. A run on PostHog credits allows everyone."""+ run_state = state or {}+ for adapter, plan_name in SUBSCRIPTION_PLAN_NAMES.items():+ if (+ run_state.get(f"{adapter}_model_access") == "own-subscription"+ and run_state.get(f"{adapter}_subscription_user_id") != actor_user_id+ ):+ raise PermissionDenied(f"Only the user who started this run can use its {plan_name}.")++def validate_task_run_sandbox_token(token: str,run_id: str | UUID,@@ -3583,6 +3603,59 @@ def validate_task_run_sandbox_token()+def issue_codex_subscription_access_grant(+ run_id: str | UUID,+ task_id: str | UUID,+ team_id: int,+ *,+ run_token: str,+ rejected_access_token_sha256: str | None,+) -> CodexAccessGrant | None:+ """The run owner's ChatGPT access token for a Codex own-subscription run.++ None when the run token does not authorize this run: wrong run, a sandbox that is no+ longer the run's active sandbox, or a run that does not use the owner's ChatGPT plan.+ Raises ``CodexReauthRequired`` when the owner must reconnect, ``CodexAuthError`` when+ OpenAI could not refresh the token.+ """+ from jwt import InvalidTokenError # noqa: PLC0415++ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415+ validate_codex_subscription_run_token,+ )+ from products.tasks.backend.temporal.metrics import increment_credential_refresh # noqa: PLC0415++ try:+ claims = validate_codex_subscription_run_token(run_token)+ except (InvalidTokenError, ValueError):+ return None+ if claims.run_id != str(run_id) or claims.task_id != str(task_id) or claims.team_id != team_id:+ return None+ run = TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).only("id", "state").first()+ if run is None:+ return None+ state = run.state or {}+ owner_id = state.get("codex_subscription_user_id")+ if (+ state.get("sandbox_id") != claims.sandbox_id+ or state.get("codex_model_access") != "own-subscription"+ or not isinstance(owner_id, int)+ ):+ return None+ try:+ grant = CodexUserIntegration.issue_access_grant(+ owner_id, rejected_access_token_sha256=rejected_access_token_sha256, source="tasks_run"+ )+ except CodexReauthRequired:+ increment_credential_refresh("codex", "orphaned")+ raise+ except CodexAuthError:+ increment_credential_refresh("codex", "failed")+ raise+ increment_credential_refresh("codex", "refreshed" if grant.refreshed else "skipped")+ return grant++def sync_task_run_session(run_id: str | UUID,task_id: str | UUID,@@ -4557,10 +4630,7 @@ def signal_task_run_user_message(run = _get_visible_run(run_id, task_id, team_id)if run is None:return None- if (run.state or {}).get("claude_model_access") == "own-subscription" and (run.state or {}).get(- "claude_subscription_user_id"- ) != actor_user_id:- raise PermissionDenied("Only the user who started this run can use its Claude plan.")+ ensure_subscription_owner(run.state, actor_user_id)if run.is_terminal or (run.state or {}).get("cancel_requested_at"):if not run.is_terminal:raise RuntimeError("Task run is still stopping. Try again shortly.")@@ -5310,6 +5380,7 @@ def bootstrap_task_run("rtk_enabled": validated_data.get("rtk_enabled"),"benjamin_enabled": validated_data.get("benjamin_enabled"),"claude_model_access": validated_data.get("claude_model_access"),+ "codex_model_access": validated_data.get("codex_model_access"),}.items():if value is not None:extra_state = extra_state or {}@@ -5390,6 +5461,8 @@ def bootstrap_task_run(run = task.create_run(environment=environment, mode=mode, branch=branch, extra_state=extra_state, acting_user_id=user_id)+ except InvalidModelAccess as error:+ return contracts.TaskRunCreateResult(error=contracts.TaskRunValidationError(kind="detail", detail=str(error)))except InvalidTaskOriginError as error:return contracts.TaskRunCreateResult(error=contracts.TaskRunValidationError(@@ -5510,6 +5583,7 @@ def start_task_run(run = _get_visible_run(run_id, task_id, team_id)if run is None:return "not_found", None+ ensure_subscription_owner(run.state, user_id)task = run.taskpending_user_message = validated_data.get("pending_user_message")@@ -5588,6 +5662,7 @@ def resume_task_run_in_cloud(run = _get_visible_run(run_id, task_id, team_id)if run is None:return "not_found", None, None+ ensure_subscription_owner(run.state, user_id)from products.tasks.backend.feature_flags import is_workflow_dispatch_restart_enabled # noqa: PLC0415from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415@@ -7885,7 +7960,7 @@ def warm_task_resume_sandbox(return Noneprevious_state = parse_run_state(previous_run.state)- if previous_state.run_source == RunSource.AGENT or previous_state.claude_model_access == "own-subscription":+ if previous_state.run_source == RunSource.AGENT or previous_state.model_access.kind == "own-subscription":return Noneresolved_runtime_adapter = runtime_adapter or previous_state.runtime_adapterresolved_model = model or previous_state.model@@ -8134,21 +8209,29 @@ def run_task(internal=task.internal,)- claude_model_access = validated_data.get("claude_model_access")- if claude_model_access is None and previous_state is not None:- claude_model_access = previous_state.claude_model_access+ access_state = {+ **(previous_state.model_dump() if previous_state is not None else {}),+ **{key: value for key, value in validated_data.items() if value is not None},+ }+ try:+ model_access = resolve_model_access(access_state)+ except ValueError as error:+ return contracts.TaskRunResult(error=contracts.TaskValidationError(kind="detail", detail=str(error)))+ claude_model_access = model_access.access_for("claude") if "claude_model_access" in access_state else None+ codex_model_access = model_access.access_for("codex") if "codex_model_access" in access_state else None- if scheduled_at is not None and claude_model_access == "own-subscription":+ if scheduled_at is not None and model_access.kind == "own-subscription":return contracts.TaskRunResult(error=contracts.TaskValidationError(kind="validation_error",code="invalid_input",detail="Scheduled runs must use the PostHog gateway.",- attr="claude_model_access",+ attr="codex_model_access" if codex_model_access == "own-subscription" else "claude_model_access",))warm_run = None if scheduled_at is not None or run_source == RunSource.AGENT else _idling_warm_run_for_task(task)- if warm_run is not None and claude_model_access == "own-subscription":+ # A warm sandbox was started before the plan choice, so it holds no run-scoped subscription token.+ if warm_run is not None and model_access.kind == "own-subscription":warm_run = Noneif warm_run is not None:_warm_retry_message_id(warm_retry_token, warm_run)@@ -8279,6 +8362,7 @@ def run_task(("rtk_enabled", validated_data.get("rtk_enabled")),("benjamin_enabled", validated_data.get("benjamin_enabled")),("claude_model_access", claude_model_access),+ ("codex_model_access", codex_model_access),):if value is not None:extra_state = extra_state or {}diff --git a/products/tasks/backend/logic/model_access.py b/products/tasks/backend/logic/model_access.pynew file mode 100644index 000000000000..d0c0641f616d--- /dev/null+++ b/products/tasks/backend/logic/model_access.py@@ -0,0 +1,43 @@+from collections.abc import Mapping+from typing import Literal++from posthog.dataclasses import frozen++ModelAccessMode = Literal["posthog-gateway", "own-subscription"]+SubscriptionAdapter = Literal["claude", "codex"]+++@frozen+class ModelAccess:+ """Who pays for a run's model use: PostHog, or the owner's plan for one adapter."""++ adapter: SubscriptionAdapter | None = None+ owner_id: int | None = None++ @property+ def kind(self) -> ModelAccessMode:+ return "posthog-gateway" if self.adapter is None else "own-subscription"++ def access_for(self, adapter: SubscriptionAdapter) -> ModelAccessMode:+ return "own-subscription" if adapter == self.adapter else "posthog-gateway"+++class InvalidModelAccess(ValueError):+ pass+++def resolve_model_access(state: Mapping[str, object]) -> ModelAccess:+ claude = state.get("claude_model_access") == "own-subscription"+ codex = state.get("codex_model_access") == "own-subscription"+ if claude and codex:+ raise InvalidModelAccess("Select only one subscription for this run.")+ if not claude and not codex:+ return ModelAccess()+ adapter: SubscriptionAdapter = "codex" if codex else "claude"+ if (state.get("runtime_adapter") or "claude") != adapter:+ raise InvalidModelAccess(f"The {adapter} subscription requires the {adapter} runtime.")+ owner = state.get(f"{adapter}_subscription_user_id")+ return ModelAccess(+ adapter=adapter,+ owner_id=owner if isinstance(owner, int) and not isinstance(owner, bool) else None,+ )diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex a8ba45acec54..d0b99cd87234 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -39,12 +39,14 @@ from products.tasks.backend.logic.services.agentsh import ()from products.tasks.backend.logic.services.mcp_url import resolve_mcp_urlfrom products.tasks.backend.logic.services.sandbox import (+ CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,WORKING_DIR,SandboxBase,build_agent_runtime_env_prefix,build_agent_server_capability_probe,build_bundled_skills_clear_command,build_health_check_command,+ build_subscription_flags,health_check_timeout_seconds,wait_for_health_check,)@@ -60,6 +62,10 @@ AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240# The whole diagnostics dict rides in the Temporal failure payload, which is capped at about 2 MiB.STARTUP_LOG_MAX_BYTES = 64 * 1024AGENT_SERVER_HEALTH_DURATION_PREFIX = "__posthog_agent_health_ms="+# The agent-server reads this fd once at boot and closes it, so processes it starts never see the+# token. The launch shell opens the file on fd 3 and deletes it before the server starts.+CODEX_RUN_TOKEN_FD = 3+CODEX_RUN_TOKEN_FILE = "/tmp/agent-codex-run-token"AGENT_SERVER_FREE_PORT_SCRIPT = ("agent_server_pids() { for p in $(pgrep -f '[a]gent-server'); do "@@ -221,7 +227,7 @@ def build_agent_server_preflight_script(*, probe_health: bool, executable_paths:f"health_output=$({health_command})","health_status=$?",'printf "%s\\n" "$health_output"',- f'case "$health_output" in *claude_credential_unavailable*) '+ f'case "$health_output" in *claude_credential_unavailable*|*codex_credential_unavailable*) 'f"exit {AGENT_SERVER_PREFLIGHT_CREDENTIAL_EXIT_CODE};; esac",f'if [ "$health_status" -eq 0 ]; then 'f"echo {shlex.quote(AGENT_SERVER_PREFLIGHT_REUSE_MARKER)}; exit 0; fi",@@ -295,6 +301,8 @@ class AgentServerLaunchMixin(SandboxBase):peer_messaging: bool = False,posthog_exec_permission_regex: str | None = None,claude_model_access: str | None = None,+ codex_model_access: str | None = None,+ codex_run_token_file: str | None = None,) -> str:env_prefix = build_agent_runtime_env_prefix(interaction_origin=interaction_origin,@@ -317,7 +325,7 @@ class AgentServerLaunchMixin(SandboxBase):peer_messaging=peer_messaging,unset_bedrock=self.disable_direct_bedrock,)- subscription_flag = " --claudeSubscription" if claude_model_access == "own-subscription" else ""+ subscription_flag = build_subscription_flags(claude_model_access, codex_model_access)create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"# Only append when opted in: agent-server builds without the option reject unknown# flags, so default runs (and resumes of old snapshots) must not see it.@@ -353,6 +361,8 @@ class AgentServerLaunchMixin(SandboxBase):f"{launch_started_at}; exec {server_cmd}")server_cmd = f"bash -c {shlex.quote(wait_for_repo)}"+ if codex_run_token_file:+ server_cmd = self._with_codex_run_token_fd(server_cmd, codex_run_token_file)inner = f"cd /scripts && {server_cmd} > /tmp/agent-server.log 2>&1"initialize_env_file = f"bash {shlex.quote(BASH_ENV_SCRIPT)}"@@ -369,6 +379,26 @@ class AgentServerLaunchMixin(SandboxBase):f"(nohup {server_cmd} > /tmp/agent-server.log 2>&1 & echo $! > /tmp/agent-server.pid)")+ def _stage_codex_run_token(self, codex_run_token: str) -> None:+ self._write_required_file(CODEX_RUN_TOKEN_FILE, codex_run_token.encode())+ # Best effort: a child process must not read the token out of the agent-server's memory.+ # agentsh still traces its own descendants under scope 1. Kernels without Yama ignore this,+ # and a sandbox with CAP_SYS_PTRACE bypasses it.+ self.execute(+ f"chmod 600 {CODEX_RUN_TOKEN_FILE}; (echo 1 > /proc/sys/kernel/yama/ptrace_scope) 2>/dev/null || true",+ timeout_seconds=5,+ )++ @staticmethod+ def _with_codex_run_token_fd(server_cmd: str, token_file: str) -> str:+ """Open the run token on fd 3 for the agent-server and remove the file before it starts.++ Runs inside the launched process tree, so it works the same under ``nohup`` and under+ ``agentsh exec``, which does not forward the caller's descriptors.+ """+ quoted_file = shlex.quote(token_file)+ return f"bash -c {shlex.quote(f'exec {CODEX_RUN_TOKEN_FD}< {quoted_file} && rm -f {quoted_file} && exec {server_cmd}')}"+def _termination_failure_reason(self) -> str:"""Provider-specific detail for a sandbox that died before becoming healthy."""return (@@ -547,6 +577,16 @@ class AgentServerLaunchMixin(SandboxBase):RuntimeError("Claude token unavailable"),capture=False,)+ if (+ "codex_credential_unavailable" in launch_result.stdout+ or "codex_credential_unavailable" in diagnostics.get("log", "")+ ):+ raise ProcessTaskFatalError(+ CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,+ {"task_id": task_id, "run_id": run_id},+ RuntimeError("ChatGPT token unavailable"),+ capture=False,+ )raise SandboxExecutionError("Agent-server failed to start",{@@ -607,6 +647,8 @@ class AgentServerLaunchMixin(SandboxBase):benjamin_enabled: bool = False,peer_messaging: bool = False,claude_model_access: str | None = None,+ codex_model_access: str | None = None,+ codex_run_token: str | None = None,) -> int | None:"""Start the agent-server HTTP server in the sandbox.@@ -629,6 +671,8 @@ class AgentServerLaunchMixin(SandboxBase):self._prepare_agent_server_launch(allowed_domains)+ codex_run_token_file = CODEX_RUN_TOKEN_FILE if codex_run_token else None+mcp_servers_arg = ""if mcp_configs:mcp_json = json.dumps([c.to_dict() for c in mcp_configs])@@ -654,6 +698,9 @@ class AgentServerLaunchMixin(SandboxBase):exec_permission_regex = Nonedef build_command(base_branch: str | None) -> str:+ # The launch shell deletes the token file, so every launch attempt needs its own copy.+ if codex_run_token:+ self._stage_codex_run_token(codex_run_token)return self._build_agent_server_command(repo_path,task_id,@@ -685,6 +732,8 @@ class AgentServerLaunchMixin(SandboxBase):peer_messaging=peer_messaging,posthog_exec_permission_regex=exec_permission_regex,claude_model_access=claude_model_access,+ codex_model_access=codex_model_access,+ codex_run_token_file=codex_run_token_file,)logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.pyindex 398f5d715a79..27a090cc12bd 100644--- a/products/tasks/backend/logic/services/connection_token.py+++ b/products/tasks/backend/logic/services/connection_token.py@@ -24,6 +24,8 @@ SANDBOX_EVENT_INGEST_AUDIENCE = "posthog:sandbox_event_ingest"SANDBOX_EVENT_INGEST_TOKEN_TTL_BUFFER = timedelta(hours=1)SANDBOX_EVENT_INGEST_TOKEN_TTL = timedelta(seconds=SANDBOX_TTL_SECONDS) + SANDBOX_EVENT_INGEST_TOKEN_TTL_BUFFER+SANDBOX_CODEX_SUBSCRIPTION_AUDIENCE = "posthog:sandbox_codex_subscription"+SANDBOX_JWT_STATE_KID_KEY = "sandbox_jwt_kid"STREAM_READ_AUDIENCE = "posthog:stream_read"@@ -52,6 +54,14 @@ class _SandboxJwtKey:public_key_pem: str+@dataclass(frozen=True)+class CodexSubscriptionRunTokenPayload:+ run_id: str+ task_id: str+ team_id: int+ sandbox_id: str++@dataclass(frozen=True)class StreamReadTokenPayload:run_id: str@@ -314,6 +324,38 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa)+def create_codex_subscription_run_token(+ task_run: TaskRun,+ *,+ sandbox_id: str,+ ttl: timedelta = SANDBOX_EVENT_INGEST_TOKEN_TTL,+) -> str:+ """Create the run-scoped JWT the agent-server presents to fetch the owner's ChatGPT access token.++ The token is a second factor next to the sandbox OAuth token: it reaches the agent-server+ over an inherited file descriptor and never enters the sandbox environment, so a process+ the agent starts holds the OAuth token but not this one. Bound to the sandbox so a token+ captured in a snapshot stops working after a resume.+ """+ return _encode_run_scoped_token(task_run, SANDBOX_CODEX_SUBSCRIPTION_AUDIENCE, ttl, {"sandbox_id": sandbox_id})+++def validate_codex_subscription_run_token(token: str) -> CodexSubscriptionRunTokenPayload:+ payload = _decode_sandbox_token(token, SANDBOX_CODEX_SUBSCRIPTION_AUDIENCE)++ run_id = payload.get("run_id")+ task_id = payload.get("task_id")+ team_id = payload.get("team_id")+ sandbox_id = payload.get("sandbox_id")++ if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:+ raise jwt.InvalidTokenError("Codex subscription run token has invalid claims")+ if not isinstance(sandbox_id, str) or not sandbox_id:+ raise jwt.InvalidTokenError("Codex subscription run token has invalid claims")++ return CodexSubscriptionRunTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id, sandbox_id=sandbox_id)++def create_stream_read_token(task_run: TaskRun, ttl: timedelta = STREAM_READ_TOKEN_TTL) -> str:"""Create a run-scoped JWT that authorizes reading a task run's live event stream.diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex e3a5090c2750..80ce17a32ffe 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -65,6 +65,7 @@ from .sandbox import (SandboxStatus,SandboxTemplate,build_agent_runtime_env_prefix,+ build_subscription_flags,parse_sandbox_repo_mount_map,redact_sandbox_command,wait_for_health_check,@@ -980,6 +981,8 @@ class DockerSandbox(AgentServerLaunchMixin):peer_messaging: bool = False,posthog_exec_permission_regex: str | None = None,claude_model_access: str | None = None,+ codex_model_access: str | None = None,+ codex_run_token_file: str | None = None,) -> str:# The host proxy URL (e.g. localhost:8003) is unreachable from inside the container;# rewrite it the same way POSTHOG_API_URL is for Docker sandboxes.@@ -1005,7 +1008,7 @@ class DockerSandbox(AgentServerLaunchMixin):benjamin_enabled=benjamin_enabled,peer_messaging=peer_messaging,)- subscription_flag = " --claudeSubscription" if claude_model_access == "own-subscription" else ""+ subscription_flag = build_subscription_flags(claude_model_access, codex_model_access)create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"# Only append when opted in: agent-server builds without the option reject unknown# flags, so default runs (and resumes of old snapshots) must not see it.@@ -1031,6 +1034,8 @@ class DockerSandbox(AgentServerLaunchMixin):f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"f"{domains_flag}{repo_ready_flag}{exec_permission_flag}{subscription_flag}")+ if codex_run_token_file:+ server_cmd = self._with_codex_run_token_fd(server_cmd, codex_run_token_file)# agentsh injects HTTP_PROXY pointing at a per-session egress proxy port; undici# (Node fetch) honors it for local-host traffic unless NO_PROXY says otherwise. Thediff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 03ff38d85b64..ef3c2da06e40 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -657,6 +657,8 @@ class SandboxBase(ABC):benjamin_enabled: bool = False,peer_messaging: bool = False,claude_model_access: str | None = None,+ codex_model_access: str | None = None,+ codex_run_token: str | None = None,) -> int | None:"""Start the agent-server HTTP server in the sandbox.@@ -829,6 +831,23 @@ def parse_sandbox_repo_mount_map() -> dict[str, str]:return result+CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE = (+ "This run could not get a ChatGPT token from PostHog. Start the task again. "+ "If it keeps failing, connect your ChatGPT account again in Settings > Harness."+)++# The agent-server option each adapter's own-subscription runs need. The launcher greps the+# binary for it before it starts a run, so both uses read the same name.+SUBSCRIPTION_CLI_FLAGS = {"claude": "--claudeSubscription", "codex": "--codexSubscription"}+++def build_subscription_flags(claude_model_access: str | None, codex_model_access: str | None) -> str:+ access = {"claude": claude_model_access, "codex": codex_model_access}+ return "".join(+ f" {flag}" for adapter, flag in SUBSCRIPTION_CLI_FLAGS.items() if access[adapter] == "own-subscription"+ )++def wait_for_health_check(execute: _ExecuteFn,sandbox_id: str,@@ -853,6 +872,15 @@ def wait_for_health_check(RuntimeError("Claude token unavailable"),capture=False,)+ if "codex_credential_unavailable" in result.stdout:+ from products.tasks.backend.exceptions import ProcessTaskFatalError++ raise ProcessTaskFatalError(+ CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,+ {"sandbox_id": sandbox_id},+ RuntimeError("ChatGPT token unavailable"),+ capture=False,+ )if result.exit_code == 0:_logger.info(f"Agent-server health check passed in sandbox {sandbox_id} ({result.stdout.strip()})")return True@@ -880,7 +908,8 @@ def build_health_check_command(f" body=$(curl -s --max-time {HEALTH_CURL_MAX_TIME_SECONDS} http://localhost:{port}/health); "" status=$?; "' if [ "$status" = "0" ]; then '- ' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; esac; '+ ' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; '+ '*codex_credential_unavailable*) echo "codex_credential_unavailable"; exit 1;; esac; '" python3 -c '""import json, sys; ""payload = json.loads(sys.argv[1]); "diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.pyindex 7e847506a430..64f77e4e4c6f 100644--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py@@ -151,6 +151,30 @@ def test_build_agent_server_command_gates_connected_project_operations(sandbox:assert "--posthogExecPermissionRegex" not in without_flag+def test_build_agent_server_command_opens_the_codex_run_token_on_fd_3(sandbox: DockerSandbox):+ with_token = sandbox._build_agent_server_command(+ None, "t1", "r1", "interactive", True, codex_run_token_file="/tmp/agent-codex-run-token"+ )+ assert "exec 3< /tmp/agent-codex-run-token && rm -f /tmp/agent-codex-run-token && exec " in with_token+ assert "exec 3<" not in sandbox._build_agent_server_command(None, "t1", "r1", "interactive", True)+++def test_start_agent_server_stages_the_codex_run_token_again_for_the_branchless_retry(sandbox: DockerSandbox):+ with (+ patch.object(sandbox, "is_running", return_value=True),+ patch.object(sandbox, "write_file", return_value=_ok_result()) as write_file,+ patch.object(sandbox, "_build_agent_server_command", return_value="run-agent-server"),+ patch.object(sandbox, "_launch_and_check", side_effect=[False, True]),+ patch.object(sandbox, "execute", return_value=_log_result()),+ ):+ sandbox.start_agent_server(+ repository=None, task_id="t1", run_id="r1", branch="feature", codex_run_token="run-token"+ )++ token_writes = [call for call in write_file.call_args_list if call.args[0] == "/tmp/agent-codex-run-token"]+ assert len(token_writes) == 2++@parameterized.expand([("supported", AGENT_SERVER_LAUNCH_CAPABILITIES), ("unsupported", ())])def test_start_agent_server_launch_failure_is_captured(_name: str, capabilities: tuple[str, ...]):config = SandboxConfig(name="test-sandbox")diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 71e3d0320997..bb933bc45c2a 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -944,7 +944,13 @@ class TestModalSandboxAgentServer:assert mock_sandbox.supports_combined_agent_server_start_and_health() is True@pytest.mark.parametrize(- "exit_code, stdout, expected", [(0, "ok:3", True), (1, "", False), (1, "claude_credential_unavailable", None)]+ "exit_code, stdout, expected",+ [+ (0, "ok:3", True),+ (1, "", False),+ (1, "claude_credential_unavailable", None),+ (1, "codex_credential_unavailable", None),+ ],)def test_wait_for_health_check(self, mock_sandbox: Any, exit_code, stdout, expected):from products.tasks.backend.exceptions import ProcessTaskFatalErrordiff --git a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.pyindex 142e12418714..c37b33be28ae 100644--- a/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py+++ b/products/tasks/backend/logic/services/tests/test_sandbox_health_check.py@@ -30,6 +30,7 @@ def _path_with_fake_curl(tmp_path: Path, body: str, delay_seconds: float) -> dic[('{"status":"ok","hasSession":true}', 0, "ok:1"),('{"status":"ok","hasSession":false}', 1, ""),+ ('{"status":"error","code":"codex_credential_unavailable"}', 1, "codex_credential_unavailable"),],)def test_health_check_loop_stops_at_wall_clock_budget(tmp_path, body, expected_exit_code, expected_stdout) -> None:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 00328fb0089f..4273ceb8fa9e 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -47,6 +47,7 @@ from products.tasks.backend.feature_flags import (is_task_run_stream_thin_tail,run_stream_presence_gated,)+from products.tasks.backend.logic.model_access import resolve_model_accessfrom products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_eventfrom products.tasks.backend.metrics import observe_task_run_created, observe_task_run_dispatch_callbackfrom products.tasks.backend.pr_urls import read_pr_urls@@ -790,8 +791,6 @@ class Task(DeletedMetaFields, models.Model):state: dict = {} if task.runtime == Task.Runtime.PI else {"mode": mode}if extra_state:state.update({k: v for k, v in extra_state.items() if k != "mode"})- if state.get("claude_model_access") == "own-subscription":- state["claude_subscription_user_id"] = acting_user_id or task.created_by_idstate.setdefault("repositories", task.repositories or ([task.repository] if task.repository else []))carry_config_snapshot = (task.origin_product == Task.OriginProduct.WORKFLOW and "config_snapshot" not in state@@ -824,6 +823,9 @@ class Task(DeletedMetaFields, models.Model):# Every run creation flows through here, so this is where team/user default AI run# preferences apply when the caller didn't pin a runtime selection.task._apply_ai_run_defaults(state, acting_user_id)+ model_access = resolve_model_access(state)+ if model_access.adapter is not None:+ state[f"{model_access.adapter}_subscription_user_id"] = acting_user_id or task.created_by_idif task.ownership_version is not None:state[TASK_OWNERSHIP_VERSION_STATE_KEY] = task.ownership_versiondiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex dfe81c823671..07a25eefea90 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -135,6 +135,9 @@ def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any])})+ # The PostHog API serves the ChatGPT token, so any caller can resume a Codex plan run.+ if attrs.get("codex_model_access") == "own-subscription" and is_sandbox_oauth_request(request):+ raise serializers.ValidationError({"codex_model_access": "Only a user can select a ChatGPT plan."})def request_distinct_id(context: dict[str, Any]) -> str | None:@@ -1263,6 +1266,28 @@ class TaskSessionSyncResponseSerializer(serializers.Serializer):content_sha256 = serializers.CharField(help_text="SHA-256 digest of the uploaded session content")+class TaskRunSubscriptionTokenRequestSerializer(serializers.Serializer):+ rejected_access_token_sha256 = serializers.RegexField(+ r"^[0-9a-f]{64}$",+ required=False,+ allow_null=True,+ default=None,+ help_text="SHA-256 hex digest of the access token Codex rejected. The server refreshes only when this "+ "names its current token; otherwise it returns the newer token it already holds.",+ )+++class TaskRunSubscriptionTokenResponseSerializer(serializers.Serializer):+ access_token = serializers.CharField(+ help_text="ChatGPT access token for the Codex app-server. It can stay valid for several days."+ )+ account_id = serializers.CharField(help_text="ChatGPT account the access token belongs to")+ plan_type = serializers.CharField(allow_null=True, help_text="ChatGPT plan of the account, when known")+ expires_at = serializers.DateTimeField(+ help_text="When the access token expires. Request a new one before this time."+ )++class TaskRunRelayMessageResponseSerializer(serializers.Serializer):status = serializers.CharField(help_text="Relay status: 'accepted' or 'skipped'")relay_id = serializers.CharField(required=False, help_text="Relay workflow ID when accepted")@@ -3399,6 +3424,18 @@ class TaskRunPreferencesFieldMixin(serializers.Serializer):"their billing choice and new runs use the PostHog gateway."),)+ codex_model_access = serializers.ChoiceField(+ choices=["posthog-gateway", "own-subscription"],+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a "+ "ChatGPT access token from the PostHog API, refreshed from the ChatGPT account "+ "the run owner connected in Desktop settings. If omitted or null, resumed runs keep their "+ "billing choice and new runs use the PostHog gateway."+ ),+ )class TaskRunCreateRequestSerializer(@@ -3569,6 +3606,8 @@ class TaskRunCreateRequestSerializer(pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []if attrs.get("claude_model_access") == "own-subscription" and is_pi_task:errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."+ if attrs.get("codex_model_access") == "own-subscription" and is_pi_task:+ errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."if pending_user_message is not None:trimmed_message = pending_user_message.strip()attrs["pending_user_message"] = trimmed_message or None@@ -3741,6 +3780,8 @@ class TaskRunBootstrapCreateRequestSerializer(if is_pi_task:if attrs.get("claude_model_access") == "own-subscription":errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."+ if attrs.get("codex_model_access") == "own-subscription":+ errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."pi_incompatible_fields = ("runtime_adapter", "context_window", "fast_mode", "initial_permission_mode")for field in pi_incompatible_fields:if attrs.get(field) is not None:diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 00fa26726abc..60b5d26ba458 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -48,6 +48,7 @@ from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticfrom posthog.event_usage import groupsfrom posthog.middleware import is_read_only_impersonationfrom posthog.models import User+from posthog.models.integration.codex import CodexAuthError, CodexReauthRequiredfrom posthog.permissions import (APIScopePermission,get_authenticator_scoped_team_ids,@@ -195,6 +196,8 @@ from products.tasks.backend.presentation.serializers import (TaskRunSetOutputRequestSerializer,TaskRunSetSummaryRequestSerializer,TaskRunStartRequestSerializer,+ TaskRunSubscriptionTokenRequestSerializer,+ TaskRunSubscriptionTokenResponseSerializer,TaskRunUpdateSerializer,TaskSearchQuerySerializer,TaskSearchResultSerializer,@@ -1730,11 +1733,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):run = tasks_facade.get_task_run_detail(run_id, task_id, self.team_id)if run is None:raise NotFound()- if (- run.state.get("claude_model_access") == "own-subscription"- and run.state.get("claude_subscription_user_id") != self._user_id()- ):- raise PermissionDenied("Only the user who started this run can use its Claude plan.")+ tasks_facade.ensure_subscription_owner(run.state, self._user_id())@validated_request(responses={@@ -2255,6 +2254,87 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):session_id, content_sha256 = resultreturn Response(TaskSessionSyncResponseSerializer({"id": session_id, "content_sha256": content_sha256}).data)+ @validated_request(+ request_serializer=TaskRunSubscriptionTokenRequestSerializer,+ parameters=[+ OpenApiParameter(+ name="X-Task-Run-Token",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.HEADER,+ required=True,+ description="Run-scoped Codex subscription token handed to the agent-server at launch",+ ),+ ],+ responses={+ 200: OpenApiResponse(+ response=TaskRunSubscriptionTokenResponseSerializer,+ description="Short-lived ChatGPT access token for this run",+ ),+ 400: OpenApiResponse(description="Missing required header"),+ 403: OpenApiResponse(description="Caller is not this run's sandbox, or the run token is invalid"),+ 404: OpenApiResponse(description="Task run not found"),+ 409: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="reauth_required: the run owner must reconnect their ChatGPT account",+ ),+ 502: OpenApiResponse(+ response=TaskRunErrorResponseSerializer,+ description="openai_unavailable: OpenAI did not answer the token refresh",+ ),+ },+ summary="Issue a ChatGPT access token for a Codex run",+ description="Give the run's agent-server a short-lived ChatGPT access token from the run owner's connected "+ "account. Only the run's sandbox may call this, and it must present the run token it received at "+ "launch. Send the digest of a token Codex rejected so the server refreshes it early, once.",+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="subscription_token",+ required_scopes=["task:write"],+ )+ def subscription_token(self, request, pk=None, **kwargs):+ task_id = self._ensure_task_accessible()+ if not is_sandbox_agent_request(request, task_id):+ raise PermissionDenied("Only this run's sandbox can request its ChatGPT access token.")+ run_token = request.headers.get("X-Task-Run-Token")+ if not run_token:+ raise ValidationError({"X-Task-Run-Token": "This header is required."})+ try:+ grant = tasks_facade.issue_codex_subscription_access_grant(+ pk,+ task_id,+ self.team_id,+ run_token=run_token,+ rejected_access_token_sha256=request.validated_data.get("rejected_access_token_sha256"),+ )+ except CodexReauthRequired:+ return Response(+ TaskRunErrorResponseSerializer(+ {"error": "The ChatGPT account for this run must be reconnected.", "code": "reauth_required"}+ ).data,+ status=status.HTTP_409_CONFLICT,+ )+ except CodexAuthError:+ return Response(+ TaskRunErrorResponseSerializer(+ {"error": "OpenAI did not answer the token refresh.", "code": "openai_unavailable"}+ ).data,+ status=status.HTTP_502_BAD_GATEWAY,+ )+ if grant is None:+ raise PermissionDenied("The task run token is invalid")+ return Response(+ TaskRunSubscriptionTokenResponseSerializer(+ {+ "access_token": grant.access_token,+ "account_id": grant.account_id,+ "plan_type": grant.plan_type,+ "expires_at": grant.expires_at,+ }+ ).data+ )+@validated_request(request_serializer=TaskRunRelayMessageRequestSerializer,responses={@@ -3072,6 +3152,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):self._ensure_subscription_owner(task_id, pk)if method == "credential_response":run = tasks_facade.get_task_run_detail(pk, task_id, self.team_id)+ # Only Claude tokens travel through the relay. Codex runs fetch theirs from the server.if (run is Noneor is_sandbox_oauth_request(request)diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex 555875246682..337b882ad1fd 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -1,5 +1,6 @@from __future__ import annotations+from collections.abc import Collectionfrom typing import TYPE_CHECKING, Any, cast, get_argsfrom uuid import UUID@@ -46,6 +47,7 @@ __all__ = [# triggered run has no legitimate reason to create/edit/delete loops, and this closes the# injected-instructions plant-a-persistent-loop path. loop:read stays granted.LOOP_FIRED_RUN_EXCLUDED_SCOPES = frozenset({"loop:write"})+SUBSCRIPTION_RUN_WITHHELD_SCOPES = frozenset({"llm_gateway:read"})# Every Signals sandbox surface mints under the dedicated Signals OAuth app, so the LLM@@ -182,9 +184,16 @@ def create_oauth_access_token(token_options["include_interactive_run_scope"] = Trueif task.origin_product == Task.OriginProduct.SLACK:token_options["include_slack_run_scope"] = True+ if run_uses_own_subscription(run_state):+ token_options["withhold_scopes"] = sorted(SUBSCRIPTION_RUN_WITHHELD_SCOPES)return create_oauth_access_token_for_user(actor, task.team_id, **token_options)+def run_uses_own_subscription(run_state: dict[str, Any] | None) -> bool:+ state = run_state or {}+ return any(state.get(f"{adapter}_model_access") == "own-subscription" for adapter in ("claude", "codex"))++def create_oauth_access_token_for_run(task: Task,state: dict[str, Any] | None,@@ -276,6 +285,7 @@ def create_oauth_access_token_for_user(include_interactive_run_scope: bool = False,include_slack_run_scope: bool = False,sandbox_task_id: UUID | None = None,+ withhold_scopes: Collection[str] = (),) -> str:"""Create an OAuth access token for a sandbox app, scoped to a specific team."""try:@@ -290,6 +300,8 @@ def create_oauth_access_token_for_user(token_options["include_interactive_run_scope"] = Trueif include_slack_run_scope:token_options["include_slack_run_scope"] = True+ if withhold_scopes:+ token_options["withhold_scopes"] = list(withhold_scopes)return _create_oauth_access_token_for_user(user, team_id, **token_options)except RuntimeError as err:raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from errdiff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.mdindex 1543ca1148bf..d9a69b066110 100644--- a/products/tasks/backend/temporal/process_task/README.md+++ b/products/tasks/backend/temporal/process_task/README.md@@ -176,6 +176,60 @@ The PID check applies only when the PID file exists, so servers launched beforeContinuation inherits the selected billing mode unless the caller explicitly changes it.Subscription runs do not reuse prewarmed sessions, because those processes have already selected their credentials.+### ChatGPT subscription access tokens++A run created with `codex_model_access: "own-subscription"` uses the user's ChatGPT plan for model usage.+The `posthog-code-codex-own-subscription-cloud` flag controls rollout, and the run must use the Codex runtime.+Owner recording and the owner check on `/command/` match the Claude path.+No ChatGPT token travels through the credential relay. Desktop reads the local `auth.json` at connect time and uploads its tokens to PostHog. It deletes that file after acceptance if cleanup succeeds. A failed upload or cleanup can leave the file behind. Cloud runs do not use that local file.++The user connects a ChatGPT account once: Desktop runs `codex login --device-auth` in an in-app terminal with a separate `CODEX_HOME`, then submits the resulting `auth.json` to `POST /api/users/@me/integrations/codex/`.+The server refreshes the chain once, stores the rotated refresh token in a `UserIntegration` row (`kind="codex"`), and never returns it.+`get_task_processing_context` fails the run early when the plan owner has no connected account or the account needs a new login.++At launch the activity mints a run-scoped JWT (audience `posthog:sandbox_codex_subscription`, bound to the run and the sandbox id).+The launcher writes it to a `chmod 600` file and the launch shell opens that file on fd 3 and deletes it before the agent-server starts, so the token is never in the environment or the command line.+The agent-server reads fd 3 once at boot and closes it, so processes it starts never see the token.+The launcher also tries to set `kernel.yama.ptrace_scope=1`. This is best effort only: the write fails in most containers because `/proc/sys` is read-only, and the local Docker sandbox runs with `CAP_SYS_PTRACE` for agentsh, which bypasses Yama.+Code that runs inside the sandbox is trusted with the run's model access for the lifetime of the run in any case, because the Codex process itself holds the access token.++The agent-server calls `POST /runs/{run_id}/subscription_token/` with its sandbox OAuth token and the run token in `X-Task-Run-Token`.+The endpoint accepts only the run's own sandbox identity plus a valid run token for the same run and sandbox, and it returns a short-lived access token, the account id, the plan type, and the expiry.+When Codex reports the token as rejected, the agent-server asks again with the SHA-256 digest of the rejected token. The server refreshes under a row lock only when that digest names the token it still holds, so two runs of one user that report the same token trigger one refresh and both receive the replacement.+A dead chain answers `409 reauth_required`; the run stops with a message that names the settings page.++```mermaid+sequenceDiagram+ participant W as Task worker+ participant S as Sandbox shell+ participant A as Agent server+ participant C as Codex+ participant P as PostHog API+ participant O as OpenAI+ W->>W: Mint a run token bound to the run and the sandbox+ W->>S: Write the token to a chmod 600 file+ S->>S: Open the file as fd 3, delete the file, exec the agent server+ A->>A: Read fd 3 once and close it+ A->>P: POST runs/{run_id}/subscription_token/ (sandbox OAuth + X-Task-Run-Token)+ P->>P: Row lock. Refresh only when the access token is near expiry.+ P->>O: Refresh with the stored refresh token+ O-->>P: New access token + rotated refresh token+ P-->>A: Access token, account id, plan type, expiry+ A->>C: Start codex in chatgptAuthTokens mode+ C->>O: Model calls+ O-->>C: 401+ C->>A: Refresh request (10 s)+ A->>P: POST subscription_token/ with the rejected token digest+ P-->>A: New token, or 409 reauth_required, or 502 openai_unavailable+ A-->>C: New token, or the run stops+```++Codex in the sandbox signs in with `chatgptAuthTokens`, which forces ephemeral storage and writes no auth file.+The sandbox OAuth token of a plan run (Claude or ChatGPT) omits `llm_gateway:read`, so nothing in the sandbox can reach the LLM gateway and bill PostHog credits.+A sandbox environment with a restricted network gets `chatgpt.com` added to its allowlist when the run is on a ChatGPT plan, because Codex calls it directly.+Subscription runs require the `--codexSubscription` startup option, and the launcher checks support before it starts the process.+Cloud usage and local usage share one plan allowance, so a run can stop at a plan rate limit that no PostHog quota controls.+Keep the flag off while deploying the backend and publishing the sandbox agent build, then enable it for the intended users.Desktop and backend use the same flag; a stale client cannot bypass the backend check.diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 8635e2b81e92..b026b404206e 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -10,7 +10,9 @@ from django.core.exceptions import ObjectDoesNotExistimport posthoganalyticsfrom temporalio import activity+from posthog.dataclasses import frozenfrom posthog.models import Team+from posthog.models.integration.codex import CodexUserIntegrationfrom posthog.temporal.common.utils import asyncify, close_db_connectionsfrom products.context_layer.backend.facade import api as context_layer_facade@@ -20,6 +22,8 @@ from products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,BENJAMIN_FEATURE_FLAG,CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ CODEX_SUBSCRIPTION_EGRESS_DOMAINS,CONTINUE_AS_NEW_FEATURE_FLAG,DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,DEV_STACK_IMAGE_NAME,@@ -34,6 +38,7 @@ from products.tasks.backend.constants import (SANDBOX_EVENT_INGEST_FEATURE_FLAG,SANDBOX_ROTATION_FEATURE_FLAG,STORE_SKILLS_STATE_KEY,+ SUBSCRIPTION_PLAN_NAMES,get_vm_sandbox_flag_payload,is_same_run_resume_state,vm_sandbox_allowed_origin_products,@@ -50,6 +55,7 @@ from products.tasks.backend.exceptions import ()from products.tasks.backend.facade.api import ensure_task_run_sessionfrom products.tasks.backend.feature_flags import is_agent_otel_telemetry_enabled+from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.agentsh import (_get_debug_only_domains,_get_debug_only_ports,@@ -169,6 +175,18 @@ class TaskProcessingContext:use_hogland_hotplug_golden: bool = Falsedev_stack_preview_enabled: bool = Falseclaude_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway"+ codex_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway"++ @property+ def model_access(self) -> ModelAccess:+ return resolve_model_access(+ {+ **(self.state or {}),+ "runtime_adapter": self.runtime_adapter,+ "claude_model_access": self.claude_model_access,+ "codex_model_access": self.codex_model_access,+ }+ )@propertydef mode(self) -> str:@@ -476,28 +494,53 @@ def _is_rtk_enabled(return True-def _resolve_claude_model_access(+@frozen+class _SubscriptionAdapter:+ flag: str+ runtime_name: str+ settings_name: str+++_SUBSCRIPTION_ADAPTERS: dict[str, _SubscriptionAdapter] = {+ "claude": _SubscriptionAdapter(+ flag=CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ runtime_name="Claude",+ settings_name="Claude subscription settings",+ ),+ "codex": _SubscriptionAdapter(+ flag=CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ runtime_name="Codex",+ settings_name="ChatGPT subscription settings",+ ),+}+++def _ensure_subscription_allowed(*,+ adapter: str,task_runtime: str,distinct_id: str | None,organization_id: str,run_id: str,- state: dict | None = None,-) -> Literal["posthog-gateway", "own-subscription"]:- if (state or {}).get("claude_model_access") != "own-subscription":- return "posthog-gateway"- if task_runtime != Task.Runtime.ACP or (state or {}).get("runtime_adapter") not in (None, "claude"):+) -> None:+ """Refuse a run on the owner's plan that the task runtime or the rollout does not allow.++ `resolve_model_access` has already paired the plan with the run's runtime adapter.+ """+ spec = _SUBSCRIPTION_ADAPTERS[adapter]+ plan_name = SUBSCRIPTION_PLAN_NAMES[adapter]+ if task_runtime != Task.Runtime.ACP:raise ProcessTaskFatalError(- "Your Claude plan requires the Claude runtime. Select Claude and try again.",+ f"Your {plan_name} requires the {spec.runtime_name} runtime. Select {spec.runtime_name} and try again.",{"run_id": run_id},- cause=ValueError("Subscription requested for a non-Claude runtime"),+ cause=ValueError(f"Subscription requested for a non-{spec.runtime_name} runtime"),capture=False,)try:enabled = bool(distinct_idand posthoganalytics.feature_enabled(- CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ spec.flag,distinct_id=distinct_id,groups={"organization": organization_id},group_properties={"organization": {"id": organization_id}},@@ -506,17 +549,34 @@ def _resolve_claude_model_access())except Exception as e:- log_with_activity_context("claude_own_subscription_flag_check_failed", run_id=run_id, error=str(e))+ log_with_activity_context(f"{adapter}_own_subscription_flag_check_failed", run_id=run_id, error=str(e))enabled = Falseif not enabled:raise ProcessTaskFatalError(- "Using your Claude plan for cloud tasks is unavailable. Try again later, "- 'or open Claude subscription settings and turn off "Cloud tasks" to use PostHog credits.',+ f"Using your {plan_name} for cloud tasks is unavailable. Try again later, "+ f'or open {spec.settings_name} and turn off "Cloud tasks" to use PostHog credits.',+ {"run_id": run_id},+ cause=ValueError(f"{plan_name} rollout unavailable"),+ capture=False,+ )+++def _plan_owner_distinct_id(team: Team, owner_id: int | None) -> str | None:+ """The rollout flag applies to whoever owns the plan the run bills to, not to whoever started it."""+ if owner_id is None:+ return None+ return team.all_users_with_access().filter(id=owner_id).values_list("distinct_id", flat=True).first()+++def _ensure_codex_account_connected(owner_id: int | None, run_id: str) -> None:+ integration = CodexUserIntegration.for_user(owner_id) if owner_id is not None else None+ if integration is None or not integration.is_connected():+ raise ProcessTaskFatalError(+ "Your ChatGPT account is not connected. Open ChatGPT subscription settings, connect it, and try again.",{"run_id": run_id},- cause=ValueError("Claude subscription rollout unavailable"),+ cause=ValueError("Codex subscription requested without a connected ChatGPT account"),capture=False,)- return "own-subscription"def _is_benjamin_enabled(@@ -1305,24 +1365,26 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProTaskRun.update_state_atomic(task_run.id, updates=state_updates)except Exception as e:log_with_activity_context("run_state_stamp_failed", run_id=run_id, error=str(e))- claude_distinct_id: str | None = distinct_id- if state.get("claude_model_access") == "own-subscription":- subscription_owner_id = state.get("claude_subscription_user_id")- claude_distinct_id = (- team.all_users_with_access().filter(id=subscription_owner_id).values_list("distinct_id", flat=True).first()- if isinstance(subscription_owner_id, int) and not isinstance(subscription_owner_id, bool)- else None++ try:+ model_access = resolve_model_access(state)+ except ValueError as error:+ raise ProcessTaskFatalError(str(error), {"run_id": run_id}, cause=error, capture=False) from error+ if model_access.adapter is not None:+ _ensure_subscription_allowed(+ adapter=model_access.adapter,+ task_runtime=task.runtime,+ distinct_id=_plan_owner_distinct_id(team, model_access.owner_id),+ organization_id=organization_id,+ run_id=run_id,)- claude_model_access = _resolve_claude_model_access(- task_runtime=task.runtime,- distinct_id=claude_distinct_id,- organization_id=organization_id,- run_id=run_id,- state=state,- )+ if model_access.adapter == "codex":+ _ensure_codex_account_connected(model_access.owner_id, run_id)+ claude_model_access = model_access.access_for("claude")+ codex_model_access = model_access.access_for("codex")pi_persistent_streaming = task.runtime == Task.Runtime.PI and not is_slack_interaction_state(state)sandbox_event_ingest_override = state.get("sandbox_event_ingest_enabled")- if claude_model_access == "own-subscription" or (+ if model_access.kind == "own-subscription" or (pi_persistent_streaming and not isinstance(sandbox_event_ingest_override, bool)):sandbox_event_ingest_enabled = True@@ -1359,6 +1421,12 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProf"use_modal_network_allowlist: {use_modal_network_allowlist} for this task run",)+ if codex_model_access == "own-subscription" and allowed_domains is not None:+ allowed_domains = [+ *allowed_domains,+ *(domain for domain in CODEX_SUBSCRIPTION_EGRESS_DOMAINS if domain not in allowed_domains),+ ]+effective_network_policy: EffectiveNetworkPolicy | None = Noneif allowed_domains is not None:try:@@ -1627,6 +1695,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPrortk_enabled=rtk_enabled,benjamin_enabled=benjamin_enabled,claude_model_access=claude_model_access,+ codex_model_access=codex_model_access,continue_as_new_enabled=_is_continue_as_new_enabled(distinct_id=distinct_id,organization_id=organization_id,diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 33378b15e9a1..24923f30a844 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -22,6 +22,7 @@ from posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import asyncify, retry_on_db_connection_dropfrom posthog.temporal.oauth import PosthogMcpScopes+from products.tasks.backend.constants import SUBSCRIPTION_PLAN_NAMESfrom products.tasks.backend.exceptions import (OAuthTokenError,ProcessTaskError,@@ -30,11 +31,15 @@ from products.tasks.backend.exceptions import (SandboxExecutionError,SandboxMissingRepositoryError,)-from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token+from products.tasks.backend.logic.services.connection_token import (+ create_codex_subscription_run_token,+ create_sandbox_event_ingest_token,+)from products.tasks.backend.logic.services.launch_preparation_metrics import launch_preparation_metric_contextfrom products.tasks.backend.logic.services.sandbox import (REPO_READY_FILE,SNAPSHOT_KIND_DIRECTORY,+ SUBSCRIPTION_CLI_FLAGS,SandboxBase,get_sandbox_class_for_sandbox_id,sandbox_repo_path,@@ -366,6 +371,7 @@ class _LaunchParams:protected_base_branch: str | Noneevent_ingest_token: str | None = field(repr=False)task_run_session_token: str | None = field(repr=False)+ codex_run_token: str | None = field(repr=False)event_ingest_url: str | Noneevent_ingest_keep_stream_open: bool@@ -484,6 +490,9 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandboevent_ingest_token = run_tokenif task.runtime == Task.Runtime.PI:task_run_session_token = run_token+ codex_run_token: str | None = None+ if ctx.model_access.adapter == "codex":+ codex_run_token = create_codex_subscription_run_token(task_run, sandbox_id=sandbox_id)mcp_configs = get_sandbox_ph_mcp_configs(token=access_token,@@ -570,6 +579,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandboprotected_base_branch=protected_base_branch,event_ingest_token=event_ingest_token,task_run_session_token=task_run_session_token,+ codex_run_token=codex_run_token,event_ingest_url=event_ingest_url,event_ingest_keep_stream_open=ctx.agent_proxy_keep_stream_open,)@@ -584,7 +594,7 @@ def _invoke_start_agent_server(wait_for_health: bool = False,) -> int | None:try:- _enforce_claude_subscription_support(sandbox, ctx)+ _enforce_subscription_support(sandbox, ctx)health_duration_ms = sandbox.start_agent_server(repository=ctx.repository if len(ctx.repositories) <= 1 else None,task_id=ctx.task_id,@@ -615,7 +625,9 @@ def _invoke_start_agent_server(rtk_enabled=ctx.rtk_enabled,benjamin_enabled=ctx.benjamin_enabled,peer_messaging=ctx.peer_messaging_enabled,- claude_model_access=ctx.claude_model_access,+ claude_model_access=ctx.model_access.access_for("claude"),+ codex_model_access=ctx.model_access.access_for("codex"),+ codex_run_token=params.codex_run_token,)return health_duration_ms if isinstance(health_duration_ms, int) else None@@ -642,19 +654,19 @@ def _invoke_start_agent_server()-def _enforce_claude_subscription_support(sandbox: SandboxBase, ctx: TaskProcessingContext) -> None:- if ctx.claude_model_access != "own-subscription":+def _enforce_subscription_support(sandbox: SandboxBase, ctx: TaskProcessingContext) -> None:+ adapter = ctx.model_access.adapter+ if adapter is None:return- result = sandbox.execute(- "grep -q -- --claudeSubscription /scripts/node_modules/.bin/agent-server",- timeout_seconds=10,- )+ plan_name = SUBSCRIPTION_PLAN_NAMES[adapter]+ flag = SUBSCRIPTION_CLI_FLAGS[adapter]+ result = sandbox.execute(f"grep -q -- {flag} /scripts/node_modules/.bin/agent-server", timeout_seconds=10)if result.exit_code != 0:raise ProcessTaskFatalError(- "This sandbox build cannot use your Claude plan yet. Start a new task. "- 'To use PostHog credits instead, turn off "Use your Claude plan for cloud tasks".',+ f"This sandbox build cannot use your {plan_name} yet. Start a new task. "+ f'To use PostHog credits instead, turn off "Use your {plan_name} for cloud tasks".',{"task_id": ctx.task_id, "run_id": ctx.run_id},- cause=RuntimeError("agent-server lacks --claudeSubscription"),+ cause=RuntimeError(f"agent-server lacks {flag}"),capture=False,)@@ -820,11 +832,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:) as health_timer:sandbox.wait_for_agent_server_ready(params.agentsh_domains,- **(- {"claude_model_access": ctx.claude_model_access}- if ctx.claude_model_access == "own-subscription"- else {}- ),+ claude_model_access=ctx.model_access.access_for("claude"),)invoke_ms = invoke_timer.elapsed_mshealth_poll_ms = health_timer.elapsed_ms@@ -969,11 +977,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu) as health_timer:sandbox.wait_for_agent_server_ready(agentsh_domains,- **(- {"claude_model_access": ctx.claude_model_access}- if ctx.claude_model_access == "own-subscription"- else {}- ),+ claude_model_access=ctx.model_access.access_for("claude"),)else:logger.warning(@@ -1008,11 +1012,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu) as health_timer:sandbox.wait_for_agent_server_ready(agentsh_domains,- **(- {"claude_model_access": ctx.claude_model_access}- if ctx.claude_model_access == "own-subscription"- else {}- ),+ claude_model_access=ctx.model_access.access_for("claude"),)_record_agent_server_launch(sandbox, ctx, params)except Exception as error:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex 50bdb372bfbc..c3def0c14b9a 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -16,6 +16,7 @@ from products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,BENJAMIN_FEATURE_FLAG,CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,CONTINUE_AS_NEW_FEATURE_FLAG,DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,DEV_STACK_IMAGE_NAME,@@ -36,6 +37,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processingGetTaskProcessingContextInput,TaskProcessingContext,VmSandboxDecision,+ _ensure_subscription_allowed,_is_agent_otel_telemetry_enabled,_is_agent_proxy_keep_stream_open_enabled,_is_benjamin_enabled,@@ -47,13 +49,16 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing_is_rtk_enabled,_is_sandbox_event_ingest_enabled,_require_template_compatible_with_custom_image,- _resolve_claude_model_access,_resolve_modal_vm_sandbox,_resolve_sandbox_backend,get_task_processing_context,)from products.tasks.backend.temporal.process_task.utils import get_actor_distinct_id+FEATURE_ENABLED_TARGET = (+ "products.tasks.backend.temporal.process_task.activities."+ "get_task_processing_context.posthoganalytics.feature_enabled"+)VM_FLAG_PAYLOAD_TARGET = "products.tasks.backend.constants.posthoganalytics.get_feature_flag_payload"BENJAMIN_PAYLOAD_TARGET = ("products.tasks.backend.temporal.process_task.activities."@@ -255,6 +260,36 @@ class TestGetTaskProcessingContextActivity:assert result.create_pr is Trueassert result.claude_model_access == ("own-subscription" if subscription else "posthog-gateway")+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize("integration_status", [None, "reauth_required", "connected"])+ def test_codex_subscription_run_needs_a_connected_chatgpt_account(+ self, activity_environment, test_task, integration_status+ ):+ owner = User.objects.create_user(+ email="[email protected]", password=None, first_name="Owner", distinct_id="codex-owner"+ )+ OrganizationMembership.objects.create(organization=test_task.team.organization, user=owner)+ if integration_status is not None:+ UserIntegration.objects.create(+ user=owner, kind="codex", integration_id="acct_1", config={"status": integration_status}+ )+ task_run = test_task.create_run(+ acting_user_id=owner.id,+ extra_state={"codex_model_access": "own-subscription", "runtime_adapter": "codex"},+ )+ input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))++ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ if integration_status == "connected":+ result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)+ assert result.codex_model_access == "own-subscription"+ else:+ with pytest.raises(ProcessTaskFatalError, match="ChatGPT account is not connected"):+ async_to_sync(activity_environment.run)(get_task_processing_context, input_data)+@pytest.mark.django_db(transaction=True)def test_get_task_processing_context_rejects_previous_owner_run(self, activity_environment, test_task):task_run = test_task.create_run()@@ -442,6 +477,44 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_environment_name == "Restricted env"assert result.allowed_domains == ["example.com"]+ @pytest.mark.django_db(transaction=True)+ def test_codex_subscription_run_can_reach_chatgpt_on_a_restricted_network(self, activity_environment, test_task):+ owner = User.objects.create_user(+ email="[email protected]", password=None, first_name="Owner", distinct_id="codex-owner"+ )+ OrganizationMembership.objects.create(organization=test_task.team.organization, user=owner)+ UserIntegration.objects.create(+ user=owner, kind="codex", integration_id="acct_1", config={"status": "connected"}+ )+ sandbox_environment = SandboxEnvironment.objects.create(+ team=test_task.team,+ created_by=test_task.created_by,+ name="Restricted env",+ network_access_level=SandboxEnvironment.NetworkAccessLevel.CUSTOM,+ allowed_domains=["example.com"],+ )+ task_run = test_task.create_run(+ acting_user_id=owner.id,+ extra_state={+ "sandbox_environment_id": str(sandbox_environment.id),+ "codex_model_access": "own-subscription",+ "runtime_adapter": "codex",+ },+ )++ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ result = async_to_sync(activity_environment.run)(+ get_task_processing_context, GetTaskProcessingContextInput(run_id=str(task_run.id))+ )++ assert result.codex_model_access == "own-subscription"+ assert result.allowed_domains == ["example.com", "chatgpt.com"]+ assert "chatgpt.com" in (result.agentsh_domain_allowlist or [])+ assert "chatgpt.com" in (result.modal_domain_allowlist or [])+@pytest.mark.django_db(transaction=True)def test_get_task_processing_context_preserves_empty_restricted_domains(self, activity_environment, test_task):sandbox_environment = SandboxEnvironment.objects.create(@@ -927,69 +1000,61 @@ class TestGetTaskProcessingContextActivity:is False)- @pytest.mark.parametrize(- "flag_value, state, expected",- [- (True, {"claude_model_access": "own-subscription"}, "own-subscription"),- (True, {"claude_model_access": "posthog-gateway"}, "posthog-gateway"),- (True, {}, "posthog-gateway"),- ],- )- def test_claude_model_access_requires_state_ask_and_flag(self, flag_value, state, expected):- with patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",- return_value=flag_value,- ) as feature_enabled_mock:- assert (- _resolve_claude_model_access(- task_runtime=Task.Runtime.ACP,- distinct_id="distinct-id",- organization_id="organization-id",- run_id="run-id",- state=state,- )- == expected- )+ SUBSCRIPTION_CASES = [+ ("claude", CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG, "Claude plan", "Claude"),+ ("codex", CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG, "ChatGPT plan", "Codex"),+ ]- if state.get("claude_model_access") == "own-subscription":- feature_enabled_mock.assert_called_once_with(- CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,+ @pytest.mark.parametrize("adapter,flag_key,plan_name,runtime_name", SUBSCRIPTION_CASES)+ def test_subscription_asks_the_plan_owners_rollout_flag(self, adapter, flag_key, plan_name, runtime_name):+ with patch(FEATURE_ENABLED_TARGET, return_value=True) as feature_enabled_mock:+ _ensure_subscription_allowed(+ adapter=adapter,+ task_runtime=Task.Runtime.ACP,distinct_id="distinct-id",- groups={"organization": "organization-id"},- group_properties={"organization": {"id": "organization-id"}},- only_evaluate_locally=False,- send_feature_flag_events=False,+ organization_id="organization-id",+ run_id="run-id",)- else:- feature_enabled_mock.assert_not_called()+ feature_enabled_mock.assert_called_once_with(+ flag_key,+ distinct_id="distinct-id",+ groups={"organization": "organization-id"},+ group_properties={"organization": {"id": "organization-id"}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )++ @pytest.mark.parametrize("adapter,flag_key,plan_name,runtime_name", SUBSCRIPTION_CASES)@pytest.mark.parametrize("flag_value", [False, None, RuntimeError("flag service failed")])- def test_claude_model_access_never_changes_requested_billing(self, flag_value: object) -> None:+ def test_subscription_model_access_never_changes_requested_billing(+ self, adapter: str, flag_key: str, plan_name: str, runtime_name: str, flag_value: object+ ) -> None:with (patch(- "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ FEATURE_ENABLED_TARGET,return_value=flag_value,side_effect=flag_value if isinstance(flag_value, Exception) else None,),- pytest.raises(ProcessTaskFatalError, match="Using your Claude plan for cloud tasks is unavailable"),+ pytest.raises(ProcessTaskFatalError, match=f"Using your {plan_name} for cloud tasks is unavailable"),):- _resolve_claude_model_access(+ _ensure_subscription_allowed(+ adapter=adapter,task_runtime=Task.Runtime.ACP,distinct_id="distinct-id",organization_id="organization-id",run_id="run-id",- state={"claude_model_access": "own-subscription"},)- @pytest.mark.parametrize("task_runtime,adapter", [(Task.Runtime.ACP, "codex"), (Task.Runtime.PI, None)])- def test_claude_subscription_rejects_other_adapters(self, task_runtime: str, adapter: str | None) -> None:- with pytest.raises(ProcessTaskFatalError, match="requires the Claude runtime"):- _resolve_claude_model_access(- task_runtime=task_runtime,+ @pytest.mark.parametrize("adapter,flag_key,plan_name,runtime_name", SUBSCRIPTION_CASES)+ def test_subscription_rejects_a_pi_task(self, adapter: str, flag_key: str, plan_name: str, runtime_name: str):+ with pytest.raises(ProcessTaskFatalError, match=f"requires the {runtime_name} runtime"):+ _ensure_subscription_allowed(+ adapter=adapter,+ task_runtime=Task.Runtime.PI,distinct_id="distinct-id",organization_id="organization-id",run_id="run-id",- state={"claude_model_access": "own-subscription", "runtime_adapter": adapter},)@pytest.mark.parametrize("launched_value", [True, False])diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex 216c04be3fe9..f9baecff55ad 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -86,6 +86,7 @@ def _context(use_modal_vm_sandbox: bool = False,use_modal_network_allowlist: bool = False,claude_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway",+ codex_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway",) -> TaskProcessingContext:return TaskProcessingContext(task_id="task-id",@@ -104,6 +105,7 @@ def _context(use_modal_vm_sandbox=use_modal_vm_sandbox,use_modal_network_allowlist=use_modal_network_allowlist,claude_model_access=claude_model_access,+ codex_model_access=codex_model_access,_branch=branch,)@@ -461,6 +463,7 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, aprotected_base_branch=None,event_ingest_token=None,task_run_session_token=None,+ codex_run_token=None,event_ingest_url=None,event_ingest_keep_stream_open=False,),@@ -489,7 +492,7 @@ async def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, a)assert result.sandbox_url == "https://sandbox.example"- sandbox.wait_for_agent_server_ready.assert_called_once_with(None)+ sandbox.wait_for_agent_server_ready.assert_called_once_with(None, claude_model_access="posthog-gateway")if expects_relaunch:preparation_meter.return_value.with_additional_attributes.assert_called_once_with({@@ -541,6 +544,7 @@ async def test_await_agent_server_ready_records_failed_relaunch(protected_base_branch=None,event_ingest_token=None,task_run_session_token=None,+ codex_run_token=None,event_ingest_url=None,event_ingest_keep_stream_open=False,),@@ -800,6 +804,7 @@ def test_subscription_compatibility_is_checked_before_launch(mocker, access, exiprotected_base_branch=None,event_ingest_token=None,task_run_session_token=None,+ codex_run_token=None,event_ingest_url=None,event_ingest_keep_stream_open=False,)@@ -1035,11 +1040,22 @@ async def test_collect_agent_shadow_result_reads_after_startup(mocker) -> None:@pytest.mark.django_db-async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker) -> None:- context = _context(sandbox_event_ingest_enabled=True, state={"mcp_builtin_agent_key": "scout"})+ ("codex_model_access", "expected_codex_run_token"),+ [("posthog-gateway", None), ("own-subscription", "codex-run-token")],+)+async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(+ mocker, codex_model_access, expected_codex_run_token+) -> None:+ context = _context(+ sandbox_event_ingest_enabled=True,+ state={"mcp_builtin_agent_key": "scout", "runtime_adapter": "codex"},+ codex_model_access=codex_model_access,+ )sandbox = mocker.Mock()sandbox.execute.return_value.stdout = ""sandbox.execute.return_value.stderr = ""+ sandbox.execute.return_value.exit_code = 0sandbox.start_agent_server.return_value = 125sandbox.read_agent_server_boot_metrics.return_value = (None, {})mocker.patch(@@ -1079,6 +1095,10 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker"products.tasks.backend.temporal.process_task.activities.start_agent_server.create_sandbox_event_ingest_token",return_value="event-ingest-token",)+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.create_codex_subscription_run_token",+ return_value="codex-run-token",+ )mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server._launch_agent_shadow",return_value=True,@@ -1121,6 +1141,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockerassert sandbox.start_agent_server.call_args.kwargs["wait_for_health"] is Trueassert result.health_poll_ms == 125assert sandbox.start_agent_server.call_args.kwargs["event_ingest_token"] == "event-ingest-token"+ assert sandbox.start_agent_server.call_args.kwargs["codex_run_token"] == expected_codex_run_tokenasync def test_start_agent_server_forwards_imported_and_relayed_mcp_servers(mocker) -> None:diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 0e9701670f88..322aeee1eead 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -66,6 +66,44 @@ class TestRuntimeModelCapabilities(SimpleTestCase):)+class TestRunStateModelAccess(SimpleTestCase):+ @parameterized.expand(+ [+ ({}, "posthog-gateway", None),+ (+ {"claude_model_access": "own-subscription", "claude_subscription_user_id": 12},+ "own-subscription",+ "claude",+ ),+ (+ {+ "runtime_adapter": "codex",+ "codex_model_access": "own-subscription",+ "codex_subscription_user_id": 12,+ },+ "own-subscription",+ "codex",+ ),+ ]+ )+ def test_decodes_legacy_fields(self, state: dict, kind: str, adapter: str | None) -> None:+ access = RunState.model_validate(state).model_access+ assert access.kind == kind+ assert access.adapter == adapter+ assert access.owner_id == (12 if adapter else None)++ @parameterized.expand(+ [+ ({"claude_model_access": "own-subscription", "codex_model_access": "own-subscription"},),+ ({"runtime_adapter": "claude", "codex_model_access": "own-subscription"},),+ ({"runtime_adapter": "codex", "claude_model_access": "own-subscription"},),+ ]+ )+ def test_rejects_incompatible_subscriptions(self, state: dict) -> None:+ with self.assertRaises(ValueError):+ _ = RunState.model_validate(state).model_access++class TestRunStateResumeCompatibility(SimpleTestCase):@parameterized.expand([diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 2354f9b514eb..a20655ff995c 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -36,6 +36,7 @@ from products.tasks.backend.constants import ()from products.tasks.backend.exceptions import CredentialUnavailableErrorfrom products.tasks.backend.feature_flags import is_mcp_exec_skills_enabled+from products.tasks.backend.logic.model_access import ModelAccess, resolve_model_accessfrom products.tasks.backend.logic.services.gateway_model_pin import GATEWAY_PRODUCT_STATE_KEY, PRODUCT_ALLOWED_MODELSfrom products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLSfrom products.tasks.backend.logic.services.mcp_url import resolve_mcp_url as _resolve_mcp_url@@ -342,6 +343,7 @@ class RunState(BaseModel, extra="allow"):context_window: str | None = Nonefast_mode: bool | None = Noneclaude_model_access: Literal["posthog-gateway", "own-subscription"] | None = None+ codex_model_access: Literal["posthog-gateway", "own-subscription"] | None = Noneresume_from_run_id: str | None = Noneresume_from_import_run: bool = Falsesame_run_resume: bool = False@@ -362,6 +364,10 @@ class RunState(BaseModel, extra="allow"):slack_sent_relay_ids: list[str] | None = Nonesandbox_template: str | None = None+ @property+ def model_access(self) -> ModelAccess:+ return resolve_model_access(self.model_dump())+def resume_snapshot_kind(self) -> SnapshotKind:if self.snapshot_kind == SNAPSHOT_KIND_DIRECTORY:return SNAPSHOT_KIND_DIRECTORY@@ -1356,7 +1362,7 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:context that scoped-token minting depends on. `ctx` is the run'sTaskProcessingContext (duck-typed to avoid an import cycle); `task` the Task row."""- if ctx.claude_model_access == "own-subscription":+ if "own-subscription" in (ctx.claude_model_access, ctx.codex_model_access):return {}try:env_vars = ai_gateway_env_vars(diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex 295c54a2b1de..b555da7e585f 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -414,6 +414,35 @@ def test_loop_fired_run_excludes_loop_write_scope(mock_create: MagicMock) -> Nonassert "task:read" in kwargs["scopes"][email protected]("adapter", ["claude", "codex"])+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")+def test_subscription_run_withholds_the_gateway_scope(mock_create: MagicMock, adapter: str) -> None:+ task = MagicMock(+ id="task-id",+ created_by=MagicMock(),+ team_id=123,+ origin_product=Task.OriginProduct.USER_CREATED,+ )++ create_oauth_access_token(task, run_state={f"{adapter}_model_access": "own-subscription"})++ assert mock_create.call_args.kwargs["withhold_scopes"] == ["llm_gateway:read"]+++@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")+def test_gateway_billed_run_keeps_the_gateway_scope(mock_create: MagicMock) -> None:+ task = MagicMock(+ id="task-id",+ created_by=MagicMock(),+ team_id=123,+ origin_product=Task.OriginProduct.USER_CREATED,+ )++ create_oauth_access_token(task, run_state={"codex_model_access": "posthog-gateway"})++ assert "withhold_scopes" not in mock_create.call_args.kwargs++@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")def test_non_loop_run_keeps_loop_write_scope(mock_create: MagicMock) -> None:task = MagicMock(diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.pyindex e3fc7a2af238..f8dda51dd2d6 100644--- a/products/tasks/backend/tests/test_agentsh.py+++ b/products/tasks/backend/tests/test_agentsh.py@@ -654,6 +654,32 @@ class TestModalSandboxAgentShWrapping(TestCase):self.assertIn("--allowedDomains", cmd)self.assertIn("example.com,api.example.com", cmd)+ def test_command_hands_the_codex_run_token_over_an_inherited_fd(self):+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox++ sandbox = ModalSandbox.__new__(ModalSandbox)+ sandbox.id = "sb-test"+ with_token = sandbox._build_agent_server_command(+ repo_path="/tmp/workspace/repos/org/repo",+ task_id="test-task",+ run_id="test-run",+ mode="background",+ create_pr=True,+ allowed_domains=["example.com"],+ codex_run_token_file="/tmp/agent-codex-run-token",+ )+ without_token = sandbox._build_agent_server_command(+ repo_path="/tmp/workspace/repos/org/repo",+ task_id="test-task",+ run_id="test-run",+ mode="background",+ create_pr=True,+ allowed_domains=["example.com"],+ )+ self.assertIn("exec 3< /tmp/agent-codex-run-token && rm -f /tmp/agent-codex-run-token && exec ", with_token)+ self.assertLess(with_token.index("agentsh exec"), with_token.index("exec 3<"))+ self.assertNotIn("exec 3<", without_token)+def test_command_includes_runtime_environment_variables(self):from products.tasks.backend.logic.services.modal_sandbox import ModalSandboxdiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex fedd33368608..426279d4d2c6 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -58,6 +58,7 @@ from products.tasks.backend.logic.services.code_usage_gate import (usage_limit_response,)from products.tasks.backend.logic.services.connection_token import (+ create_codex_subscription_run_token,create_sandbox_event_ingest_token,get_sandbox_jwt_public_key,reset_sandbox_jwt_key_cache,@@ -4348,15 +4349,20 @@ class TestTaskAPI(BaseTaskAPITest):("benjamin_enabled", False),("claude_model_access", "own-subscription"),("claude_model_access", "posthog-gateway"),+ ("codex_model_access", "own-subscription"),+ ("codex_model_access", "posthog-gateway"),])@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_persists_agent_toggle(self, field, value, mock_workflow):task = self.create_task()+ payload = {field: value}+ if field == "codex_model_access":+ payload.update(runtime_adapter="codex", model="gpt-5.4")response = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV).post(f"/api/projects/@current/tasks/{task.id}/run/",- {field: value},+ payload,format="json",)@@ -4401,6 +4407,55 @@ class TestTaskAPI(BaseTaskAPITest):assert field not in (task_run.state or {})mock_workflow.assert_called_once()+ @parameterized.expand(+ [+ ("claude", "claude-opus-5", "claude_model_access", "claude_subscription_user_id"),+ ("codex", "gpt-5.4", "codex_model_access", "codex_subscription_user_id"),+ ]+ )+ def test_create_run_endpoint_persists_subscription_choice(self, adapter, model, access_field, owner_field):+ task = self.create_task()++ response = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV).post(+ f"/api/projects/@current/tasks/{task.id}/runs/",+ {"environment": "cloud", "runtime_adapter": adapter, "model": model, access_field: "own-subscription"},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ task_run = TaskRun.objects.get(id=response.json()["id"])+ assert task_run.state[access_field] == "own-subscription"+ assert task_run.state[owner_field] == self.user.id++ @parameterized.expand(+ [+ (endpoint, claude_access, codex_access)+ for endpoint in ("run", "runs")+ for claude_access, codex_access in (+ ("own-subscription", "own-subscription"),+ ("posthog-gateway", "own-subscription"),+ )+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_rejects_invalid_subscription_choice(+ self, endpoint: str, claude_access: str, codex_access: str, mock_workflow: MagicMock+ ) -> None:+ task = self.create_task()+ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/{endpoint}/",+ {+ "runtime_adapter": "claude",+ "model": "claude-opus-5",+ "claude_model_access": claude_access,+ "codex_model_access": codex_access,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert not TaskRun.objects.filter(task=task).exists()+ mock_workflow.assert_not_called()+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_rejects_invalid_initial_permission_mode(self, mock_workflow):task = self.create_task()@@ -5197,6 +5252,51 @@ class TestTaskAPI(BaseTaskAPITest):assert response.json()["latest_run"]["state"]["claude_subscription_user_id"] == self.user.idmock_workflow.assert_called_once()+ @parameterized.expand([("claude", "claude-sonnet-4-5"), ("codex", "gpt-5.4")])+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_stores_the_plan_choice_and_its_owner_for_each_adapter(+ self, adapter: str, model: str, mock_workflow: MagicMock+ ) -> None:+ task = self.create_task()++ response = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV).post(+ f"/api/projects/@current/tasks/{task.id}/run/",+ {+ "mode": "interactive",+ "runtime_adapter": adapter,+ "model": model,+ f"{adapter}_model_access": "own-subscription",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])+ assert run.state[f"{adapter}_model_access"] == "own-subscription"+ assert run.state[f"{adapter}_subscription_user_id"] == self.user.id+ mock_workflow.assert_called_once()++ @parameterized.expand(+ [(action, adapter) for action in ("start", "resume_in_cloud") for adapter in ("claude", "codex")]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_launch_refuses_a_run_on_another_users_plan(+ self, action: str, adapter: str, mock_workflow: MagicMock+ ) -> None:+ task = self.create_task()+ run = task.create_run(environment=TaskRun.Environment.CLOUD)+ run.state = {+ **(run.state or {}),+ f"{adapter}_model_access": "own-subscription",+ f"{adapter}_subscription_user_id": self.user.id + 1,+ }+ run.save(update_fields=["state"])++ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/{action}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_workflow.assert_not_called()+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_resume_rejects_inherited_invalid_reasoning_effort(self, mock_workflow):task = self.create_task()@@ -12243,14 +12343,16 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["error"], "permission_response is not supported for Pi tasks.")- @parameterized.expand([(True,), (False,)])+ @parameterized.expand([("claude", True), ("claude", False), ("codex", True), ("codex", False)])@patch("products.tasks.backend.temporal.client.signal_task_followup_message")- def test_command_signals_user_message(self, subscription_owner_matches, mock_signal_followup):+ def test_command_signals_user_message(self, adapter, subscription_owner_matches, mock_signal_followup):task = self.create_task()run = self._create_run_with_sandbox(task)run.state.update(- claude_model_access="own-subscription",- claude_subscription_user_id=self.user.id if subscription_owner_matches else self.user.id + 1,+ {+ f"{adapter}_model_access": "own-subscription",+ f"{adapter}_subscription_user_id": self.user.id if subscription_owner_matches else self.user.id + 1,+ })run.save(update_fields=["state"])@@ -12918,6 +13020,105 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["detail"], "The task session content size is invalid")+ def _connect_codex(self, user, *, status_value="connected", expires_in=timedelta(hours=1)):+ expires_at = django_timezone.now() + expires_in+ access_token = jwt.encode(+ {"https://api.openai.com/auth": {"chatgpt_account_id": "acct_1", "chatgpt_plan_type": "plus"}},+ "unused",+ algorithm="HS256",+ )+ return UserIntegration.objects.create(+ user=user,+ kind="codex",+ integration_id="acct_1",+ config={"status": status_value, "plan_type": "plus"},+ sensitive_config={+ "access_token": access_token,+ "refresh_token": "rt_stored",+ "access_token_expires_at": expires_at.isoformat(),+ },+ )++ def _create_codex_subscription_run(self, owner, sandbox_id="sandbox-1"):+ task = self.create_task(created_by=owner)+ run = self._create_run_with_sandbox(task)+ run.state = {+ **run.state,+ "codex_model_access": "own-subscription",+ "codex_subscription_user_id": owner.id,+ }+ run.save(update_fields=["state"])+ self._open_sandbox_session(run, sandbox_id)+ return task, run++ def _subscription_token_url(self, task, run):+ return f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/subscription_token/"++ def test_subscription_token_returns_only_a_short_lived_access_token_to_the_runs_sandbox(self):+ owner = self.create_organization_user("codex-owner")+ self._connect_codex(owner)+ task, run = self._create_codex_subscription_run(owner)+ client = self._sandbox_oauth_client(task.id)++ with patch("requests.request") as openai:+ response = client.post(+ self._subscription_token_url(task, run),+ {},+ format="json",+ HTTP_X_TASK_RUN_TOKEN=create_codex_subscription_run_token(run, sandbox_id="sandbox-1"),+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertEqual(set(body), {"access_token", "account_id", "plan_type", "expires_at"})+ self.assertEqual(body["account_id"], "acct_1")+ self.assertEqual(body["plan_type"], "plus")+ self.assertNotIn("rt_stored", json.dumps(body))+ openai.assert_not_called()++ @parameterized.expand(+ [+ ("human_session", "session", "sandbox-1", None, status.HTTP_403_FORBIDDEN),+ ("missing_run_token", "sandbox", "sandbox-1", "", status.HTTP_400_BAD_REQUEST),+ ("wrong_sandbox", "sandbox", "other-sandbox", None, status.HTTP_403_FORBIDDEN),+ ("wrong_audience", "sandbox", "sandbox-1", "ingest", status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_subscription_token_refuses_callers_without_the_run_secret(+ self, _name, caller, token_sandbox_id, token_override, expected_status+ ):+ self._connect_codex(self.user)+ task, run = self._create_codex_subscription_run(self.user)+ client = self._sandbox_oauth_client(task.id) if caller == "sandbox" else self.client+ if token_override == "ingest":+ run_token = create_sandbox_event_ingest_token(run)+ elif token_override == "":+ run_token = None+ else:+ run_token = create_codex_subscription_run_token(run, sandbox_id=token_sandbox_id)+ headers = {"X-Task-Run-Token": run_token} if run_token is not None else {}++ response = client.post(self._subscription_token_url(task, run), {}, format="json", headers=headers)++ self.assertEqual(response.status_code, expected_status)+ self.assertNotIn("access_token", response.json())++ def test_subscription_token_reports_a_dead_chatgpt_chain_as_reauth_required(self):+ owner = self.create_organization_user("codex-owner")+ self._connect_codex(owner, status_value="reauth_required")+ task, run = self._create_codex_subscription_run(owner)+ client = self._sandbox_oauth_client(task.id)++ response = client.post(+ self._subscription_token_url(task, run),+ {"rejected_access_token_sha256": "0" * 64},+ format="json",+ HTTP_X_TASK_RUN_TOKEN=create_codex_subscription_run_token(run, sandbox_id="sandbox-1"),+ )++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(response.json()["code"], "reauth_required")+@patch("posthog.storage.object_storage.get_presigned_url")def test_task_session_is_readable_for_a_public_channel_task(self, mock_download_url):other_user = self.create_organization_user("task-owner")diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex a8b42ab69f4b..f81beb5b4f74 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -2056,9 +2056,21 @@ class TestRunTaskWarmActivation(APIBaseTest):run.refresh_from_db()assert run.state.get("await_user_message") is True- @parameterized.expand([("context_window", "1m"), ("claude_model_access", "own-subscription")])- def test_runtime_selection_mismatch_does_not_activate_warm_run(self, field, value):- task, run = self._warm_run()+ @parameterized.expand(+ [+ ("context_window", {"context_window": "1m"}, None),+ ("claude_model_access", {"claude_model_access": "own-subscription"}, None),+ # A codex plan requires the codex runtime, so the warm run has to be warmed on it too.+ # Otherwise the runtime alone decides the mismatch and the plan gate goes untested.+ (+ "codex_model_access",+ {"codex_model_access": "own-subscription", "runtime_adapter": "codex"},+ {"runtime_adapter": "codex"},+ ),+ ]+ )+ def test_runtime_selection_mismatch_does_not_activate_warm_run(self, _name, requested, warm_state):+ task, run = self._warm_run(extra_state=warm_state)with (patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as mock_trigger,@@ -2071,7 +2083,7 @@ class TestRunTaskWarmActivation(APIBaseTest):"mode": "interactive","branch": "main","pending_user_message": "do it",- field: value,+ **requested,},)diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex e49cc21c6189..016da7993de0 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -2788,9 +2788,9 @@ export interface RelayedMcpServerApi {* * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription*/-export type ClaudeModelAccessEnumApi = (typeof ClaudeModelAccessEnumApi)[keyof typeof ClaudeModelAccessEnumApi]+export type ModelAccessEnumApi = (typeof ModelAccessEnumApi)[keyof typeof ModelAccessEnumApi]-export const ClaudeModelAccessEnumApi = {+export const ModelAccessEnumApi = {PosthogGateway: 'posthog-gateway',OwnSubscription: 'own-subscription',} as const@@ -2896,7 +2896,12 @@ export interface ClaudeTaskRunCreateSchemaApi {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnumApi | null+ claude_model_access?: ModelAccessEnumApi | null+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnumApi | null/*** Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.* @nullable@@ -3034,7 +3039,12 @@ export interface CodexTaskRunCreateSchemaApi {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnumApi | null+ claude_model_access?: ModelAccessEnumApi | null+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnumApi | null/*** Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.* @nullable@@ -3497,7 +3507,12 @@ export interface TaskRunBootstrapCreateRequestApi {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnumApi | null+ claude_model_access?: ModelAccessEnumApi | null+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnumApi | null/** Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.** * `local` - local@@ -4375,6 +4390,29 @@ export interface StreamReadTokenResponseApi {stream_base_url: string | null}+export interface TaskRunSubscriptionTokenRequestApi {+ /**+ * SHA-256 hex digest of the access token Codex rejected. The server refreshes only when this names its current token; otherwise it returns the newer token it already holds.+ * @nullable+ * @pattern ^[0-9a-f]{64}$+ */+ rejected_access_token_sha256?: string | null+}++export interface TaskRunSubscriptionTokenResponseApi {+ /** ChatGPT access token for the Codex app-server. It can stay valid for several days. */+ access_token: string+ /** ChatGPT account the access token belongs to */+ account_id: string+ /**+ * ChatGPT plan of the account, when known+ * @nullable+ */+ plan_type: string | null+ /** When the access token expires. Request a new one before this time. */+ expires_at: string+}+export interface TaskSessionResponseApi {/** Task session identifier */id: stringdiff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 0b3e5f8615c5..95a2fe11c14e 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -129,6 +129,8 @@ import type {TaskRunRelayMessageResponseApi,TaskRunResponseApi,TaskRunStartRequestApi,+ TaskRunSubscriptionTokenRequestApi,+ TaskRunSubscriptionTokenResponseApi,TaskSearchResultApi,TaskSessionResponseApi,TaskSessionSyncResponseApi,@@ -2453,6 +2455,32 @@ export const tasksRunsStreamTokenRetrieve = async (})}+export const getTasksRunsSubscriptionTokenCreateUrl = (projectId: string, taskId: string, id: string) => {+ return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/subscription_token/`+}++/**+ * Give the run's agent-server a short-lived ChatGPT access token from the run owner's connected account. Only the run's sandbox may call this, and it must present the run token it received at launch. Send the digest of a token Codex rejected so the server refreshes it early, once.+ * @summary Issue a ChatGPT access token for a Codex run+ */+export const tasksRunsSubscriptionTokenCreate = async (+ projectId: string,+ taskId: string,+ id: string,+ taskRunSubscriptionTokenRequestApi?: TaskRunSubscriptionTokenRequestApi,+ options?: RequestInit+): Promise<TaskRunSubscriptionTokenResponseApi> => {+ return apiMutator<TaskRunSubscriptionTokenResponseApi>(+ getTasksRunsSubscriptionTokenCreateUrl(projectId, taskId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(taskRunSubscriptionTokenRequestApi),+ }+ )+}+export const getTasksRunsTaskSessionRetrieveUrl = (projectId: string, taskId: string, id: string) => {return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/task_session/`}diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex ee721042beb7..6725fe751133 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1892,6 +1892,17 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([.describe("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),+ codex_model_access: zod+ .union([+ zod+ .enum(['posthog-gateway', 'own-subscription'])+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),+ zod.null(),+ ])+ .optional()+ .describe(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ ),scheduled_at: zod.string().nullish()@@ -2062,6 +2073,17 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([.describe("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),+ codex_model_access: zod+ .union([+ zod+ .enum(['posthog-gateway', 'own-subscription'])+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),+ zod.null(),+ ])+ .optional()+ .describe(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ ),scheduled_at: zod.string().nullish()@@ -2545,6 +2567,17 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod.describe("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),+ codex_model_access: zod+ .union([+ zod+ .enum(['posthog-gateway', 'own-subscription'])+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),+ zod.null(),+ ])+ .optional()+ .describe(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ ),environment: zod.enum(['local', 'cloud']).describe('\* `local` - local\n\* `cloud` - cloud')@@ -3366,6 +3399,22 @@ export const TasksRunsStartCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Give the run's agent-server a short-lived ChatGPT access token from the run owner's connected account. Only the run's sandbox may call this, and it must present the run token it received at launch. Send the digest of a token Codex rejected so the server refreshes it early, once.+ * @summary Issue a ChatGPT access token for a Codex run+ */+export const tasksRunsSubscriptionTokenCreateBodyRejectedAccessTokenSha256RegExp = new RegExp('^[0-9a-f]{64}$')++export const TasksRunsSubscriptionTokenCreateBody = /* @__PURE__ */ zod.object({+ rejected_access_token_sha256: zod+ .string()+ .regex(tasksRunsSubscriptionTokenCreateBodyRejectedAccessTokenSha256RegExp)+ .nullish()+ .describe(+ 'SHA-256 hex digest of the access token Codex rejected. The server refreshes only when this names its current token; otherwise it returns the newer token it already holds.'+ ),+})+/*** Create a stable, editable artifact handle from direct markdown/text content or an existing run artifact. Slack adapters deliver into the mapped Slack thread; document artifacts use external connector storage when available.* @summary Create a living artifact for a task rundiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex bcd9fa1e2316..409adfa95be4 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -860,6 +860,9 @@ tools:tasks-runs-stream-token-retrieve:operation: tasks_runs_stream_token_retrieveenabled: false+ tasks-runs-subscription-token-create:+ operation: tasks_runs_subscription_token_create+ enabled: falsetasks-runs-task-session-retrieve:operation: tasks_runs_task_session_retrieveenabled: falsediff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex a6e0df051978..13d5dfc00958 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -641,6 +641,15 @@ tools:users-hedgehog-config-retrieve:operation: users_hedgehog_config_retrieveenabled: false+ users-integrations-codex-create:+ operation: users_integrations_codex_create+ enabled: false+ users-integrations-codex-destroy:+ operation: users_integrations_codex_destroy+ enabled: false+ users-integrations-codex-retrieve:+ operation: users_integrations_codex_retrieve+ enabled: falseusers-integrations-github-branches-retrieve:operation: users_integrations_github_branches_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d907f4f29324..545622496855 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19933,18 +19933,6 @@ export namespace Schemas {total_with_tags: number;}- /**- * * `posthog-gateway` - posthog-gateway- * * `own-subscription` - own-subscription- */- export type ClaudeModelAccessEnum = typeof ClaudeModelAccessEnum[keyof typeof ClaudeModelAccessEnum];--- export const ClaudeModelAccessEnum = {- PosthogGateway: 'posthog-gateway',- OwnSubscription: 'own-subscription',- } as const;-/*** * `claude` - claude*/@@ -19994,6 +19982,18 @@ export namespace Schemas {name: string;}+ /**+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription+ */+ export type ModelAccessEnum = typeof ModelAccessEnum[keyof typeof ModelAccessEnum];+++ export const ModelAccessEnum = {+ PosthogGateway: 'posthog-gateway',+ OwnSubscription: 'own-subscription',+ } as const;+/*** * `interactive` - interactive* * `background` - background@@ -20110,7 +20110,12 @@ export namespace Schemas {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnum | null;+ claude_model_access?: ModelAccessEnum | null;+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnum | null;/*** Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.* @nullable@@ -20478,6 +20483,20 @@ export namespace Schemas {StaleVersion: 'stale_version',} as const;+ /**+ * * `connected` - Connected+ * * `reauth_required` - Reauth Required+ * * `not_connected` - Not Connected+ */+ export type CodexIntegrationStatusEnum = typeof CodexIntegrationStatusEnum[keyof typeof CodexIntegrationStatusEnum];+++ export const CodexIntegrationStatusEnum = {+ Connected: 'connected',+ ReauthRequired: 'reauth_required',+ NotConnected: 'not_connected',+ } as const;+/*** * `codex` - codex*/@@ -20532,7 +20551,12 @@ export namespace Schemas {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnum | null;+ claude_model_access?: ModelAccessEnum | null;+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnum | null;/*** Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.* @nullable@@ -96639,7 +96663,12 @@ export namespace Schemas {** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */- claude_model_access?: ClaudeModelAccessEnum | null;+ claude_model_access?: ModelAccessEnum | null;+ /** How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ *+ * * `posthog-gateway` - posthog-gateway+ * * `own-subscription` - own-subscription */+ codex_model_access?: ModelAccessEnum | null;/** Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.** * `local` - local@@ -97353,6 +97382,29 @@ export namespace Schemas {pending_user_artifact_ids?: string[];}+ export interface TaskRunSubscriptionTokenRequest {+ /**+ * SHA-256 hex digest of the access token Codex rejected. The server refreshes only when this names its current token; otherwise it returns the newer token it already holds.+ * @nullable+ * @pattern ^[0-9a-f]{64}$+ */+ rejected_access_token_sha256?: string | null;+ }++ export interface TaskRunSubscriptionTokenResponse {+ /** ChatGPT access token for the Codex app-server. It can stay valid for several days. */+ access_token: string;+ /** ChatGPT account the access token belongs to */+ account_id: string;+ /**+ * ChatGPT plan of the account, when known+ * @nullable+ */+ plan_type: string | null;+ /** When the access token expires. Request a new one before this time. */+ expires_at: string;+ }+/*** * `task` - task* * `pull_request` - pull_request@@ -98957,6 +99009,47 @@ export namespace Schemas {total: number;}+ export interface UserCodexAuthTokens {+ /** The ChatGPT access token (a JWT) from the `tokens` object of the Codex `auth.json`. */+ access_token: string;+ /** The single-use ChatGPT refresh token from the same `tokens` object. */+ refresh_token: string;+ /**+ * The OpenID id token from the same `tokens` object, when present. Used to read the account email.+ * @nullable+ */+ id_token?: string | null;+ }++ export interface UserCodexConnectRequest {+ /** The `tokens` object of the `auth.json` that `codex login` wrote. PostHog refreshes the chain once, stores the rotated tokens, and refreshes them for cloud runs from then on. */+ tokens: UserCodexAuthTokens;+ }++ export interface UserCodexIntegration {+ /** `connected` when cloud runs can use the account; `reauth_required` when OpenAI rejected the refresh token and the user must log in and connect again; `not_connected` when no account is connected.+ *+ * * `connected` - Connected+ * * `reauth_required` - Reauth Required+ * * `not_connected` - Not Connected */+ status: CodexIntegrationStatusEnum;+ /**+ * The ChatGPT plan type OpenAI reports for the account.+ * @nullable+ */+ plan_type?: string | null;+ /**+ * The email of the connected ChatGPT account.+ * @nullable+ */+ email?: string | null;+ /**+ * When the account was connected.+ * @nullable+ */+ connected_at?: string | null;+ }+export interface UserCustomerAnalyticsConfig {/** Account properties pinned in sidebar display order. */readonly pinned_properties: readonly PinnedAccountProperty[];diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 3fcfe8c513f0..c66f1c985bc0 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -1351,6 +1351,17 @@ export const TasksRunCreateBody = () => zod.union([.describe("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),+ codex_model_access: zod+ .union([+ zod+ .enum(['posthog-gateway', 'own-subscription'])+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),+ zod.null(),+ ])+ .optional()+ .describe(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ ),scheduled_at: zod.string().nullish()@@ -1521,6 +1532,17 @@ export const TasksRunCreateBody = () => zod.union([.describe("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),+ codex_model_access: zod+ .union([+ zod+ .enum(['posthog-gateway', 'own-subscription'])+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),+ zod.null(),+ ])+ .optional()+ .describe(+ "How the Codex runtime pays for model use. 'own-subscription' makes the sandbox fetch a ChatGPT access token from the PostHog API, refreshed from the ChatGPT account the run owner connected in Desktop settings. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ ),scheduled_at: zod.string().nullish()