Skip to content

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

feat(tasks): let MCP start task runs (#95135)

Alessandro Pogliaghi830372ce0200
diff --git a/docs/internal/task-run-api.md b/docs/internal/task-run-api.md
new file mode 100644
index 000000000000..e3f40f0ff0d6
--- /dev/null
+++ b/docs/internal/task-run-api.md
@@ -0,0 +1,52 @@
+# Create tasks and start runs
+
+`POST /api/projects/{team_id}/tasks/` creates a task without starting a run by default.
+Set `start_run` to `true` to create the task and start its first background run in one request.
+This mode uses the `tasks-mcp-agent-run-start` feature flag and the internal-project restriction.
+Sandbox tokens cannot start another cloud run.
+This restriction also applies to warm creation, warm activation, warm resumes, and cloud resumes.
+Requests through a PostHog connection keep the sandbox origin and the same run restrictions.
+The origin marker does not grant sandbox access.
+PostHog Desktop access, runtime access, and usage limits still apply.
+Repository-backed report discussions also require Desktop access.
+
+The response has status `201` and contains the task and its `latest_run`.
+If task creation succeeds but run creation or dispatch fails, the response also contains `run_error`.
+Keep the task ID and inspect its runs before you retry.
+Do not repeat task creation to recover from a run failure.
+If a database read fails after dispatch, the response still includes the created run.
+
+`branch` selects the base branch for the first run.
+Optional run hints can be `null`.
+Pi runs reject ACP runtime, model, reasoning-effort, and permission-mode hints.
+The combined request rejects `pending_user_artifact_ids` before it creates a task.
+It also rejects inaccessible sandbox environments and custom images before task creation.
+Custom images must be ready.
+It also rejects signal-report tasks before creation so caller-selected origins cannot grant full MCP permissions.
+Create these tasks without `start_run`, then start them through the report workflow.
+To attach files, first create the task, then upload the files, then start its run.
+
+`POST /api/projects/{team_id}/tasks/{task_id}/run/` starts a run for an existing task.
+Its response includes `run_error` if workflow dispatch fails.
+A resumed run keeps its previous base branch and agent source.
+The server stores the base branch in `pr_base_branch`, including `null` for the repository default.
+Resumes use only this protected value, not the editable run branch or `state.branch`.
+Older runs without a stored base branch use the repository default.
+Cloud resumes of agent-sourced runs require the agent-run feature flag and the internal-project restriction.
+Warm resumes of agent-sourced runs return an empty response without creating a sandbox.
+Agent-sourced runs do not reuse warm sandboxes.
+A request cannot select a different base branch for the restored snapshot.
+The bootstrap endpoint, `POST .../tasks/{task_id}/runs/`, does not accept the agent source.
+Agent-sourced runs use the read-only MCP permission preset.
+Run state updates cannot change or remove the run source or base branch.
+The `state` field must be a JSON object.
+
+## MCP tools
+
+- `tasks-create` creates an idle task. It does not accept run-start inputs.
+- `tasks-create-and-run` creates a task and starts its first run.
+- `tasks-run-create` starts a run for an existing task.
+
+The two run-start tools require the agent-run feature flag.
+They are not available to sandbox tokens.
+These operations are not idempotent. If a response is lost, inspect the task and its runs before you retry.
diff --git a/posthog/api/posthog_connection.py b/posthog/api/posthog_connection.py
index 445e5a76b9f4..57b757671a1e 100644
--- a/posthog/api/posthog_connection.py
+++ b/posthog/api/posthog_connection.py
@@ -39,6 +39,7 @@ from posthog.auth import (
is_mcp_request,
)
from posthog.models.integration import POSTHOG_CONNECT_KIND, Integration, OauthIntegration, posthog_connect_base_url
+from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER, is_sandbox_origin_request
from posthog.permissions import get_authenticator_scopes
from posthog.rate_limit import PostHogConnectionForwardThrottle
@@ -159,6 +160,7 @@ def _forward_through_connection(
query: dict[str, Any] | None = None,
data: Any = None,
mcp_origin: bool = False,
+ sandbox_origin: bool = False,
) -> ForwardResult:
"""Replay one request against the connected project, injecting the connection's token.
@@ -169,6 +171,8 @@ def _forward_through_connection(
token = _connection_access_token(integration)
base = posthog_connect_base_url(integration.config.get("region"))
headers = {"Authorization": f"Bearer {token}", CONNECTION_MARKER_HEADER: "1"}
+ if sandbox_origin:
+ headers[SANDBOX_ORIGIN_HEADER] = "1"
if mcp_origin:
headers["User-Agent"] = f"posthog-connection; {MCP_USER_AGENT_MARKER}"
@@ -333,6 +337,7 @@ class PostHogConnectionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
query=payload.get("query"),
data=payload.get("data"),
mcp_origin=is_mcp_request(request),
+ sandbox_origin=is_sandbox_origin_request(request),
)
body = {"status": result.status, "data": result.data}
# A failure on this side is mirrored as the outer status too, so a caller that only reads the
diff --git a/posthog/api/test/test_posthog_connection.py b/posthog/api/test/test_posthog_connection.py
index c0b3cd4ca41d..86b9edbac5ff 100644
--- a/posthog/api/test/test_posthog_connection.py
+++ b/posthog/api/test/test_posthog_connection.py
@@ -1,17 +1,22 @@
import json
import time
+from datetime import timedelta
import pytest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test.client import Client as HttpClient
+from django.utils import timezone
from rest_framework import status
from posthog.api.posthog_connection import CONNECTION_MAX_INFLIGHT_PER_CONNECTION
from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.integration import Integration
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
FORWARD_PATH = "posthog.api.posthog_connection.requests.request"
@@ -103,6 +108,43 @@ class TestPostHogConnectionForward:
)
assert "User-Agent" not in mock_request.call_args[1]["headers"]
+ @pytest.mark.parametrize("sandbox", [False, True])
+ def test_forward_preserves_sandbox_origin(self, client: HttpClient, sandbox: bool):
+ application = OAuthApplication.objects.create(
+ name="Connection client",
+ 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",
+ user=self.user,
+ organization=self.organization,
+ )
+ token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_connection_caller_token",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="integration:write task:write" + (" internal_run:read" if sandbox else ""),
+ scoped_teams=[self.team.id],
+ )
+ self.integration.config["granted_scopes"] = ["task:write"]
+ self.integration.save(update_fields=["config"])
+
+ with patch(FORWARD_PATH) as mock_request:
+ mock_request.return_value = _mock_response(200, {})
+ response = client.post(
+ self._forward_url(),
+ {"method": "POST", "path": "api/projects/2/tasks/", "data": {"start_run": True}},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token.token}",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ headers = mock_request.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer AT"
+ assert headers.get(SANDBOX_ORIGIN_HEADER) == ("1" if sandbox else None)
+
def test_forward_sends_body_only_for_write_methods(self, client: HttpClient):
client.force_login(self.user)
with patch(FORWARD_PATH) as mock_request:
diff --git a/posthog/oauth_provenance.py b/posthog/oauth_provenance.py
index 54420ec11554..a0bfca678fa5 100644
--- a/posthog/oauth_provenance.py
+++ b/posthog/oauth_provenance.py
@@ -11,11 +11,29 @@ pulls in enough of the model layer that importing it here would cycle back throu
"""
from posthog.models.oauth import OAuthRefreshToken
-from posthog.temporal.oauth import POSTHOG_DESKTOP_OAUTH_CLIENT_IDS
+from posthog.temporal.oauth import POSTHOG_DESKTOP_OAUTH_CLIENT_IDS, SANDBOX_OAUTH_APP_CLIENT_IDS
# Minted server-side only, so its presence proves the token was not obtained by a person
# through the consent flow. See INTERNAL_SCOPES in posthog/temporal/oauth.py.
INTERNAL_RUN_SCOPE = "internal_run:read"
+SANDBOX_ORIGIN_HEADER = "X-PostHog-Sandbox-Origin"
+
+
+def is_sandbox_oauth_request(request) -> bool:
+ token = get_oauth_access_token(request)
+ application = getattr(token, "application", None)
+ return (
+ application is not None
+ and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS
+ and (
+ getattr(token, "sandbox_task_id", None) is not None
+ or INTERNAL_RUN_SCOPE in (getattr(token, "scope", "") or "").split()
+ )
+ )
+
+
+def is_sandbox_origin_request(request) -> bool:
+ return request.headers.get(SANDBOX_ORIGIN_HEADER) == "1" or is_sandbox_oauth_request(request)
def get_oauth_access_token(request) -> object | None:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 7219e3872bc6..4d6a359520f2 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -603,6 +603,8 @@ SPECTACULAR_SETTINGS = {
"ResolvedAccessSourceEnum": "products.access_control.backend.facade.enums.RESOLVED_ACCESS_SOURCE_CHOICES",
"ResolvedAccessSourceSubjectEnum": "products.access_control.backend.facade.enums.RESOLVED_ACCESS_SOURCE_SUBJECT_CHOICES",
"TaskArtifactStatusEnum": ["active", "failed"],
+ "RunSourceEnum": ["manual", "signal_report", "agent"],
+ "TaskBootstrapRunSourceEnum": ["manual", "signal_report"],
#
# The same choice set is declared in more than one product. A shared Choices
# class would cross a product boundary, so the entry names the set centrally.
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 9ea96c717f8a..38dcd0bf0657 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -698,7 +698,6 @@ rest_framework.Request products.data_catalog.backend.facade.api.upsert_metric fa
rest_framework.Request products.endpoints.backend.facade.api.generate_openapi_spec facade-accepts(request) 1
rest_framework.Request products.tasks.backend.facade.access.code_access_required_response facade-accepts(request) 1
rest_framework.Request products.tasks.backend.facade.client_provenance.get_task_client_provenance facade-accepts(request) 1
-rest_framework.Request products.tasks.backend.facade.client_provenance.is_sandbox_oauth_request facade-accepts(request) 1
rest_framework.Response products.tasks.backend.facade.access.code_access_required_response facade-returns 1
rest_framework.Response products.tasks.backend.facade.access.compute_quota_limit_response facade-returns 1
rest_framework.Response products.tasks.backend.facade.access.usage_limit_response facade-returns 1
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 63035c876495..f61cd3de9eb7 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -241,6 +241,8 @@ __all__ = [
"get_task_run_session",
"sync_task_run_session",
"get_task_run_detail",
+ "get_task_run_source",
+ "get_task_run_claude_model_access",
"get_task_run_sandbox_connection",
"resolve_task_run_preview_redirect",
"task_run_preview_ready",
@@ -503,7 +505,9 @@ def _task_run_log_url(run: TaskRun) -> str | None:
return presigned_url
-def _task_run_detail_to_dto(run: TaskRun, *, include_agent_state: bool = False) -> contracts.TaskRunDetailDTO:
+def _task_run_detail_to_dto(
+ run: TaskRun, *, include_agent_state: bool = False, include_log_url: bool = True
+) -> contracts.TaskRunDetailDTO:
"""Map a ``TaskRun`` to its HTTP detail DTO.
Reproduces the SMF-derived fields ``TaskRunDetailSerializer`` computed: ``log_url`` does
@@ -526,7 +530,7 @@ def _task_run_detail_to_dto(run: TaskRun, *, include_agent_state: bool = False)
provider=state.provider.value if state.provider is not None else None,
model=state.model,
reasoning_effort=state.reasoning_effort.value if state.reasoning_effort is not None else None,
- log_url=_task_run_log_url(run),
+ log_url=_task_run_log_url(run) if include_log_url else None,
error_message=run.error_message,
output=run.output,
state=_public_task_run_state(run.state, include_agent_keys=include_agent_state),
@@ -637,6 +641,7 @@ def _task_detail_to_dto(
*,
include_latest_run: bool = True,
latest_run: TaskRun | None | _LatestRunUnset = _LATEST_RUN_UNSET,
+ include_latest_run_log_url: bool = True,
) -> contracts.TaskDetailDTO:
"""Map a ``Task`` to its HTTP detail DTO."""
if not include_latest_run:
@@ -667,7 +672,11 @@ def _task_detail_to_dto(
archived=task.archived,
archived_at=task.archived_at,
ci_prompt=task.ci_prompt,
- latest_run=_task_run_detail_to_dto(resolved_latest_run) if resolved_latest_run is not None else None,
+ latest_run=(
+ _task_run_detail_to_dto(resolved_latest_run, include_log_url=include_latest_run_log_url)
+ if resolved_latest_run is not None
+ else None
+ ),
created_at=task.created_at,
updated_at=task.updated_at,
last_activity_at=task.last_activity_at or task.updated_at,
@@ -2237,6 +2246,8 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int
# These keys are reserved for server-owned run state, never PATCH input.
_PROTECTED_RUN_STATE_KEYS = frozenset(
{
+ "run_source",
+ "pr_base_branch",
"github_credential_source",
TASK_OWNERSHIP_VERSION_STATE_KEY,
"pr_authorship_mode",
@@ -2486,6 +2497,22 @@ def list_task_runs(task_id: str | UUID, team_id: int) -> list[contracts.TaskRunD
return [_task_run_detail_to_dto(run) for run in runs]
+def get_task_run_source(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
+ return (
+ TaskRun.objects.filter(pk=run_id, team_id=team_id, task_id=task_id)
+ .values_list("state__run_source", flat=True)
+ .first()
+ )
+
+
+def get_task_run_claude_model_access(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
+ return (
+ TaskRun.objects.filter(pk=run_id, team_id=team_id, task_id=task_id)
+ .values_list("state__claude_model_access", flat=True)
+ .first()
+ )
+
+
def get_task_run_detail(
run_id: str | UUID, task_id: str | UUID, team_id: int, *, include_agent_state: bool = False
) -> contracts.TaskRunDetailDTO | None:
@@ -2770,6 +2797,8 @@ def update_task_run(
return None
validated_data = dict(validated_data)
+ if "state" in validated_data and not isinstance(validated_data["state"], dict):
+ raise ValueError("Run state must be an object.")
if (
"status" in validated_data
and not caller_is_agent
@@ -4784,6 +4813,23 @@ def _github_credential_source_extra_state(pr_authorship_mode, github_user_token:
return {"github_credential_source": source.value}
+def _task_run_runtime_state_fields(validated_data: dict) -> dict[str, Any]:
+ return {
+ key: validated_data.get(key)
+ for key in (
+ "pr_authorship_mode",
+ "auto_publish",
+ "run_source",
+ "signal_report_id",
+ "runtime_adapter",
+ "model",
+ "reasoning_effort",
+ "context_window",
+ "fast_mode",
+ )
+ }
+
+
def bootstrap_task_run(
task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
) -> contracts.TaskRunCreateResult | None:
@@ -4815,14 +4861,10 @@ def bootstrap_task_run(
branch = validated_data.get("branch")
sandbox_environment_id = validated_data.get("sandbox_environment_id")
pr_authorship_mode = validated_data.get("pr_authorship_mode")
- auto_publish = validated_data.get("auto_publish")
run_source = validated_data.get("run_source")
- signal_report_id = validated_data.get("signal_report_id")
runtime_adapter = validated_data.get("runtime_adapter")
model = validated_data.get("model")
reasoning_effort = validated_data.get("reasoning_effort")
- context_window = validated_data.get("context_window")
- fast_mode = validated_data.get("fast_mode")
github_user_token = validated_data.get("github_user_token")
initial_permission_mode = validated_data.get("initial_permission_mode")
imported_mcp_servers = validated_data.get("imported_mcp_servers")
@@ -4836,17 +4878,10 @@ def bootstrap_task_run(
provider = get_provider_for_runtime_adapter(runtime_adapter)
for key, value in {
+ **_task_run_runtime_state_fields(validated_data),
"pr_base_branch": branch,
"pr_authorship_mode": pr_authorship_mode,
- "auto_publish": auto_publish,
- "run_source": run_source,
- "signal_report_id": signal_report_id,
- "runtime_adapter": runtime_adapter,
"provider": provider,
- "model": model,
- "reasoning_effort": reasoning_effort,
- "context_window": context_window,
- "fast_mode": fast_mode,
"rtk_enabled": validated_data.get("rtk_enabled"),
"benjamin_enabled": validated_data.get("benjamin_enabled"),
"claude_model_access": validated_data.get("claude_model_access"),
@@ -4956,6 +4991,9 @@ def bootstrap_task_run(
return contracts.TaskRunCreateResult(run=_task_run_detail_to_dto(_task_run_queryset().get(pk=run.pk)))
+WORKFLOW_START_FAILED_ERROR = "Failed to start task workflow."
+
+
def _trigger_task_processing_workflow(
task: Task,
run: TaskRun,
@@ -4964,7 +5002,7 @@ def _trigger_task_processing_workflow(
initial_message: str | None = None,
initial_artifact_ids: list[str] | None = None,
raise_on_error: bool = False,
-) -> None:
+) -> str | None:
from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415
WorkflowDispatchOptions,
enqueue_or_start_workflow,
@@ -4999,30 +5037,33 @@ def _trigger_task_processing_workflow(
),
)
logger.info("Workflow trigger completed for task %s, run %s", task.id, run.id)
+ return None
except Exception as e:
logger.exception("Failed to trigger task processing workflow for task %s, run %s: %s", task.id, run.id, e)
if raise_on_error:
raise
+ return WORKFLOW_START_FAILED_ERROR
# Statuses from which a cloud run may be started via the start endpoint.
_STARTABLE_TASK_RUN_STATUSES = (TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED)
-def check_task_run_startable(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str:
+def check_task_run_startable(run_id: str | UUID, task_id: str | UUID, team_id: int) -> tuple[str, str | None]:
"""Whether a run can be started via the start endpoint.
Returns ``"not_found"`` (run missing), ``"not_cloud"``, ``"bad_status:<current>"``, or
- ``"ok"``. The usage gate (429) is applied by the view between this check and ``start_task_run``.
+ ``"ok"``, together with the stored run source. The view applies the usage gate before ``start_task_run``.
"""
run = _get_visible_run(run_id, task_id, team_id)
if run is None:
- return "not_found"
+ return "not_found", None
+ run_source = (run.state or {}).get("run_source")
if run.environment != TaskRun.Environment.CLOUD:
- return "not_cloud"
+ return "not_cloud", run_source
if run.status not in _STARTABLE_TASK_RUN_STATUSES:
- return f"bad_status:{run.status}"
- return "ok"
+ return f"bad_status:{run.status}", run_source
+ return "ok", run_source
def start_task_run(
@@ -5909,6 +5950,64 @@ def _capture_no_repo_selection_override(
logger.warning("signal_report_no_repo_selection_overridden capture failed for report %s: %s", report_id, e)
+def create_task_and_run(
+ team_id: int,
+ user_id: int | None,
+ *,
+ validated_data: dict,
+ run_data: dict,
+ client_provenance: TaskClientProvenance | None = None,
+ code_access_allowed: bool = False,
+) -> contracts.TaskRunResult:
+ from products.signals.backend.facade.api import ReportTaskCapExceeded
+
+ if custom_image_id := run_data.get("custom_image_id"):
+ custom_image = SandboxCustomImage.get_accessible_for_task(
+ image_id=custom_image_id, team_id=team_id, task_created_by_id=user_id
+ )
+ if custom_image is None:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(kind="detail", detail="Invalid custom_image_id")
+ )
+ if not custom_image.is_ready:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="detail", detail=f"Custom image is not ready (status: {custom_image.status})"
+ )
+ )
+ if sandbox_environment_id := run_data.get("sandbox_environment_id"):
+ sandbox_environment = SandboxEnvironment.get_accessible_for_task(
+ environment_id=sandbox_environment_id, team_id=team_id, task_created_by_id=user_id
+ )
+ if sandbox_environment is None:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(kind="detail", detail="Invalid sandbox_environment_id")
+ )
+
+ create_data = dict(validated_data)
+ create_data.pop("branch", None)
+ task = create_task(
+ team_id,
+ user_id,
+ validated_data=create_data,
+ client_provenance=client_provenance,
+ code_access_allowed=code_access_allowed,
+ )
+ try:
+ result = run_task(task.id, team_id, user_id, validated_data=run_data)
+ if result is None:
+ return contracts.TaskRunResult(task=task, run_error="Failed to create task run.")
+ return contracts.TaskRunResult(
+ task=result.task or task,
+ run_error=result.error.detail if result.error else result.run_error,
+ )
+ except ReportTaskCapExceeded as error:
+ return contracts.TaskRunResult(task=task, run_error=error.detail)
+ except Exception:
+ logger.exception("Failed to create first run for task %s", task.id)
+ return contracts.TaskRunResult(task=task, run_error="Failed to create task run.")
+
+
def create_task(
team_id: int,
user_id: int | None,
@@ -6084,6 +6183,7 @@ def create_task(
warm_task,
team_id,
message=pending_user_message or description or None,
+ branch=warm_branch,
description=description or None,
artifact_ids=pending_user_artifact_ids,
auto_publish=warm_auto_publish,
@@ -6931,6 +7031,7 @@ def _activate_warm_run(
team_id: int,
*,
message: str | None,
+ branch: str | None,
artifact_ids: list[str],
description: str | None = None,
auto_publish: bool | None = None,
@@ -6952,7 +7053,7 @@ def _activate_warm_run(
if description and not (task.description or "").strip():
task.description = description
task.save(update_fields=["description", "updated_at"])
- activation_state_updates: dict[str, object] = {}
+ activation_state_updates: dict[str, object] = {"pr_base_branch": branch}
if auto_publish is not None:
# Before the signal: the agent-server re-reads run state when the forwarded
# first message arrives, so the choice must already be persisted by then.
@@ -7119,6 +7220,7 @@ def warm_task_sandbox(
)
extra_state: dict = {
"branch": branch,
+ "pr_base_branch": branch,
"initial_permission_mode": resolved_permission_mode,
}
if sandbox_environment is not None:
@@ -7171,6 +7273,7 @@ def warm_task_resume_sandbox(
WarmSourceChanged,
)
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ RunSource,
get_pr_authorship_mode,
get_provider_for_runtime_adapter,
get_reasoning_effort_error,
@@ -7214,7 +7317,7 @@ def warm_task_resume_sandbox(
return None
previous_state = parse_run_state(previous_run.state)
- if previous_state.claude_model_access == "own-subscription":
+ if previous_state.run_source == RunSource.AGENT or previous_state.claude_model_access == "own-subscription":
return None
resolved_runtime_adapter = runtime_adapter or previous_state.runtime_adapter
resolved_model = model or previous_state.model
@@ -7277,7 +7380,7 @@ def warm_task_resume_sandbox(
for protected_key in ("wizard_head_branch", "self_driving_head_branch", "github_read_access"):
if protected_key in (previous_run.state or {}):
extra_state[protected_key] = (previous_run.state or {})[protected_key]
- extra_state = {key: value for key, value in extra_state.items() if value is not None}
+ extra_state = {key: value for key, value in extra_state.items() if value is not None or key == "pr_base_branch"}
stable_selection = {
key: value
for key, value in extra_state.items()
@@ -7375,6 +7478,7 @@ def run_task(
team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)
)
mode = validated_data.get("mode", "background")
+ run_source = validated_data.get("run_source")
branch = validated_data.get("branch")
resume_from_run_id = validated_data.get("resume_from_run_id")
pending_user_message = validated_data.get("pending_user_message")
@@ -7396,6 +7500,17 @@ def run_task(
)
)
previous_state = parse_run_state(previous_run.state)
+ if previous_state.run_source == RunSource.AGENT:
+ run_source = RunSource.AGENT
+ previous_branch = previous_state.pr_base_branch
+ if branch is not None and branch != previous_branch:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="detail", detail="A resumed run must use its previous base branch. Omit branch to resume."
+ )
+ )
+
+ branch = previous_branch
if branch is None and not resume_from_run_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:
# The inbox "Create PR" button sends no branch, so without this the run would target the
@@ -7425,7 +7540,7 @@ def run_task(
if claude_model_access is None and previous_state is not None:
claude_model_access = previous_state.claude_model_access
- warm_run = _idling_warm_run_for_task(task)
+ warm_run = None if run_source == RunSource.AGENT else _idling_warm_run_for_task(task)
if warm_run is not None and claude_model_access == "own-subscription":
warm_run = None
if warm_run is not None:
@@ -7437,10 +7552,7 @@ def run_task(
warm_resume_matches = (warm_state.get("resume_from_run_id") or None) == (
str(resume_from_run_id) if resume_from_run_id else None
)
- effective_branch = branch
- if effective_branch is None and previous_state is not None:
- effective_branch = previous_state.pr_base_branch
- if warm_resume_matches and (effective_branch or None) == (warm_run.branch or None):
+ if warm_resume_matches and (branch or None) == (warm_run.branch or None):
desired_runtime_adapter = validated_data.get("runtime_adapter")
desired_model = validated_data.get("model")
desired_context_window = validated_data.get("context_window")
@@ -7514,6 +7626,7 @@ def run_task(
task,
team_id,
message=pending_user_message or (task.description or None),
+ branch=branch,
description=task.description or None,
artifact_ids=pending_user_artifact_ids,
auto_publish=validated_data.get("auto_publish"),
@@ -7529,7 +7642,6 @@ def run_task(
custom_image_id_supplied_by_user = custom_image_id is not None
pr_authorship_mode = validated_data.get("pr_authorship_mode")
auto_publish = validated_data.get("auto_publish")
- run_source = validated_data.get("run_source")
signal_report_id = validated_data.get("signal_report_id")
runtime_adapter = validated_data.get("runtime_adapter")
model = validated_data.get("model")
@@ -7544,15 +7656,9 @@ def run_task(
pr_authorship_mode = PrAuthorshipMode.BOT
runtime_state_fields = {
+ **_task_run_runtime_state_fields(validated_data),
"pr_authorship_mode": pr_authorship_mode,
- "auto_publish": auto_publish,
"run_source": run_source,
- "signal_report_id": signal_report_id,
- "runtime_adapter": runtime_adapter,
- "model": model,
- "reasoning_effort": reasoning_effort,
- "context_window": context_window,
- "fast_mode": fast_mode,
}
extra_state: dict | None = None
@@ -7621,13 +7727,10 @@ def run_task(
reasoning_effort = runtime_state_fields["reasoning_effort"]
context_window = runtime_state_fields["context_window"]
fast_mode = runtime_state_fields["fast_mode"]
- if branch is None and prev_state.pr_base_branch is not None:
- branch = prev_state.pr_base_branch
provider = get_provider_for_runtime_adapter(runtime_adapter)
run_state_values = {
- "pr_base_branch": branch,
"pr_authorship_mode": pr_authorship_mode,
"auto_publish": auto_publish,
"run_source": run_source,
@@ -7642,9 +7745,10 @@ def run_task(
if is_pi_task:
for key in ("runtime_adapter", "provider", "model", "reasoning_effort"):
run_state_values.pop(key)
+ extra_state = extra_state or {}
+ extra_state["pr_base_branch"] = branch
for key, value in run_state_values.items():
if value is not None:
- extra_state = extra_state or {}
extra_state[key] = value.value if hasattr(value, "value") else value
reasoning_effort_error = get_reasoning_effort_error(
@@ -7797,7 +7901,7 @@ def run_task(
initial_message = (
pending_user_message if resume_from_run_id else pending_user_message or task.description or None
)
- _trigger_task_processing_workflow(
+ run_error = _trigger_task_processing_workflow(
task,
task_run,
user_id,
@@ -7806,9 +7910,18 @@ def run_task(
raise_on_error=False,
)
else:
- _trigger_task_processing_workflow(task, task_run, user_id, raise_on_error=False)
+ run_error = _trigger_task_processing_workflow(task, task_run, user_id, raise_on_error=False)
- return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id))
+ try:
+ if run_error is None:
+ task_run.refresh_from_db(fields=["status"])
+ if task_run.status == TaskRun.Status.FAILED:
+ run_error = WORKFLOW_START_FAILED_ERROR
+ task_detail = get_task_detail(task.id, team_id, user_id)
+ except Exception:
+ logger.exception("Failed to hydrate task %s after starting run %s", task.id, task_run.id)
+ task_detail = _task_detail_to_dto(task, latest_run=task_run, include_latest_run_log_url=False)
+ return contracts.TaskRunResult(task=task_detail, run_error=run_error)
# --- Task presence beacons ---
diff --git a/products/tasks/backend/facade/client_provenance.py b/products/tasks/backend/facade/client_provenance.py
index b59050c02e67..c939fbdd8caf 100644
--- a/products/tasks/backend/facade/client_provenance.py
+++ b/products/tasks/backend/facade/client_provenance.py
@@ -1,24 +1,14 @@
from rest_framework.request import Request
-from posthog.auth import OAuthAccessTokenAuthentication
-from posthog.oauth_provenance import is_interactive_desktop_grant
-from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
+from posthog.oauth_provenance import (
+ is_interactive_desktop_grant,
+ is_sandbox_oauth_request as is_sandbox_oauth_request,
+ is_sandbox_origin_request as is_sandbox_origin_request,
+)
from products.tasks.backend.models import TaskClientProvenance
-def is_sandbox_oauth_request(request: Request) -> bool:
- authenticator = getattr(request, "successful_authenticator", None)
- if not isinstance(authenticator, OAuthAccessTokenAuthentication):
- return False
- token = authenticator.access_token
- return (
- token.application is not None
- and token.application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS
- and (token.sandbox_task_id is not None or "internal_run:read" in (token.scope or "").split())
- )
-
-
def get_task_client_provenance(request: Request) -> TaskClientProvenance | None:
if is_interactive_desktop_grant(request):
return TaskClientProvenance.POSTHOG_DESKTOP
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 921213010cf3..d84752d2a9d0 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -206,6 +206,11 @@ class TaskDetailDTO:
origin_key: str | None = None
+@dataclass(frozen=True)
+class TaskCreateResponseDTO(TaskDetailDTO):
+ run_error: str | None = None
+
+
@dataclass(frozen=True)
class ChannelDTO:
"""The HTTP representation of a task channel."""
@@ -436,6 +441,7 @@ class TaskRunResult:
task: "TaskDetailDTO | None" = None
error: TaskValidationError | None = None
+ run_error: str | None = None
@dataclass(frozen=True)
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 571920bf06d2..eecc8e7bffb2 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -37,7 +37,7 @@ StreamConnectionOutcome = Literal[
]
StreamWriteSkippedPath = Literal["ingest", "mirror", "relay"]
_ALLOWED_MODES = {"background", "interactive"}
-_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}
+_ALLOWED_RUN_SOURCES = {"manual", "signal_report", "agent"}
_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}
_ALLOWED_TASK_RUNTIMES = {"acp", "pi"}
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 86ac961278ba..55aca5fca3ad 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -35,6 +35,7 @@ from products.tasks.backend.facade.contracts import (
SlackThreadReferenceDTO,
TaskActivityDTO,
TaskActivityPageDTO,
+ TaskCreateResponseDTO,
TaskDetailDTO,
TaskMentionDTO,
TaskRunDetailDTO,
@@ -75,14 +76,22 @@ TASK_RUN_REASONING_EFFORT_CHOICES = [
def _is_pi_task_run_request(context: dict[str, Any]) -> bool:
+ if "task_runtime" in context:
+ return context["task_runtime"] == tasks_facade.TaskRuntime.PI
view = context.get("view")
request = context.get("request")
team = context.get("team")
task_id = getattr(view, "kwargs", {}).get("parent_lookup_task_id")
+ if task_id is None and getattr(view, "action", None) == "run":
+ task_id = getattr(view, "kwargs", {}).get("pk")
user_id = getattr(getattr(request, "user", None), "id", None)
if task_id is None or team is None:
return False
+ try:
+ task_id = serializers.UUIDField().run_validation(task_id)
+ except serializers.ValidationError:
+ return False
task_runtime = tasks_facade.task_runtime(
task_id,
@@ -104,13 +113,11 @@ def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any]
task_id = kwargs.get("parent_lookup_task_id") or kwargs.get("pk")
team = context.get("team")
if team is not None and task_id is not None:
- run = tasks_facade.get_task_run_detail(run_id, task_id, team.id)
- if run is not None:
- access = run.state.get("claude_model_access")
- if access == "own-subscription" and not is_sandbox_oauth_request(request):
- raise serializers.ValidationError(
- {"claude_model_access": "Open PostHog Desktop to resume this run with your Claude plan."}
- )
+ access = tasks_facade.get_task_run_claude_model_access(run_id, task_id, team.id)
+ if access == "own-subscription" and not is_sandbox_oauth_request(request):
+ raise serializers.ValidationError(
+ {"claude_model_access": "Open PostHog Desktop to resume this run with your Claude plan."}
+ )
if access == "own-subscription" and is_sandbox_oauth_request(request):
raise serializers.ValidationError({"claude_model_access": "Only a user can select a Claude subscription."})
@@ -284,7 +291,7 @@ class TaskRunUpdateSerializer(serializers.Serializer):
required=False, allow_null=True, help_text="Current stage of the run (e.g. research, plan, build)"
)
output = serializers.JSONField(required=False, allow_null=True, help_text="Output from the run")
- state = serializers.JSONField(required=False, help_text="State of the run")
+ state = serializers.DictField(required=False, help_text="State of the run")
state_remove_keys = serializers.ListField(
child=serializers.CharField(),
required=False,
@@ -608,6 +615,22 @@ class TaskSerializer(DataclassSerializer):
]
+class TaskCreateResponseSerializer(TaskSerializer):
+ run_error = serializers.CharField(
+ required=False,
+ help_text="Error returned when the task was created but its first run could not start.",
+ )
+
+ class Meta(TaskSerializer.Meta):
+ dataclass = TaskCreateResponseDTO
+ fields = [*TaskSerializer.Meta.fields, "run_error"]
+
+
+@extend_schema_serializer(component_name="TaskRunResponse")
+class TaskRunResponseSerializer(TaskCreateResponseSerializer):
+ run_error = serializers.CharField(required=False, help_text="Error returned when the run could not start.")
+
+
TASK_DESCRIPTION_PREVIEW_LENGTH = 1000
TASK_DESCRIPTION_PREVIEW_HELP_TEXT = (
f"First {TASK_DESCRIPTION_PREVIEW_LENGTH} characters of the description, so a summary "
@@ -742,9 +765,8 @@ class TaskWriteSerializer(serializers.Serializer):
allow_blank=True,
write_only=True,
help_text=(
- "Branch the user has selected for this cloud task. Write-only and not persisted on the "
- "task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch "
- "is otherwise carried on the run). Omit to match a warm Run on the default branch."
+ "Base branch for the first run when start_run is true, or for matching a pre-warmed run. "
+ "Omit to use the repository's default branch. Write-only and not persisted on the task."
),
)
# These three warm-reuse hints are all optional: clients send an explicit
@@ -759,9 +781,8 @@ class TaskWriteSerializer(serializers.Serializer):
allow_null=True,
write_only=True,
help_text=(
- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: "
- "used only to reuse a pre-warmed Run started on the same runtime. A value differing from the "
- "warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime."
+ "Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. "
+ "A different adapter prevents warm reuse. Write-only and not persisted on the task."
),
)
model = serializers.CharField(
@@ -770,7 +791,7 @@ class TaskWriteSerializer(serializers.Serializer):
allow_blank=False,
allow_null=True,
write_only=True,
- help_text="Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.",
+ help_text="LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.",
)
reasoning_effort = serializers.ChoiceField(
choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS],
@@ -778,7 +799,7 @@ class TaskWriteSerializer(serializers.Serializer):
default=None,
allow_null=True,
write_only=True,
- help_text="Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.",
+ help_text="Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.",
)
initial_permission_mode = serializers.ChoiceField(
choices=ALL_INITIAL_PERMISSION_MODE_CHOICES,
@@ -787,8 +808,8 @@ class TaskWriteSerializer(serializers.Serializer):
allow_null=True,
write_only=True,
help_text=(
- "Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same "
- "mode. Omit to reuse a warm Run whatever mode it booted on."
+ "Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. "
+ "Omit to match any warm permission mode. Write-only."
),
)
pending_user_message = serializers.CharField(
@@ -798,10 +819,9 @@ class TaskWriteSerializer(serializers.Serializer):
allow_blank=True,
write_only=True,
help_text=(
- "First user message to forward when creation reuses a pre-warmed Run. Write-only and not "
- "persisted on the task: lets clients deliver a message that differs from `description` "
- "(e.g. a resolved skill invocation with channel context folded in). Ignored when no warm "
- "Run is reused — cold creation takes the first message via the run start endpoint instead."
+ "First user message when start_run is true or creation reuses a pre-warmed run. "
+ "This message can differ from description. Ignored if creation does not start a run. "
+ "Write-only and not persisted on the task."
),
)
pending_user_artifact_ids = serializers.ListField(
@@ -813,7 +833,7 @@ class TaskWriteSerializer(serializers.Serializer):
"Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded "
"first message when creation reuses that warm Run, e.g. skill bundles or file attachments. "
"If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is "
- "created cold. Ignored when no warm Run is matched."
+ "created cold. Ignored when no warm Run is matched. Not supported when start_run is true."
),
)
auto_publish = serializers.BooleanField(
@@ -822,11 +842,9 @@ class TaskWriteSerializer(serializers.Serializer):
default=None,
write_only=True,
help_text=(
- "When true, the cloud run agent pushes its work and opens a draft pull request on "
- "completion without waiting for an explicit ask. Write-only and not persisted on the "
- "task: persisted into the reused warm Run's state when creation activates one, so "
- "resumes of that Run honor it. Ignored when no warm Run is reused — cold creation "
- "takes it via the run start endpoint instead."
+ "When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. "
+ "Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. "
+ "Ignored if creation does not start a run. Write-only and not persisted on the task."
),
)
channel = TeamScopedPrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
@@ -1007,6 +1025,12 @@ class TaskWriteSerializer(serializers.Serializer):
class TaskCreateSerializer(TaskWriteSerializer):
+ start_run = serializers.BooleanField(
+ required=False,
+ default=False,
+ write_only=True,
+ help_text="Start the task's first cloud run immediately after creation.",
+ )
signal_report_discussion_question = serializers.CharField(
required=False,
allow_blank=True,
@@ -1034,14 +1058,14 @@ class TaskCreateSerializer(TaskWriteSerializer):
default=None,
allow_null=True,
write_only=True,
- help_text="Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.",
+ help_text="Sandbox environment for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.",
)
custom_image_id = serializers.UUIDField(
required=False,
default=None,
allow_null=True,
write_only=True,
- help_text="Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.",
+ help_text="Custom image for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.",
)
runtime = serializers.ChoiceField(
choices=tasks_facade.TaskRuntime.choices,
@@ -1059,6 +1083,41 @@ class TaskCreateSerializer(TaskWriteSerializer):
"signal_report"
):
raise serializers.ValidationError({"signal_report": "Requires signal_report when set."})
+ if attrs.get("start_run"):
+ if attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT:
+ raise serializers.ValidationError(
+ {
+ "start_run": "Create signal-report tasks without start_run, then start them through the report workflow."
+ }
+ )
+ if attrs.get("pending_user_artifact_ids"):
+ raise serializers.ValidationError(
+ {"pending_user_artifact_ids": "Create the task before you upload artifacts and start its run."}
+ )
+ run_payload = {
+ key: attrs[key]
+ for key in (
+ "branch",
+ "runtime_adapter",
+ "model",
+ "reasoning_effort",
+ "sandbox_environment_id",
+ "custom_image_id",
+ "initial_permission_mode",
+ "pending_user_message",
+ "auto_publish",
+ )
+ if attrs.get(key) is not None
+ }
+ run_payload.update(mode="background", run_source=RunSource.AGENT)
+ run_serializer = TaskRunCreateRequestSerializer(
+ data=run_payload,
+ context={**self.context, "task_runtime": attrs.get("runtime", tasks_facade.TaskRuntime.ACP)},
+ )
+ run_serializer.is_valid(raise_exception=True)
+ attrs["run_data"] = {
+ key: run_serializer.validated_data[key] for key in run_payload if key in run_serializer.validated_data
+ }
return attrs
@@ -3111,7 +3170,43 @@ def get_relayed_imported_mcp_name_collision_error(attrs: dict) -> str | None:
return None
-class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, serializers.Serializer):
+class TaskRunPreferencesFieldMixin(serializers.Serializer):
+ rtk_enabled = serializers.BooleanField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Whether rtk command-output compression is enabled for this run. Omitted or null "
+ "follows the server-side default (enabled); false opts this run out."
+ ),
+ )
+ benjamin_enabled = serializers.BooleanField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted "
+ "or null lets the server decide from the feature flag; true or false pins the choice "
+ "for this run."
+ ),
+ )
+ claude_model_access = serializers.ChoiceField(
+ choices=["posthog-gateway", "own-subscription"],
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "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. If omitted or null, resumed runs "
+ "keep their billing choice and new runs use the PostHog gateway."
+ ),
+ )
+
+
+class TaskRunCreateRequestSerializer(
+ ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, TaskRunPreferencesFieldMixin, serializers.Serializer
+):
"""Request body for creating a new task run"""
PR_AUTHORSHIP_MODE_CHOICES = [mode.value for mode in PrAuthorshipMode]
@@ -3238,41 +3333,15 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
"Codex runtimes accept 'plan', 'auto', 'read-only', and 'full-access'."
),
)
- rtk_enabled = serializers.BooleanField(
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "Whether rtk command-output compression is enabled for this run. Omitted or null "
- "follows the server-side default (enabled); false opts this run out."
- ),
- )
- benjamin_enabled = serializers.BooleanField(
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted "
- "or null lets the server decide from the feature flag; true or false pins the choice "
- "for this run."
- ),
- )
- claude_model_access = serializers.ChoiceField(
- choices=["posthog-gateway", "own-subscription"],
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "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. If omitted or null, resumed runs "
- "keep their billing choice and new runs use the PostHog gateway."
- ),
- )
def validate(self, attrs):
_validate_subscription_caller(attrs, self.context)
errors: dict[str, str] = {}
+ is_pi_task = _is_pi_task_run_request(self.context)
+ if is_pi_task:
+ for field in ("runtime_adapter", "model", "reasoning_effort", "initial_permission_mode"):
+ if attrs.get(field) is not None:
+ errors[field] = "This field cannot be used with a Pi task. Remove it and try again."
if collision_error := get_relayed_imported_mcp_name_collision_error(attrs):
errors["relayed_mcp_servers"] = collision_error
initial_permission_mode = attrs.get("initial_permission_mode")
@@ -3282,7 +3351,7 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
pending_user_message = attrs.get("pending_user_message")
pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []
- if attrs.get("claude_model_access") == "own-subscription" and _is_pi_task_run_request(self.context):
+ if attrs.get("claude_model_access") == "own-subscription" and is_pi_task:
errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."
if pending_user_message is not None:
trimmed_message = pending_user_message.strip()
@@ -3331,12 +3400,12 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
class TaskRunBootstrapCreateRequestSerializer(
- ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, serializers.Serializer
+ ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, TaskRunPreferencesFieldMixin, serializers.Serializer
):
"""Request body for creating a task run without starting execution yet."""
PR_AUTHORSHIP_MODE_CHOICES = [mode.value for mode in PrAuthorshipMode]
- RUN_SOURCE_CHOICES = [source.value for source in RunSource]
+ RUN_SOURCE_CHOICES = [source.value for source in RunSource if source != RunSource.AGENT]
RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]
REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICES
@@ -3444,37 +3513,6 @@ class TaskRunBootstrapCreateRequestSerializer(
"and 'read-only'."
),
)
- rtk_enabled = serializers.BooleanField(
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "Whether rtk command-output compression is enabled for this run. Omitted or null "
- "follows the server-side default (enabled); false opts this run out."
- ),
- )
- benjamin_enabled = serializers.BooleanField(
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted "
- "or null lets the server decide from the feature flag; true or false pins the choice "
- "for this run."
- ),
- )
- claude_model_access = serializers.ChoiceField(
- choices=["posthog-gateway", "own-subscription"],
- required=False,
- allow_null=True,
- default=None,
- help_text=(
- "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. If omitted or null, resumed runs "
- "keep their billing choice and new runs use the PostHog gateway."
- ),
- )
def validate(self, attrs):
_validate_subscription_caller(attrs, self.context)
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index f219d3fa4203..65fea76662a1 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -76,7 +76,11 @@ from products.tasks.backend.facade.access import (
usage_limit_response,
)
from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_task_usage
-from products.tasks.backend.facade.client_provenance import get_task_client_provenance, is_sandbox_oauth_request
+from products.tasks.backend.facade.client_provenance import (
+ get_task_client_provenance,
+ is_sandbox_oauth_request,
+ is_sandbox_origin_request,
+)
from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceeded
from products.tasks.backend.facade.contracts import TaskAnalysisError, TaskRunLogAppendUnserialized
from products.tasks.backend.facade.metrics import (
@@ -92,7 +96,12 @@ from products.tasks.backend.facade.metrics import (
observe_stream_resume_gap,
)
from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices
-from products.tasks.backend.facade.run_config import WARMABLE_ORIGIN_PRODUCTS, TaskArtifactAdapter, TaskArtifactType
+from products.tasks.backend.facade.run_config import (
+ WARMABLE_ORIGIN_PRODUCTS,
+ RunSource,
+ TaskArtifactAdapter,
+ TaskArtifactType,
+)
from products.tasks.backend.facade.streams import (
MAX_IDENTIFIER_CHARS,
TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
@@ -133,6 +142,7 @@ from products.tasks.backend.presentation.serializers import (
TaskCommentDetailSerializer,
TaskCommentsQuerySerializer,
TaskCommentsResponseSerializer,
+ TaskCreateResponseSerializer,
TaskCreateSerializer,
TaskHandoffRequestSerializer,
TaskListItemSerializer,
@@ -177,6 +187,7 @@ from products.tasks.backend.presentation.serializers import (
TaskRunPostHogReferencesResponseSerializer,
TaskRunRelayMessageRequestSerializer,
TaskRunRelayMessageResponseSerializer,
+ TaskRunResponseSerializer,
TaskRunSessionLogsQuerySerializer,
TaskRunSetOutputRequestSerializer,
TaskRunStartRequestSerializer,
@@ -239,6 +250,13 @@ def _pi_cloud_runtime_disabled_response() -> Response:
)
+def _agent_run_disabled_response() -> Response:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Agent-started task runs are not available for this project"}).data,
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+
TASKS_PREWARM_SANDBOX_FLAG = "tasks-prewarm-sandbox"
# One rollout per origin product — the Code app and PostHog AI reach different populations, so a shared
@@ -311,6 +329,7 @@ TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60
TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
+TASKS_MCP_AGENT_RUN_START_FLAG = "tasks-mcp-agent-run-start"
SESSION_LOG_PAGE_MAX_BYTES = 16 * 1024 * 1024
@@ -333,6 +352,25 @@ def _can_bypass_visibility(request, team_id: int | None) -> bool:
)
+def _agent_run_enabled(request, team) -> bool:
+ if not _is_internal_debug_team(team.id):
+ return False
+ distinct_id = getattr(request.user, "distinct_id", None) or str(getattr(request.user, "uuid", ""))
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ TASKS_MCP_AGENT_RUN_START_FLAG,
+ distinct_id,
+ groups={"organization": str(team.organization_id), "project": str(team.uuid)},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("Failed to evaluate agent run feature flag")
+ return False
+
+
class _SchemaAwareLimitOffsetPagination(LimitOffsetPagination):
"""LimitOffsetPagination subclass that surfaces `default_limit`/`max_limit` in the OpenAPI schema."""
@@ -420,6 +458,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
pagination_class = TasksPagination
+ lookup_value_regex = UUID_LOOKUP_REGEX
# Fallback for drf-spectacular introspection only; every action declares its own
# request/response schema via @validated_request / @extend_schema.
serializer_class = TaskSerializer
@@ -637,7 +676,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
],
responses={
- 201: TaskSerializer,
+ 201: TaskCreateResponseSerializer,
402: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
description=(
@@ -648,7 +687,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
403: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
- description="PostHog Desktop access is required for a create that can activate a warm sandbox",
+ description=(
+ "Agent-started runs are limited to the internal project and cannot start from a sandbox token. "
+ "Immediate runs also require PostHog Desktop access and an enabled Pi cloud runtime."
+ ),
),
429: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
@@ -669,6 +711,21 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def create(self, request, **kwargs):
serializer = self._write_serializer(request.data, serializer_class=TaskCreateSerializer)
+ validated_data = dict(serializer.validated_data)
+ start_run = validated_data.pop("start_run", False)
+ run_data = validated_data.pop("run_data", {})
+ origin_product = validated_data.get("origin_product", tasks_facade.TaskOriginProduct.USER_CREATED)
+ relationship = serializer.validated_data.get("signal_report_task_relationship")
+
+ if start_run and (not self._agent_run_enabled(request) or is_sandbox_origin_request(request)):
+ return _agent_run_disabled_response()
+
+ if (
+ start_run
+ and validated_data.get("runtime") == tasks_facade.TaskRuntime.PI
+ and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user)
+ ):
+ return _pi_cloud_runtime_disabled_response()
# A create that carries warm-reuse hints can activate an idling sandbox in place, which starts
# the agent without the client ever calling the run endpoint — so the gates that endpoint puts
@@ -677,18 +734,26 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Scoped to warmable origins, which is what a warm can ever be reused for; the code-access
# exempt Inbox shapes are not among them, matching how the warm endpoint gates.
# `origin_product` is optional on the wire; `create_task` defaults it the same way.
- if (
- "branch" in serializer.validated_data
- and serializer.validated_data.get("origin_product", tasks_facade.TaskOriginProduct.USER_CREATED)
- in WARMABLE_ORIGIN_PRODUCTS
- ):
- if access_response := code_access_required_response(request, self.organization):
+ can_activate_warm_run = "branch" in validated_data and origin_product in WARMABLE_ORIGIN_PRODUCTS
+ if can_activate_warm_run and is_sandbox_origin_request(request):
+ return _agent_run_disabled_response()
+ if start_run or can_activate_warm_run:
+ is_code_access_exempt = (
+ origin_product == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
+ and validated_data.get("signal_report") is not None
+ and relationship not in (None, "implementation")
+ and validated_data.get("repository") is None
+ and not validated_data.get("repositories")
+ and validated_data.get("github_integration") is None
+ and validated_data.get("github_user_integration") is None
+ )
+ if not is_code_access_exempt and (
+ access_response := code_access_required_response(request, self.organization)
+ ):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
return limit_response
- validated_data = dict(serializer.validated_data)
- relationship = validated_data.get("signal_report_task_relationship")
discussion_question = validated_data.pop("signal_report_discussion_question", None)
# Inbox "Discuss" runs repo-less so the generally-available Inbox never 403s a caller the
@@ -710,18 +775,34 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
try:
- task = tasks_facade.create_task(
- self.team_id,
- self._user_id(),
- validated_data=validated_data,
- client_provenance=get_task_client_provenance(request),
- code_access_allowed=code_access_allowed,
- **(
- {"warm_retry_token": request.headers["X-PostHog-Warm-Retry"]}
- if "X-PostHog-Warm-Retry" in request.headers
- else {}
- ),
- )
+ run_error = None
+ if start_run:
+ create_result = tasks_facade.create_task_and_run(
+ self.team_id,
+ self._user_id(),
+ validated_data=validated_data,
+ run_data=run_data,
+ client_provenance=get_task_client_provenance(request),
+ code_access_allowed=code_access_allowed,
+ )
+ if create_result.error is not None:
+ return self._task_error_response(create_result.error)
+ assert create_result.task is not None
+ task = create_result.task
+ run_error = create_result.run_error
+ else:
+ task = tasks_facade.create_task(
+ self.team_id,
+ self._user_id(),
+ validated_data=validated_data,
+ client_provenance=get_task_client_provenance(request),
+ code_access_allowed=code_access_allowed,
+ **(
+ {"warm_retry_token": request.headers["X-PostHog-Warm-Retry"]}
+ if "X-PostHog-Warm-Retry" in request.headers
+ else {}
+ ),
+ )
except ComputeBillingLimitExceeded as error:
return compute_quota_limit_response(error.reason)
except ReportTaskCapExceeded as error:
@@ -729,7 +810,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
except tasks_facade.WarmRunActivationUnavailable as error:
return self._warm_activation_unavailable_response(error)
self._forward_signals_discussion_note(request, task, relationship, discussion_question)
- return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)
+ response_data = TaskSerializer(task).data
+ if run_error:
+ response_data["run_error"] = run_error
+ return Response(response_data, status=status.HTTP_201_CREATED)
def _warm_activation_unavailable_response(self, error: tasks_facade.WarmRunActivationUnavailable) -> Response:
return Response(
@@ -1164,7 +1248,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@validated_request(
request_serializer=TaskRunCreateRequestSerializer,
responses={
- 200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
+ 200: OpenApiResponse(response=TaskRunResponseSerializer, description="Task with updated latest run"),
400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),
402: OpenApiResponse(
response=TaskRunErrorResponseSerializer,
@@ -1200,6 +1284,16 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
@action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
def run(self, request, pk=None, **kwargs):
+ run_source = request.validated_data.get("run_source")
+ if resume_id := request.validated_data.get("resume_from_run_id"):
+ previous_source = tasks_facade.get_task_run_source(resume_id, pk, self.team_id)
+ if previous_source == RunSource.AGENT:
+ run_source = previous_source
+ if is_sandbox_origin_request(request) or (
+ run_source == RunSource.AGENT and not self._agent_run_enabled(request)
+ ):
+ return _agent_run_disabled_response()
+
# Original order: 404 if the task isn't visible, then gate (always cloud) before the run.
if not tasks_facade.task_visible(pk, self.team_id, self._user_id(), for_control=True):
raise NotFound()
@@ -1244,7 +1338,13 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
if result.error is not None:
return self._task_error_response(result.error)
- return Response(TaskSerializer(result.task).data)
+ response_data = TaskSerializer(result.task).data
+ if result.run_error:
+ response_data["run_error"] = result.run_error
+ return Response(response_data)
+
+ def _agent_run_enabled(self, request) -> bool:
+ return _agent_run_enabled(request, self.team)
def _warm_enabled(self, origin_product: str) -> bool:
"""Person + org level gate for the sandbox-warming feature. Fail-closed on any error.
@@ -1306,6 +1406,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
@action(detail=False, methods=["post"], url_path="warm", required_scopes=["task:write"])
def warm(self, request, **kwargs):
+ if is_sandbox_origin_request(request):
+ return _agent_run_disabled_response()
origin_product = request.validated_data["origin_product"]
if not self._warm_enabled(origin_product):
return Response(status=status.HTTP_200_OK)
@@ -1376,6 +1478,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
@action(detail=True, methods=["post"], url_path="warm", url_name="warm-resume", required_scopes=["task:write"])
def warm_resume(self, request, pk=None, **kwargs):
+ if is_sandbox_origin_request(request):
+ return _agent_run_disabled_response()
gate = tasks_facade.task_control_runtime_and_origin(pk, self.team_id, self._user_id())
if gate is None:
raise NotFound()
@@ -1544,6 +1648,18 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
+ def _cloud_run_access_response(self, task_id: str) -> Response | None:
+ user = cast(User, self.request.user)
+ if tasks_facade.task_runtime(
+ task_id, self.team_id, self._user_id(), for_control=True
+ ) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, user):
+ return _pi_cloud_runtime_disabled_response()
+ if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
+ access_response := code_access_required_response(self.request, self.organization, task_id=task_id)
+ ):
+ return access_response
+ return usage_limit_response(user, self.team_id)
+
def _ensure_task_accessible(self) -> str:
"""Gate access to the parent task, including exact task-bound sandbox access."""
task_id = self._task_id()
@@ -1649,16 +1765,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Gate cloud runs before the run row is created; local runs aren't limited.
if environment == tasks_facade.TaskRunEnvironment.CLOUD:
- if tasks_facade.task_runtime(
- task_id, self.team_id, self._user_id(), for_control=True
- ) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):
- return _pi_cloud_runtime_disabled_response()
- if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request, self.organization, task_id=task_id)
- ):
+ if is_sandbox_origin_request(request):
+ return _agent_run_disabled_response()
+ if access_response := self._cloud_run_access_response(task_id):
return access_response
- if limit_response := usage_limit_response(request.user, self.team_id):
- return limit_response
result = tasks_facade.bootstrap_task_run(
task_id, self.team_id, self._user_id(), validated_data=dict(request.validated_data)
@@ -1693,9 +1803,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=True, methods=["post"], url_path="start", required_scopes=["task:write"])
def start(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
- startable = tasks_facade.check_task_run_startable(pk, task_id, self.team_id)
+ startable, run_source = tasks_facade.check_task_run_startable(pk, task_id, self.team_id)
if startable == "not_found":
raise NotFound()
+ if is_sandbox_origin_request(request) or (
+ run_source == RunSource.AGENT and not _agent_run_enabled(request, self.team)
+ ):
+ return _agent_run_disabled_response()
if tasks_facade.task_runtime(
task_id, self.team_id, self._user_id(), for_control=True
@@ -3339,21 +3453,17 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
required_scopes=["task:write"],
)
def resume_in_cloud(self, request, pk=None, **kwargs):
+ if is_sandbox_origin_request(request):
+ return _agent_run_disabled_response()
task_id = self._ensure_task_accessible()
if tasks_facade.get_task_run_detail(pk, task_id, self.team_id) is None:
raise NotFound()
- if tasks_facade.task_runtime(
- task_id, self.team_id, self._user_id(), for_control=True
- ) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):
- return _pi_cloud_runtime_disabled_response()
-
- # A resumed run also consumes cloud capacity, so apply the cloud access gates.
- if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
- access_response := code_access_required_response(request, self.organization, task_id=task_id)
+ if tasks_facade.get_task_run_source(pk, task_id, self.team_id) == RunSource.AGENT and not _agent_run_enabled(
+ request, self.team
):
+ return _agent_run_disabled_response()
+ if access_response := self._cloud_run_access_response(task_id):
return access_response
- if limit_response := usage_limit_response(request.user, self.team_id):
- return limit_response
if one_shot_response := self._one_shot_analysis_response(task_id):
return one_shot_response
diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.md
index fd20108c38c6..1543ca1148bf 100644
--- a/products/tasks/backend/temporal/process_task/README.md
+++ b/products/tasks/backend/temporal/process_task/README.md
@@ -50,6 +50,8 @@ User ─────────────────────────
## Components
+For combined task creation, run-start responses, and MCP tools, see [Create tasks and start runs](../../../../../docs/internal/task-run-api.md).
+
### PostHog API
`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming, checks server-side PostHog Desktop access before provisioning or activating a run. Composer prewarming carries the complete ordered repository selection, so single- and multi-repository submissions can reuse only a matching sandbox. A terminal task can also prewarm a successor through `POST .../tasks/{id}/warm/`; the source run must remain the task's latest terminal run, and the normal `run` request activates that successor with `resume_from_run_id`. Runtime, model, branch, permission mode, and sandbox configuration must match; reasoning effort may change and is applied before the warmed agent's first turn. Full-filesystem resume snapshots bundle their agent binary, so prewarming probes for the deferred-resume capability and falls back to a fresh sandbox when an old snapshot lacks it. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 23bd32da9eba..720c66541412 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -81,6 +81,7 @@ class GitHubCredentialSource(StrEnum):
class RunSource(StrEnum):
MANUAL = "manual"
SIGNAL_REPORT = "signal_report"
+ AGENT = "agent"
# Origins whose runs are meant to carry a human git identity; everything else is bot-authored.
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 2c2e9e38b2b6..68c7bffc723c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -228,7 +228,7 @@ class BaseTaskAPITest(TestCase):
self.mock_feature_flag = self.feature_flag_patcher.start()
def check_flag(flag_name, *_args, **_kwargs):
- if flag_name in {"tasks", "pi-harness"}:
+ if flag_name in {"tasks", "pi-harness", "tasks-mcp-agent-run-start"}:
return enabled
return False
@@ -1532,6 +1532,328 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(data["repository"], "posthog/posthog")
self.assertEqual(data["repositories"], ["posthog/posthog"])
self.assertEqual(data["runtime"], Task.Runtime.ACP)
+ self.assertIsNone(data["latest_run"])
+
+ @parameterized.expand([False, True])
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_task_can_start_first_run(self, null_hints, mock_workflow, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Delegated task",
+ "description": "Complete the delegated work",
+ "repository": "posthog/posthog",
+ "branch": "existing-branch",
+ "start_run": True,
+ **(
+ dict.fromkeys(
+ [
+ "runtime_adapter",
+ "model",
+ "reasoning_effort",
+ "sandbox_environment_id",
+ "custom_image_id",
+ "initial_permission_mode",
+ "pending_user_message",
+ ]
+ )
+ if null_hints
+ else {}
+ ),
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ task = Task.objects.get(id=response.json()["id"])
+ run = task.runs.get()
+ self.assertEqual(response.json()["latest_run"]["id"], str(run.id))
+ self.assertEqual(run.branch, "existing-branch")
+ self.assertEqual(run.state["mode"], "background")
+ self.assertEqual(run.state["run_source"], "agent")
+ self.assertEqual(mock_workflow.call_args.kwargs["posthog_mcp_scopes"], "read_only")
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch(
+ "products.tasks.backend.temporal.client.execute_task_processing_workflow",
+ side_effect=RuntimeError("workflow unavailable"),
+ )
+ def test_create_task_returns_run_error_when_first_run_cannot_start(self, _mock_workflow, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Delegated task", "description": "Complete the delegated work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["run_error"], "Failed to start task workflow.")
+ self.assertTrue(Task.objects.filter(id=response.json()["id"]).exists())
+ self.assertIsNotNone(response.json()["latest_run"])
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_task_returns_run_error_when_temporal_marks_run_failed(self, mock_workflow, _mock_internal_team):
+ internal_error = 'Failed client connect: tonic::transport::Error(ConnectError("tcp", 127.0.0.1:7233))'
+
+ def fail_run(**kwargs):
+ TaskRun.objects.filter(id=kwargs["run_id"]).update(
+ status=TaskRun.Status.FAILED, error_message=internal_error
+ )
+
+ mock_workflow.side_effect = fail_run
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Delegated task", "description": "Complete the delegated work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["run_error"], "Failed to start task workflow.")
+ self.assertNotIn("127.0.0.1", response.json()["run_error"])
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.presentation.views.api.tasks_facade.run_task", side_effect=RuntimeError("failed"))
+ def test_create_task_returns_created_task_when_run_creation_raises(self, _mock_run_task, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Delegated task", "description": "Complete the delegated work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["run_error"], "Failed to create task run.")
+ self.assertEqual(Task.objects.filter(title="Delegated task").count(), 1)
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ def test_create_task_validates_first_run_payload(self, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Invalid model", "model": "claude-sonnet-5", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Task.objects.filter(description="Invalid model").exists())
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Invalid branch", "branch": "", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Task.objects.filter(description="Invalid branch").exists())
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_task_accepts_blank_first_run_message(self, _mock_workflow, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Blank message", "pending_user_message": " ", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertIsNotNone(response.json()["latest_run"])
+
+ @parameterized.expand(
+ [
+ (combined_create, read_target)
+ for combined_create in (True, False)
+ for read_target in (
+ "products.tasks.backend.facade.api._task_run_log_url",
+ "products.tasks.backend.models.TaskRun.refresh_from_db",
+ )
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_run_response_preserves_run_when_response_hydration_fails(
+ self, combined_create, read_target, mock_workflow, _mock_internal_team
+ ):
+ task = None if combined_create else self.create_task()
+ url = "/api/projects/@current/tasks/" if task is None else f"/api/projects/@current/tasks/{task.id}/run/"
+ payload = {"description": "Hydration failure", "start_run": True} if combined_create else {}
+ with patch(read_target, side_effect=RuntimeError("read unavailable")):
+ response = self.client.post(url, payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED if combined_create else status.HTTP_200_OK)
+ run = Task.objects.get(id=response.json()["id"]).runs.get()
+ self.assertEqual(response.json()["latest_run"]["id"], str(run.id))
+ self.assertNotIn("run_error", response.json())
+ mock_workflow.assert_called_once()
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_interactive_desktop_oauth_can_start_agent_runs(self, _mock_workflow, _mock_internal_team):
+ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)
+ response = client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Desktop task", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ task = Task.objects.get(id=response.json()["id"])
+ response = client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"run_source": "agent"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_create_task_cannot_start_first_run_outside_internal_team(self):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Delegated task", "description": "Complete the delegated work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Task.objects.filter(title="Delegated task").exists())
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ def test_create_task_cannot_start_first_run_when_flag_is_disabled(self, _mock_internal_team):
+ self.set_tasks_feature_flag(False)
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Disabled run", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Task.objects.filter(description="Disabled run").exists())
+ self.mock_feature_flag.assert_any_call(
+ "tasks-mcp-agent-run-start",
+ self.user.distinct_id,
+ groups={"organization": str(self.organization.id), "project": str(self.team.uuid)},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+
+ @parameterized.expand(
+ [
+ (payload, forwarded)
+ for payload in ({}, {"run_source": "manual"}, {"run_source": "agent"})
+ for forwarded in (False, True)
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ def test_sandbox_oauth_cannot_start_agent_runs(self, run_payload, forwarded, _mock_internal_team):
+ parent = self.create_task()
+ if forwarded:
+ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)
+ client.defaults["HTTP_X_POSTHOG_SANDBOX_ORIGIN"] = "1"
+ else:
+ client = self._sandbox_oauth_client(parent.id, internal_scope=True)
+ task_count = Task.objects.count()
+
+ response = client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Child task", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(Task.objects.count(), task_count)
+
+ response = client.post(
+ f"/api/projects/@current/tasks/{parent.id}/run/",
+ run_payload,
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(parent.runs.exists())
+
+ @parameterized.expand(
+ [(origin, forwarded) for origin in ("user_created", "posthog_ai") for forwarded in (False, True)]
+ )
+ @patch("products.tasks.backend.facade.api._activate_warm_run")
+ def test_sandbox_oauth_cannot_activate_warm_run(self, origin_product, forwarded, mock_activate):
+ parent = self.create_task()
+ if forwarded:
+ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)
+ client.defaults["HTTP_X_POSTHOG_SANDBOX_ORIGIN"] = "1"
+ else:
+ client = self._sandbox_oauth_client(parent.id, internal_scope=True)
+ task_count = Task.objects.count()
+
+ response = client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Child task", "branch": "main", "origin_product": origin_product},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(Task.objects.count(), task_count)
+ mock_activate.assert_not_called()
+
+ @parameterized.expand(
+ [
+ (action, forwarded)
+ for action in ("warm", "warm_resume", "resume_in_cloud", "start", "bootstrap")
+ for forwarded in (False, True)
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_sandbox_oauth_cannot_start_indirect_cloud_runs(self, action, forwarded, mock_workflow):
+ task = self.create_task()
+ run = task.create_run(environment=TaskRun.Environment.CLOUD)
+ if forwarded:
+ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)
+ client.defaults["HTTP_X_POSTHOG_SANDBOX_ORIGIN"] = "1"
+ else:
+ client = self._sandbox_oauth_client(task.id, internal_scope=True)
+ paths = {
+ "warm": "/api/projects/@current/tasks/warm/",
+ "warm_resume": f"/api/projects/@current/tasks/{task.id}/warm/",
+ "resume_in_cloud": f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/",
+ "start": f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/start/",
+ "bootstrap": f"/api/projects/@current/tasks/{task.id}/runs/",
+ }
+
+ payload = {"resume_from_run_id": str(run.id)} if action == "warm_resume" else {}
+ if action == "bootstrap":
+ payload = {"environment": "cloud"}
+ response = client.post(paths[action], payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(task.runs.count(), 1)
+ mock_workflow.assert_not_called()
+
+ @parameterized.expand([False, True])
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_signal_report_run_rejected_before_creation(
+ self, restricted_token, mock_workflow, _mock_internal_team
+ ):
+ from products.signals.backend.models import SignalReport
+
+ report = SignalReport.objects.create(team=self.team)
+ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV, scope="task:write") if restricted_token else self.client
+ task_count = Task.objects.count()
+ response = client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "description": "Implement the report",
+ "origin_product": "signal_report",
+ "signal_report": str(report.id),
+ "start_run": True,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "start_run")
+ self.assertEqual(Task.objects.count(), task_count)
+ mock_workflow.assert_not_called()
+
+ def test_run_endpoint_rejects_malformed_task_id(self):
+ response = self.client.post("/api/projects/@current/tasks/not-a-uuid/run/")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
@patch("products.tasks.backend.facade.api._find_idling_warm_run")
def test_create_task_with_multiple_repositories(self, mock_find_warm_run):
@@ -2771,10 +3093,14 @@ class TestTaskAPI(BaseTaskAPITest):
("manual", {"run_source": "manual"}, "full"),
# signal_report implementation runs log their work as report artefacts (task:write tools).
("signal_report", {"run_source": "signal_report"}, "full"),
+ ("agent", {"run_source": "agent"}, "read_only"),
]
)
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_run_endpoint_resolves_mcp_scope_from_run_source(self, _name, payload, expected_scope, mock_workflow):
+ def test_run_endpoint_resolves_mcp_scope_from_run_source(
+ self, _name, payload, expected_scope, mock_workflow, _mock_internal_team
+ ):
task = self.create_task()
response = self.client.post(
@@ -2786,6 +3112,211 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(mock_workflow.call_args.kwargs["posthog_mcp_scopes"], expected_scope)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_run_endpoint_rejects_agent_source_outside_internal_team(self, mock_workflow):
+ task = self.create_task()
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"run_source": "agent"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ mock_workflow.assert_not_called()
+
+ @parameterized.expand([({},), ({"run_source": "manual"},)])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch(
+ "products.tasks.backend.facade.api.get_task_run_detail", side_effect=AssertionError("Run details not needed")
+ )
+ def test_run_endpoint_gates_inherited_agent_source(self, payload, _mock_detail, mock_workflow):
+ task = self.create_task()
+ previous_run = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, state={"run_source": "agent"}
+ )
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {**payload, "resume_from_run_id": str(previous_run.id)},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(task.runs.count(), 1)
+ mock_workflow.assert_not_called()
+
+ @patch(
+ "products.tasks.backend.temporal.client.execute_task_processing_workflow",
+ side_effect=RuntimeError("unavailable"),
+ )
+ def test_run_endpoint_returns_dispatch_error(self, _mock_workflow):
+ task = self.create_task()
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/", {}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["run_error"], "Failed to start task workflow.")
+ self.assertIsNotNone(response.json()["latest_run"])
+
+ @parameterized.expand([({"pr_base_branch": "main"},), ({"pr_base_branch": None},), ({},)])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_run_endpoint_rejects_different_resume_branch(self, base_state, mock_workflow):
+ task = self.create_task()
+ previous_run = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, state=base_state
+ )
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"resume_from_run_id": str(previous_run.id), "branch": "other"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(task.runs.count(), 1)
+ mock_workflow.assert_not_called()
+
+ @parameterized.expand([({"pr_base_branch": None}, "release"), ({"pr_base_branch": None}, None), ({}, "release")])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_resume_ignores_mutable_run_branch(self, base_state, stored_branch, mock_workflow):
+ task = self.create_task()
+ previous_run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ branch=stored_branch,
+ state={"branch": "release", **base_state},
+ )
+ payload = {"resume_from_run_id": str(previous_run.id)}
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/", payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn("run_error", response.json())
+ run = task.runs.exclude(id=previous_run.id).get()
+ self.assertIsNone(run.branch)
+ self.assertIsNone(run.state["pr_base_branch"])
+ mock_workflow.assert_called_once()
+
+ @parameterized.expand(
+ [
+ ("merge", {"state": {"run_source": "manual", "pr_base_branch": "other"}}, True),
+ ("remove", {"state_remove_keys": ["run_source", "pr_base_branch"]}, True),
+ ("append", {"state_append": {"run_source": ["manual"], "pr_base_branch": ["other"]}}, True),
+ ("empty_list", {"state": []}, False),
+ ("default_branch", {"branch": "other", "state": {"branch": "other"}}, True),
+ ]
+ )
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_sandbox_cannot_change_resume_source_or_branch(
+ self, _name, payload, valid, mock_workflow, _mock_internal, _mock_publish
+ ):
+ task = self.create_task()
+ base_branch = None if _name == "default_branch" else "release"
+ start_response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"run_source": "agent", **({"branch": base_branch} if base_branch is not None else {})},
+ format="json",
+ )
+ self.assertEqual(start_response.status_code, status.HTTP_200_OK)
+ run = task.runs.get()
+ self.assertEqual(run.state["pr_base_branch"], base_branch)
+ run.status = TaskRun.Status.IN_PROGRESS
+ run.save(update_fields=["status"])
+ client = self._sandbox_oauth_client(task.id, internal_scope=True)
+ response = client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/", payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK if valid else status.HTTP_400_BAD_REQUEST)
+ if not valid:
+ with self.assertRaisesRegex(ValueError, "Run state must be an object"):
+ tasks_facade.update_task_run(
+ run.id, task.id, self.team.id, validated_data=payload, caller_is_agent=True
+ )
+ run.refresh_from_db()
+ self.assertEqual(run.state["run_source"], "agent")
+ self.assertEqual(run.state["pr_base_branch"], base_branch)
+ run.status = TaskRun.Status.COMPLETED
+ run.save(update_fields=["status"])
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/", {"resume_from_run_id": str(run.id)}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ resumed_run = task.runs.exclude(id=run.id).get()
+ self.assertEqual(resumed_run.state["run_source"], "agent")
+ self.assertEqual(resumed_run.state["pr_base_branch"], base_branch)
+ self.assertEqual(resumed_run.branch, base_branch)
+ self.assertEqual(mock_workflow.call_args.kwargs["posthog_mcp_scopes"], "read_only")
+
+ @parameterized.expand(
+ [
+ ({"pending_user_artifact_ids": ["00000000-0000-4000-8000-000000000001"]},),
+ ({"runtime": "pi", "initial_permission_mode": "default"},),
+ ({"runtime": "pi", "runtime_adapter": "claude", "model": "claude-sonnet-4-6"},),
+ ({"sandbox_environment_id": "00000000-0000-4000-8000-000000000001"},),
+ ({"custom_image_id": "00000000-0000-4000-8000-000000000001"},),
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ def test_start_run_create_rejects_invalid_inputs_before_creation(self, payload, _mock_internal_team):
+ task_count = Task.objects.count()
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Do work", "start_run": True, **payload},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(Task.objects.count(), task_count)
+
+ @parameterized.expand(
+ [
+ (resource, restriction)
+ for resource in ("custom_image", "sandbox_environment")
+ for restriction in ("private", "other_team", "allowed")
+ ]
+ + [("custom_image", "not_ready")]
+ )
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_start_run_create_checks_resource_access_before_creation(
+ self, resource, restriction, mock_workflow, _mock_internal_team
+ ):
+ resource_team = (
+ Team.objects.create(organization=self.organization) if restriction == "other_team" else self.team
+ )
+ resource_model = SandboxCustomImage if resource == "custom_image" else SandboxEnvironment
+ resource_fields = {"team": resource_team, "name": "Run resource", "private": restriction == "private"}
+ if resource == "custom_image":
+ resource_fields["status"] = (
+ SandboxCustomImage.Status.DRAFT if restriction == "not_ready" else SandboxCustomImage.Status.READY
+ )
+ resource_fields["modal_image_name"] = "posthog-test-image:latest"
+ with team_scope(resource_team.id):
+ run_resource = resource_model.objects.create(**resource_fields)
+ task_count = Task.objects.count()
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"description": "Resource check", "start_run": True, f"{resource}_id": str(run_resource.id)},
+ format="json",
+ )
+
+ allowed = restriction == "allowed"
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED if allowed else status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(Task.objects.count(), task_count + int(allowed))
+ if allowed:
+ mock_workflow.assert_called_once()
+ else:
+ mock_workflow.assert_not_called()
+
+ def test_bootstrap_run_rejects_agent_source(self):
+ task = self.create_task()
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/",
+ {"environment": "cloud", "run_source": "agent"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(task.runs.exists())
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_sandbox_environment_id(self, mock_workflow):
task = self.create_task(created_by=self.user)
@@ -3383,7 +3914,10 @@ class TestTaskAPI(BaseTaskAPITest):
mock_workflow.assert_not_called()
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- def test_start_run_endpoint_triggers_workflow_for_existing_cloud_run(self, mock_workflow):
+ @patch(
+ "products.tasks.backend.facade.api.get_task_run_detail", side_effect=AssertionError("Run details not needed")
+ )
+ def test_start_run_endpoint_triggers_workflow_for_existing_cloud_run(self, _mock_detail, mock_workflow):
task = self.create_task()
task_run = task.create_run(environment=TaskRun.Environment.CLOUD)
task_run.artifacts = [
@@ -6006,27 +6540,51 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.COMPLETED)
self.assertIsNotNone(run.completed_at)
+ @parameterized.expand(
+ [
+ (None, False, False, status.HTTP_200_OK),
+ ("manual", False, False, status.HTTP_200_OK),
+ ("agent", True, True, status.HTTP_200_OK),
+ ("agent", False, True, status.HTTP_403_FORBIDDEN),
+ ("agent", True, False, status.HTTP_403_FORBIDDEN),
+ ]
+ )
@patch("products.tasks.backend.presentation.views.api.tasks_facade.pi_cloud_runtime_enabled", return_value=True)
@patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")
@patch("products.tasks.backend.facade.streams.reset_task_run_stream", return_value=True)
- def test_resume_in_cloud_starts_pi_task(self, mock_reset_stream, mock_resume, _mock_pi_enabled):
+ def test_resume_in_cloud_checks_agent_run_access(
+ self, run_source, flag_enabled, internal_team, expected_status, mock_reset_stream, mock_resume, _mock_pi_enabled
+ ):
+ self.mock_feature_flag.side_effect = lambda flag, *_args, **_kwargs: (
+ flag in {"tasks", "pi-harness"} or (flag == "tasks-mcp-agent-run-start" and flag_enabled)
+ )
task = self.create_task(runtime=Task.Runtime.PI)
+ run_state = {"pr_authorship_mode": "bot"}
+ if run_source is not None:
+ run_state["run_source"] = run_source
run = TaskRun.objects.create(
task=task,
team=self.team,
environment=TaskRun.Environment.CLOUD,
status=TaskRun.Status.COMPLETED,
- state={"pr_authorship_mode": "bot"},
+ state=run_state,
)
- response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/")
+ with patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=internal_team):
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, expected_status)
run.refresh_from_db()
self.assertEqual(run.environment, TaskRun.Environment.CLOUD)
- self.assertEqual(run.status, TaskRun.Status.QUEUED)
- mock_reset_stream.assert_called_once_with(str(run.id), use_dedicated=False)
- mock_resume.assert_called_once_with(str(run.id), run.workflow_id)
+ if expected_status == status.HTTP_200_OK:
+ self.assertEqual(run.status, TaskRun.Status.QUEUED)
+ mock_reset_stream.assert_called_once_with(str(run.id), use_dedicated=False)
+ mock_resume.assert_called_once_with(str(run.id), run.workflow_id)
+ else:
+ self.assertEqual(run.status, TaskRun.Status.COMPLETED)
+ self.assertEqual(run.state, run_state)
+ mock_reset_stream.assert_not_called()
+ mock_resume.assert_not_called()
@patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")
def test_resume_in_cloud_rejects_local_run(self, mock_resume):
@@ -13232,6 +13790,99 @@ class TestCloudUsageGate(BaseTaskAPITest):
status=status_value,
)
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ def test_start_run_report_discussion_rejects_unsupported_origin(self, _mock_internal_team):
+ from products.signals.backend.models import SignalReport
+
+ self._desktop_access_enabled = False
+ report = SignalReport.objects.create(team=self.team)
+ integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Blocked discussion",
+ "description": "Discuss the report",
+ "origin_product": "signal_report",
+ "signal_report": str(report.id),
+ "signal_report_task_relationship": "discussion",
+ "start_run": True,
+ "github_integration": integration.id,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ self.assertFalse(Task.objects.filter(title="Blocked discussion").exists())
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_start_run_create_without_code_access_creates_no_task(self, mock_gate, _mock_internal_team):
+ self.set_tasks_feature_flag(False)
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Blocked task", "description": "Run work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Task.objects.filter(title="Blocked task").exists())
+ mock_gate.assert_not_called()
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_start_run_signal_implementation_rejects_unsupported_origin(self, mock_gate, _mock_internal_team):
+ from products.signals.backend.models import SignalReport
+
+ self.set_tasks_feature_flag(False)
+ report = SignalReport.objects.create(team=self.team)
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Blocked task",
+ "description": "Run work",
+ "origin_product": "signal_report",
+ "signal_report": str(report.id),
+ "start_run": True,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Task.objects.filter(title="Blocked task").exists())
+ mock_gate.assert_not_called()
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_start_run_create_over_limit_creates_no_task(self, mock_gate, _mock_internal_team):
+ mock_gate.return_value = self.OVER_LIMIT
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {"title": "Blocked task", "description": "Run work", "start_run": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertFalse(Task.objects.filter(title="Blocked task").exists())
+
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.facade.api.pi_cloud_runtime_enabled", return_value=False)
+ def test_start_run_create_with_disabled_pi_runtime_creates_no_task(self, _mock_pi_enabled, _mock_internal_team):
+ response = self.client.post(
+ "/api/projects/@current/tasks/",
+ {
+ "title": "Blocked Pi task",
+ "description": "Run work",
+ "runtime": Task.Runtime.PI,
+ "start_run": True,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(Task.objects.filter(title="Blocked Pi task").exists())
+
@patch("products.tasks.backend.facade.api.warm_task_sandbox")
@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)
def test_warm_without_code_access_returns_403_before_provisioning(self, _mock_warm_enabled, mock_warm):
@@ -13360,39 +14011,23 @@ class TestCloudUsageGate(BaseTaskAPITest):
mock_gate.assert_not_called()
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
- @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None)
- def test_task_bound_internal_run_bypasses_access_for_its_own_task(self, _mock_gate, mock_workflow):
- self.set_tasks_feature_flag(False)
- task = self.create_task()
- client = self._sandbox_oauth_client(task.id, internal_scope=True)
-
- response = client.post(
- f"/api/projects/@current/tasks/{task.id}/run/",
- {"mode": "background"},
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertTrue(TaskRun.objects.filter(task=task).exists())
- mock_workflow.assert_called_once()
-
+ @parameterized.expand([True, False])
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
- def test_task_bound_internal_run_cannot_bypass_access_for_another_task(self, mock_gate, mock_workflow):
+ def test_task_bound_internal_run_cannot_start_cloud_run(self, same_task, mock_gate, mock_workflow):
self.set_tasks_feature_flag(False)
bound_task = self.create_task()
- other_task = self.create_task()
+ target_task = bound_task if same_task else self.create_task()
client = self._sandbox_oauth_client(bound_task.id, internal_scope=True)
response = client.post(
- f"/api/projects/@current/tasks/{other_task.id}/run/",
+ f"/api/projects/@current/tasks/{target_task.id}/run/",
{"mode": "background"},
format="json",
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertFalse(TaskRun.objects.filter(task=other_task).exists())
+ self.assertFalse(TaskRun.objects.filter(task=target_task).exists())
mock_gate.assert_not_called()
mock_workflow.assert_not_called()
diff --git a/products/tasks/backend/tests/test_client_provenance.py b/products/tasks/backend/tests/test_client_provenance.py
index 80e9d3c96199..e025552cf937 100644
--- a/products/tasks/backend/tests/test_client_provenance.py
+++ b/products/tasks/backend/tests/test_client_provenance.py
@@ -5,6 +5,7 @@ from parameterized import parameterized
from rest_framework.request import Request
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER, is_sandbox_oauth_request, is_sandbox_origin_request
from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
POSTHOG_DESKTOP_MOBILE_APP_CLIENT_ID_EU,
@@ -99,3 +100,9 @@ class TestTaskClientProvenance:
def test_missing_authentication_provenance_fails_closed(self) -> None:
assert get_task_client_provenance(cast(Request, SimpleNamespace())) is None
+
+ def test_forwarded_sandbox_origin_does_not_grant_sandbox_identity(self) -> None:
+ request = cast(Request, SimpleNamespace(headers={SANDBOX_ORIGIN_HEADER: "1"}))
+
+ assert is_sandbox_origin_request(request)
+ assert not is_sandbox_oauth_request(request)
diff --git a/products/tasks/backend/tests/test_constants.py b/products/tasks/backend/tests/test_constants.py
index 9ece85972ef0..2ae07ac688c6 100644
--- a/products/tasks/backend/tests/test_constants.py
+++ b/products/tasks/backend/tests/test_constants.py
@@ -1,10 +1,15 @@
import re
+from pathlib import Path
from django.conf import settings
+import yaml
+
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX
from products.tasks.backend.presentation.serializers import TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES
+TASKS_MCP_CONFIG = Path(__file__).resolve().parents[3] / "tasks" / "mcp" / "tools.yaml"
+
def test_exec_permission_regex_only_matches_connected_project_tools():
pattern = re.compile(POSTHOG_EXEC_PERMISSION_REGEX, re.IGNORECASE)
@@ -21,3 +26,13 @@ def test_inline_artifact_ceiling_stays_reachable_through_the_request_body_limit(
largest_encoded_body = TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES * 4 // 3
assert largest_encoded_body < settings.DATA_UPLOAD_MAX_MEMORY_SIZE
+
+
+def test_task_mcp_tools_can_start_runs():
+ tools = yaml.safe_load(TASKS_MCP_CONFIG.read_text())["tools"]
+
+ assert not {"start_run", "branch"}.intersection(tools["tasks-create"]["include_params"])
+ assert tools["tasks-create-and-run"]["input_schema"] == "TaskAgentCreateSchema"
+ assert tools["tasks-create-and-run"]["feature_flag"] == tools["tasks-run-create"]["feature_flag"]
+ assert tools["tasks-run-create"]["enabled"] is True
+ assert tools["tasks-run-create"]["input_schema"] == "TaskAgentRunCreateSchema"
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index c686021fd42f..aa8784d1f6f2 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -713,7 +713,7 @@ class TestFacadeReadsAndMappers(TestCase):
},
)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -740,7 +740,7 @@ class TestFacadeReadsAndMappers(TestCase):
status=TaskRun.Status.COMPLETED,
)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -784,7 +784,7 @@ class TestFacadeReadsAndMappers(TestCase):
state={"custom_image_id": str(image.id)},
)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -814,7 +814,7 @@ class TestFacadeReadsAndMappers(TestCase):
state={"self_driving_head_branch": "posthog-self-driving/fix-abc123"},
)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -841,7 +841,7 @@ class TestFacadeReadsAndMappers(TestCase):
state={"ai_stage": "implementation"},
)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -872,7 +872,7 @@ class TestFacadeReadsAndMappers(TestCase):
SignalTeamConfig.objects.update_or_create(team=self.team, defaults={"autostart_base_branches": overrides})
task = self._make_task(repository="Acme/Web", origin_product=Task.OriginProduct.SIGNAL_REPORT)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -893,7 +893,7 @@ class TestFacadeReadsAndMappers(TestCase):
)
task = self._make_task(repository="Acme/Web", origin_product=Task.OriginProduct.USER_CREATED)
- with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):
+ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None):
result = facade.run_task(
task.id,
self.team.id,
@@ -2045,7 +2045,7 @@ class TestSelfDrivingFreeTrialFacadeGates(TestCase):
with (
self._on_trial(),
patch("products.signals.backend.free_trial.capture_signal_report_free_trial_paused") as capture_mock,
- patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"),
+ patch("products.tasks.backend.facade.api._trigger_task_processing_workflow", return_value=None),
):
if expect_refusal:
with self.assertRaises(FreeTrialPullRequestRefused) as raised:
diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.py
index 5781e5ed3b77..a4eedecaf4bc 100644
--- a/products/tasks/backend/tests/test_presentation_serializers.py
+++ b/products/tasks/backend/tests/test_presentation_serializers.py
@@ -20,6 +20,7 @@ from products.tasks.backend.presentation.serializers import (
TaskRunCommandRequestSerializer,
TaskRunCreateRequestSerializer,
TaskRunLivingArtifactCreateRequestSerializer,
+ TaskRunUpdateSerializer,
TaskWriteSerializer,
)
@@ -93,6 +94,12 @@ class TestTaskRunLivingArtifactCreateRequestSerializer(SimpleTestCase):
class TestTaskRunCreateRequestSerializer(SimpleTestCase):
+ @parameterized.expand([([],), ([["run_source", "manual"]],), (None,), ("manual",), (1,), (False,)])
+ def test_rejects_non_object_run_state(self, state):
+ serializer = TaskRunUpdateSerializer(data={"state": state})
+ assert not serializer.is_valid()
+ assert "state" in serializer.errors
+
@parameterized.expand(
[
(TaskRunCreateRequestSerializer, True),
@@ -142,8 +149,8 @@ class TestTaskRunCreateRequestSerializer(SimpleTestCase):
)
with patch.object(
tasks_facade,
- "get_task_run_detail",
- return_value=SimpleNamespace(state={"claude_model_access": "own-subscription"}),
+ "get_task_run_claude_model_access",
+ return_value="own-subscription",
):
assert serializer.is_valid() is (not sandbox and not resume), serializer.errors
if sandbox or resume:
diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.py
index 7481fcfb1802..303772ca57d8 100644
--- a/products/tasks/backend/tests/test_task_run_metrics.py
+++ b/products/tasks/backend/tests/test_task_run_metrics.py
@@ -154,7 +154,7 @@ class TestTaskRunMetrics(TestCase):
before = _sample_value("posthog_tasks_prewarmed_activated_total", labels)
with patch.object(facade, "signal_task_run_user_message", return_value=True):
- facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", branch=None, artifact_ids=[])
assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before + 1
@@ -181,7 +181,7 @@ class TestTaskRunMetrics(TestCase):
patch.object(facade, "signal_task_run_user_message", side_effect=_terminalize_during_signal),
self.assertRaises(facade.WarmRunActivationUnavailable),
):
- facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", branch=None, artifact_ids=[])
assert _sample_value("posthog_tasks_prewarmed_unused_total", labels) == before + 1
assert _sample_value("posthog_tasks_prewarmed_activated_total", activation_labels) == activated_before
@@ -223,7 +223,7 @@ class TestTaskRunMetrics(TestCase):
before = _sample_value("posthog_tasks_prewarmed_activated_total", labels)
with patch.object(facade, "signal_task_run_user_message", return_value=True):
- facade._activate_warm_run(run, self.task, self.team.id, message="go", artifact_ids=[])
+ facade._activate_warm_run(run, self.task, self.team.id, message="go", branch=None, artifact_ids=[])
assert _sample_value("posthog_tasks_prewarmed_activated_total", labels) == before
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index b840f585dbe0..54f44bf6729d 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -434,7 +434,7 @@ class TestRedispatchOrphanedTaskRun(TestCase):
WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
)
- @parameterized.expand([(None, "full"), ("manual", "full"), ("signal_report", "full")])
+ @parameterized.expand([(None, "full"), ("manual", "full"), ("signal_report", "full"), ("agent", "read_only")])
def test_falls_back_to_run_source_scopes_when_dispatch_params_absent(
self, run_source: str | None, expected_scopes: str
) -> None:
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 290bda274b7d..a29ca670165b 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -886,6 +886,7 @@ class TestCreateTaskWarmReuse(APIBaseTest):
assert str(dto.id) == str(warm_task.id)
run.refresh_from_db()
assert "await_user_message" not in run.state
+ assert run.state["pr_base_branch"] == "main"
def test_does_not_reuse_warm_task_from_a_different_github_integration(self):
warm_task, _ = self._warm_run()
@@ -912,6 +913,7 @@ class TestCreateTaskWarmReuse(APIBaseTest):
assert str(dto.id) == str(warm_task.id)
run.refresh_from_db()
assert "await_user_message" not in run.state
+ assert run.state["pr_base_branch"] is None
def test_create_endpoint_returns_structured_compute_quota_denial_before_warm_activation(self):
warm_task, run = self._warm_run()
@@ -1265,7 +1267,8 @@ class TestWarmRunRelease(APIBaseTest):
class TestWarmTaskResumeSandbox(APIBaseTest):
- def test_warms_and_activates_a_successor_for_the_latest_terminal_run(self):
+ @parameterized.expand(["release", None])
+ def test_warms_and_activates_a_successor_for_the_latest_terminal_run(self, base_branch):
task = Task.objects.create(
team=self.team,
title="",
@@ -1275,10 +1278,10 @@ class TestWarmTaskResumeSandbox(APIBaseTest):
)
terminal = task.create_run(
mode="interactive",
- branch="main",
+ branch="release",
extra_state={
"snapshot_external_id": "snapshot-1",
- "pr_base_branch": "main",
+ "pr_base_branch": base_branch,
"auto_publish": True,
"runtime_adapter": "claude",
"model": "claude-sonnet-5",
@@ -1306,6 +1309,8 @@ class TestWarmTaskResumeSandbox(APIBaseTest):
assert warmed is not None
warm_run = TaskRun.objects.get(id=warmed.run_id)
+ assert warm_run.branch == base_branch
+ assert warm_run.state["pr_base_branch"] == base_branch
assert warm_run.state["resume_from_run_id"] == str(terminal.id)
assert warm_run.state["snapshot_external_id"] == "snapshot-1"
assert warm_run.state["await_user_message"] is True
@@ -1335,6 +1340,7 @@ class TestWarmTaskResumeSandbox(APIBaseTest):
signal.assert_called_once()
warm_run.refresh_from_db()
assert "await_user_message" not in warm_run.state
+ assert warm_run.state["pr_base_branch"] == base_branch
def _terminal_run(self, task: Task) -> TaskRun:
terminal = task.create_run(
@@ -1393,6 +1399,21 @@ class TestWarmTaskResumeSandbox(APIBaseTest):
# The replacement resumes from the original terminal run, not from the successor handed back.
assert TaskRun.objects.get(id=second.run_id).state["resume_from_run_id"] == str(terminal.id)
+ def test_does_not_warm_an_agent_resume_source(self):
+ task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ created_by=self.user,
+ )
+ terminal = self._terminal_run(task)
+ terminal.state = {**terminal.state, "run_source": "agent"}
+ terminal.save(update_fields=["state"])
+
+ assert self._warm_resume(task, terminal) is None
+ assert task.runs.count() == 1
+
def test_does_not_warm_from_a_source_the_task_has_moved_past(self):
# The relaxation above must not become a wildcard: a terminal run that is not a released
# successor of the named source still means the task moved on.
@@ -1542,7 +1563,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
task, run = self._warm_run(branch="main")
with (
patch(f"{FACADE}.signal_task_run_user_message") as m_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as m_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as m_trigger,
):
facade.run_task(
task.id,
@@ -1557,6 +1578,34 @@ class TestRunTaskWarmActivation(APIBaseTest):
run.refresh_from_db()
assert run.state.get("await_user_message") is True # warm run untouched
+ def test_agent_run_does_not_activate_warm_run(self):
+ task, run = self._warm_run(branch="main")
+ 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,
+ ):
+ result = facade.run_task(
+ task.id,
+ self.team.id,
+ self.user.id,
+ validated_data={
+ "mode": "background",
+ "branch": "main",
+ "run_source": "agent",
+ "pending_user_message": "do it",
+ },
+ )
+
+ assert result is not None and result.error is None
+ mock_signal.assert_not_called()
+ mock_trigger.assert_called_once()
+ assert task.runs.count() == 2
+ run.refresh_from_db()
+ assert run.state.get("await_user_message") is True
+ agent_run = task.runs.exclude(id=run.id).get()
+ assert agent_run.state["mode"] == "background"
+ assert agent_run.state["run_source"] == "agent"
+
def test_resume_successor_is_not_activated_for_a_run_that_asks_for_no_resume(self):
# A successor's filesystem was restored from the run it resumes, so handing it to a request
# that named no resume source would silently start "fresh" work on inherited state.
@@ -1574,7 +1623,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
)
with (
patch(f"{FACADE}.signal_task_run_user_message") as m_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as m_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as m_trigger,
):
facade.run_task(
task.id,
@@ -1605,7 +1654,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
with (
patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as mock_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as mock_trigger,
):
facade.run_task(
task.id,
@@ -1629,7 +1678,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
task, run = self._warm_run()
with (
patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as mock_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as mock_trigger,
):
facade.run_task(
task.id,
@@ -1652,7 +1701,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
task, run = self._warm_run()
with (
patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as mock_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as mock_trigger,
):
facade.run_task(
task.id,
@@ -1705,7 +1754,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
with (
patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,
- patch(f"{FACADE}._trigger_task_processing_workflow") as mock_trigger,
+ patch(f"{FACADE}._trigger_task_processing_workflow", return_value=None) as mock_trigger,
):
result = facade.run_task(
task.id,
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 35bd005104b2..9a26bc7870f0 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2003,22 +2003,22 @@ export interface TaskCreateApi {
*/
ci_prompt?: string | null
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnumApi | null
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -2027,7 +2027,7 @@ export interface TaskCreateApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -2038,17 +2038,17 @@ export interface TaskCreateApi {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[]
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null
@@ -2057,6 +2057,8 @@ export interface TaskCreateApi {
* @nullable
*/
channel?: string | null
+ /** Start the task's first cloud run immediately after creation. */
+ start_run?: boolean
/**
* Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task.
* @maxLength 4000
@@ -2065,12 +2067,12 @@ export interface TaskCreateApi {
/** Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted. */
naming_source?: string
/**
- * Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.
+ * Sandbox environment for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.
* @nullable
*/
sandbox_environment_id?: string | null
/**
- * Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.
+ * Custom image for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.
* @nullable
*/
custom_image_id?: string | null
@@ -2081,6 +2083,70 @@ export interface TaskCreateApi {
runtime?: TaskRuntimeEnumApi
}
+/**
+ * @nullable
+ */
+export type TaskCreateResponseDTOApiJsonSchema = { [key: string]: unknown } | null
+
+/**
+ * Detail response for a task.
+ *
+ * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /
+ * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and
+ * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.
+ */
+export interface TaskCreateResponseDTOApi {
+ id: string
+ /** @nullable */
+ task_number: number | null
+ slug: string
+ title: string
+ title_manually_set: boolean
+ description: string
+ origin_product: string
+ /** Agent protocol and harness used for this task's runs.
+ *
+ * * `acp` - ACP
+ * * `pi` - Pi */
+ runtime: TaskRuntimeEnumApi
+ /** @nullable */
+ repository: string | null
+ repositories: string[]
+ /** @nullable */
+ github_integration: number | null
+ /** @nullable */
+ github_user_integration: string | null
+ /** @nullable */
+ signal_report: string | null
+ /** @nullable */
+ json_schema: TaskCreateResponseDTOApiJsonSchema
+ internal: boolean
+ archived: boolean
+ /** @nullable */
+ archived_at: string | null
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTOApi | null
+ /** @nullable */
+ created_at?: string | null
+ /** @nullable */
+ updated_at?: string | null
+ /** @nullable */
+ last_activity_at?: string | null
+ created_by?: TaskUserBasicInfoApi | null
+ /** @nullable */
+ ci_prompt: string | null
+ /** @nullable */
+ channel?: string | null
+ readonly slack_thread_references: readonly SlackThreadReferenceDTOApi[]
+ /**
+ * Stable key of the server-side flow that created this task, e.g. `desktop_onboarding_session:<user_id>`. Null for tasks people create themselves.
+ * @nullable
+ */
+ origin_key?: string | null
+ /** Error returned when the task was created but its first run could not start. */
+ run_error?: string
+}
+
export interface TaskWriteApi {
/**
* Short human-readable title. Auto-generated from `description` when omitted.
@@ -2157,22 +2223,22 @@ export interface TaskWriteApi {
*/
ci_prompt?: string | null
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnumApi | null
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -2181,7 +2247,7 @@ export interface TaskWriteApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -2192,17 +2258,17 @@ export interface TaskWriteApi {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[]
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null
@@ -2289,22 +2355,22 @@ export interface PatchedTaskWriteApi {
*/
ci_prompt?: string | null
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnumApi | null
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -2313,7 +2379,7 @@ export interface PatchedTaskWriteApi {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnumApi | null
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -2324,17 +2390,17 @@ export interface PatchedTaskWriteApi {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi | null
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[]
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null
@@ -2566,6 +2632,17 @@ export interface RelayedMcpServerApi {
name: string
}
+/**
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription
+ */
+export type ClaudeModelAccessEnumApi = (typeof ClaudeModelAccessEnumApi)[keyof typeof ClaudeModelAccessEnumApi]
+
+export const ClaudeModelAccessEnumApi = {
+ PosthogGateway: 'posthog-gateway',
+ OwnSubscription: 'own-subscription',
+} as const
+
/**
* * `interactive` - interactive
* * `background` - background
@@ -2591,12 +2668,14 @@ export const PrAuthorshipModeEnumApi = {
/**
* * `manual` - manual
* * `signal_report` - signal_report
+ * * `agent` - agent
*/
export type RunSourceEnumApi = (typeof RunSourceEnumApi)[keyof typeof RunSourceEnumApi]
export const RunSourceEnumApi = {
Manual: 'manual',
SignalReport: 'signal_report',
+ Agent: 'agent',
} as const
/**
@@ -2637,17 +2716,6 @@ export const InitialPermissionModeEnumApi = {
Auto: 'auto',
} as const
-/**
- * * `posthog-gateway` - posthog-gateway
- * * `own-subscription` - own-subscription
- */
-export type ClaudeModelAccessEnumApi = (typeof ClaudeModelAccessEnumApi)[keyof typeof ClaudeModelAccessEnumApi]
-
-export const ClaudeModelAccessEnumApi = {
- PosthogGateway: 'posthog-gateway',
- OwnSubscription: 'own-subscription',
-} as const
-
/**
* Request body for creating a new task run
*/
@@ -2662,6 +2730,21 @@ export interface ClaudeTaskRunCreateSchemaApi {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServerApi[] | null
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -2699,7 +2782,8 @@ export interface ClaudeTaskRunCreateSchemaApi {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnumApi
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string
@@ -2738,21 +2822,6 @@ export interface ClaudeTaskRunCreateSchemaApi {
* * `bypassPermissions` - bypassPermissions
* * `auto` - auto */
initial_permission_mode?: InitialPermissionModeEnumApi
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnumApi | null
}
/**
@@ -2794,6 +2863,21 @@ export interface CodexTaskRunCreateSchemaApi {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServerApi[] | null
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -2831,7 +2915,8 @@ export interface CodexTaskRunCreateSchemaApi {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnumApi
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string
@@ -2869,21 +2954,6 @@ export interface CodexTaskRunCreateSchemaApi {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: CodexTaskRunCreateSchemaInitialPermissionModeEnumApi
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnumApi | null
}
export interface TaskRunResumeRequestSchemaApi {
@@ -2914,7 +2984,8 @@ export interface TaskRunResumeRequestSchemaApi {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnumApi
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string
@@ -2927,6 +2998,70 @@ export type TaskRunCreateRequestSchemaApi =
| CodexTaskRunCreateSchemaApi
| TaskRunResumeRequestSchemaApi
+/**
+ * @nullable
+ */
+export type TaskRunResponseApiJsonSchema = { [key: string]: unknown } | null
+
+/**
+ * Detail response for a task.
+ *
+ * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /
+ * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and
+ * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.
+ */
+export interface TaskRunResponseApi {
+ id: string
+ /** @nullable */
+ task_number: number | null
+ slug: string
+ title: string
+ title_manually_set: boolean
+ description: string
+ origin_product: string
+ /** Agent protocol and harness used for this task's runs.
+ *
+ * * `acp` - ACP
+ * * `pi` - Pi */
+ runtime: TaskRuntimeEnumApi
+ /** @nullable */
+ repository: string | null
+ repositories: string[]
+ /** @nullable */
+ github_integration: number | null
+ /** @nullable */
+ github_user_integration: string | null
+ /** @nullable */
+ signal_report: string | null
+ /** @nullable */
+ json_schema: TaskRunResponseApiJsonSchema
+ internal: boolean
+ archived: boolean
+ /** @nullable */
+ archived_at: string | null
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTOApi | null
+ /** @nullable */
+ created_at?: string | null
+ /** @nullable */
+ updated_at?: string | null
+ /** @nullable */
+ last_activity_at?: string | null
+ created_by?: TaskUserBasicInfoApi | null
+ /** @nullable */
+ ci_prompt: string | null
+ /** @nullable */
+ channel?: string | null
+ readonly slack_thread_references: readonly SlackThreadReferenceDTOApi[]
+ /**
+ * Stable key of the server-side flow that created this task, e.g. `desktop_onboarding_session:<user_id>`. Null for tasks people create themselves.
+ * @nullable
+ */
+ origin_key?: string | null
+ /** Error returned when the run could not start. */
+ run_error?: string
+}
+
/**
* * `plan` - plan
* * `context` - context
@@ -3153,6 +3288,18 @@ export const RunEnvironmentEnumApi = {
Cloud: 'cloud',
} as const
+/**
+ * * `manual` - manual
+ * * `signal_report` - signal_report
+ */
+export type TaskBootstrapRunSourceEnumApi =
+ (typeof TaskBootstrapRunSourceEnumApi)[keyof typeof TaskBootstrapRunSourceEnumApi]
+
+export const TaskBootstrapRunSourceEnumApi = {
+ Manual: 'manual',
+ SignalReport: 'signal_report',
+} as const
+
/**
* Request body for creating a task run without starting execution yet.
*/
@@ -3167,6 +3314,21 @@ export interface TaskRunBootstrapCreateRequestApi {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServerApi[] | null
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
/** Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.
*
* * `local` - local
@@ -3201,7 +3363,7 @@ export interface TaskRunBootstrapCreateRequestApi {
*
* * `manual` - manual
* * `signal_report` - signal_report */
- run_source?: RunSourceEnumApi
+ run_source?: TaskBootstrapRunSourceEnumApi
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string
/** Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.
@@ -3244,23 +3406,13 @@ export interface TaskRunBootstrapCreateRequestApi {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnumApi | null
}
+/**
+ * State of the run
+ */
+export type PatchedTaskRunUpdateApiState = { [key: string]: unknown }
+
/**
* State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race.
*/
@@ -3308,7 +3460,7 @@ export interface PatchedTaskRunUpdateApi {
/** Output from the run */
output?: unknown
/** State of the run */
- state?: unknown
+ state?: PatchedTaskRunUpdateApiState
/** State keys to remove atomically before applying any state updates. */
state_remove_keys?: string[]
/** State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race. */
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 7e8b4f7b421a..3376a1a53908 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -82,6 +82,7 @@ import type {
TaskCommentDetailApi,
TaskCommentsResponseApi,
TaskCreateApi,
+ TaskCreateResponseDTOApi,
TaskDetailDTOApi,
TaskHandoffRequestApi,
TaskMentionsListParams,
@@ -123,6 +124,7 @@ import type {
TaskRunPostHogReferencesResponseApi,
TaskRunRelayMessageRequestApi,
TaskRunRelayMessageResponseApi,
+ TaskRunResponseApi,
TaskRunStartRequestApi,
TaskSearchResultApi,
TaskSessionResponseApi,
@@ -1304,8 +1306,8 @@ export const tasksCreate = async (
projectId: string,
taskCreateApi?: TaskCreateApi,
options?: RequestInit
-): Promise<TaskDetailDTOApi> => {
- return apiMutator<TaskDetailDTOApi>(getTasksCreateUrl(projectId), {
+): Promise<TaskCreateResponseDTOApi> => {
+ return apiMutator<TaskCreateResponseDTOApi>(getTasksCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -1567,8 +1569,8 @@ export const tasksRunCreate = async (
id: string,
taskRunCreateRequestSchemaApi?: TaskRunCreateRequestSchemaApi,
options?: RequestInit
-): Promise<TaskDetailDTOApi> => {
- return apiMutator<TaskDetailDTOApi>(getTasksRunCreateUrl(projectId, id), {
+): Promise<TaskRunResponseApi> => {
+ return apiMutator<TaskRunResponseApi>(getTasksRunCreateUrl(projectId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index cba338c4cb03..3d7304768209 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1170,6 +1170,7 @@ export const tasksCreateBodyBranchMax = 255
export const tasksCreateBodyPendingUserArtifactIdsItemMax = 128
+export const tasksCreateBodyStartRunDefault = false
export const tasksCreateBodySignalReportDiscussionQuestionMax = 4000
export const TasksCreateBody = /* @__PURE__ */ zod.object({
@@ -1248,20 +1249,18 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
.max(tasksCreateBodyBranchMax)
.nullish()
.describe(
- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ "Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task."
),
runtime_adapter: zod
.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
.optional()
.describe(
- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"
+ "Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.\n\n\* `claude` - claude\n\* `codex` - codex"
),
model: zod
.string()
.nullish()
- .describe(
- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'
- ),
+ .describe('LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.'),
reasoning_effort: zod
.union([
zod
@@ -1273,7 +1272,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ 'Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
initial_permission_mode: zod
.union([
@@ -1286,27 +1285,31 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ 'Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
),
pending_user_message: zod
.string()
.nullish()
.describe(
- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'
+ 'First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
pending_user_artifact_ids: zod
.array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))
.optional()
.describe(
- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."
+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true."
),
auto_publish: zod
.boolean()
.nullish()
.describe(
- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
+ 'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ start_run: zod
+ .boolean()
+ .default(tasksCreateBodyStartRunDefault)
+ .describe("Start the task's first cloud run immediately after creation."),
signal_report_discussion_question: zod
.string()
.max(tasksCreateBodySignalReportDiscussionQuestionMax)
@@ -1323,11 +1326,15 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
sandbox_environment_id: zod
.uuid()
.nullish()
- .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),
+ .describe(
+ 'Sandbox environment for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.'
+ ),
custom_image_id: zod
.uuid()
.nullish()
- .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),
+ .describe(
+ 'Custom image for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.'
+ ),
runtime: zod
.enum(['acp', 'pi'])
.describe('\* `acp` - ACP\n\* `pi` - Pi')
@@ -1430,20 +1437,18 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
.max(tasksUpdateBodyBranchMax)
.nullish()
.describe(
- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ "Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task."
),
runtime_adapter: zod
.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
.optional()
.describe(
- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"
+ "Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.\n\n\* `claude` - claude\n\* `codex` - codex"
),
model: zod
.string()
.nullish()
- .describe(
- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'
- ),
+ .describe('LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.'),
reasoning_effort: zod
.union([
zod
@@ -1455,7 +1460,7 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ 'Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
initial_permission_mode: zod
.union([
@@ -1468,25 +1473,25 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ 'Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
),
pending_user_message: zod
.string()
.nullish()
.describe(
- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'
+ 'First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
pending_user_artifact_ids: zod
.array(zod.string().max(tasksUpdateBodyPendingUserArtifactIdsItemMax))
.optional()
.describe(
- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."
+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true."
),
auto_publish: zod
.boolean()
.nullish()
.describe(
- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
+ 'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
})
@@ -1584,20 +1589,18 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(tasksPartialUpdateBodyBranchMax)
.nullish()
.describe(
- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ "Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task."
),
runtime_adapter: zod
.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
.optional()
.describe(
- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"
+ "Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.\n\n\* `claude` - claude\n\* `codex` - codex"
),
model: zod
.string()
.nullish()
- .describe(
- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'
- ),
+ .describe('LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.'),
reasoning_effort: zod
.union([
zod
@@ -1609,7 +1612,7 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ 'Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
initial_permission_mode: zod
.union([
@@ -1622,25 +1625,25 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ 'Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
),
pending_user_message: zod
.string()
.nullish()
.describe(
- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'
+ 'First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
pending_user_artifact_ids: zod
.array(zod.string().max(tasksPartialUpdateBodyPendingUserArtifactIdsItemMax))
.optional()
.describe(
- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."
+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true."
),
auto_publish: zod
.boolean()
.nullish()
.describe(
- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
+ 'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
})
@@ -1764,6 +1767,29 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Names of desktop-only MCP servers the creating client (PostHog Desktop) relays into the cloud sandbox over the durable event\/command channel. Names only — the server configuration (command, env, URL, headers) never crosses the wire.'
),
+ rtk_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
+ ),
+ benjamin_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
+ ),
+ claude_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 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. 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"
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -1812,11 +1838,11 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
'When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask.'
),
run_source: zod
- .enum(['manual', 'signal_report'])
- .describe('\* `manual` - manual\n\* `signal_report` - signal_report')
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
.optional()
.describe(
- 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report'
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
),
signal_report_id: zod
.string()
@@ -1861,29 +1887,6 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Initial permission mode for Claude runtimes.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto'
),
- rtk_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
- ),
- benjamin_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
- ),
- claude_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 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. 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"
- ),
})
.describe('Request body for creating a new task run'),
zod
@@ -1928,6 +1931,29 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Names of desktop-only MCP servers the creating client (PostHog Desktop) relays into the cloud sandbox over the durable event\/command channel. Names only — the server configuration (command, env, URL, headers) never crosses the wire.'
),
+ rtk_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
+ ),
+ benjamin_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
+ ),
+ claude_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 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. 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"
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -1976,11 +2002,11 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
'When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask.'
),
run_source: zod
- .enum(['manual', 'signal_report'])
- .describe('\* `manual` - manual\n\* `signal_report` - signal_report')
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
.optional()
.describe(
- 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report'
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
),
signal_report_id: zod
.string()
@@ -2025,29 +2051,6 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Initial permission mode for Codex runtimes.\n\n\* `plan` - plan\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
),
- rtk_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
- ),
- benjamin_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
- ),
- claude_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 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. 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"
- ),
})
.describe('Request body for creating a new task run'),
zod.object({
@@ -2089,11 +2092,11 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
'Whether pull requests for this run should be authored by the user or the bot.\n\n\* `user` - user\n\* `bot` - bot'
),
run_source: zod
- .enum(['manual', 'signal_report'])
- .describe('\* `manual` - manual\n\* `signal_report` - signal_report')
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
.optional()
.describe(
- 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report'
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
),
signal_report_id: zod
.string()
@@ -2392,6 +2395,29 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod
.describe(
'Names of desktop-only MCP servers the creating client (PostHog Desktop) relays into the cloud sandbox over the durable event\/command channel. Names only — the server configuration (command, env, URL, headers) never crosses the wire.'
),
+ rtk_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
+ ),
+ benjamin_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
+ ),
+ claude_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 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. 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')
@@ -2481,29 +2507,6 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod
.describe(
"Initial permission mode for the agent session. Claude runtimes accept PostHog permission presets like 'plan'. Codex runtimes accept native Codex modes like 'plan', 'auto', and 'read-only'.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access"
),
- rtk_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
- ),
- benjamin_enabled: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
- ),
- claude_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 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. 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"
- ),
})
.describe('Request body for creating a task run without starting execution yet.')
@@ -2524,7 +2527,7 @@ export const TasksRunsPartialUpdateBody = /* @__PURE__ */ zod.object({
branch: zod.string().nullish().describe('Git branch name to associate with the task'),
stage: zod.string().nullish().describe('Current stage of the run (e.g. research, plan, build)'),
output: zod.unknown().optional().describe('Output from the run'),
- state: zod.unknown().optional().describe('State of the run'),
+ state: zod.record(zod.string(), zod.unknown()).optional().describe('State of the run'),
state_remove_keys: zod
.array(zod.string())
.optional()
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 7c3d3fc08ee9..181907ccb3ae 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -435,12 +435,9 @@ tools:
enrich_url: '{id}'
title: Create task
description: >
- Create an agent task in the current project — a unit of work an AI agent picks up and actions, such as
- investigating an inbox report, fixing an error, or opening a pull request. `description` is the prompt
- handed to the agent, so make it specific and actionable. Pass `repository` in `organization/repo` format for
- code tasks so the agent knows where to work; omit it for investigation-only tasks. This creates the task
- record only — it does not start the agent. Returns the created task including its URL; open that URL to
- start the run. Requires the calling token's organization to have Tasks access enabled.
+ Create a task without starting a run. Set `description` to the agent's instructions. For code tasks, set
+ `repository` to `organization/repo`. A person can start the task at the returned URL. Use
+ `tasks-create-and-run` to start a run immediately when that tool is available.
include_params:
- title
- description
@@ -462,8 +459,41 @@ tools:
- origin_product
- repository
- internal
+ - latest_run.id
+ - latest_run.stage
+ - latest_run.status
+ - run_error
- created_at
- updated_at
+ tasks-create-and-run:
+ operation: tasks_create
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ input_schema: TaskAgentCreateSchema
+ enrich_url: '{id}'
+ title: Create task and start run
+ description: >
+ Create a task and start its first background run. Set `description` to the agent's instructions. For code
+ tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error`
+ if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is
+ lost, search for the task before you retry. A repeated call can create another task.
+ feature_flag: tasks-mcp-agent-run-start
+ response:
+ include:
+ - id
+ - task_number
+ - title
+ - description
+ - repository
+ - latest_run.id
+ - latest_run.stage
+ - latest_run.status
+ - run_error
tasks-destroy:
operation: tasks_destroy
enabled: false
@@ -612,7 +642,33 @@ tools:
- latest_run.state.sandbox_url
tasks-run-create:
operation: tasks_run_create
- enabled: false
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ input_schema: TaskAgentRunCreateSchema
+ enrich_url: '{id}'
+ title: Start task run
+ description: >
+ Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and
+ `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress.
+ Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated
+ call can start another run.
+ feature_flag: tasks-mcp-agent-run-start
+ response:
+ include:
+ - run_error
+ - id
+ - task_number
+ - title
+ - description
+ - repository
+ - latest_run.id
+ - latest_run.stage
+ - latest_run.status
tasks-runs-analysis-activity-create:
operation: tasks_runs_analysis_activity_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a842233dad84..a7e4acf9cb56 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11378,7 +11378,7 @@
"feature_flag": "tasks"
},
"tasks-create": {
- "description": "Create an agent task in the current project — a unit of work an AI agent picks up and actions, such as investigating an inbox report, fixing an error, or opening a pull request. `description` is the prompt handed to the agent, so make it specific and actionable. Pass `repository` in `organization/repo` format for code tasks so the agent knows where to work; omit it for investigation-only tasks. This creates the task record only — it does not start the agent. Returns the created task including its URL; open that URL to start the run. Requires the calling token's organization to have Tasks access enabled.",
+ "description": "Create a task without starting a run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. A person can start the task at the returned URL. Use `tasks-create-and-run` to start a run immediately when that tool is available.",
"category": "Tasks",
"feature": "tasks",
"summary": "Create task",
@@ -11392,6 +11392,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-create-and-run": {
+ "description": "Create a task and start its first background run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Create task and start run",
+ "title": "Create task and start run",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks-mcp-agent-run-start"
+ },
"tasks-list": {
"description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled.",
"category": "Tasks",
@@ -11467,6 +11482,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-run-create": {
+ "description": "Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Start task run",
+ "title": "Start task run",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks-mcp-agent-run-start"
+ },
"tasks-runs-list": {
"description": "List all runs for a specific task. Returns lightweight run metadata only — call tasks-runs-retrieve for full run detail including state, output, and artifacts.",
"category": "Tasks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c88a98b56ffb..fa0b67a0f24d 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -12023,7 +12023,7 @@
"feature_flag": "tasks"
},
"tasks-create": {
- "description": "Create an agent task in the current project — a unit of work an AI agent picks up and actions, such as investigating an inbox report, fixing an error, or opening a pull request. `description` is the prompt handed to the agent, so make it specific and actionable. Pass `repository` in `organization/repo` format for code tasks so the agent knows where to work; omit it for investigation-only tasks. This creates the task record only — it does not start the agent. Returns the created task including its URL; open that URL to start the run. Requires the calling token's organization to have Tasks access enabled.",
+ "description": "Create a task without starting a run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. A person can start the task at the returned URL. Use `tasks-create-and-run` to start a run immediately when that tool is available.",
"category": "Tasks",
"feature": "tasks",
"summary": "Create task",
@@ -12037,6 +12037,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-create-and-run": {
+ "description": "Create a task and start its first background run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Create task and start run",
+ "title": "Create task and start run",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks-mcp-agent-run-start"
+ },
"tasks-list": {
"description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled.",
"category": "Tasks",
@@ -12112,6 +12127,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-run-create": {
+ "description": "Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Start task run",
+ "title": "Start task run",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks-mcp-agent-run-start"
+ },
"tasks-runs-list": {
"description": "List all runs for a specific task. Returns lightweight run metadata only — call tasks-runs-retrieve for full run detail including state, output, and artifacts.",
"category": "Tasks",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 88c3eb34ea21..0e23a35333a7 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -1297,6 +1297,79 @@
],
"description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."
},
+ "TaskAgentCreateSchema": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Instructions for the agent."
+ },
+ "repository": {
+ "description": "Repository in organization/repo format.",
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "branch": {
+ "description": "Base branch for the run.",
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 255
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": ["description"]
+ },
+ "TaskAgentRunCreateSchema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "description": "Task ID."
+ },
+ "branch": {
+ "description": "Git branch to check out in the sandbox.",
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 255
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "resume_from_run_id": {
+ "description": "ID of a previous run to resume from.",
+ "type": "string",
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
+ },
+ "pending_user_message": {
+ "description": "Initial or follow-up message for the run.",
+ "type": "string"
+ }
+ },
+ "required": ["id"]
+ },
"UsageMetricFiltersSchema": {
"anyOf": [
{
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d2cb2fd07077..72f826f185b2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18322,6 +18322,7 @@ export namespace Schemas {
/**
* * `manual` - manual
* * `signal_report` - signal_report
+ * * `agent` - agent
*/
export type RunSourceEnum = typeof RunSourceEnum[keyof typeof RunSourceEnum];
@@ -18329,6 +18330,7 @@ export namespace Schemas {
export const RunSourceEnum = {
Manual: 'manual',
SignalReport: 'signal_report',
+ Agent: 'agent',
} as const;
/**
@@ -18395,6 +18397,21 @@ export namespace Schemas {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServer[] | null;
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null;
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null;
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnum | null;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -18432,7 +18449,8 @@ export namespace Schemas {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnum;
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string;
@@ -18471,21 +18489,6 @@ export namespace Schemas {
* * `bypassPermissions` - bypassPermissions
* * `auto` - auto */
initial_permission_mode?: InitialPermissionModeEnum;
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null;
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null;
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnum | null;
}
export type ClickhouseEventProperties = { [key: string]: unknown };
@@ -18811,6 +18814,21 @@ export namespace Schemas {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServer[] | null;
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null;
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null;
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnum | null;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -18848,7 +18866,8 @@ export namespace Schemas {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnum;
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string;
@@ -18886,21 +18905,6 @@ export namespace Schemas {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: CodexTaskRunCreateSchemaInitialPermissionModeEnum;
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null;
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null;
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnum | null;
}
export type PropertyGroupOperatorEnum = typeof PropertyGroupOperatorEnum[keyof typeof PropertyGroupOperatorEnum];
@@ -71595,6 +71599,11 @@ export namespace Schemas {
output?: unknown;
}
+ /**
+ * State of the run
+ */
+ export type PatchedTaskRunUpdateState = { [key: string]: unknown };
+
/**
* State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race.
*/
@@ -71623,7 +71632,7 @@ export namespace Schemas {
/** Output from the run */
output?: unknown;
/** State of the run */
- state?: unknown;
+ state?: PatchedTaskRunUpdateState;
/** State keys to remove atomically before applying any state updates. */
state_remove_keys?: string[];
/** State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race. */
@@ -71783,22 +71792,22 @@ export namespace Schemas {
*/
ci_prompt?: string | null;
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null;
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnum | null;
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null;
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -71807,7 +71816,7 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -71818,17 +71827,17 @@ export namespace Schemas {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null;
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[];
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null;
@@ -89293,6 +89302,18 @@ export namespace Schemas {
artifacts: TaskArtifact[];
}
+ /**
+ * * `manual` - manual
+ * * `signal_report` - signal_report
+ */
+ export type TaskBootstrapRunSourceEnum = typeof TaskBootstrapRunSourceEnum[keyof typeof TaskBootstrapRunSourceEnum];
+
+
+ export const TaskBootstrapRunSourceEnum = {
+ Manual: 'manual',
+ SignalReport: 'signal_report',
+ } as const;
+
export interface TaskCommentAnchor {
/** Anchor kind. */
kind?: string;
@@ -89499,22 +89520,22 @@ export namespace Schemas {
*/
ci_prompt?: string | null;
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null;
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnum | null;
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null;
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -89523,7 +89544,7 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -89534,17 +89555,17 @@ export namespace Schemas {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null;
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[];
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null;
@@ -89553,6 +89574,8 @@ export namespace Schemas {
* @nullable
*/
channel?: string | null;
+ /** Start the task's first cloud run immediately after creation. */
+ start_run?: boolean;
/**
* Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task.
* @maxLength 4000
@@ -89561,12 +89584,12 @@ export namespace Schemas {
/** Text the server generates the title from instead of `description`. Lets a client whose `description` is only an attachment summary (e.g. pasted text stored as a file) supply the real content for naming, so `description` (the prompt passed to the agent) stays unchanged. Not persisted. */
naming_source?: string;
/**
- * Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.
+ * Sandbox environment for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.
* @nullable
*/
sandbox_environment_id?: string | null;
/**
- * Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.
+ * Custom image for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.
* @nullable
*/
custom_image_id?: string | null;
@@ -89577,6 +89600,70 @@ export namespace Schemas {
runtime?: TaskRuntimeEnum;
}
+ /**
+ * @nullable
+ */
+ export type TaskCreateResponseDTOJsonSchema = { [key: string]: unknown } | null;
+
+ /**
+ * Detail response for a task.
+ *
+ * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /
+ * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and
+ * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.
+ */
+ export interface TaskCreateResponseDTO {
+ id: string;
+ /** @nullable */
+ task_number: number | null;
+ slug: string;
+ title: string;
+ title_manually_set: boolean;
+ description: string;
+ origin_product: string;
+ /** Agent protocol and harness used for this task's runs.
+ *
+ * * `acp` - ACP
+ * * `pi` - Pi */
+ runtime: TaskRuntimeEnum;
+ /** @nullable */
+ repository: string | null;
+ repositories: string[];
+ /** @nullable */
+ github_integration: number | null;
+ /** @nullable */
+ github_user_integration: string | null;
+ /** @nullable */
+ signal_report: string | null;
+ /** @nullable */
+ json_schema: TaskCreateResponseDTOJsonSchema;
+ internal: boolean;
+ archived: boolean;
+ /** @nullable */
+ archived_at: string | null;
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTO | null;
+ /** @nullable */
+ created_at?: string | null;
+ /** @nullable */
+ updated_at?: string | null;
+ /** @nullable */
+ last_activity_at?: string | null;
+ created_by?: TaskUserBasicInfo | null;
+ /** @nullable */
+ ci_prompt: string | null;
+ /** @nullable */
+ channel?: string | null;
+ readonly slack_thread_references: readonly SlackThreadReferenceDTO[];
+ /**
+ * Stable key of the server-side flow that created this task, e.g. `desktop_onboarding_session:<user_id>`. Null for tasks people create themselves.
+ * @nullable
+ */
+ origin_key?: string | null;
+ /** Error returned when the task was created but its first run could not start. */
+ run_error?: string;
+ }
+
/**
* Request body for handing a task off to a colleague: they become its owner.
*/
@@ -89985,6 +90072,21 @@ export namespace Schemas {
* @nullable
*/
relayed_mcp_servers?: RelayedMcpServer[] | null;
+ /**
+ * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
+ * @nullable
+ */
+ rtk_enabled?: boolean | null;
+ /**
+ * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
+ * @nullable
+ */
+ benjamin_enabled?: boolean | null;
+ /** 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. 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 */
+ claude_model_access?: ClaudeModelAccessEnum | null;
/** Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.
*
* * `local` - local
@@ -90019,7 +90121,7 @@ export namespace Schemas {
*
* * `manual` - manual
* * `signal_report` - signal_report */
- run_source?: RunSourceEnum;
+ run_source?: TaskBootstrapRunSourceEnum;
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string;
/** Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.
@@ -90062,21 +90164,6 @@ export namespace Schemas {
* * `read-only` - read-only
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum;
- /**
- * Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.
- * @nullable
- */
- rtk_enabled?: boolean | null;
- /**
- * Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.
- * @nullable
- */
- benjamin_enabled?: boolean | null;
- /** 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. 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 */
- claude_model_access?: ClaudeModelAccessEnum | null;
}
export interface TaskRunCancelRequest {
@@ -90200,7 +90287,8 @@ export namespace Schemas {
/** High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.
*
* * `manual` - manual
- * * `signal_report` - signal_report */
+ * * `signal_report` - signal_report
+ * * `agent` - agent */
run_source?: RunSourceEnum;
/** Optional signal report identifier when this run was started from Inbox. */
signal_report_id?: string;
@@ -90630,6 +90718,70 @@ export namespace Schemas {
relay_id?: string;
}
+ /**
+ * @nullable
+ */
+ export type TaskRunResponseJsonSchema = { [key: string]: unknown } | null;
+
+ /**
+ * Detail response for a task.
+ *
+ * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /
+ * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and
+ * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.
+ */
+ export interface TaskRunResponse {
+ id: string;
+ /** @nullable */
+ task_number: number | null;
+ slug: string;
+ title: string;
+ title_manually_set: boolean;
+ description: string;
+ origin_product: string;
+ /** Agent protocol and harness used for this task's runs.
+ *
+ * * `acp` - ACP
+ * * `pi` - Pi */
+ runtime: TaskRuntimeEnum;
+ /** @nullable */
+ repository: string | null;
+ repositories: string[];
+ /** @nullable */
+ github_integration: number | null;
+ /** @nullable */
+ github_user_integration: string | null;
+ /** @nullable */
+ signal_report: string | null;
+ /** @nullable */
+ json_schema: TaskRunResponseJsonSchema;
+ internal: boolean;
+ archived: boolean;
+ /** @nullable */
+ archived_at: string | null;
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTO | null;
+ /** @nullable */
+ created_at?: string | null;
+ /** @nullable */
+ updated_at?: string | null;
+ /** @nullable */
+ last_activity_at?: string | null;
+ created_by?: TaskUserBasicInfo | null;
+ /** @nullable */
+ ci_prompt: string | null;
+ /** @nullable */
+ channel?: string | null;
+ readonly slack_thread_references: readonly SlackThreadReferenceDTO[];
+ /**
+ * Stable key of the server-side flow that created this task, e.g. `desktop_onboarding_session:<user_id>`. Null for tasks people create themselves.
+ * @nullable
+ */
+ origin_key?: string | null;
+ /** Error returned when the run could not start. */
+ run_error?: string;
+ }
+
export interface TaskRunStartRequest {
/** Initial or follow-up user message to include in the run prompt. */
pending_user_message?: string;
@@ -90944,22 +91096,22 @@ export namespace Schemas {
*/
ci_prompt?: string | null;
/**
- * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task.
* @maxLength 255
* @nullable
*/
branch?: string | null;
- /** Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.
+ /** Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.
*
* * `claude` - claude
* * `codex` - codex */
runtime_adapter?: RuntimeAdapterEnum | null;
/**
- * Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.
+ * LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
* @nullable
*/
model?: string | null;
- /** Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.
+ /** Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.
*
* * `low` - low
* * `medium` - medium
@@ -90968,7 +91120,7 @@ export namespace Schemas {
* * `max` - max
* * `ultracode` - ultracode */
reasoning_effort?: ReasoningEffortEnum | null;
- /** Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.
+ /** Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.
*
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -90979,17 +91131,17 @@ export namespace Schemas {
* * `full-access` - full-access */
initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnum | null;
/**
- * First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.
+ * First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
pending_user_message?: string | null;
/**
- * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched.
+ * Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true.
* @items.maxLength 128
*/
pending_user_artifact_ids?: string[];
/**
- * When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead.
+ * When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.
* @nullable
*/
auto_publish?: boolean | null;
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 0dc5fa62285a..d9469a335398 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 24 enabled ops
+ * PostHog API - MCP 25 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1021,6 +1021,7 @@ export const tasksCreateBodyBranchMax = 255
export const tasksCreateBodyPendingUserArtifactIdsItemMax = 128
+export const tasksCreateBodyStartRunDefault = false
export const tasksCreateBodySignalReportDiscussionQuestionMax = 4000
export const TasksCreateBody = () => zod.object({
@@ -1099,20 +1100,18 @@ export const TasksCreateBody = () => zod.object({
.max(tasksCreateBodyBranchMax)
.nullish()
.describe(
- 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ "Base branch for the first run when start_run is true, or for matching a pre-warmed run. Omit to use the repository's default branch. Write-only and not persisted on the task."
),
runtime_adapter: zod
.union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
.optional()
.describe(
- "Selected runtime adapter ('claude' or 'codex'). Write-only and not persisted on the task: used only to reuse a pre-warmed Run started on the same runtime. A value differing from the warm Run's runtime skips reuse so the task isn't silently run on the wrong runtime.\n\n\* `claude` - claude\n\* `codex` - codex"
+ "Runtime adapter ('claude' or 'codex') for the first run when start_run is true, or for matching a pre-warmed run. A different adapter prevents warm reuse. Write-only and not persisted on the task.\n\n\* `claude` - claude\n\* `codex` - codex"
),
model: zod
.string()
.nullish()
- .describe(
- 'Selected LLM model identifier. Write-only; used only to reuse a warm Run started on the same model.'
- ),
+ .describe('LLM model for the first run when start_run is true, or for matching a pre-warmed run. Write-only.'),
reasoning_effort: zod
.union([
zod
@@ -1124,7 +1123,7 @@ export const TasksCreateBody = () => zod.object({
])
.optional()
.describe(
- 'Selected reasoning effort. Write-only; used only to reuse a warm Run started on the same effort.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ 'Reasoning effort for the first run when start_run is true, or for matching a pre-warmed run. Write-only.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
),
initial_permission_mode: zod
.union([
@@ -1137,27 +1136,31 @@ export const TasksCreateBody = () => zod.object({
])
.optional()
.describe(
- 'Selected agent permission mode. Write-only; used only to reuse a warm Run booted on the same mode. Omit to reuse a warm Run whatever mode it booted on.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ 'Agent permission mode for the first run when start_run is true, or for matching a pre-warmed run. Omit to match any warm permission mode. Write-only.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
),
pending_user_message: zod
.string()
.nullish()
.describe(
- 'First user message to forward when creation reuses a pre-warmed Run. Write-only and not persisted on the task: lets clients deliver a message that differs from `description` (e.g. a resolved skill invocation with channel context folded in). Ignored when no warm Run is reused — cold creation takes the first message via the run start endpoint instead.'
+ 'First user message when start_run is true or creation reuses a pre-warmed run. This message can differ from description. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
pending_user_artifact_ids: zod
.array(zod.string().max(tasksCreateBodyPendingUserArtifactIdsItemMax))
.optional()
.describe(
- "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched."
+ "Run artifact ids (already uploaded to the pre-warmed Run) to attach to the forwarded first message when creation reuses that warm Run, e.g. skill bundles or file attachments. If any id is missing from the warm Run's manifest, warm reuse is skipped and the task is created cold. Ignored when no warm Run is matched. Not supported when start_run is true."
),
auto_publish: zod
.boolean()
.nullish()
.describe(
- "When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask. Write-only and not persisted on the task: persisted into the reused warm Run's state when creation activates one, so resumes of that Run honor it. Ignored when no warm Run is reused — cold creation takes it via the run start endpoint instead."
+ 'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.string().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ start_run: zod
+ .boolean()
+ .default(tasksCreateBodyStartRunDefault)
+ .describe("Start the task's first cloud run immediately after creation."),
signal_report_discussion_question: zod
.string()
.max(tasksCreateBodySignalReportDiscussionQuestionMax)
@@ -1174,11 +1177,15 @@ export const TasksCreateBody = () => zod.object({
sandbox_environment_id: zod
.string()
.nullish()
- .describe('Sandbox environment selected for matching a pre-warmed cloud run. Not persisted on the task.'),
+ .describe(
+ 'Sandbox environment for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.'
+ ),
custom_image_id: zod
.string()
.nullish()
- .describe('Custom image selected for matching a pre-warmed cloud run. Not persisted on the task.'),
+ .describe(
+ 'Custom image for the first run when start_run is true, or for matching a pre-warmed run. Not persisted on the task.'
+ ),
runtime: zod
.enum(['acp', 'pi'])
.describe('\* `acp` - ACP\n\* `pi` - Pi')
@@ -1192,8 +1199,29 @@ export const TasksCreateBody = () => zod.object({
* Retrieve a single task by ID.
* @summary Get task
*/
+export const tasksRetrievePathIdRegExp = new RegExp(
+ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
+)
+
export const TasksRetrieveParams = () => zod.object({
- id: zod.string(),
+ id: zod.string().regex(tasksRetrievePathIdRegExp),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+/**
+ * Create a new task run and kick off the workflow.
+ * @summary Run task
+ */
+export const tasksRunCreatePathIdRegExp = new RegExp(
+ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
+)
+
+export const TasksRunCreateParams = () => zod.object({
+ id: zod.string().regex(tasksRunCreatePathIdRegExp),
project_id: zod
.string()
.describe(
@@ -1201,6 +1229,433 @@ export const TasksRetrieveParams = () => zod.object({
),
})
+export const TasksRunCreateHeader = () => zod.object({
+ 'X-PostHog-Warm-Retry': zod
+ .string()
+ .optional()
+ .describe('Retry token from a warm_run_activation_unavailable response; prevents creating a replacement run.'),
+})
+
+export const tasksRunCreateBodyOneImportedMcpServersItemNameMax = 64
+
+export const tasksRunCreateBodyOneImportedMcpServersItemUrlMax = 2048
+
+export const tasksRunCreateBodyOneImportedMcpServersItemHeadersItemNameMax = 256
+
+export const tasksRunCreateBodyOneImportedMcpServersItemHeadersItemValueMax = 4096
+
+export const tasksRunCreateBodyOneRelayedMcpServersItemNameMax = 64
+
+export const tasksRunCreateBodyOneModeDefault = `background`
+export const tasksRunCreateBodyOneBranchMax = 255
+
+export const tasksRunCreateBodyOnePendingUserArtifactIdsItemMax = 128
+
+export const tasksRunCreateBodyTwoImportedMcpServersItemNameMax = 64
+
+export const tasksRunCreateBodyTwoImportedMcpServersItemUrlMax = 2048
+
+export const tasksRunCreateBodyTwoImportedMcpServersItemHeadersItemNameMax = 256
+
+export const tasksRunCreateBodyTwoImportedMcpServersItemHeadersItemValueMax = 4096
+
+export const tasksRunCreateBodyTwoRelayedMcpServersItemNameMax = 64
+
+export const tasksRunCreateBodyTwoModeDefault = `background`
+export const tasksRunCreateBodyTwoBranchMax = 255
+
+export const tasksRunCreateBodyTwoPendingUserArtifactIdsItemMax = 128
+
+export const tasksRunCreateBodyThreeModeDefault = `background`
+export const tasksRunCreateBodyThreeBranchMax = 255
+
+export const TasksRunCreateBody = () => zod.union([
+ zod
+ .object({
+ imported_mcp_servers: zod
+ .array(
+ zod
+ .object({
+ type: zod.enum(['http', 'sse']).describe('\* `http` - http\n\* `sse` - sse'),
+ name: zod.string().max(tasksRunCreateBodyOneImportedMcpServersItemNameMax),
+ url: zod.url().max(tasksRunCreateBodyOneImportedMcpServersItemUrlMax),
+ headers: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(tasksRunCreateBodyOneImportedMcpServersItemHeadersItemNameMax),
+ value: zod
+ .string()
+ .max(tasksRunCreateBodyOneImportedMcpServersItemHeadersItemValueMax),
+ })
+ )
+ .optional(),
+ })
+ .describe("One client-imported MCP server, in the agent server's --mcpServers entry shape.")
+ )
+ .nullish()
+ .describe(
+ 'Local url-based MCP servers from the creating client (PostHog Desktop) to make available inside the cloud sandbox. Header values are treated as credentials: stored encrypted and never returned by the API.'
+ ),
+ relayed_mcp_servers: zod
+ .array(
+ zod
+ .object({
+ name: zod.string().max(tasksRunCreateBodyOneRelayedMcpServersItemNameMax),
+ })
+ .describe(
+ 'One desktop-only MCP server relayed into the run — a name only, never configuration.'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Names of desktop-only MCP servers the creating client (PostHog Desktop) relays into the cloud sandbox over the durable event\/command channel. Names only — the server configuration (command, env, URL, headers) never crosses the wire.'
+ ),
+ rtk_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
+ ),
+ benjamin_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
+ ),
+ claude_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 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. 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"
+ ),
+ mode: zod
+ .enum(['interactive', 'background'])
+ .describe('\* `interactive` - interactive\n\* `background` - background')
+ .default(tasksRunCreateBodyOneModeDefault)
+ .describe(
+ "Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs\n\n\* `interactive` - interactive\n\* `background` - background"
+ ),
+ branch: zod
+ .string()
+ .max(tasksRunCreateBodyOneBranchMax)
+ .nullish()
+ .describe('Git branch to checkout in the sandbox'),
+ resume_from_run_id: zod
+ .string()
+ .optional()
+ .describe('ID of a previous run to resume from. Must belong to the same task.'),
+ pending_user_message: zod
+ .string()
+ .optional()
+ .describe('Initial or follow-up user message to include in the run prompt.'),
+ pending_user_artifact_ids: zod
+ .array(zod.string().max(tasksRunCreateBodyOnePendingUserArtifactIdsItemMax))
+ .optional()
+ .describe('Identifiers for staged task artifacts that should be attached to the initial run prompt.'),
+ sandbox_environment_id: zod
+ .string()
+ .optional()
+ .describe('Optional sandbox environment to apply for this cloud run.'),
+ custom_image_id: zod
+ .string()
+ .optional()
+ .describe(
+ "Optional custom base image for this cloud run's sandbox (Modal VM runtime only); takes precedence over the environment's image."
+ ),
+ pr_authorship_mode: zod
+ .enum(['user', 'bot'])
+ .describe('\* `user` - user\n\* `bot` - bot')
+ .optional()
+ .describe(
+ 'Whether pull requests for this run should be authored by the user or the bot.\n\n\* `user` - user\n\* `bot` - bot'
+ ),
+ auto_publish: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask.'
+ ),
+ run_source: zod
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
+ .optional()
+ .describe(
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
+ ),
+ signal_report_id: zod
+ .string()
+ .optional()
+ .describe('Optional signal report identifier when this run was started from Inbox.'),
+ runtime_adapter: zod
+ .enum(['claude'])
+ .describe('\* `claude` - claude')
+ .describe(
+ "Agent runtime adapter to launch for this run. Must be 'claude' for Claude runtimes.\n\n\* `claude` - claude"
+ ),
+ model: zod.string().describe('LLM model identifier to run in the Claude runtime.'),
+ reasoning_effort: zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ )
+ .optional()
+ .describe(
+ 'Reasoning effort to request 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'
+ ),
+ context_window: zod
+ .enum(['200k', '1m'])
+ .describe('\* `200k` - 200k\n\* `1m` - 1m')
+ .optional()
+ .describe(
+ 'Context window size for models that support the 1M window.\n\n\* `200k` - 200k\n\* `1m` - 1m'
+ ),
+ fast_mode: zod.boolean().nullish().describe('Enable fast mode for models that support it.'),
+ github_user_token: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional GitHub user token from PostHog Desktop for user-authored cloud pull requests. Prefer linking GitHub from Settings → Linked accounts so the server can manage tokens; this field remains supported for callers that still manage their own tokens.'
+ ),
+ initial_permission_mode: zod
+ .enum(['default', 'acceptEdits', 'plan', 'bypassPermissions', 'auto'])
+ .describe(
+ '\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto'
+ )
+ .optional()
+ .describe(
+ 'Initial permission mode for Claude runtimes.\n\n\* `default` - default\n\* `acceptEdits` - acceptEdits\n\* `plan` - plan\n\* `bypassPermissions` - bypassPermissions\n\* `auto` - auto'
+ ),
+ })
+ .describe('Request body for creating a new task run'),
+ zod
+ .object({
+ imported_mcp_servers: zod
+ .array(
+ zod
+ .object({
+ type: zod.enum(['http', 'sse']).describe('\* `http` - http\n\* `sse` - sse'),
+ name: zod.string().max(tasksRunCreateBodyTwoImportedMcpServersItemNameMax),
+ url: zod.url().max(tasksRunCreateBodyTwoImportedMcpServersItemUrlMax),
+ headers: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(tasksRunCreateBodyTwoImportedMcpServersItemHeadersItemNameMax),
+ value: zod
+ .string()
+ .max(tasksRunCreateBodyTwoImportedMcpServersItemHeadersItemValueMax),
+ })
+ )
+ .optional(),
+ })
+ .describe("One client-imported MCP server, in the agent server's --mcpServers entry shape.")
+ )
+ .nullish()
+ .describe(
+ 'Local url-based MCP servers from the creating client (PostHog Desktop) to make available inside the cloud sandbox. Header values are treated as credentials: stored encrypted and never returned by the API.'
+ ),
+ relayed_mcp_servers: zod
+ .array(
+ zod
+ .object({
+ name: zod.string().max(tasksRunCreateBodyTwoRelayedMcpServersItemNameMax),
+ })
+ .describe(
+ 'One desktop-only MCP server relayed into the run — a name only, never configuration.'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Names of desktop-only MCP servers the creating client (PostHog Desktop) relays into the cloud sandbox over the durable event\/command channel. Names only — the server configuration (command, env, URL, headers) never crosses the wire.'
+ ),
+ rtk_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether rtk command-output compression is enabled for this run. Omitted or null follows the server-side default (enabled); false opts this run out.'
+ ),
+ benjamin_enabled: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
+ ),
+ claude_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 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. 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"
+ ),
+ mode: zod
+ .enum(['interactive', 'background'])
+ .describe('\* `interactive` - interactive\n\* `background` - background')
+ .default(tasksRunCreateBodyTwoModeDefault)
+ .describe(
+ "Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs\n\n\* `interactive` - interactive\n\* `background` - background"
+ ),
+ branch: zod
+ .string()
+ .max(tasksRunCreateBodyTwoBranchMax)
+ .nullish()
+ .describe('Git branch to checkout in the sandbox'),
+ resume_from_run_id: zod
+ .string()
+ .optional()
+ .describe('ID of a previous run to resume from. Must belong to the same task.'),
+ pending_user_message: zod
+ .string()
+ .optional()
+ .describe('Initial or follow-up user message to include in the run prompt.'),
+ pending_user_artifact_ids: zod
+ .array(zod.string().max(tasksRunCreateBodyTwoPendingUserArtifactIdsItemMax))
+ .optional()
+ .describe('Identifiers for staged task artifacts that should be attached to the initial run prompt.'),
+ sandbox_environment_id: zod
+ .string()
+ .optional()
+ .describe('Optional sandbox environment to apply for this cloud run.'),
+ custom_image_id: zod
+ .string()
+ .optional()
+ .describe(
+ "Optional custom base image for this cloud run's sandbox (Modal VM runtime only); takes precedence over the environment's image."
+ ),
+ pr_authorship_mode: zod
+ .enum(['user', 'bot'])
+ .describe('\* `user` - user\n\* `bot` - bot')
+ .optional()
+ .describe(
+ 'Whether pull requests for this run should be authored by the user or the bot.\n\n\* `user` - user\n\* `bot` - bot'
+ ),
+ auto_publish: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'When true, the cloud run agent pushes its work and opens a draft pull request on completion without waiting for an explicit ask.'
+ ),
+ run_source: zod
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
+ .optional()
+ .describe(
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
+ ),
+ signal_report_id: zod
+ .string()
+ .optional()
+ .describe('Optional signal report identifier when this run was started from Inbox.'),
+ runtime_adapter: zod
+ .enum(['codex'])
+ .describe('\* `codex` - codex')
+ .describe(
+ "Agent runtime adapter to launch for this run. Must be 'codex' for Codex runtimes.\n\n\* `codex` - codex"
+ ),
+ model: zod.string().describe('LLM model identifier to run in the Codex runtime.'),
+ reasoning_effort: zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ )
+ .optional()
+ .describe(
+ 'Reasoning effort to request 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'
+ ),
+ context_window: zod
+ .enum(['200k', '1m'])
+ .describe('\* `200k` - 200k\n\* `1m` - 1m')
+ .optional()
+ .describe(
+ 'Context window size for models that support the 1M window.\n\n\* `200k` - 200k\n\* `1m` - 1m'
+ ),
+ fast_mode: zod.boolean().nullish().describe('Enable fast mode for models that support it.'),
+ github_user_token: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional GitHub user token from PostHog Desktop for user-authored cloud pull requests. Prefer linking GitHub from Settings → Linked accounts so the server can manage tokens; this field remains supported for callers that still manage their own tokens.'
+ ),
+ initial_permission_mode: zod
+ .enum(['plan', 'auto', 'read-only', 'full-access'])
+ .describe(
+ '\* `plan` - plan\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ )
+ .optional()
+ .describe(
+ 'Initial permission mode for Codex runtimes.\n\n\* `plan` - plan\n\* `auto` - auto\n\* `read-only` - read-only\n\* `full-access` - full-access'
+ ),
+ })
+ .describe('Request body for creating a new task run'),
+ zod.object({
+ mode: zod
+ .enum(['interactive', 'background'])
+ .describe('\* `interactive` - interactive\n\* `background` - background')
+ .default(tasksRunCreateBodyThreeModeDefault)
+ .describe(
+ "Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs\n\n\* `interactive` - interactive\n\* `background` - background"
+ ),
+ branch: zod
+ .string()
+ .max(tasksRunCreateBodyThreeBranchMax)
+ .nullish()
+ .describe('Git branch to checkout in the sandbox'),
+ resume_from_run_id: zod
+ .string()
+ .optional()
+ .describe('ID of a previous run to resume from. Must belong to the same task.'),
+ pending_user_message: zod
+ .string()
+ .optional()
+ .describe('Initial or follow-up user message to include in the run prompt.'),
+ sandbox_environment_id: zod
+ .string()
+ .optional()
+ .describe('Optional sandbox environment to apply for this cloud run.'),
+ custom_image_id: zod
+ .string()
+ .optional()
+ .describe(
+ "Optional custom base image for this cloud run's sandbox (Modal VM runtime only); takes precedence over the environment's image."
+ ),
+ pr_authorship_mode: zod
+ .enum(['user', 'bot'])
+ .describe('\* `user` - user\n\* `bot` - bot')
+ .optional()
+ .describe(
+ 'Whether pull requests for this run should be authored by the user or the bot.\n\n\* `user` - user\n\* `bot` - bot'
+ ),
+ run_source: zod
+ .enum(['manual', 'signal_report', 'agent'])
+ .describe('\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent')
+ .optional()
+ .describe(
+ 'High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.\n\n\* `manual` - manual\n\* `signal_report` - signal_report\n\* `agent` - agent'
+ ),
+ signal_report_id: zod
+ .string()
+ .optional()
+ .describe('Optional signal report identifier when this run was started from Inbox.'),
+ github_user_token: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional GitHub user token from PostHog Desktop for user-authored cloud pull requests. Prefer linking GitHub from Settings → Linked accounts so the server can manage tokens; this field remains supported for callers that still manage their own tokens.'
+ ),
+ }),
+])
+
/**
* Get a list of runs for a specific task.
* @summary List task runs
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index c8f817e2d918..f7d55d1b5ef5 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -226,6 +226,7 @@ export class RequestStateResolver {
const excludeTools = [
...switchToolsToExclude({ organizationId }),
...tasksContextToolsToExclude(clientProfile, props.taskId),
+ ...(apiKeyScopes.includes('internal_run:read') ? ['tasks-run-create', 'tasks-create-and-run'] : []),
]
const filterOptions = {
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 96fe68cca7a7..315394d523bd 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -654,6 +654,24 @@ export const ProjectSetActiveSchema = z.object({
projectId: z.number().int().positive(),
})
+export const TaskAgentCreateSchema = z
+ .object({
+ title: z.string().max(255).optional(),
+ description: z.string().min(1).describe('Instructions for the agent.'),
+ repository: z.string().nullish().describe('Repository in organization/repo format.'),
+ branch: z.string().min(1).max(255).nullish().describe('Base branch for the run.'),
+ })
+ .transform((input) => ({ ...input, start_run: true as const }))
+
+export const TaskAgentRunCreateSchema = z
+ .object({
+ id: z.string().uuid().describe('Task ID.'),
+ branch: z.string().max(255).nullish().describe('Git branch to check out in the sandbox.'),
+ resume_from_run_id: z.string().uuid().optional().describe('ID of a previous run to resume from.'),
+ pending_user_message: z.string().optional().describe('Initial or follow-up message for the run.'),
+ })
+ .transform((input) => ({ ...input, mode: 'background' as const, run_source: 'agent' as const }))
+
// Debug MCP UI Apps
export const DebugMcpUiAppsSchema = z.object({
message: z.string().optional().describe('Optional message to include in the debug data'),
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index 6c2e99b39b44..df3ebb59e003 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -3,7 +3,11 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/tasks/api'
-import { ChannelInstructionsBaseVersionSchema } from '@/schema/tool-inputs'
+import {
+ ChannelInstructionsBaseVersionSchema,
+ TaskAgentCreateSchema,
+ TaskAgentRunCreateSchema,
+} from '@/schema/tool-inputs'
import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'
import {
executeConfirmedAction,
@@ -604,6 +608,7 @@ const TasksCreateSchema = () => {
pending_user_artifact_ids: true,
auto_publish: true,
channel: true,
+ start_run: true,
signal_report_discussion_question: true,
naming_source: true,
sandbox_environment_id: true,
@@ -618,7 +623,10 @@ const TasksCreateSchema = () => {
})
}
-const tasksCreate = (): ToolBase<ReturnType<typeof TasksCreateSchema>, WithPostHogUrl<Schemas.TaskDetailDTO>> => ({
+const tasksCreate = (): ToolBase<
+ ReturnType<typeof TasksCreateSchema>,
+ WithPostHogUrl<Schemas.TaskCreateResponseDTO>
+> => ({
name: 'tasks-create',
schema: TasksCreateSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof TasksCreateSchema>>) => {
@@ -633,7 +641,7 @@ const tasksCreate = (): ToolBase<ReturnType<typeof TasksCreateSchema>, WithPostH
if (params.repository !== undefined) {
body['repository'] = params.repository
}
- const result = await context.api.request<Schemas.TaskDetailDTO>({
+ const result = await context.api.request<Schemas.TaskCreateResponseDTO>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/`,
body,
@@ -646,6 +654,10 @@ const tasksCreate = (): ToolBase<ReturnType<typeof TasksCreateSchema>, WithPostH
'origin_product',
'repository',
'internal',
+ 'latest_run.id',
+ 'latest_run.stage',
+ 'latest_run.status',
+ 'run_error',
'created_at',
'updated_at',
]) as typeof result
@@ -653,6 +665,34 @@ const tasksCreate = (): ToolBase<ReturnType<typeof TasksCreateSchema>, WithPostH
},
})
+const TasksCreateAndRunSchema = () => TaskAgentCreateSchema
+
+const tasksCreateAndRun = (): ToolBase<ReturnType<typeof TasksCreateAndRunSchema>, Schemas.TaskCreateResponseDTO> => ({
+ name: 'tasks-create-and-run',
+ schema: TasksCreateAndRunSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TasksCreateAndRunSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const parsedParams = TasksCreateAndRunSchema().parse(params)
+ const result = await context.api.request<Schemas.TaskCreateResponseDTO>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/`,
+ body: parsedParams,
+ })
+ const filtered = pickResponseFields(result, [
+ 'id',
+ 'task_number',
+ 'title',
+ 'description',
+ 'repository',
+ 'latest_run.id',
+ 'latest_run.stage',
+ 'latest_run.status',
+ 'run_error',
+ ]) as typeof result
+ return await withPostHogUrl(context, filtered, `/tasks/${filtered.id}`)
+ },
+})
+
const TasksListSchema = () => {
const TasksListQueryParams = orvalSchemas.TasksListQueryParams()
return TasksListQueryParams
@@ -827,6 +867,35 @@ const tasksRetrieve = (): ToolBase<ReturnType<typeof TasksRetrieveSchema>, WithP
},
})
+const TasksRunCreateSchema = () => TaskAgentRunCreateSchema
+
+const tasksRunCreate = (): ToolBase<ReturnType<typeof TasksRunCreateSchema>, Schemas.TaskRunResponse> => ({
+ name: 'tasks-run-create',
+ schema: TasksRunCreateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TasksRunCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const parsedParams = TasksRunCreateSchema().parse(params)
+ const { id, ...body } = parsedParams
+ const result = await context.api.request<Schemas.TaskRunResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(id))}/run/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, [
+ 'run_error',
+ 'id',
+ 'task_number',
+ 'title',
+ 'description',
+ 'repository',
+ 'latest_run.id',
+ 'latest_run.stage',
+ 'latest_run.status',
+ ]) as typeof result
+ return await withPostHogUrl(context, filtered, `/tasks/${filtered.id}`)
+ },
+})
+
const TasksRunsListSchema = () => {
const TasksRunsListParams = orvalSchemas.TasksRunsListParams()
const TasksRunsListQueryParams = orvalSchemas.TasksRunsListQueryParams()
@@ -947,11 +1016,13 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'tasks-config-create': tasksConfigCreate,
'tasks-config-list': tasksConfigList,
'tasks-create': tasksCreate,
+ 'tasks-create-and-run': tasksCreateAndRun,
'tasks-list': tasksList,
'tasks-me-config-create': tasksMeConfigCreate,
'tasks-me-config-list': tasksMeConfigList,
'tasks-models-retrieve': tasksModelsRetrieve,
'tasks-retrieve': tasksRetrieve,
+ 'tasks-run-create': tasksRunCreate,
'tasks-runs-list': tasksRunsList,
'tasks-runs-retrieve': tasksRunsRetrieve,
'tasks-runs-session-logs-retrieve': tasksRunsSessionLogsRetrieve,
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 2bb97e30512f..2c0f438533ea 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -197,7 +197,11 @@ export const getToolsFromContext = async (
const apiKey = await context.stateManager.getApiKey()
const scopes = apiKey?.scopes ?? []
- const candidates = tools.filter((tool) => hasScopes(scopes, tool.scopes))
+ const candidates = tools.filter(
+ (tool) =>
+ hasScopes(scopes, tool.scopes) &&
+ (!scopes.includes('internal_run:read') || !['tasks-run-create', 'tasks-create-and-run'].includes(tool.name))
+ )
return filterStaffOnlyTools(candidates, apiKey ?? { scopes: [] }, () => context.stateManager.getUser())
}
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index dd4302125615..a075667613f5 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockSessionStore, mockTokenStore } = vi.hoisted(() => ({
+const { mockSessionStore, mockTokenStore, mockApiKey } = vi.hoisted(() => ({
mockSessionStore: new Map<string, unknown>(),
mockTokenStore: new Map<string, unknown>(),
+ mockApiKey: { scopes: ['*'], scoped_teams: [] },
}))
vi.mock('@/lib/posthog/flags', () => ({
@@ -63,7 +64,7 @@ vi.mock('@/hono/request-context', () => {
getContext: vi.fn(async () => ({
stateManager: {
setDefaultOrganizationAndProject: vi.fn(async () => {}),
- getApiKey: vi.fn(async () => ({ scopes: ['*'], scoped_teams: [] })),
+ getApiKey: vi.fn(async () => mockApiKey),
getAiConsentGiven: vi.fn(async () => undefined),
getOrFetchGroupTypes: vi.fn(async () => undefined),
getEnvironmentPrompt: vi.fn(async () => undefined),
@@ -81,6 +82,7 @@ vi.mock('@/hono/request-context', () => {
import type { RedisLike } from '@/hono/cache/RedisCache'
import { MCP_EXEC_SKILLS_FEATURE_FLAG } from '@/hono/constants'
import { RequestStateResolver } from '@/hono/request-state-resolver'
+import { ToolCatalog } from '@/hono/tool-catalog'
import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'
import type { RequestProperties } from '@/lib/request-properties'
import { TASKS_CONTEXT_TOOL_NAMES } from '@/tools/tasksContext'
@@ -123,6 +125,30 @@ describe('RequestStateResolver MCP client contexts', () => {
beforeEach(() => {
mockSessionStore.clear()
mockTokenStore.clear()
+ mockApiKey.scopes = ['*']
+ })
+
+ it.each([
+ ['cli', false],
+ ['cli', true],
+ ['tools', false],
+ ['tools', true],
+ ] as const)('filters run-start tools in %s mode with sandbox=%s', async (mode, sandbox) => {
+ if (sandbox) {
+ mockApiKey.scopes.push('internal_run:read')
+ }
+ vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'tasks-mcp-agent-run-start': true, tasks: true })
+ const catalog = new ToolCatalog()
+ await catalog.warmup()
+ const resolver = new RequestStateResolver(catalog, {} as RedisLike, {} as Env)
+
+ const result = await resolver.resolve(makeProps({ mode }))
+ const names = result.allTools.map((tool) => tool.name)
+
+ for (const name of ['tasks-run-create', 'tasks-create-and-run']) {
+ expect(names.includes(name)).toBe(!sandbox)
+ }
+ expect(names).toContain('tasks-create')
})
it('stores client props, but not resolved mode, for a new MCP session', async () => {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json
new file mode 100644
index 000000000000..6366182713d3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json
@@ -0,0 +1,40 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "branch": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "minLength": 1,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Base branch for the run."
+ },
+ "description": {
+ "description": "Instructions for the agent.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "repository": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Repository in organization/repo format."
+ },
+ "title": {
+ "maxLength": 255,
+ "type": "string"
+ }
+ },
+ "required": ["description"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
index f9bfd8020ef3..076f4303eaa3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
@@ -2,6 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"id": {
+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json
new file mode 100644
index 000000000000..5c6e8faf683b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json
@@ -0,0 +1,35 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "branch": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Git branch to check out in the sandbox."
+ },
+ "id": {
+ "description": "Task ID.",
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ },
+ "pending_user_message": {
+ "description": "Initial or follow-up message for the run.",
+ "type": "string"
+ },
+ "resume_from_run_id": {
+ "description": "ID of a previous run to resume from.",
+ "format": "uuid",
+ "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tasks-generated.test.ts b/services/mcp/tests/unit/tasks-generated.test.ts
new file mode 100644
index 000000000000..d7edecb768d1
--- /dev/null
+++ b/services/mcp/tests/unit/tasks-generated.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+
+import { GENERATED_TOOL_MAP } from '@/tools/generated'
+
+describe('Generated task tools', () => {
+ it('does not expose run inputs on tasks-create', () => {
+ const schema = GENERATED_TOOL_MAP['tasks-create']!().schema
+
+ expect(schema.parse({ description: 'Do work', branch: 'main', start_run: true })).toEqual({
+ description: 'Do work',
+ })
+ })
+
+ it('starts a background run with tasks-create-and-run', () => {
+ const schema = GENERATED_TOOL_MAP['tasks-create-and-run']!().schema
+
+ expect(schema.parse({ description: 'Do work', branch: 'main', start_run: false })).toEqual({
+ description: 'Do work',
+ branch: 'main',
+ start_run: true,
+ })
+ })
+
+ it('requires UUIDs for tasks-run-create identifiers', () => {
+ const schema = GENERATED_TOOL_MAP['tasks-run-create']!().schema
+
+ expect(() => schema.parse({ id: 'not-a-uuid' })).toThrow()
+ expect(() => schema.parse({ id: '00000000-0000-4000-8000-000000000001', resume_from_run_id: 'bad' })).toThrow()
+ })
+
+ it('forces tasks-run-create to background mode', () => {
+ const schema = GENERATED_TOOL_MAP['tasks-run-create']!().schema
+
+ expect(schema.parse({ id: '00000000-0000-4000-8000-000000000001', mode: 'interactive' })).toMatchObject({
+ mode: 'background',
+ run_source: 'agent',
+ })
+ })
+})
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index d69489f8f2d1..d6e7f8260cc2 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -28,6 +28,30 @@ const collectAlwaysAvailableToolNames = (): string[] =>
.map(([name]) => name)
describe('Tool Filtering - Features', () => {
+ it.each([false, true])('hides run-start tools from sandbox tokens: %s', async (sandbox) => {
+ const context = {
+ stateManager: {
+ getApiKey: async () => ({
+ scopes: ['task:read', 'task:write', ...(sandbox ? ['internal_run:read'] : [])],
+ }),
+ getAiConsentGiven: async () => true,
+ },
+ } as unknown as Context
+ const tools = await getToolsFromContext(context, {
+ featureFlags: { tasks: true, 'tasks-mcp-agent-run-start': true },
+ })
+ const names = tools.map((tool) => tool.name)
+ expect(names).toContain('tasks-create')
+ expect(names.includes('tasks-create-and-run')).toBe(!sandbox)
+ expect(names.includes('tasks-run-create')).toBe(!sandbox)
+ })
+
+ it('does not advertise run-start tools before rollout', () => {
+ const names = getToolsForFeatures({ featureFlags: { tasks: true, 'tasks-mcp-agent-run-start': false } })
+ expect(names).toContain('tasks-create')
+ expect(names).not.toContain('tasks-create-and-run')
+ expect(names).not.toContain('tasks-run-create')
+ })
const featureTests = [
{
features: undefined,
@@ -964,6 +988,7 @@ describe('Tool Filtering - Feature Flags', () => {
'revamped-py-notebooks',
'notebook-generated-widgets',
'tasks',
+ 'tasks-mcp-agent-run-start',
'dashboard-widgets',
'marketing-analytics-mcp',
'product-business-knowledge',
@@ -989,7 +1014,7 @@ describe('Tool Filtering - Feature Flags', () => {
'warehouse-multi-destination',
])
)
- expect(flags).toHaveLength(35)
+ expect(flags).toHaveLength(36)
})
it('every loops tool is gated on the loops flag', () => {
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index 880ac5d2d3b9..4cb1d588945a 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -96,6 +96,7 @@ describe('Tool schema snapshots', () => {
const featureFlags = {
tracing: true,
tasks: true,
+ 'tasks-mcp-agent-run-start': true,
loops: true,
'dashboard-widgets': true,
'agent-platform': true,