:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): let a task agent default run on the pi harness (#100803)
Shy Alter09da650b5c9c
diff --git a/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx b/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsxindex c724dfef690e..a48214b8f0a3 100644--- a/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx+++ b/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx@@ -20,9 +20,12 @@ import {listRuntimeAdapters,modelsForRuntimeAdapter,} from 'products/posthog_ai/frontend/utils/composerModels'+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import { type AIRunPreferenceDraft, taskAgentDefaultsLogic } from './taskAgentDefaultsLogic'+const PI_HARNESS_LABEL = 'Pi'+function PreferenceEditor({draft,dirty,@@ -75,6 +78,7 @@ function PreferenceEditor({return groups}, [catalogue])const effortOptions = useMemo(() => getEffortsForModel(catalogue, draft.model), [catalogue, draft.model])+ const editingDisabled = restrictionReason ?? (saving ? 'Saving…' : undefined)return (<div className="flex flex-wrap items-end gap-2">@@ -95,7 +99,7 @@ function PreferenceEditor({}options={[{ options: [{ value: null as string | null, label: inheritLabel }] }, ...modelOptions]}placeholder={inheritLabel}- disabledReason={restrictionReason ?? (saving ? 'Saving…' : undefined)}+ disabledReason={editingDisabled}data-attr="task-agent-default-model"/></LemonField.Pure>@@ -108,9 +112,7 @@ function PreferenceEditor({{ value: null as string | null, label: 'Default effort' },...effortOptions.map(({ value, label }) => ({ value: value as string, label })),]}- disabledReason={- restrictionReason ?? (saving ? 'Saving…' : draft.model ? undefined : 'Pick a model first')- }+ disabledReason={editingDisabled ?? (draft.model ? undefined : 'Pick a model first')}data-attr="task-agent-default-effort"/></LemonField.Pure>@@ -171,6 +173,7 @@ export function TaskAgentMyPreferenceSettings(): JSX.Element {useValues(taskAgentDefaultsLogic)const { catalogue } = useValues(modelCatalogueLogic)const { setMyDraft, submitMyDraft, resetMyPreference } = useActions(taskAgentDefaultsLogic)+ const isPiDefault = resolvedDefaults?.runtime === TaskRuntimeEnumApi.Pireturn (<div className="flex flex-col gap-2">@@ -187,12 +190,21 @@ export function TaskAgentMyPreferenceSettings(): JSX.Element {<p className="text-secondary mb-0">{resolvedDefaults?.model ? (<>- Runs you start without picking a model will use{' '}- <strong>{getModelLabel(catalogue, resolvedDefaults.model)}</strong>+ {isPiDefault ? 'Runs you start in PostHog Desktop' : 'Runs you start'} without picking a model+ will use{' '}+ <strong>+ {isPiDefault ? `${PI_HARNESS_LABEL} · ` : ''}+ {getModelLabel(catalogue, resolvedDefaults.model)}+ </strong>{resolvedDefaults.reasoning_effort ? (- <> ({getEffortLabel(resolvedDefaults.reasoning_effort)} effort)</>+ <>+ {' '}+ ({getEffortLabel(resolvedDefaults.reasoning_effort)}{' '}+ {isPiDefault ? 'thinking' : 'effort'})+ </>) : null}{' '}from {resolvedDefaults.source === 'user' ? 'your default above' : 'the project default'}.+ {isPiDefault ? ' Runs you start elsewhere use their built-in model.' : ''}</>) : (<>No default is set. Runs use each surface's built-in model.</>diff --git a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.tsindex e0ac0c668dc0..f7bb8dbf3e19 100644--- a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts+++ b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts@@ -66,7 +66,7 @@ describe('taskAgentDefaultsLogic', () => {canResetMyPreference: false,myDraftDirty: false,})- expect(posted).toEqual([{ runtime_adapter: null, model: null, reasoning_effort: null }])+ expect(posted).toEqual([{ runtime: null, runtime_adapter: null, model: null, reasoning_effort: null }])})// Nothing stored and nothing picked means there's nothing to fall back to — the button has to say so@@ -85,6 +85,33 @@ describe('taskAgentDefaultsLogic', () => {await expectLogic(logic).toMatchValues({ canResetMyPreference: true, myDraftDirty: true })})+ it('does not seed the editor from a Pi default, but still offers to clear it', async () => {+ useConfigMocks({ runtime: 'pi', model: 'gpt-5.6-terra', reasoning_effort: 'off' })+ mount()++ await expectLogic(logic)+ .toDispatchActions(['loadMyConfigSuccess'])+ .toMatchValues({+ myDraft: { model: null, reasoning_effort: null },+ myDraftDirty: false,+ canResetMyPreference: true,+ })+ })++ it('moves a Pi default onto the ACP harness when an ACP model is picked', async () => {+ useConfigMocks({ runtime: 'pi', model: 'gpt-5.6-terra', reasoning_effort: 'off' })+ mount()+ await expectLogic(logic).toDispatchActions(['loadMyConfigSuccess'])++ logic.actions.setMyDraft({ model: 'claude-opus-5', reasoning_effort: null })+ logic.actions.submitMyDraft()++ await expectLogic(logic).toDispatchActions(['saveMyPreferencesSuccess'])+ expect(posted).toEqual([+ { runtime: 'acp', runtime_adapter: 'claude', model: 'claude-opus-5', reasoning_effort: null },+ ])+ })+// Saving the project default refetches the personal config; that load result used to// overwrite whatever the person was editing in the other card, and the Save button then// read "No changes to save" over the silently discarded pick.diff --git a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.tsindex 85af283e4f53..9958288bfa36 100644--- a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts+++ b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts@@ -8,6 +8,7 @@ import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCaimport { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'import { getRuntimeAdapterForModel } from 'products/posthog_ai/frontend/utils/composerModels'import { tasksConfigCreate, tasksConfigList, tasksMeConfigCreate } from 'products/tasks/frontend/generated/api'+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type {ModelChoiceApi,TasksAIRunPreferencesApi,@@ -32,17 +33,26 @@ function isDraftChanged(draft: AIRunPreferenceDraft, stored: AIRunPreferenceDrafreturn draft.model !== stored.model || draft.reasoning_effort !== stored.reasoning_effort}+// A Pi default is authored in PostHog Desktop, and its models are not in this catalogue, so it+// cannot be edited here. Seeding it as empty keeps the editor on ACP, and any save made here+// moves the stored default to ACP rather than blocking the person.function draftFromStored(stored: TasksAIRunPreferencesApi | null | undefined): AIRunPreferenceDraft {- return { model: stored?.model ?? null, reasoning_effort: stored?.reasoning_effort ?? null }+ return stored?.model && stored.runtime !== TaskRuntimeEnumApi.Pi+ ? { model: stored.model, reasoning_effort: stored.reasoning_effort ?? null }+ : EMPTY_DRAFT}// The adapter is a property of the model, so it comes off the catalogue rather than the model id's// spelling — the settings picker offers Codex models too, and a new harness must not be mislabelled.function payloadFromDraft(draft: AIRunPreferenceDraft, catalogue: ModelChoiceApi[]): TasksAIRunPreferencesApi {+ if (!draft.model) {+ return { runtime: null, runtime_adapter: null, model: null, reasoning_effort: null }+ }return {- runtime_adapter: draft.model ? getRuntimeAdapterForModel(catalogue, draft.model) : null,+ runtime: TaskRuntimeEnumApi.Acp,+ runtime_adapter: getRuntimeAdapterForModel(catalogue, draft.model),model: draft.model,- reasoning_effort: draft.model ? (draft.reasoning_effort as TasksAIRunPreferencesApi['reasoning_effort']) : null,+ reasoning_effort: draft.reasoning_effort as TasksAIRunPreferencesApi['reasoning_effort'],}}@@ -59,6 +69,7 @@ export interface taskAgentDefaultsLogicValues {myPreferenceStored: AIRunPreferenceDraftmyPreferences: TasksUserConfigResponseApi | nullmyPreferencesLoading: boolean+ myStoredPreferences: TasksAIRunPreferencesApi | nullteamDraft: AIRunPreferenceDraftteamDraftDirty: booleanteamDraftState: DraftState@@ -143,13 +154,17 @@ export interface taskAgentDefaultsLogicMeta {__keaTypeGenInternalSelectorTypes: {teamDraft: (teamDraftState: DraftState) => AIRunPreferenceDraftmyDraft: (myDraftState: DraftState) => AIRunPreferenceDraft- myPreferenceStored: (+ myStoredPreferences: (myPreferences: TasksUserConfigResponseApi | null,myConfig: TasksUserConfigResponseApi | null- ) => AIRunPreferenceDraft+ ) => TasksAIRunPreferencesApi | null+ myPreferenceStored: (myStoredPreferences: TasksAIRunPreferencesApi | null) => AIRunPreferenceDraftteamDraftDirty: (teamDraft: AIRunPreferenceDraft, teamPreferences: TasksAIRunPreferencesApi | null) => booleanmyDraftDirty: (myDraft: AIRunPreferenceDraft, myPreferenceStored: AIRunPreferenceDraft) => boolean- canResetMyPreference: (myDraft: AIRunPreferenceDraft, myPreferenceStored: AIRunPreferenceDraft) => boolean+ canResetMyPreference: (+ myDraft: AIRunPreferenceDraft,+ myStoredPreferences: TasksAIRunPreferencesApi | null+ ) => boolean}}@@ -252,10 +267,16 @@ export const taskAgentDefaultsLogic = kea<taskAgentDefaultsLogicType>([// The save response is read first so the reset button settles in the same tick as the// save; `myConfig` (refreshed alongside it) is what's there on mount and after a// project-level write.- myPreferenceStored: [+ myStoredPreferences: [(s) => [s.myPreferences, s.myConfig],- (saved: TasksUserConfigResponseApi | null, loaded: TasksUserConfigResponseApi | null) =>- draftFromStored((saved ?? loaded)?.ai_run_preferences),+ (+ saved: TasksUserConfigResponseApi | null,+ loaded: TasksUserConfigResponseApi | null+ ): TasksAIRunPreferencesApi | null => (saved ?? loaded)?.ai_run_preferences ?? null,+ ],+ myPreferenceStored: [+ (s) => [s.myStoredPreferences],+ (stored: TasksAIRunPreferencesApi | null): AIRunPreferenceDraft => draftFromStored(stored),],// Whether there's anything to send.teamDraftDirty: [@@ -270,9 +291,9 @@ export const taskAgentDefaultsLogic = kea<taskAgentDefaultsLogicType>([// Nothing to fall back to when neither the draft nor the stored preference pins a model — the// effort alone is never stored without one.canResetMyPreference: [- (s) => [s.myDraft, s.myPreferenceStored],- (draft: AIRunPreferenceDraft, stored: AIRunPreferenceDraft): boolean =>- Boolean(draft.model || stored.model),+ (s) => [s.myDraft, s.myStoredPreferences],+ (draft: AIRunPreferenceDraft, stored: TasksAIRunPreferencesApi | null): boolean =>+ Boolean(draft.model || stored?.model),],}),diff --git a/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.test.ts b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.test.tsnew file mode 100644index 000000000000..bf6dddd2f1d0--- /dev/null+++ b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.test.ts@@ -0,0 +1,65 @@+import { initKeaTests } from '~/test/init'++import { tasksMeConfigList } from 'products/tasks/frontend/generated/api'+import type { TasksResolvedAIRunDefaultsApi } from 'products/tasks/frontend/generated/api.schemas'++import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksMeConfigList: jest.fn(),+}))++describe('taskRunDefaultsLogic', () => {+ let logic: ReturnType<typeof taskRunDefaultsLogic.build>++ const ACP_DEFAULT: TasksResolvedAIRunDefaultsApi = {+ runtime: 'acp',+ runtime_adapter: 'codex',+ model: 'gpt-5.5',+ reasoning_effort: 'medium',+ source: 'user',+ }+ const PI_DEFAULT: TasksResolvedAIRunDefaultsApi = {+ runtime: 'pi',+ runtime_adapter: null,+ model: 'gpt-5.6-terra',+ reasoning_effort: 'off',+ source: 'user',+ }++ async function mountWithResolved(resolved: TasksResolvedAIRunDefaultsApi): Promise<void> {+ ;(tasksMeConfigList as jest.Mock).mockResolvedValue({+ ai_run_preferences: {},+ resolved_ai_run_defaults: resolved,+ })+ logic = taskRunDefaultsLogic()+ logic.mount()+ await logic.asyncActions.loadMyConfig()+ }++ beforeEach(() => {+ initKeaTests()+ jest.clearAllMocks()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('carries an ACP default through to the composer values', async () => {+ await mountWithResolved(ACP_DEFAULT)++ expect(logic.values.defaultModel).toBe('gpt-5.5')+ expect(logic.values.defaultEffort).toBe('medium')+ expect(logic.values.defaultRuntimeAdapter).toBe('codex')+ })++ it('reads a Pi default as no default for the web composer, while still reporting it', async () => {+ await mountWithResolved(PI_DEFAULT)++ expect(logic.values.defaultModel).toBeNull()+ expect(logic.values.defaultEffort).toBeNull()+ expect(logic.values.defaultRuntimeAdapter).toBeNull()+ expect(logic.values.resolvedDefaults).toEqual(PI_DEFAULT)+ })+})diff --git a/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.tsindex 2092dda6e10c..2b7e5a157a08 100644--- a/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts+++ b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'import { projectLogic } from 'scenes/projectLogic'import { tasksMeConfigList } from 'products/tasks/frontend/generated/api'+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type {TasksResolvedAIRunDefaultsApi,TasksUserConfigResponseApi,@@ -12,6 +13,7 @@ import type {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskRunDefaultsLogicValues {currentProjectId: number | null // projectLogic+ acpDefaults: TasksResolvedAIRunDefaultsApi | nulldefaultEffort: string | nulldefaultModel: string | nulldefaultRuntimeAdapter: string | null@@ -43,9 +45,10 @@ export interface taskRunDefaultsLogicActions {export interface taskRunDefaultsLogicMeta {__keaTypeGenInternalSelectorTypes: {resolvedDefaults: (myConfig: TasksUserConfigResponseApi | null) => TasksResolvedAIRunDefaultsApi | null- defaultModel: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null- defaultEffort: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null- defaultRuntimeAdapter: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null+ acpDefaults: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => TasksResolvedAIRunDefaultsApi | null+ defaultModel: (acpDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null+ defaultEffort: (acpDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null+ defaultRuntimeAdapter: (acpDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null}}@@ -93,22 +96,27 @@ export const taskRunDefaultsLogic = kea<taskRunDefaultsLogicType>([(myConfig: TasksUserConfigResponseApi | null): TasksResolvedAIRunDefaultsApi | null =>myConfig?.resolved_ai_run_defaults ?? null,],+ acpDefaults: [+ (s) => [s.resolvedDefaults],+ (defaults: TasksResolvedAIRunDefaultsApi | null): TasksResolvedAIRunDefaultsApi | null =>+ defaults?.runtime === TaskRuntimeEnumApi.Pi ? null : (defaults ?? null),+ ],// Whatever runtime the default names: the composer's pickers are runtime-aware (they scope the// permission modes to the selected model's harness), so a Codex default renders as readily as a// Claude one. Filtering by adapter here would drop the preference to the built-in model rather// than to the next level that configured one, which reads as the setting being ignored.defaultModel: [- (s) => [s.resolvedDefaults],+ (s) => [s.acpDefaults],(defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.model ?? null,],defaultEffort: [- (s) => [s.resolvedDefaults],+ (s) => [s.acpDefaults],(defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.reasoning_effort ?? null,],// The server already resolved which runtime the default belongs to; carrying it beats// re-deriving from the client catalogue, which can be stale and mislabel the harness.defaultRuntimeAdapter: [- (s) => [s.resolvedDefaults],+ (s) => [s.acpDefaults],(defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.runtime_adapter ?? null,],}),diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.pyindex e38c9361510e..749b8c7c81e5 100644--- a/products/slack_app/backend/services/run_preferences.py+++ b/products/slack_app/backend/services/run_preferences.py@@ -57,7 +57,9 @@ def _central_run_default(team_id: int, user_id: int | None) -> ResolvedAIRunConf)resolved = ai_run_defaults.resolve_ai_run_defaults(team_id, user_id)- return resolved if resolved.model else None+ if resolved.runtime != ai_run_defaults.ACP or not resolved.model:+ return None+ return resolveddef _coherent_preferences(diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex dc8033376418..c47466aceb45 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -2225,6 +2225,9 @@ def _resolve_run_defaults_state(logger.exception("slack_app_home_run_defaults_resolution_failed", slack_user_id=slack_user_id)return RunDefaultsState(settings_url=settings_url)+ if resolved.runtime != ai_run_defaults.ACP:+ return RunDefaultsState(settings_url=settings_url)+return RunDefaultsState(model=resolved.model,reasoning_effort=resolved.reasoning_effort,diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.pyindex 71a88cf64aa8..24c668b1d004 100644--- a/products/slack_app/backend/tests/services/test_run_preferences.py+++ b/products/slack_app/backend/tests/services/test_run_preferences.py@@ -219,3 +219,30 @@ class TestAvailableModelChoices:models = {c.model for c in choices}assert {"claude-sonnet-5", "gpt-5.6-sol", "zai-org/glm-5.3"} <= modelsassert all(c.label and c.runtime_adapter for c in choices)+++class TestCentralRunDefault:+ def _resolved(self, **kwargs):+ from products.tasks.backend.facade.ai_run_defaults import ResolvedAIRunConfig++ return ResolvedAIRunConfig(**kwargs)++ def test_an_acp_default_is_carried_through(self):+ resolved = self._resolved(runtime="acp", runtime_adapter="claude", model="claude-fable-5", source="team")+ with patch(+ "products.tasks.backend.facade.ai_run_defaults.resolve_ai_run_defaults",+ return_value=resolved,+ ):+ assert run_preferences._central_run_default(team_id=1, user_id=7) is resolved++ @pytest.mark.parametrize(+ "runtime, model",+ [("pi", "gpt-5.6-terra"), ("acp", None)],+ ids=["a_pi_default_slack_cannot_run", "a_default_with_no_model"],+ )+ def test_a_default_slack_cannot_use_falls_back_to_its_own_floor(self, runtime, model):+ with patch(+ "products.tasks.backend.facade.ai_run_defaults.resolve_ai_run_defaults",+ return_value=self._resolved(runtime=runtime, runtime_adapter=None, model=model, source="user"),+ ):+ assert run_preferences._central_run_default(team_id=1, user_id=7) is Nonediff --git a/products/slack_app/backend/tests/test_app_home_run_defaults_card.py b/products/slack_app/backend/tests/test_app_home_run_defaults_card.pyindex 0d98828362c6..346a1e161b6b 100644--- a/products/slack_app/backend/tests/test_app_home_run_defaults_card.py+++ b/products/slack_app/backend/tests/test_app_home_run_defaults_card.py@@ -1,4 +1,5 @@from posthog.test.base import APIBaseTest+from unittest.mock import patchfrom posthog.models import Teamfrom posthog.models.integration import Integration@@ -37,3 +38,13 @@ class TestRunDefaultsCardRouting(APIBaseTest):state = _resolve_run_defaults_state(self.int_b, "U1", accessible=[])assert state.model is Noneassert state.settings_url is None++ def test_card_ignores_a_pi_default(self):+ update_team_ai_run_preferences(+ self.team.id, runtime_adapter=None, model="gpt-5.6-terra", reasoning_effort=None, runtime="pi"+ )+ with patch("products.tasks.backend.logic.services.ai_run_defaults.pi_cloud_runtime_enabled", return_value=True):+ state = _resolve_run_defaults_state(self.int_b, "U1", accessible=[self.int_a])+ assert state.model is None+ assert state.applies is False+ assert state.settings_url is not Nonediff --git a/products/tasks/backend/facade/ai_run_defaults.py b/products/tasks/backend/facade/ai_run_defaults.pyindex 9a36f1f62d54..a0f8124c5ae2 100644--- a/products/tasks/backend/facade/ai_run_defaults.py+++ b/products/tasks/backend/facade/ai_run_defaults.py@@ -1,12 +1,14 @@"""Facade re-exports for AI run default preferences.-Team-level and per-(user, project) default `(runtime_adapter, model,-reasoning_effort)` triples, applied to task runs created without an explicit+Team-level and per-(user, project) default `(runtime, runtime_adapter, model,+reasoning_effort)` selections, applied to task runs created without an explicitruntime selection. Presentation and other products import from here ratherthan reaching the internal ``logic.services`` module."""from products.tasks.backend.logic.services.ai_run_defaults import (+ ACP,+ PI,ResolvedAIRunConfig,build_ai_run_preferences_payload,get_team_ai_run_preferences,@@ -18,6 +20,8 @@ from products.tasks.backend.logic.services.ai_run_defaults import ()__all__ = [+ "ACP",+ "PI","ResolvedAIRunConfig","build_ai_run_preferences_payload","get_team_ai_run_preferences",diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 056ea7bd7d35..ed3949c99bfc 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -68,7 +68,6 @@ from products.tasks.backend.constants import (DEV_STACK_PREVIEW_STATE_KEY,MAX_CUSTOM_IMAGES_PER_TEAM,MAX_CUSTOM_IMAGES_PER_USER,- PI_CLOUD_RUNTIME_FEATURE_FLAG,PR_LOOP_ENABLED_STATE_KEY,PR_STATES as PR_STATES, # re-exported for presentationRESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,@@ -82,7 +81,11 @@ from products.tasks.backend.constants import (is_same_run_resume_state,)from products.tasks.backend.error_telemetry import truncate_error_message-from products.tasks.backend.feature_flags import get_model_access_error, is_workflow_dispatch_shadow_enabled+from products.tasks.backend.feature_flags import (+ get_model_access_error,+ is_workflow_dispatch_shadow_enabled,+ pi_cloud_runtime_enabled,+)from products.tasks.backend.github_repository_access import (inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,)@@ -5610,25 +5613,6 @@ def get_conversation_task_dtos(return {task.id: _task_detail_to_dto(task, user_id=user_id, include_latest_run=False) for task in tasks}-def pi_cloud_runtime_enabled(team: Team, user: User) -> bool:- distinct_id = user.distinct_id or f"user_{user.id}"- organization_id = str(team.organization_id)- try:- return bool(- posthoganalytics.feature_enabled(- PI_CLOUD_RUNTIME_FEATURE_FLAG,- distinct_id,- groups={"organization": organization_id},- group_properties={"organization": {"id": organization_id}},- only_evaluate_locally=False,- send_feature_flag_events=False,- )- )- except Exception:- logger.exception("pi-harness flag check failed; treating as disabled")- return False--def task_analysis_enabled(team: Team, user: User) -> bool:"""Rollout gate for the PostHog-funded analysis endpoint, fail-closed like the Pi gates."""distinct_id = user.distinct_id or f"user_{user.id}"diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex c67b9b4e1342..db3ecc05d96d 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -1,4 +1,5 @@import logging+from typing import TYPE_CHECKINGfrom django.conf import settings@@ -11,12 +12,17 @@ from products.tasks.backend.constants import (AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG,DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,MCP_EXEC_SKILLS_FEATURE_FLAG,+ PI_CLOUD_RUNTIME_FEATURE_FLAG,WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG,get_required_model_flag,)+if TYPE_CHECKING:+ from posthog.models.team.team import Team+ from posthog.models.user import User+logger = logging.getLogger(__name__)NATIVE_STEERING_SIGNALS_FEATURE_FLAG = "tasks-native-steering-signals"@@ -150,6 +156,29 @@ def is_agent_otel_telemetry_enabled(*, distinct_id: str, organization_id: str) -return False+def pi_cloud_runtime_enabled(team: "Team", user: "User") -> bool:+ """Whether this user may run the Pi harness in the cloud; fail-closed when evaluation fails.++ Lives here rather than in the facade so the run-defaults service can gate a stored Pi+ preference without importing the facade, which imports this module's own callers.+ """+ organization_id = str(team.organization_id)+ try:+ return bool(+ posthoganalytics.feature_enabled(+ PI_CLOUD_RUNTIME_FEATURE_FLAG,+ user.distinct_id or f"user_{user.id}",+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("pi-harness flag check failed; treating as disabled")+ return False++def get_model_access_error(model: str | None, *, distinct_id: str | None) -> str | None:"""Reject a gated model the caller isn't entitled to; `None` when the selection is allowed.diff --git a/products/tasks/backend/logic/services/ai_run_defaults.py b/products/tasks/backend/logic/services/ai_run_defaults.pyindex 4f62bb3ce054..71105df312aa 100644--- a/products/tasks/backend/logic/services/ai_run_defaults.py+++ b/products/tasks/backend/logic/services/ai_run_defaults.py@@ -1,7 +1,7 @@"""Central AI run defaults for task runs.-Resolves the effective `(runtime_adapter, model, reasoning_effort)` triple for a-new task run from, in order: explicit per-run values, the acting user's+Resolves the effective `(runtime, runtime_adapter, model, reasoning_effort)` selection+for a new task run from, in order: explicit per-run values, the acting user'sper-project preference (`UserTasksConfig`), and the project default(`TeamTasksConfig`). Surfaces with their own preference layer (e.g. the Slackapp's per-workspace/per-user settings) resolve first and pass the result as@@ -25,6 +25,7 @@ stored default can never launch a model the run paths would refuse."""from dataclasses import dataclass+from functools import cachefrom typing import Any, Literalfrom django.core.exceptions import ValidationError@@ -35,30 +36,42 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.tasks.backend.feature_flags import get_model_access_error, get_required_model_flag+from products.tasks.backend.feature_flags import (+ get_model_access_error,+ get_required_model_flag,+ pi_cloud_runtime_enabled,+)from products.tasks.backend.logic.services.model_catalogue import filter_unsupported_effort-from products.tasks.backend.models import TeamTasksConfig, UserTasksConfig+from products.tasks.backend.models import Task, TeamTasksConfig, UserTasksConfigfrom products.tasks.backend.temporal.process_task.utils import (PUBLIC_REASONING_EFFORTS,+ ReasoningEffort,RuntimeAdapter,validate_model_selection,)+PI_REASONING_EFFORTS = frozenset(ReasoningEffort) - {ReasoningEffort.ULTRACODE}++ACP = Task.Runtime.ACP.value+PI = Task.Runtime.PI.value+@dataclass(frozen=True)class ResolvedAIRunConfig:- """The effective AI run triple plus which preference level supplied it."""+ """The effective AI run selection plus which preference level supplied it."""runtime_adapter: str | None = Nonemodel: str | None = Nonereasoning_effort: str | None = Nonesource: Literal["explicit", "user", "team", "none"] = "none"+ runtime: str = ACPdef resolve_ai_run_selection(team_id: int,user_id: int | None,*,+ runtime: str = ACP,runtime_adapter: str | None = None,model: str | None = None,reasoning_effort: str | None = None,@@ -69,10 +82,11 @@ def resolve_ai_run_selection(A partial pin (either `runtime_adapter` or `model` alone) is treated as explicit andreturned untouched — filling in the other half from a preference would pair valuesthe caller never chose together. When defaults apply, an explicitly passed- `reasoning_effort` survives and the default triple's effort only fills a gap.+ `reasoning_effort` survives and the default's effort only fills a gap."""if runtime_adapter or model:return ResolvedAIRunConfig(+ runtime=runtime,runtime_adapter=runtime_adapter,model=model,reasoning_effort=reasoning_effort,@@ -80,9 +94,11 @@ def resolve_ai_run_selection()resolved = resolve_ai_run_defaults(team_id, user_id)- if not (resolved.runtime_adapter and resolved.model):- return ResolvedAIRunConfig(reasoning_effort=reasoning_effort, source="none")+ usable = bool(resolved.runtime == runtime and resolved.model and (runtime == PI or resolved.runtime_adapter))+ if not usable:+ return ResolvedAIRunConfig(runtime=runtime, reasoning_effort=reasoning_effort, source="none")return ResolvedAIRunConfig(+ runtime=runtime,runtime_adapter=resolved.runtime_adapter,model=resolved.model,reasoning_effort=reasoning_effort or resolved.reasoning_effort,@@ -139,21 +155,23 @@ def resolve_ai_run_defaults("""canonical_team_id = _canonical_team_id(team_id)- # Entitlement gating is lazy: the distinct_id lookup only happens when a level- # actually resolves to a flag-gated model, which keeps the per-run-creation- # hot path free of an extra query in the common case.- acting_distinct_id: str | None = None- acting_distinct_id_loaded = False-- def _model_accessible(model: str | None) -> bool:- if get_required_model_flag(model) is None:+ # Entitlement gating is lazy: the acting user is only read when a level actually+ # resolves to a gated model, which keeps the per-run-creation hot path free of an+ # extra query in the common case.+ @cache+ def _acting_user() -> User | None:+ return User.objects.filter(id=user_id).first() if user_id is not None else None++ def _level_usable(resolved: ResolvedAIRunConfig) -> bool:+ """Whether the acting user may launch what this level stores."""+ user = _acting_user()+ if resolved.runtime == PI:+ team = Team.objects.filter(id=canonical_team_id).first()+ if not (user and team and pi_cloud_runtime_enabled(team, user)):+ return False+ if get_required_model_flag(resolved.model) is None:return True- nonlocal acting_distinct_id, acting_distinct_id_loaded- if not acting_distinct_id_loaded:- acting_distinct_id_loaded = True- if user_id is not None:- acting_distinct_id = User.objects.filter(id=user_id).values_list("distinct_id", flat=True).first()- return get_model_access_error(model, distinct_id=acting_distinct_id) is None+ return get_model_access_error(resolved.model, distinct_id=user.distinct_id if user else None) is Noneif user_preferences is None and user_id is not None:user_preferences = (@@ -166,14 +184,14 @@ def resolve_ai_run_defaults(# A default naming a model the acting user isn't entitled to falls through to# the next level, the same way an unusable pair does — a stored default must# never launch a model the cold run path would have refused.- if resolved is not None and _model_accessible(resolved.model):+ if resolved is not None and _level_usable(resolved):return resolvedteam_prefs = (TeamTasksConfig.objects.filter(team_id=canonical_team_id).values_list("ai_run_preferences", flat=True).first())resolved = _resolve_from_preferences(team_prefs, source="team")- if resolved is not None and _model_accessible(resolved.model):+ if resolved is not None and _level_usable(resolved):return resolvedreturn ResolvedAIRunConfig(source="none")@@ -183,13 +201,25 @@ def _resolve_from_preferences(preferences: dict[str, Any] | None, *, source: Literal["user", "team"]) -> ResolvedAIRunConfig | None:"""A `ResolvedAIRunConfig` from a stored preference payload, or `None` when the- payload carries no usable `(runtime_adapter, model)` pair (fall through to the- next level)."""+ payload carries nothing usable (fall through to the next level)."""prefs = preferences or {}+ runtime = prefs.get("runtime") or ACPruntime_adapter = prefs.get("runtime_adapter") or Nonemodel = prefs.get("model") or Nonereasoning_effort = prefs.get("reasoning_effort") or None+ if runtime == PI:+ if not model:+ return None+ if reasoning_effort not in PI_REASONING_EFFORTS:+ reasoning_effort = None+ return ResolvedAIRunConfig(+ runtime=PI,+ model=model,+ reasoning_effort=reasoning_effort,+ source=source,+ )+if not (runtime_adapter and model):return None# A stored adapter the registry no longer knows can't pick a harness; skip the level.@@ -199,6 +229,7 @@ def _resolve_from_preferences(reasoning_effort = filter_unsupported_effort(runtime_adapter, model, reasoning_effort)return ResolvedAIRunConfig(+ runtime=ACP,runtime_adapter=runtime_adapter,model=model,reasoning_effort=reasoning_effort,@@ -210,18 +241,30 @@ def validate_ai_run_preferences(runtime_adapter: str | None,model: str | None,reasoning_effort: str | None,+ runtime: str | None = None,) -> None:- """Validate the `(runtime_adapter, model, reasoning_effort)` triple on the write- path so half-set rows never reach the DB.+ """Validate a stored selection on the write path so half-set rows never reach the DB.- The storage rule — both halves of the pair or neither — lives here; whether the- three values may be used together is the model catalogue's call, so that part- defers to `validate_model_selection`. Deliberately not strict on model-id- membership: the gateway's model list drifts, and resolution handles stale ids- leniently.+ Each harness states what a complete selection is. ACP keeps the pair rule — both+ halves or neither — and defers "may these be used together" to the model catalogue.+ Pi carries a model and no adapter, and its depths are its own vocabulary, so it takes+ neither the catalogue's word nor the ACP effort list. Deliberately not strict on+ model-id membership: the gateway's model list drifts, and resolution handles stale+ ids leniently.Raises `django.core.exceptions.ValidationError` on inconsistency."""+ if runtime == PI:+ if model is None:+ raise ValidationError("model must be set to configure a Pi default.")+ if runtime_adapter is not None:+ raise ValidationError("runtime_adapter cannot be set with runtime 'pi' — Pi has no ACP adapter.")+ if reasoning_effort is not None and reasoning_effort not in PI_REASONING_EFFORTS:+ raise ValidationError(+ f"Unknown reasoning_effort '{reasoning_effort}'. Valid: {', '.join(sorted(PI_REASONING_EFFORTS))}."+ )+ return+if (runtime_adapter is None) != (model is None):raise ValidationError("runtime_adapter and model must be set together — set both to configure a default, or both to null to clear it."@@ -245,29 +288,37 @@ def validate_ai_run_preferences_payload(prefs: dict) -> None:`build_ai_run_preferences_payload`, so unknown keys cannot occur on that path.Raises `django.core.exceptions.ValidationError` on unknown keys, non-string- values, or an inconsistent triple.+ values, or an inconsistent selection."""- allowed_keys = ("runtime_adapter", "model", "reasoning_effort")+ allowed_keys = ("runtime", "runtime_adapter", "model", "reasoning_effort")unknown = sorted(set(prefs) - set(allowed_keys))if unknown:raise ValidationError(f"Unknown keys: {', '.join(unknown)}. Allowed: {', '.join(allowed_keys)}.")non_strings = sorted(key for key, value in prefs.items() if not isinstance(value, str))if non_strings:raise ValidationError(f"Values must be strings: {', '.join(non_strings)}.")- validate_ai_run_preferences(prefs.get("runtime_adapter"), prefs.get("model"), prefs.get("reasoning_effort"))+ runtime = prefs.get("runtime")+ if runtime is not None and runtime not in (ACP, PI):+ raise ValidationError(f"Unknown runtime '{runtime}'. Valid: {ACP}, {PI}.")+ validate_ai_run_preferences(+ prefs.get("runtime_adapter"), prefs.get("model"), prefs.get("reasoning_effort"), runtime+ )def build_ai_run_preferences_payload(runtime_adapter: str | None,model: str | None,reasoning_effort: str | None,+ runtime: str | None = None,) -> dict[str, str]:- """Pack the triple into the JSON shape stored on `ai_run_preferences`.+ """Pack the selection into the JSON shape stored on `ai_run_preferences`.Drops keys whose value is falsy so a cleared preference is stored as an- empty object rather than a triple of nulls.+ empty object rather than a row of nulls. `runtime` rides along only with a model,+ so clearing a preference leaves no harness behind for the next read to find."""payload = {+ "runtime": runtime if model else None,"runtime_adapter": runtime_adapter,"model": model,"reasoning_effort": reasoning_effort,@@ -291,13 +342,14 @@ def update_team_ai_run_preferences(runtime_adapter: str | None,model: str | None,reasoning_effort: str | None,+ runtime: str | None = None,) -> dict[str, str]:- """Validate and store the team-level preference triple; returns the stored payload.+ """Validate and store the team-level preference; returns the stored payload.- Raises `django.core.exceptions.ValidationError` on an inconsistent triple.+ Raises `django.core.exceptions.ValidationError` on an inconsistent selection."""- validate_ai_run_preferences(runtime_adapter, model, reasoning_effort)- payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort, runtime)+ payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort, runtime)team = Team.objects.get(id=_canonical_team_id(team_id))config = get_or_create_team_extension(team, TeamTasksConfig)config.ai_run_preferences = payload@@ -324,12 +376,13 @@ def update_user_ai_run_preferences(runtime_adapter: str | None,model: str | None,reasoning_effort: str | None,+ runtime: str | None = None,) -> dict[str, str]:- """Validate and upsert the per-(user, project) preference triple; returns the stored- payload. Raises `django.core.exceptions.ValidationError` on an inconsistent triple.+ """Validate and upsert the per-(user, project) preference; returns the stored payload.+ Raises `django.core.exceptions.ValidationError` on an inconsistent selection."""- validate_ai_run_preferences(runtime_adapter, model, reasoning_effort)- payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort, runtime)+ payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort, runtime)canonical_team_id = _canonical_team_id(team_id)# team_id repeated in the lookup kwargs: for_team() only filters reads — creation# needs the value passed explicitly.diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 5fe4c8c48001..2f003c2505a8 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -56,6 +56,7 @@ from products.tasks.backend.facade.run_config import (WARMABLE_ORIGIN_PRODUCTS,LLMProvider,PrAuthorshipMode,+ ReasoningEffort,RunSource,RuntimeAdapter,TaskArtifactAdapter,@@ -68,12 +69,7 @@ from products.tasks.backend.facade.run_config import (logger = logging.getLogger(__name__)-PI_THINKING_LEVEL_CHOICES = ("off", "minimal", "low", "medium", "high", "xhigh", "max")-TASK_RUN_REASONING_EFFORT_CHOICES = [- "off",- "minimal",- *(effort.value for effort in PUBLIC_REASONING_EFFORTS),-]+TASK_RUN_REASONING_EFFORT_CHOICES = [effort.value for effort in ReasoningEffort]def _is_pi_task_run_request(context: dict[str, Any]) -> bool:@@ -3559,9 +3555,8 @@ class TaskRunBootstrapCreateRequestSerializer(if attrs.get(field) is not None:errors[field] = "This field cannot be used with a Pi task."- reasoning_effort = attrs.get("reasoning_effort")- if reasoning_effort is not None and reasoning_effort not in PI_THINKING_LEVEL_CHOICES:- errors["reasoning_effort"] = "This thinking level is not supported by Pi."+ if attrs.get("reasoning_effort") == ReasoningEffort.ULTRACODE:+ errors["reasoning_effort"] = "This reasoning effort cannot be used with a Pi task."if errors:raise serializers.ValidationError(errors)@@ -4637,16 +4632,27 @@ class AgentProxyCallbackResponseSerializer(serializers.Serializer):class TasksAIRunPreferencesSerializer(serializers.Serializer):- """The default AI run triple stored at team or user level.+ """The default AI run selection stored at team or user level.Write payload for the tasks config endpoints and the `ai_run_preferences` block of- their responses. `runtime_adapter` and `model` must be set together; send all three- as null to clear a stored preference.+ their responses. What a complete selection is depends on the harness: an ACP default+ sets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send+ every field as null to clear a stored preference."""RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]- REASONING_EFFORT_CHOICES = [effort.value for effort in PUBLIC_REASONING_EFFORTS]+ REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICES+ runtime = serializers.ChoiceField(+ choices=tasks_facade.TaskRuntime.choices,+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the "+ "Pi harness. Defaults to 'acp' when omitted."+ ),+ )runtime_adapter = serializers.ChoiceField(choices=RUNTIME_ADAPTER_CHOICES,required=False,@@ -4654,7 +4660,8 @@ class TasksAIRunPreferencesSerializer(serializers.Serializer):default=None,help_text=("Default agent runtime adapter for new task runs. Use 'claude' for the Claude "- "runtime or 'codex' for the Codex runtime. Must be set together with `model`."+ "runtime or 'codex' for the Codex runtime. Must be set together with `model`, and "+ "must be null when `runtime` is 'pi'."),)model = serializers.CharField(@@ -4662,26 +4669,36 @@ class TasksAIRunPreferencesSerializer(serializers.Serializer):allow_null=True,allow_blank=False,default=None,- help_text="Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.",+ help_text=(+ "Default LLM model identifier for new task runs. Must be set together with "+ "`runtime_adapter` on the ACP harness, and is required on its own for a Pi default."+ ),)reasoning_effort = serializers.ChoiceField(choices=REASONING_EFFORT_CHOICES,required=False,allow_null=True,default=None,- help_text="Default reasoning effort for models that expose an effort control.",+ help_text=(+ "Default reasoning effort for models that expose an effort control. A Pi default "+ "stores a Pi thinking level here, which also allows 'off' and 'minimal'."+ ),)class TasksResolvedAIRunDefaultsSerializer(serializers.Serializer):- """The AI run triple a new run will effectively use when the caller pins nothing,+ """The AI run selection a new run will effectively use when the caller pins nothing,plus which preference level supplied it."""# Not bound to `ResolvedAIRunConfig` via DataclassSerializer: that dataclass also carries the# internal `explicit` resolution state this endpoint never returns, and its per-field defaults# would mark every field optional when the response always sends all four.+ runtime = serializers.CharField(+ help_text="Harness the effective default runs on: 'acp' or 'pi'. 'acp' when no preference is stored."+ )runtime_adapter = serializers.CharField(- allow_null=True, help_text="Effective default runtime adapter, or null when no preference is stored."+ allow_null=True,+ help_text="Effective default runtime adapter, or null when no preference is stored or the harness is Pi.",)model = serializers.CharField(allow_null=True, help_text="Effective default model identifier, or null when no preference is stored."diff --git a/products/tasks/backend/presentation/views/config_api.py b/products/tasks/backend/presentation/views/config_api.pyindex ea5eb99feb5c..86f122a44e8f 100644--- a/products/tasks/backend/presentation/views/config_api.py+++ b/products/tasks/backend/presentation/views/config_api.py@@ -32,18 +32,18 @@ def _user_id(request: Request) -> int:return cast(User, request.user).id-def _validated_triple(request: Request) -> dict:+def _validated_preferences(request: Request) -> dict:serializer = TasksAIRunPreferencesSerializer(data=request.data)serializer.is_valid(raise_exception=True)- triple = serializer.validated_data+ preferences = serializer.validated_data# Storing a flag-gated model the writer isn't entitled to would only ever# produce runs the resolver skips or the run paths refuse — reject it here# so the settings page says so immediately. Resolution re-checks per acting# user, which also covers entitlements that change after the write.- error = get_model_access_error(triple.get("model"), distinct_id=cast(User, request.user).distinct_id)+ error = get_model_access_error(preferences.get("model"), distinct_id=cast(User, request.user).distinct_id)if error is not None:raise ValidationError({"model": error})- return triple+ return preferencesclass TasksTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@@ -77,9 +77,9 @@ class TasksTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):),)def create(self, request: Request, *args, **kwargs) -> Response:- triple = _validated_triple(request)+ preferences = _validated_preferences(request)try:- payload = ai_run_defaults.update_team_ai_run_preferences(self.team_id, **triple)+ payload = ai_run_defaults.update_team_ai_run_preferences(self.team_id, **preferences)except DjangoValidationError as e:raise ValidationError(e.messages)return Response(TasksTeamConfigResponseSerializer({"ai_run_preferences": payload}).data)@@ -130,9 +130,9 @@ class TasksUserConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):),)def create(self, request: Request, *args, **kwargs) -> Response:- triple = _validated_triple(request)+ preferences = _validated_preferences(request)try:- payload = ai_run_defaults.update_user_ai_run_preferences(self.team_id, _user_id(request), **triple)+ payload = ai_run_defaults.update_user_ai_run_preferences(self.team_id, _user_id(request), **preferences)except DjangoValidationError as e:raise ValidationError(e.messages)return self._response(request, payload)diff --git a/products/tasks/backend/tests/test_admin.py b/products/tasks/backend/tests/test_admin.pyindex fbbb8990dda1..3d29cebf62cf 100644--- a/products/tasks/backend/tests/test_admin.py+++ b/products/tasks/backend/tests/test_admin.py@@ -203,6 +203,8 @@ class TestTasksConfigAdminForms(BaseTest):("model_without_adapter", {"model": "claude-opus-4-8"}),("unknown_key", {"runtime_adapter": "claude", "model": "claude-opus-4-8", "profile": "max"}),("non_string_value", {"runtime_adapter": "claude", "model": 7}),+ ("pi_with_an_adapter", {"runtime": "pi", "runtime_adapter": "claude", "model": "gpt-5.6-terra"}),+ ("unknown_runtime", {"runtime": "acp2", "runtime_adapter": "claude", "model": "claude-opus-4-8"}),])def test_rejects_invalid_preference_payloads(self, _name: str, payload: dict) -> None:@@ -223,6 +225,16 @@ class TestTasksConfigAdminForms(BaseTest):user_form = self.user_form_class(data={"team": self.team.pk, "user": self.user.pk, "ai_run_preferences": {}})assert user_form.is_valid(), user_form.errors+ def test_accepts_a_pi_payload(self) -> None:+ form = self.user_form_class(+ data={+ "team": self.team.pk,+ "user": self.user.pk,+ "ai_run_preferences": {"runtime": "pi", "model": "gpt-5.6-terra", "reasoning_effort": "off"},+ }+ )+ assert form.is_valid(), form.errors+def test_rejects_a_row_keyed_on_an_environment_team(self) -> None:env_team = Team.objects.create(organization=self.organization, project=self.project, parent_team=self.team, name="env"diff --git a/products/tasks/backend/tests/test_ai_run_defaults.py b/products/tasks/backend/tests/test_ai_run_defaults.pyindex 3f06a97e0499..f349aa98ccc8 100644--- a/products/tasks/backend/tests/test_ai_run_defaults.py+++ b/products/tasks/backend/tests/test_ai_run_defaults.py@@ -1,8 +1,11 @@from typing import Any+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.core.exceptions import ValidationError+from parameterized import parameterizedfrom posthog.models import Integration, Organization, Team, User@@ -17,6 +20,7 @@ from products.tasks.backend.logic.services.ai_run_defaults import (resolve_ai_run_selection,update_team_ai_run_preferences,update_user_ai_run_preferences,+ validate_ai_run_preferences,)from products.tasks.backend.models import Task, TeamTasksConfig, UserTasksConfigfrom products.tasks.backend.presentation.serializers import TaskRunCreateRequestSerializer@@ -25,6 +29,26 @@ FACADE = "products.tasks.backend.facade.api"TEAM_TRIPLE = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}USER_TRIPLE = {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "medium"}+PI_PREFS_WITH_PI_ONLY_EFFORT = {+ "runtime": "pi",+ "runtime_adapter": None,+ "model": "gpt-5.6-terra",+ "reasoning_effort": "off",+}++RESOLVER = "products.tasks.backend.logic.services.ai_run_defaults"+++EMPTY_PREFERENCES: dict[str, Any] = {+ "runtime": None,+ "runtime_adapter": None,+ "model": None,+ "reasoning_effort": None,+}+++def pi_harness_enabled(enabled: bool = True):+ return patch(f"{RESOLVER}.pi_cloud_runtime_enabled", return_value=enabled)class TestResolveAIRunDefaults(APIBaseTest):@@ -51,6 +75,44 @@ class TestResolveAIRunDefaults(APIBaseTest):"high",)+ def test_row_stored_before_pi_reads_as_the_acp_harness(self):+ self._set_team(TEAM_TRIPLE)+ assert resolve_ai_run_defaults(self.team.id, self.user.id).runtime == "acp"++ def test_pi_preference_resolves_with_its_thinking_level_and_no_adapter(self):+ self._set_user(PI_PREFS_WITH_PI_ONLY_EFFORT)+ with pi_harness_enabled():+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert resolved.source == "user"+ assert (resolved.runtime, resolved.runtime_adapter, resolved.model, resolved.reasoning_effort) == (+ "pi",+ None,+ "gpt-5.6-terra",+ "off",+ )++ def test_a_stored_effort_pi_cannot_use_is_dropped(self):+ self._set_user({**PI_PREFS_WITH_PI_ONLY_EFFORT, "reasoning_effort": "ultracode"})+ with pi_harness_enabled():+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert (resolved.model, resolved.reasoning_effort) == ("gpt-5.6-terra", None)++ def test_a_pi_row_with_no_model_falls_through_to_the_team(self):+ self._set_team(TEAM_TRIPLE)+ self._set_user({"runtime": "pi", "runtime_adapter": None, "model": None, "reasoning_effort": "high"})+ with pi_harness_enabled():+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert (resolved.source, resolved.runtime, resolved.model) == ("team", "acp", "claude-opus-4-8")++ def test_a_pi_preference_leaves_an_acp_run_with_no_default(self):+ self._set_team(TEAM_TRIPLE)+ self._set_user(PI_PREFS_WITH_PI_ONLY_EFFORT)+ with pi_harness_enabled():+ for_acp = resolve_ai_run_selection(self.team.id, self.user.id)+ for_pi = resolve_ai_run_selection(self.team.id, self.user.id, runtime="pi")+ assert (for_acp.source, for_acp.model) == ("none", None)+ assert (for_pi.source, for_pi.model) == ("user", "gpt-5.6-terra")+def test_user_triple_replaces_team_triple_wholesale(self):self._set_team(TEAM_TRIPLE)self._set_user({"runtime_adapter": "codex", "model": "gpt-5.5"})@@ -141,6 +203,35 @@ class TestResolveAIRunDefaults(APIBaseTest):)+class TestValidateAIRunPreferences:+ """The write-path guard. The config endpoints reject most of this at the serializer, so+ these call it directly: the admin form and any future writer reach it with no serializer+ in front."""++ @parameterized.expand(+ [+ ("pi_with_an_adapter", "pi", "codex", "gpt-5.6-terra", None),+ ("pi_without_a_model", "pi", None, None, "high"),+ ("pi_with_a_value_that_is_not_a_depth", "pi", None, "gpt-5.6-terra", "deep"),+ ("acp_with_a_value_that_is_not_a_depth", None, "codex", "gpt-5.6-terra", "deep"),+ ("acp_with_a_model_and_no_adapter", None, None, "gpt-5.6-terra", None),+ ]+ )+ def test_rejects(self, _name, runtime, runtime_adapter, model, reasoning_effort):+ with pytest.raises(ValidationError):+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort, runtime=runtime)++ @parameterized.expand(+ [+ ("a_pi_pair", "pi", None, "gpt-5.6-terra", "off"),+ ("an_acp_triple", None, "codex", "gpt-5.6-terra", "high"),+ ("an_all_null_clear", None, None, None, None),+ ]+ )+ def test_accepts(self, _name, runtime, runtime_adapter, model, reasoning_effort):+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort, runtime=runtime)++class TestRunCreateSerializerModeWithoutAdapter(APIBaseTest):# A composer that pins nothing must still be able to state the launch mode — the# server resolves the runtime from the stored default and clamps the mode to it.@@ -182,12 +273,32 @@ class TestModelAccessGating(APIBaseTest):),)- RESOLVER = "products.tasks.backend.logic.services.ai_run_defaults"+ def test_pi_default_without_the_harness_flag_falls_through_to_team(self):+ self._set_user(PI_PREFS_WITH_PI_ONLY_EFFORT)+ self._set_team(USER_TRIPLE)+ with pi_harness_enabled(enabled=False):+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert resolved.source == "team"+ assert (resolved.runtime, resolved.model) == ("acp", "gpt-5.5")++ def test_pi_gate_identifies_a_user_without_a_distinct_id(self):+ User.objects.filter(id=self.user.id).update(distinct_id=None)+ self._set_user(PI_PREFS_WITH_PI_ONLY_EFFORT)+ with pi_harness_enabled():+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert resolved.source == "user"++ def test_pi_team_default_without_the_harness_flag_resolves_to_none(self):+ self._set_team(PI_PREFS_WITH_PI_ONLY_EFFORT)+ with pi_harness_enabled(enabled=False):+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)+ assert resolved.source == "none"+ assert resolved.model is Nonedef test_gated_user_default_falls_through_to_team(self):self._set_user(TEAM_TRIPLE) # names the gated modelself._set_team(USER_TRIPLE)- flag_patch, access_patch = self._gate(self.RESOLVER)+ flag_patch, access_patch = self._gate(RESOLVER)with flag_patch, access_patch as access_mock:resolved = resolve_ai_run_defaults(self.team.id, self.user.id)assert resolved.source == "team"@@ -196,7 +307,7 @@ class TestModelAccessGating(APIBaseTest):def test_gated_team_default_resolves_to_none(self):self._set_team(TEAM_TRIPLE)- flag_patch, access_patch = self._gate(self.RESOLVER)+ flag_patch, access_patch = self._gate(RESOLVER)with flag_patch, access_patch:resolved = resolve_ai_run_defaults(self.team.id, self.user.id)assert resolved.source == "none"@@ -251,6 +362,13 @@ class TestCreateRunAppliesDefaults(APIBaseTest):run = self._task(internal=True).create_run()assert "model" not in run.state+ def test_acp_task_never_inherits_a_pi_default(self):+ update_team_ai_run_preferences(self.team.id, **PI_PREFS_WITH_PI_ONLY_EFFORT)+ with pi_harness_enabled():+ run = self._task().create_run()+ assert "model" not in run.state+ assert "ai_defaults_source" not in run.state+def test_pi_runtime_task_never_inherits_defaults(self):update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)run = self._task(runtime=Task.Runtime.PI).create_run()@@ -327,16 +445,14 @@ class TestTasksConfigAPI(APIBaseTest):def test_team_config_round_trip(self):response = self.client.get(f"/api/projects/{self.team.id}/tasks/config/")assert response.status_code == 200- assert response.json() == {- "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}- }+ assert response.json() == {"ai_run_preferences": EMPTY_PREFERENCES}response = self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE)assert response.status_code == 200- assert response.json()["ai_run_preferences"] == TEAM_TRIPLE+ assert response.json()["ai_run_preferences"] == {**TEAM_TRIPLE, "runtime": None}response = self.client.get(f"/api/projects/{self.team.id}/tasks/config/")- assert response.json()["ai_run_preferences"] == TEAM_TRIPLE+ assert response.json()["ai_run_preferences"] == {**TEAM_TRIPLE, "runtime": None}@parameterized.expand([@@ -347,26 +463,39 @@ class TestTasksConfigAPI(APIBaseTest):"unsupported_effort",{"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "reasoning_effort": "max"},),+ ("pi_with_an_adapter", {"runtime": "pi", "runtime_adapter": "codex", "model": "gpt-5.6-terra"}),+ ("pi_without_a_model", {"runtime": "pi", "reasoning_effort": "high"}),+ ("pi_with_an_acp_only_depth", {"runtime": "pi", "model": "gpt-5.6-terra", "reasoning_effort": "ultracode"}),+ (+ "acp_with_a_pi_only_depth",+ {"runtime_adapter": "codex", "model": "gpt-5.6-terra", "reasoning_effort": "off"},+ ),])- def test_invalid_triples_are_rejected(self, _name: str, payload: dict[str, Any]):+ def test_invalid_preferences_are_rejected(self, _name: str, payload: dict[str, Any]):# Both endpoints share the validation path; asserting both keeps either from losing it.for path in ("config", "@me/config"):response = self.client.post(f"/api/projects/{self.team.id}/tasks/{path}/", payload)assert response.status_code == 400, (path, response.content)+ def test_pi_preference_round_trip(self):+ stored = {"runtime": "pi", "runtime_adapter": None, "model": "gpt-5.6-terra", "reasoning_effort": "off"}+ with pi_harness_enabled():+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", PI_PREFS_WITH_PI_ONLY_EFFORT)+ assert response.status_code == 200, response.content+ body = response.json()+ assert body["ai_run_preferences"] == stored+ assert body["resolved_ai_run_defaults"]["runtime"] == "pi"+ assert body["resolved_ai_run_defaults"]["runtime_adapter"] is None+ assert body["resolved_ai_run_defaults"]["source"] == "user"+def test_clearing_the_team_default(self):self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE)- response = self.client.post(- f"/api/projects/{self.team.id}/tasks/config/",- {"runtime_adapter": None, "model": None, "reasoning_effort": None},- )+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/config/", EMPTY_PREFERENCES)assert response.status_code == 200- assert response.json() == {- "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}- }+ assert response.json() == {"ai_run_preferences": EMPTY_PREFERENCES}assert self.client.get(f"/api/projects/{self.team.id}/tasks/config/").json() == {- "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}+ "ai_run_preferences": EMPTY_PREFERENCES}def test_unauthenticated_requests_are_rejected(self):@@ -391,24 +520,24 @@ class TestTasksConfigAPI(APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/tasks/@me/config/")assert response.status_code == 200body = response.json()- assert body["ai_run_preferences"] == {"runtime_adapter": None, "model": None, "reasoning_effort": None}+ assert body["ai_run_preferences"] == EMPTY_PREFERENCESassert body["resolved_ai_run_defaults"]["source"] == "team"assert body["resolved_ai_run_defaults"]["model"] == "claude-opus-4-8"response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", USER_TRIPLE)assert response.status_code == 200body = response.json()- assert body["ai_run_preferences"] == USER_TRIPLE+ assert body["ai_run_preferences"] == {**USER_TRIPLE, "runtime": None}assert body["resolved_ai_run_defaults"]["source"] == "user"assert body["resolved_ai_run_defaults"]["model"] == "gpt-5.5"response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/",- {"runtime_adapter": None, "model": None, "reasoning_effort": None},+ EMPTY_PREFERENCES,)assert response.status_code == 200body = response.json()- assert body["ai_run_preferences"] == {"runtime_adapter": None, "model": None, "reasoning_effort": None}+ assert body["ai_run_preferences"] == EMPTY_PREFERENCESassert body["resolved_ai_run_defaults"]["source"] == "team"# The project default decides what every unpinned run on the project launches with, so a member@@ -427,11 +556,7 @@ class TestTasksConfigAPI(APIBaseTest):team_id=self.team.id, user_id=other.id, defaults={"ai_run_preferences": USER_TRIPLE})response = self.client.get(f"/api/projects/{self.team.id}/tasks/@me/config/")- assert response.json()["ai_run_preferences"] == {- "runtime_adapter": None,- "model": None,- "reasoning_effort": None,- }+ assert response.json()["ai_run_preferences"] == EMPTY_PREFERENCESclass TestConfigEndpointScopes(APIBaseTest):diff --git a/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.pyindex cfdbd6d8fd99..e2fb05f2f3e6 100644--- a/products/tasks/backend/tests/test_feature_flags.py+++ b/products/tasks/backend/tests/test_feature_flags.py@@ -3,10 +3,14 @@ from unittest.mock import patchfrom django.test import override_settings+from posthog.models.team.team import Team+from posthog.models.user import User+from products.tasks.backend.feature_flags import (get_model_access_error,is_dev_stack_image_bake_enabled,is_mcp_exec_skills_enabled,+ pi_cloud_runtime_enabled,)@@ -145,3 +149,27 @@ class TestIsMcpExecSkillsEnabled:side_effect=RuntimeError("flags down"),):assert is_mcp_exec_skills_enabled("org-1", "user-1") is False+++class TestPiCloudRuntimeEnabled:+ team = Team(organization_id="org-1")++ @pytest.mark.parametrize("distinct_id, actor", [("user-1", "user-1"), ("", "user_7"), (None, "user_7")])+ def test_evaluates_for_the_user_and_organization_server_side(self, distinct_id, actor):+ with patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=True,+ ) as feature_enabled_mock:+ assert pi_cloud_runtime_enabled(self.team, User(id=7, distinct_id=distinct_id)) is True++ assert feature_enabled_mock.call_args.args == ("pi-harness", actor)+ kwargs = feature_enabled_mock.call_args.kwargs+ assert kwargs["groups"] == {"organization": "org-1"}+ assert kwargs["only_evaluate_locally"] is False++ def test_fails_closed_on_flag_service_error(self):+ with patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flags down"),+ ):+ assert pi_cloud_runtime_enabled(self.team, User(id=7, distinct_id="user-1")) is Falsediff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 0c77a8645732..9976e406515e 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4553,32 +4553,40 @@ export interface TaskThreadMessageWriteApi {}/**- * The default AI run triple stored at team or user level.+ * The default AI run selection stored at team or user level.** Write payload for the tasks config endpoints and the `ai_run_preferences` block of- * their responses. `runtime_adapter` and `model` must be set together; send all three- * as null to clear a stored preference.+ * their responses. What a complete selection is depends on the harness: an ACP default+ * sets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send+ * every field as null to clear a stored preference.*/export interface TasksAIRunPreferencesApi {- /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.+ /** Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.+ *+ * * `acp` - ACP+ * * `pi` - Pi */+ runtime?: TaskRuntimeEnumApi | null+ /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.** * `claude` - claude* * `codex` - codex */runtime_adapter?: RuntimeAdapterEnumApi | null/**- * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.+ * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.* @nullable*/model?: string | null- /** Default reasoning effort for models that expose an effort control.+ /** Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.*+ * * `off` - off+ * * `minimal` - minimal* * `low` - low* * `medium` - medium* * `high` - high* * `xhigh` - xhigh* * `max` - max* * `ultracode` - ultracode */- reasoning_effort?: ReasoningEffortEnumApi | null+ reasoning_effort?: TaskRunReasoningEffortEnumApi | null}/**@@ -4596,12 +4604,14 @@ export const TasksResolvedAIRunDefaultsSourceEnumApi = {} as const/**- * The AI run triple a new run will effectively use when the caller pins nothing,+ * The AI run selection a new run will effectively use when the caller pins nothing,* plus which preference level supplied it.*/export interface TasksResolvedAIRunDefaultsApi {+ /** Harness the effective default runs on: 'acp' or 'pi'. 'acp' when no preference is stored. */+ runtime: string/**- * Effective default runtime adapter, or null when no preference is stored.+ * Effective default runtime adapter, or null when no preference is stored or the harness is Pi.* @nullable*/runtime_adapter: string | nulldiff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex c44bc1694840..6d35824a6353 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -3449,32 +3449,40 @@ export const TasksThreadMessagesSendToAgentCreateBody = /* @__PURE__ */ zod*/export const TasksMeConfigCreateBody = /* @__PURE__ */ zod.object({+ runtime: zod+ .union([zod.enum(['acp', 'pi']).describe('\* `acp` - ACP\n\* `pi` - Pi'), zod.null()])+ .optional()+ .describe(+ "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),runtime_adapter: zod.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()]).optional().describe(- "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n\* `claude` - claude\n\* `codex` - codex"),model: zod.string().nullish()- .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),+ .describe(+ 'Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.'+ ),reasoning_effort: zod.union([zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']).describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ '\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'),zod.null(),]).optional().describe(- 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode"),}).describe(- 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'+ 'The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.')/**@@ -3482,32 +3490,40 @@ export const TasksMeConfigCreateBody = /* @__PURE__ */ zod*/export const TasksConfigCreateBody = /* @__PURE__ */ zod.object({+ runtime: zod+ .union([zod.enum(['acp', 'pi']).describe('\* `acp` - ACP\n\* `pi` - Pi'), zod.null()])+ .optional()+ .describe(+ "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),runtime_adapter: zod.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()]).optional().describe(- "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n\* `claude` - claude\n\* `codex` - codex"),model: zod.string().nullish()- .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),+ .describe(+ 'Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.'+ ),reasoning_effort: zod.union([zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']).describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ '\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'),zod.null(),]).optional().describe(- 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode"),}).describe(- 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'+ 'The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.')/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8164a6e1cf0c..5ebcab34d584 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93173,32 +93173,40 @@ export namespace Schemas {}/**- * The default AI run triple stored at team or user level.+ * The default AI run selection stored at team or user level.** Write payload for the tasks config endpoints and the `ai_run_preferences` block of- * their responses. `runtime_adapter` and `model` must be set together; send all three- * as null to clear a stored preference.+ * their responses. What a complete selection is depends on the harness: an ACP default+ * sets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send+ * every field as null to clear a stored preference.*/export interface TasksAIRunPreferences {- /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.+ /** Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.+ *+ * * `acp` - ACP+ * * `pi` - Pi */+ runtime?: TaskRuntimeEnum | null;+ /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.** * `claude` - claude* * `codex` - codex */runtime_adapter?: RuntimeAdapterEnum | null;/**- * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.+ * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.* @nullable*/model?: string | null;- /** Default reasoning effort for models that expose an effort control.+ /** Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.*+ * * `off` - off+ * * `minimal` - minimal* * `low` - low* * `medium` - medium* * `high` - high* * `xhigh` - xhigh* * `max` - max* * `ultracode` - ultracode */- reasoning_effort?: ReasoningEffortEnum | null;+ reasoning_effort?: TaskRunReasoningEffortEnum | null;}/**@@ -93216,12 +93224,14 @@ export namespace Schemas {} as const;/**- * The AI run triple a new run will effectively use when the caller pins nothing,+ * The AI run selection a new run will effectively use when the caller pins nothing,* plus which preference level supplied it.*/export interface TasksResolvedAIRunDefaults {+ /** Harness the effective default runs on: 'acp' or 'pi'. 'acp' when no preference is stored. */+ runtime: string;/**- * Effective default runtime adapter, or null when no preference is stored.+ * Effective default runtime adapter, or null when no preference is stored or the harness is Pi.* @nullable*/runtime_adapter: string | null;diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 8c2d9401181b..330418832a37 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -1775,32 +1775,40 @@ export const TasksMeConfigCreateParams = () => zod.object({export const TasksMeConfigCreateBody = () => zod.object({+ runtime: zod+ .union([zod.enum(['acp', 'pi']).describe('\* `acp` - ACP\n\* `pi` - Pi'), zod.null()])+ .optional()+ .describe(+ "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),runtime_adapter: zod.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()]).optional().describe(- "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n\* `claude` - claude\n\* `codex` - codex"),model: zod.string().nullish()- .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),+ .describe(+ 'Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.'+ ),reasoning_effort: zod.union([zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']).describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ '\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'),zod.null(),]).optional().describe(- 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode"),}).describe(- 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'+ 'The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.')/**@@ -1832,32 +1840,40 @@ export const TasksConfigCreateParams = () => zod.object({export const TasksConfigCreateBody = () => zod.object({+ runtime: zod+ .union([zod.enum(['acp', 'pi']).describe('\* `acp` - ACP\n\* `pi` - Pi'), zod.null()])+ .optional()+ .describe(+ "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n\* `acp` - ACP\n\* `pi` - Pi"+ ),runtime_adapter: zod.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()]).optional().describe(- "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n\* `claude` - claude\n\* `codex` - codex"),model: zod.string().nullish()- .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),+ .describe(+ 'Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default.'+ ),reasoning_effort: zod.union([zod- .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+ .enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']).describe(- '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ '\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'),zod.null(),]).optional().describe(- 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'+ "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n\* `off` - off\n\* `minimal` - minimal\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode"),}).describe(- 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'+ 'The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.')/**diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 9a19bd6c9479..8cd4a9cb6ef4 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -547,6 +547,9 @@ const tasksConfigCreate = (): ToolBase<handler: async (context: Context, params: z.infer<ReturnType<typeof TasksConfigCreateSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}+ if (params.runtime !== undefined) {+ body['runtime'] = params.runtime+ }if (params.runtime_adapter !== undefined) {body['runtime_adapter'] = params.runtime_adapter}@@ -787,6 +790,9 @@ const tasksMeConfigCreate = (): ToolBase<handler: async (context: Context, params: z.infer<ReturnType<typeof TasksMeConfigCreateSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}+ if (params.runtime !== undefined) {+ body['runtime'] = params.runtime+ }if (params.runtime_adapter !== undefined) {body['runtime_adapter'] = params.runtime_adapter}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-config-create.jsonindex 28a860a12b94..b727022fb032 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-config-create.json@@ -1,6 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",- "description": "The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.",+ "description": "The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.","properties": {"model": {"anyOf": [@@ -11,20 +11,33 @@"type": "null"}],- "description": "Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`."+ "description": "Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default."},"reasoning_effort": {"anyOf": [{- "description": "* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode",- "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"],+ "description": "* `off` - off\n* `minimal` - minimal\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode",+ "enum": ["off", "minimal", "low", "medium", "high", "xhigh", "max", "ultracode"],"type": "string"},{"type": "null"}],- "description": "Default reasoning effort for models that expose an effort control.\n\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode"+ "description": "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n* `off` - off\n* `minimal` - minimal\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode"+ },+ "runtime": {+ "anyOf": [+ {+ "description": "* `acp` - ACP\n* `pi` - Pi",+ "enum": ["acp", "pi"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n* `acp` - ACP\n* `pi` - Pi"},"runtime_adapter": {"anyOf": [@@ -37,7 +50,7 @@"type": "null"}],- "description": "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n* `claude` - claude\n* `codex` - codex"+ "description": "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n* `claude` - claude\n* `codex` - codex"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-me-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-me-config-create.jsonindex 28a860a12b94..b727022fb032 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-me-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-me-config-create.json@@ -1,6 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",- "description": "The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.",+ "description": "The default AI run selection stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. What a complete selection is depends on the harness: an ACP default\nsets `runtime_adapter` and `model` together, a Pi default sets `model` alone. Send\nevery field as null to clear a stored preference.","properties": {"model": {"anyOf": [@@ -11,20 +11,33 @@"type": "null"}],- "description": "Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`."+ "description": "Default LLM model identifier for new task runs. Must be set together with `runtime_adapter` on the ACP harness, and is required on its own for a Pi default."},"reasoning_effort": {"anyOf": [{- "description": "* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode",- "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"],+ "description": "* `off` - off\n* `minimal` - minimal\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode",+ "enum": ["off", "minimal", "low", "medium", "high", "xhigh", "max", "ultracode"],"type": "string"},{"type": "null"}],- "description": "Default reasoning effort for models that expose an effort control.\n\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode"+ "description": "Default reasoning effort for models that expose an effort control. A Pi default stores a Pi thinking level here, which also allows 'off' and 'minimal'.\n\n* `off` - off\n* `minimal` - minimal\n* `low` - low\n* `medium` - medium\n* `high` - high\n* `xhigh` - xhigh\n* `max` - max\n* `ultracode` - ultracode"+ },+ "runtime": {+ "anyOf": [+ {+ "description": "* `acp` - ACP\n* `pi` - Pi",+ "enum": ["acp", "pi"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Harness the default runs on: 'acp' for the Claude and Codex adapters, 'pi' for the Pi harness. Defaults to 'acp' when omitted.\n\n* `acp` - ACP\n* `pi` - Pi"},"runtime_adapter": {"anyOf": [@@ -37,7 +50,7 @@"type": "null"}],- "description": "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n* `claude` - claude\n* `codex` - codex"+ "description": "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`, and must be null when `runtime` is 'pi'.\n\n* `claude` - claude\n* `codex` - codex"}},"type": "object"